src_fm_fc_ms_ff
stringlengths 43
86.8k
| target
stringlengths 20
276k
|
---|---|
NoteValidationRule implements IValidationRule { @Override public ValidationResult validate(Transaction tx, ILedger ledger) { if (tx.getNote() == null) { return ValidationResult.success; } int length = tx.getNote().length(); if (length > 0 && length <= maxLength) { Matcher m = notePattern.matcher(tx.getNote()); if (m.matches()) { return ValidationResult.success; } } return ValidationResult.error("Invalid note"); } NoteValidationRule(); NoteValidationRule(Pattern notePattern, int maxLength); @Override ValidationResult validate(Transaction tx, ILedger ledger); } | @Test public void success_without_note() throws Exception { Transaction tx = Builder.newTransaction(timeProvider).build(networkID, sender); validate(tx); }
@Test public void empty_note() throws Exception { expectedException.expect(ValidateException.class); expectedException.expectMessage("Invalid note"); Transaction tx = Builder.newTransaction(timeProvider).note("").build(networkID, sender); validate(tx); }
@Test public void invalid_note_length() throws Exception { expectedException.expect(ValidateException.class); expectedException.expectMessage("Invalid note"); Random random = new Random(); char[] symbols = alphabet.toCharArray(); char[] buffer = new char[Constant.TRANSACTION_NOTE_MAX_LENGTH_V2 + 1]; for (int i = 0; i < buffer.length; i++) { buffer[i] = symbols[random.nextInt(symbols.length)]; } Transaction tx = Builder.newTransaction(timeProvider).note(new String(buffer)).build(networkID, sender); validate(tx); }
@Test public void illegal_symbol() throws Exception { expectedException.expect(ValidateException.class); expectedException.expectMessage("Invalid note"); Transaction tx = Builder.newTransaction(timeProvider).note("|note|").build(networkID, sender); validate(tx); }
@Test public void check_alphabet() throws Exception { Transaction tx = Builder.newTransaction(timeProvider).note(alphabet).build(networkID, sender); validate(tx); }
@Test public void forbidden_note_success() throws Exception { Transaction tx = Builder.newTransaction(timeProvider).build(networkID, sender); validate(tx); }
@Test public void success() throws Exception { Transaction tx = Builder.newTransaction(timeProvider).note("Note").build(networkID, sender); validate(tx); } |
LengthValidationRule implements IValidationRule { @Override public ValidationResult validate(Transaction tx, ILedger ledger) { int length = tx.getLength(); if (length > Constant.TRANSACTION_MAX_PAYLOAD_LENGTH) { return ValidationResult.error("Invalid transaction length."); } return ValidationResult.success; } @Override ValidationResult validate(Transaction tx, ILedger ledger); } | @Test public void success() throws Exception { Transaction tx = Builder.newTransaction(timeProvider).build(networkID, sender); validate(tx); }
@Test public void length_exceeds_limit() throws Exception { expectedException.expect(ValidateException.class); expectedException.expectMessage("Invalid transaction length."); Transaction tx = spy(Builder.newTransaction(timeProvider).build(networkID, sender)); when(tx.getLength()).thenReturn(Constant.TRANSACTION_MAX_PAYLOAD_LENGTH + 1); validate(tx); } |
SyncTransactionService extends BaseService implements ITransactionSynchronizationService { @Override public Transaction[] getTransactions(String lastBlockId, String[] ignoreList) throws RemotePeerException, IOException { List<TransactionID> ignoreIDs = new ArrayList<>(); try { if (!blockchain.getLastBlock().getID().equals(new BlockID(lastBlockId)) && !fork.isPassed(timeProvider.get())) { return new Transaction[0]; } for (String encodedID : ignoreList) { ignoreIDs.add(new TransactionID(encodedID)); } } catch (IllegalArgumentException e) { throw new RemotePeerException("Unsupported request. Invalid transaction ID format.", e); } try { List<Transaction> list = new ArrayList<>(); int blockSize = Constant.BLOCK_TRANSACTION_LIMIT; final Iterator<TransactionID> indexes = backlog.iterator(); while (indexes.hasNext() && list.size() < TRANSACTION_LIMIT && blockSize > 0) { TransactionID id = indexes.next(); if (!ignoreIDs.contains(id)) { Transaction tx = backlog.get(id); if (tx != null) { list.add(tx); } } blockSize--; } return list.toArray(new Transaction[0]); } catch (Exception e) { throw new IOException("Failed to get the transaction list.", e); } } SyncTransactionService(IFork fork,
ITimeProvider timeProvider,
IBacklog backlog,
IBlockchainProvider blockchain); @Override Transaction[] getTransactions(String lastBlockId,
String[] ignoreList); } | @Test public void getTransactions_shouldnt_return_ignore_trs() throws Exception { Transaction[] trs = sts.getTransactions(lastBlockIdStr, new String[] {ignoreTrIdStr}); assertEquals(2, trs.length); assertEquals(unconfTr1, trs[0]); assertEquals(unconfTr2, trs[1]); }
@Test(expected = RemotePeerException.class) public void getTransactions_with_wrong_lastblockid_should_throw() throws Exception { sts.getTransactions("xxx", new String[0]); }
@Test(expected = RemotePeerException.class) public void getTransactions_with_bad_ignorelist_should_throw() throws Exception { sts.getTransactions(lastBlockIdStr, new String[] {"bad_tr_id"}); }
@Test public void getTransactions_with_notlast_lastblockid_should_return_no_trs() throws Exception { Transaction[] trs = sts.getTransactions("EON-B-NA7Z7-YSK86-7BWKU", new String[0]); assertEquals(0, trs.length); }
@Test public void getTransactions_should_return_unconfirmed_trs() throws Exception { Transaction[] trs = sts.getTransactions(lastBlockIdStr, new String[0]); assertEquals(3, trs.length); assertEquals(unconfTr1, trs[0]); assertEquals(unconfTr2, trs[1]); assertEquals(ignoreTr, trs[2]); } |
AccountBotService { public State getState(String id) throws RemotePeerException, IOException { Account account = getAccount(id); if (account != null) { return State.OK; } IBacklog backlog = this.backlog; for (TransactionID item : backlog) { Transaction transaction = backlog.get(item); if (transaction != null && transaction.getType() == TransactionType.Registration) { if (transaction.getData().keySet().contains(id)) { return State.Processing; } } } return State.NotFound; } AccountBotService(IBacklog backlog, LedgerProvider ledgerProvider, IBlockchainProvider blockchain); State getState(String id); Info getInformation(String id); EONBalance getBalance(String id); } | @Test public void getState_for_existing_account_should_return_OK() throws Exception { AccountID id = new AccountID(12345L); ledger = ledger.putAccount(new Account(id)); assertEquals(AccountBotService.State.OK, service.getState(id.toString())); }
@Test public void getState_for_processing_account() throws Exception { ISigner sender = new TestSigner("00112233445566778899aabbccddeeff00112233445566778899aabbccddeeff"); ISigner newAccount = new TestSigner("112233445566778899aabbccddeeff00112233445566778899aabbccddeeff00"); Transaction tx = RegistrationBuilder.createNew(newAccount.getPublicKey()).build(new BlockID(0L), sender); backlog.put(tx); AccountID id = new AccountID(newAccount.getPublicKey()); assertEquals(AccountBotService.State.Processing, service.getState(id.toString())); }
@Test public void getState_for_notexisting_account() throws Exception { assertEquals(AccountBotService.State.NotFound, service.getState(new AccountID(12345L).toString())); } |
AccountBotService { public EONBalance getBalance(String id) throws RemotePeerException, IOException { Account account = getAccount(id); EONBalance balance = new EONBalance(); if (account == null) { balance.state = State.Unauthorized; } else { balance.state = State.OK; BalanceProperty b = AccountProperties.getBalance(account); balance.amount = b.getValue(); ColoredBalanceProperty coloredBalance = AccountProperties.getColoredBalance(account); if (coloredBalance != null) { Map<String, Long> cMap = new HashMap<>(); for (ColoredCoinID coinID : coloredBalance) { cMap.put(coinID.toString(), coloredBalance.getBalance(coinID)); } if (!cMap.isEmpty()) { balance.coloredCoins = cMap; } } } return balance; } AccountBotService(IBacklog backlog, LedgerProvider ledgerProvider, IBlockchainProvider blockchain); State getState(String id); Info getInformation(String id); EONBalance getBalance(String id); } | @Test public void getBalance_for_existing_account() throws Exception { AccountID id = new AccountID(12345L); Account account = new Account(id); account = AccountProperties.setProperty(account, new BalanceProperty(100L)); ledger = ledger.putAccount(account); AccountBotService.EONBalance balance = service.getBalance(id.toString()); assertEquals(AccountBotService.State.OK, balance.state); assertEquals(100L, balance.amount); assertNull(balance.coloredCoins); }
@Test public void getBalance_for_notexisting_account() throws Exception { AccountBotService.EONBalance balance = service.getBalance(new AccountID(12345L).toString()); assertEquals(AccountBotService.State.Unauthorized, balance.state); assertEquals(0, balance.amount); assertNull(balance.coloredCoins); }
@Test public void getBalance_for_existing_account_with_colored_coins() throws Exception { AccountID id = new AccountID(12345L); Account account = new Account(id); account = AccountProperties.setProperty(account, new BalanceProperty(100L)); ColoredBalanceProperty coloredBalance = new ColoredBalanceProperty(); coloredBalance.setBalance(100L, new ColoredCoinID(1L)); coloredBalance.setBalance(200L, new ColoredCoinID(2L)); account = AccountProperties.setProperty(account, coloredBalance); ledger = ledger.putAccount(account); AccountBotService.EONBalance balance = service.getBalance(id.toString()); assertEquals(AccountBotService.State.OK, balance.state); assertEquals(100L, balance.amount); assertNotNull(balance.coloredCoins); assertTrue(balance.coloredCoins.size() == 2); assertEquals(balance.coloredCoins.get(new ColoredCoinID(1L).toString()), Long.valueOf(100L)); assertEquals(balance.coloredCoins.get(new ColoredCoinID(2L).toString()), Long.valueOf(200L)); } |
AccountBotService { public Info getInformation(String id) throws RemotePeerException, IOException { Account account = getAccount(id); Info info = new Info(); if (account == null) { info.state = State.Unauthorized; } else { info.state = State.OK; info.publicKey = Format.convert(AccountProperties.getRegistration(account).getPublicKey()); ValidationModeProperty validationMode = AccountProperties.getValidationMode(account); if (validationMode.getTimestamp() == -1) { info.signType = SignType.Normal; } else { Quorum quorum = null; VotingRights rights = null; HashMap<String, Integer> delegates = new HashMap<>(); for (Map.Entry<AccountID, Integer> e : validationMode.delegatesEntrySet()) { delegates.put(e.getKey().toString(), e.getValue()); } if (!delegates.isEmpty()) { rights = new VotingRights(); rights.delegates = delegates; } HashMap<Integer, Integer> types = new HashMap<>(); for (Map.Entry<Integer, Integer> e : validationMode.quorumsEntrySet()) { types.put(e.getKey(), e.getValue()); } if (validationMode.getBaseQuorum() != ValidationModeProperty.MAX_QUORUM || !types.isEmpty()) { quorum = new Quorum(); quorum.quorum = validationMode.getBaseQuorum(); if (!types.isEmpty()) { quorum.quorumByTypes = types; } } if (validationMode.isNormal()) { info.signType = SignType.Normal; } else if (validationMode.isPublic()) { if (rights.delegates == null) { throw new IllegalStateException(id); } info.signType = SignType.Public; info.seed = validationMode.getSeed(); } else if (validationMode.isMultiFactor()) { rights.weight = validationMode.getBaseWeight(); info.signType = SignType.MFA; } info.votingRights = rights; info.quorum = quorum; } VotePollsProperty voter = AccountProperties.getVoter(account); if (voter.getTimestamp() != -1) { HashMap<String, Integer> vMap = new HashMap<>(); for (Map.Entry<AccountID, Integer> entry : voter.pollsEntrySet()) { vMap.put(entry.getKey().toString(), entry.getValue()); } info.voter = vMap; } ColoredCoinProperty coloredCoin = AccountProperties.getColoredCoin(account); if (coloredCoin.isIssued()) { info.coloredCoin = new ColoredCoinID(account.getID()).toString(); } GeneratingBalanceProperty generatingBalance = AccountProperties.getDeposit(account); info.deposit = generatingBalance.getValue(); BalanceProperty balance = AccountProperties.getBalance(account); info.amount = balance.getValue(); } return info; } AccountBotService(IBacklog backlog, LedgerProvider ledgerProvider, IBlockchainProvider blockchain); State getState(String id); Info getInformation(String id); EONBalance getBalance(String id); } | @Test public void getInformation_for_existing_account() throws Exception { ISigner signer = new TestSigner("00112233445566778899aabbccddeeff00112233445566778899aabbccddeeff"); AccountID id = new AccountID(signer.getPublicKey()); Account account = new Account(id); account = AccountProperties.setProperty(account, new RegistrationDataProperty(signer.getPublicKey())); ValidationModeProperty validationMode = new ValidationModeProperty(); validationMode.setBaseWeight(100); account = AccountProperties.setProperty(account, validationMode); account = AccountProperties.setProperty(account, new GeneratingBalanceProperty(1000L, 0)); ledger = ledger.putAccount(account); AccountBotService.Info info = service.getInformation(id.toString()); assertEquals(AccountBotService.State.OK, info.state); Assert.assertEquals(Format.convert(signer.getPublicKey()), info.publicKey); assertTrue(1000L == info.deposit); assertNull(info.votingRights); assertNull(info.quorum); assertEquals(AccountBotService.SignType.Normal, info.signType); assertNull(info.coloredCoin); }
@Test public void getInformation_for_existing_colored_coin() throws Exception { ISigner signer = new TestSigner("00112233445566778899aabbccddeeff00112233445566778899aabbccddeeff"); AccountID id = new AccountID(signer.getPublicKey()); Account account = new Account(id); account = AccountProperties.setProperty(account, new RegistrationDataProperty(signer.getPublicKey())); ValidationModeProperty validationMode = new ValidationModeProperty(); validationMode.setBaseWeight(100); account = AccountProperties.setProperty(account, validationMode); account = AccountProperties.setProperty(account, new GeneratingBalanceProperty(1000L, 0)); ColoredCoinProperty coloredCoin = new ColoredCoinProperty(); coloredCoin.setEmitMode(ColoredCoinEmitMode.PRESET); coloredCoin.setAttributes(new ColoredCoinProperty.Attributes(2, 0)); coloredCoin.setMoneySupply(50000L); account = AccountProperties.setProperty(account, coloredCoin); ledger = ledger.putAccount(account); AccountBotService.Info info = service.getInformation(id.toString()); assertEquals(AccountBotService.State.OK, info.state); assertEquals(Format.convert(signer.getPublicKey()), info.publicKey); assertTrue(1000L == info.deposit); assertNull(info.votingRights); assertNull(info.quorum); assertEquals(AccountBotService.SignType.Normal, info.signType); Assert.assertEquals(info.coloredCoin, new ColoredCoinID(id).toString()); }
@Test public void getInformation_for_public_account() throws Exception { String seed = "00112233445566778899aabbccddeeff00112233445566778899aabbccddeeff"; ISigner signer = new TestSigner(seed); AccountID id = new AccountID(signer.getPublicKey()); Account account = new Account(id); account = AccountProperties.setProperty(account, new RegistrationDataProperty(signer.getPublicKey())); ValidationModeProperty validationMode = new ValidationModeProperty(); validationMode.setPublicMode(seed); validationMode.setWeightForAccount(new AccountID(1L), 70); validationMode.setWeightForAccount(new AccountID(2L), 50); validationMode.setTimestamp(0); account = AccountProperties.setProperty(account, validationMode); ledger = ledger.putAccount(account); AccountBotService.Info info = service.getInformation(id.toString()); assertEquals(AccountBotService.State.OK, info.state); assertEquals(AccountBotService.SignType.Public, info.signType); assertEquals(seed, info.seed); assertEquals(Format.convert(signer.getPublicKey()), info.publicKey); assertEquals(0L, info.deposit); assertEquals(0L, info.amount); assertNull(info.quorum); assertNull(info.votingRights.weight); assertTrue(info.votingRights.delegates.get(new AccountID(1L).toString()) == 70); assertTrue(info.votingRights.delegates.get(new AccountID(2L).toString()) == 50); assertTrue(info.votingRights.delegates.size() == 2); assertNull(info.coloredCoin); }
@Test public void getInformation_for_mfa_account() throws Exception { ISigner signer = new TestSigner("00112233445566778899aabbccddeeff00112233445566778899aabbccddeeff"); AccountID id = new AccountID(signer.getPublicKey()); Account account = new Account(id); account = AccountProperties.setProperty(account, new RegistrationDataProperty(signer.getPublicKey())); ValidationModeProperty validationMode = new ValidationModeProperty(); validationMode.setBaseWeight(70); validationMode.setWeightForAccount(new AccountID(1L), 40); validationMode.setQuorum(40); validationMode.setQuorum(TransactionType.Payment, 90); validationMode.setTimestamp(0); account = AccountProperties.setProperty(account, validationMode); ledger = ledger.putAccount(account); AccountBotService.Info info = service.getInformation(id.toString()); assertEquals(AccountBotService.State.OK, info.state); assertEquals(AccountBotService.SignType.MFA, info.signType); assertEquals(Format.convert(signer.getPublicKey()), info.publicKey); assertEquals(0L, info.deposit); assertEquals(0L, info.amount); assertTrue(info.quorum.quorum == 40); assertTrue(info.quorum.quorumByTypes.get(TransactionType.Payment) == 90); assertTrue(info.quorum.quorumByTypes.size() == 1); assertTrue(info.votingRights.weight == 70); assertTrue(info.votingRights.delegates.get(new AccountID(1L).toString()) == 40); assertTrue(info.votingRights.delegates.size() == 1); assertNull(info.coloredCoin); }
@Test public void getInformation_for_notexisting_account() throws Exception { AccountBotService.Info info = service.getInformation(new AccountID(12345L).toString()); assertEquals(AccountBotService.State.Unauthorized, info.state); assertNull(info.publicKey); assertEquals(0L, info.deposit); assertEquals(0L, info.amount); assertNull(info.signType); assertNull(info.quorum); assertNull(info.votingRights); assertNull(info.coloredCoin); } |
SyncMetadataService extends BaseService implements IMetadataService { @Override public String[] getWellKnownNodes() throws RemotePeerException, IOException { Collection<String> wellKnownPeers = new ArrayList<>(); String[] addresses = context.getPeers().getPeersList(); for (String address : addresses) { PeerInfo peer = context.getPeers().getPeerByAddress(address); if (peer != null) { if (peer.getState() == PeerInfo.STATE_CONNECTED && peer.getBlacklistingTime() == 0 && peer.getAddress() != null && peer.getAddress().length() > 0 && !peer.isInner()) { wellKnownPeers.add(peer.getAddress()); } } } return wellKnownPeers.toArray(new String[0]); } SyncMetadataService(IFork fork, ExecutionContext context, IBlockchainProvider blockchain, Storage storage); @Override SalientAttributes getAttributes(); @Override String[] getWellKnownNodes(); @Override boolean addPeer(long peerID, String address); } | @Test public void getWellKnownNodes_should_return_array() throws Exception { SyncMetadataService sms = new SyncMetadataService(fork, ctx, blockchain, storage); String[] wkn = sms.getWellKnownNodes(); assertEquals(2, wkn.length); assertEquals(peer1Addr, wkn[0]); assertEquals(peer2Addr, wkn[1]); }
@Test public void getWellKnownNodes_shouldnt_return_notconnected_peers() throws Exception { when(peer1.getState()).thenReturn(PeerInfo.STATE_AMBIGUOUS); when(peer2.getState()).thenReturn(PeerInfo.STATE_DISCONNECTED); SyncMetadataService sms = new SyncMetadataService(fork, ctx, blockchain, storage); String[] wkn = sms.getWellKnownNodes(); assertEquals(0, wkn.length); }
@Test public void getWellKnownNodes_shouldnt_return_blacklist_peers() throws Exception { when(peer1.getBlacklistingTime()).thenReturn(60L); when(peer2.getBlacklistingTime()).thenReturn(-60L); SyncMetadataService sms = new SyncMetadataService(fork, ctx, blockchain, storage); String[] wkn = sms.getWellKnownNodes(); assertEquals(0, wkn.length); }
@Test public void getWellKnownNodes_shouldnt_return_noaddress_peers() throws Exception { when(peer1.getAddress()).thenReturn(null); when(peer2.getAddress()).thenReturn(""); SyncMetadataService sms = new SyncMetadataService(fork, ctx, blockchain, storage); String[] wkn = sms.getWellKnownNodes(); assertEquals(0, wkn.length); }
@Test public void getWellKnownNodes_shouldnt_return_inner_peers() throws Exception { when(peer1.isInner()).thenReturn(true); when(peer2.isInner()).thenReturn(true); SyncMetadataService sms = new SyncMetadataService(fork, ctx, blockchain, storage); String[] wkn = sms.getWellKnownNodes(); assertEquals(0, wkn.length); } |
ColoredCoinBotService { public Info getInfo(String id) throws RemotePeerException, IOException { Account account = getColoredAccount(id); Info info = new Info(); info.state = State.Unauthorized; if (account == null) { return info; } ColoredCoinProperty coloredCoin = AccountProperties.getColoredCoin(account); if (!coloredCoin.isIssued()) { return info; } info.state = State.OK; info.decimal = coloredCoin.getAttributes().decimalPoint; info.timestamp = coloredCoin.getAttributes().timestamp; info.supply = coloredCoin.getMoneySupply(); info.auto = (coloredCoin.getEmitMode() == ColoredCoinEmitMode.AUTO); return info; } ColoredCoinBotService(LedgerProvider ledgerProvider, IBlockchainProvider blockchain); Info getInfo(String id); } | @Test public void getInformation_OK() throws Exception { AccountID id = new AccountID(1L); targetAccount = new Account(id); ColoredCoinProperty coloredCoin = new ColoredCoinProperty(); coloredCoin.setEmitMode(ColoredCoinEmitMode.PRESET); coloredCoin.setMoneySupply(10000L); coloredCoin.setAttributes(new ColoredCoinProperty.Attributes(8, 1)); targetAccount = AccountProperties.setProperty(targetAccount, coloredCoin); ColoredCoinBotService.Info info = service.getInfo(id.toString()); assertEquals(info.state, ColoredCoinBotService.State.OK); assertEquals(info.decimal, Integer.valueOf(8)); assertEquals(info.supply, Long.valueOf(10000L)); assertEquals(info.timestamp, Integer.valueOf(1)); assertFalse(info.auto); }
@Test public void getInformation_not_found() throws Exception { AccountID id = new AccountID(1L); ColoredCoinBotService.Info info = service.getInfo(id.toString()); assertEquals(info.state, ColoredCoinBotService.State.Unauthorized); assertNull(info.decimal); assertNull(info.supply); }
@Test public void getInformation_illegal_state() throws Exception { AccountID id = new AccountID(1L); targetAccount = new Account(id); ColoredCoinBotService.Info info = service.getInfo(id.toString()); assertEquals(info.state, ColoredCoinBotService.State.Unauthorized); assertNull(info.decimal); assertNull(info.supply); } |
Fork implements IFork { @Override public boolean isCome(int timestamp) { return items.getFirst().isCome(timestamp); } Fork(BlockID genesisBlockID, ForkItem[] items, String beginAll); Fork(BlockID genesisBlockID, ForkItem[] items); Fork(BlockID genesisBlockID, ForkItem[] items, long beginAll); @Override BlockID getGenesisBlockID(); @Override boolean isPassed(int timestamp); @Override boolean isCome(int timestamp); @Override int getNumber(int timestamp); @Override Set<Integer> getTransactionTypes(int timestamp); @Override int getBlockVersion(int timestamp); @Override ILedger convert(ILedger ledger, int timestamp); @Override ITransactionParser getParser(int timestamp); long getMinDepositSize(); void setMinDepositSize(long minDepositSize); } | @Test public void isCome() { assertFalse("Before fork", forkState.isCome(50)); assertFalse("Fork started", forkState.isCome(100)); assertTrue("On fork", forkState.isCome(150)); assertTrue("Fork ended", forkState.isCome(200)); assertTrue("After fork", forkState.isCome(250)); } |
Fork implements IFork { @Override public boolean isPassed(int timestamp) { return items.getFirst().isPassed(timestamp); } Fork(BlockID genesisBlockID, ForkItem[] items, String beginAll); Fork(BlockID genesisBlockID, ForkItem[] items); Fork(BlockID genesisBlockID, ForkItem[] items, long beginAll); @Override BlockID getGenesisBlockID(); @Override boolean isPassed(int timestamp); @Override boolean isCome(int timestamp); @Override int getNumber(int timestamp); @Override Set<Integer> getTransactionTypes(int timestamp); @Override int getBlockVersion(int timestamp); @Override ILedger convert(ILedger ledger, int timestamp); @Override ITransactionParser getParser(int timestamp); long getMinDepositSize(); void setMinDepositSize(long minDepositSize); } | @Test public void isPassed() { assertFalse("Before fork", forkState.isPassed(50)); assertFalse("Fork started", forkState.isPassed(100)); assertFalse("On fork", forkState.isPassed(150)); assertFalse("Fork ended", forkState.isPassed(200)); assertTrue("After fork", forkState.isPassed(250)); } |
Fork implements IFork { @Override public int getNumber(int timestamp) { Item item = getItem(timestamp); return (item == null) ? -1 : item.getNumber(); } Fork(BlockID genesisBlockID, ForkItem[] items, String beginAll); Fork(BlockID genesisBlockID, ForkItem[] items); Fork(BlockID genesisBlockID, ForkItem[] items, long beginAll); @Override BlockID getGenesisBlockID(); @Override boolean isPassed(int timestamp); @Override boolean isCome(int timestamp); @Override int getNumber(int timestamp); @Override Set<Integer> getTransactionTypes(int timestamp); @Override int getBlockVersion(int timestamp); @Override ILedger convert(ILedger ledger, int timestamp); @Override ITransactionParser getParser(int timestamp); long getMinDepositSize(); void setMinDepositSize(long minDepositSize); } | @Test public void getNumber() { assertEquals("Before fork", 1, forkState.getNumber(50)); assertEquals("Fork started", 1, forkState.getNumber(100)); assertEquals("On fork", 2, forkState.getNumber(150)); assertEquals("Fork ended", 2, forkState.getNumber(200)); assertEquals("After fork", 2, forkState.getNumber(250)); } |
PeerStarter { public static PeerStarter create(Config config) throws SQLException, IOException, ClassNotFoundException { PeerStarter peerStarter = new PeerStarter(config); peerStarter.initialize(); return peerStarter; } PeerStarter(Config config); static PeerStarter create(Config config); void initialize(); ExecutionContext getExecutionContext(); void setExecutionContext(ExecutionContext executionContext); Storage getStorage(); ITimeProvider getTimeProvider(); void setTimeProvider(ITimeProvider timeProvider); Backlog getBacklog(); void setBacklog(Backlog backlog); BlockchainProvider getBlockchainProvider(); void setBlockchainProvider(BlockchainProvider blockchainProvider); Fork getFork(); void setFork(Fork fork); JrpcServiceProxyFactory getProxyFactory(); void setProxyFactory(JrpcServiceProxyFactory proxyFactory); ISigner getSigner(); void setSigner(ISigner signer); BlockGenerator getBlockGenerator(); void setBlockGenerator(BlockGenerator blockGenerator); BacklogCleaner getCleaner(); void setCleaner(BacklogCleaner cleaner); CryptoProvider getSignatureVerifier(); void setSignatureVerifier(CryptoProvider cryptoProvider); LedgerProvider getLedgerProvider(); void setLedgerProvider(LedgerProvider ledgerProvider); BlockchainEventManager getBlockchainEventManager(); void setBlockchainEventManager(BlockchainEventManager blockchainEventManager); BacklogEventManager getBacklogEventManager(); void setBacklogEventManager(BacklogEventManager backlogEventManager); Config getConfig(); TransactionValidatorFabricImpl getTransactionValidatorFabric(); void setTransactionValidatorFabric(TransactionValidatorFabricImpl transactionValidatorFabric); ITransactionEstimator getEstimator(); void setEstimator(ITransactionEstimator estimator); IAccountHelper getAccountHelper(); void setAccountHelper(IAccountHelper accountHelper); ITransactionMapper getTransactionMapper(); void setTransactionMapper(ITransactionMapper transactionMapper); } | @Test public void testSyncSnapshotDisable() throws Exception { String connectURI = "jdbc:sqlite:file:memInitializerJsonTest2?mode=memory&cache=shared"; try { PeerStarter ps1 = create(connectURI, genesisJson, genesisForks, true); PeerStarter ps2 = create(connectURI, genesisJson, genesisForks, false); assertTrue("Snapshot mode switched", true); } catch (Exception ex) { assertTrue("Snapshot mode cannot be switched", false); } }
@Test public void testSyncSnapshotEnable() throws Exception { String connectURI = "jdbc:sqlite:file:memInitializerJsonTest3?mode=memory&cache=shared"; try { PeerStarter ps1 = create(connectURI, genesisJson, genesisForks, false); PeerStarter ps2 = create(connectURI, genesisJson, genesisForks, true); assertTrue("Snapshot mode switched", false); } catch (Exception ex) { assertTrue("Snapshot mode cannot be switched", true); } } |
BencodeFormatter implements IFormatter { @Override public byte[] getBytes(Map<String, Object> map) { Objects.requireNonNull(map); try { try (ByteArrayOutputStream outStream = new ByteArrayOutputStream()) { try (BencodeOutputStream bencodeStream = new BencodeOutputStream(outStream, Charset.forName("UTF-8"))) { bencodeStream.writeDictionary(map); } String str = outStream.toString("UTF-8"); return str.toUpperCase(locale).getBytes(); } } catch (IOException e) { throw new RuntimeException(e); } } BencodeFormatter(); BencodeFormatter(Locale locale); @Override byte[] getBytes(Map<String, Object> map); } | @Test public void test_reference() { tx.setReference(new TransactionID(132L)); byte[] bytes = formatter.getBytes(mapper.convert(tx)); Assert.assertEquals( "D10:ATTACHMENTDE8:DEADLINEI3600E3:FEEI10E7:NETWORK23:EON-B-22222-22222-2222J9:REFERENCE23:EON-T-66222-22222-2224L6:SENDER21:EON-65222-22222-222LK9:TIMESTAMPI1E4:TYPEI100E7:VERSIONI1EE", new String(bytes)); }
@Test public void test_attachment() { tx.setData(new HashMap<String, Object>() { { put("int", 123); put("str", "data"); } }); byte[] bytes = formatter.getBytes(mapper.convert(tx)); Assert.assertEquals( "D10:ATTACHMENTD3:INTI123E3:STR4:DATAE8:DEADLINEI3600E3:FEEI10E7:NETWORK23:EON-B-22222-22222-2222J6:SENDER21:EON-65222-22222-222LK9:TIMESTAMPI1E4:TYPEI100E7:VERSIONI1EE", new String(bytes)); }
@Test public void test_note() { tx.setNote("test"); byte[] bytes = formatter.getBytes(mapper.convert(tx)); Assert.assertEquals( "D10:ATTACHMENTDE8:DEADLINEI3600E3:FEEI10E7:NETWORK23:EON-B-22222-22222-2222J4:NOTE4:TEST6:SENDER21:EON-65222-22222-222LK9:TIMESTAMPI1E4:TYPEI100E7:VERSIONI1EE", new String(bytes)); }
@Test public void test_nested() { Transaction tx2 = new Transaction(); tx2.setVersion(1); tx2.setFee(10); tx2.setTimestamp(1); tx2.setDeadline(3600); tx2.setType(100); tx2.setSenderID(new AccountID(100L)); tx2.setSignature(new byte[64]); tx.setNestedTransactions(new HashMap<String, Transaction>() { { put(tx2.getID().toString(), tx2); } }); byte[] bytes = formatter.getBytes(mapper.convert(tx)); Assert.assertEquals( "D10:ATTACHMENTDE5:BILLSD23:EON-T-32222-2NVPE-L3ZGVD10:ATTACHMENTDE8:DEADLINEI3600E3:FEEI10E7:NETWORK23:EON-B-22222-22222-2222J6:SENDER21:EON-65222-22222-222LK9:TIMESTAMPI1E4:TYPEI100E7:VERSIONI1EEE8:DEADLINEI3600E3:FEEI10E7:NETWORK23:EON-B-22222-22222-2222J6:SENDER21:EON-65222-22222-222LK9:TIMESTAMPI1E4:TYPEI100E7:VERSIONI1EE", new String(bytes)); }
@Test public void test_payer() { tx.setPayer(new AccountID(123L)); byte[] bytes = formatter.getBytes(mapper.convert(tx)); Assert.assertEquals( "D10:ATTACHMENTDE8:DEADLINEI3600E3:FEEI10E7:NETWORK23:EON-B-22222-22222-2222J5:PAYER21:EON-V5222-22222-22JXK6:SENDER21:EON-65222-22222-222LK9:TIMESTAMPI1E4:TYPEI100E7:VERSIONI1EE", new String(bytes)); } |
DTOConverter { public static DbBlock convert(Block block) { DbBlock dbBlock = new DbBlock(); dbBlock.setId(block.getID().getValue()); dbBlock.setVersion(block.getVersion()); dbBlock.setTimestamp(block.getTimestamp()); dbBlock.setPreviousBlock(block.getPreviousBlock().getValue()); dbBlock.setSenderID(block.getSenderID().getValue()); dbBlock.setSignature(Format.convert(block.getSignature())); dbBlock.setHeight(block.getHeight()); dbBlock.setGenerationSignature(Format.convert(block.getGenerationSignature())); dbBlock.setCumulativeDifficulty(block.getCumulativeDifficulty().toString()); dbBlock.setSnapshot(block.getSnapshot()); dbBlock.setTag(0); return dbBlock; } static DbBlock convert(Block block); static Block convert(DbBlock dbBlock, final Storage storage); static DbTransaction convert(Transaction transaction); static Transaction convert(DbTransaction dbTransaction); } | @Test public void transaction_base() throws Exception { Transaction a = Builder.newTransaction(timestamp).attach(null).build(networkID, signer); Transaction b = DTOConverter.convert(DTOConverter.convert(a)); assetEquals(a, b); }
@Test public void transaction_contains_reference() throws Exception { Transaction a = Builder.newTransaction(timestamp).attach(null).refBy(referencedTx).build(networkID, signer); Transaction b = DTOConverter.convert(DTOConverter.convert(a)); assetEquals(a, b); }
@Test public void transaction_contains_nested_transaction() throws Exception { Transaction a = Builder.newTransaction(timestamp) .attach(null) .addNested(Builder.newTransaction(timestamp).build(networkID, signer1)) .addNested(Builder.newTransaction(timestamp).build(networkID, signer2)) .build(networkID, signer); Transaction b = DTOConverter.convert(DTOConverter.convert(a)); assetEquals(a, b); }
@Test public void transaction_contains_confirmations() throws Exception { Transaction a = Builder.newTransaction(timestamp) .attach(null) .build(networkID, signer, new ISigner[] {signer1, signer2}); Transaction b = DTOConverter.convert(DTOConverter.convert(a)); assetEquals(a, b); }
@Test public void transaction_contains_payer() throws Exception { Transaction a = Builder.newTransaction(timestamp) .payedBy(new AccountID(signer2.getPublicKey())) .build(networkID, signer, new ISigner[] {signer1, signer2}); Transaction b = DTOConverter.convert(DTOConverter.convert(a)); assetEquals(a, b); }
@Test public void transaction_contains_nested_transaction_payed() throws Exception { Transaction a = Builder.newTransaction(timestamp) .attach(null) .addNested(Builder.newTransaction(timestamp) .payedBy(new AccountID(signer2.getPublicKey())) .build(networkID, signer1)) .addNested(Builder.newTransaction(timestamp) .payedBy(new AccountID(signer1.getPublicKey())) .build(networkID, signer2)) .build(networkID, signer); Transaction b = DTOConverter.convert(DTOConverter.convert(a)); assetEquals(a, b); }
@Test public void db_transaction_format() throws Exception { Transaction tx1 = Builder.newTransaction(timestamp).build(networkID, signer1); Transaction tx2 = Builder.newTransaction(timestamp).build(networkID, signer2); Transaction tx = Builder.newTransaction(timestamp) .refBy(referencedTx) .attach(attachment) .note("note") .addNested(tx1) .addNested(tx2) .payedBy(new AccountID(signer2.getPublicKey())) .build(networkID, signer, new ISigner[] {signer1, signer2}); DbTransaction dbTx = DTOConverter.convert(tx); Assert.assertEquals(dbTx.getVersion(), tx.getVersion()); Assert.assertEquals(dbTx.getType(), tx.getType()); Assert.assertEquals(dbTx.getTimestamp(), timestamp); Assert.assertEquals(dbTx.getDeadline(), 3600); Assert.assertEquals(dbTx.getFee(), 10L); Assert.assertEquals(dbTx.getNote(), "note"); Assert.assertEquals(dbTx.getReference(), referencedTx.getValue()); Assert.assertEquals(dbTx.getSenderID(), new AccountID(signer.getPublicKey()).getValue()); Assert.assertEquals(dbTx.getSignature(), Format.convert(tx.getSignature())); Assert.assertEquals(dbTx.getAttachment(), new String(bencode.encode(attachment))); Assert.assertEquals(dbTx.getConfirmations(), new String(bencode.encode(tx.getConfirmations()))); Assert.assertEquals(dbTx.getPayerID(), tx.getPayer().getValue()); Map<String, Object> map = new HashMap<>(); map.put(tx1.getID().toString(), StorageTransactionMapper.convert(tx1)); map.put(tx2.getID().toString(), StorageTransactionMapper.convert(tx2)); Assert.assertEquals(dbTx.getNestedTransactions(), new String(bencode.encode(map))); } |
VersionValidationRule implements IValidationRule { @Override public ValidationResult validate(Transaction tx, ILedger ledger) { if (tx.getVersion() != 1) { return ValidationResult.error("Version is not supported."); } return ValidationResult.success; } @Override ValidationResult validate(Transaction tx, ILedger ledger); } | @Test public void success() throws Exception { Transaction tx = Builder.newTransaction(timeProvider).build(networkID, sender); validate(tx); }
@Test public void unknown_version() throws Exception { expectedException.expect(ValidateException.class); expectedException.expectMessage("Version is not supported."); Transaction tx = Builder.newTransaction(timeProvider).version(12345).build(networkID, sender); validate(tx); } |
FeePerByteValidationRule implements IValidationRule { @Override public ValidationResult validate(Transaction tx, ILedger ledger) { int length = tx.getLength(); long fee = tx.getFee(); if (fee < length * Constant.TRANSACTION_MIN_FEE_PER_BYTE) { return ValidationResult.error("Invalid fee."); } return ValidationResult.success; } @Override ValidationResult validate(Transaction tx, ILedger ledger); } | @Test public void success() throws Exception { Transaction tx = Builder.newTransaction(timeProvider).build(networkID, sender); validate(tx); }
@Test public void fee_zero() throws Exception { expectedException.expect(ValidateException.class); expectedException.expectMessage("Invalid fee."); Transaction tx = Builder.newTransaction(timeProvider).forFee(0L).build(networkID, sender); tx.setLength(1); validate(tx); }
@Test public void too_small_fee() throws Exception { expectedException.expect(ValidateException.class); expectedException.expectMessage("Invalid fee."); Transaction tx = Builder.newTransaction(timeProvider).forFee(10L).build(networkID, sender); tx.setLength(1024 + 1); validate(tx); } |
FutureTimestampValidationRule implements IValidationRule { @Override public ValidationResult validate(Transaction tx, ILedger ledger) { if (tx.isFuture(timeProvider.get())) { return ValidationResult.error(new LifecycleException()); } return ValidationResult.success; } FutureTimestampValidationRule(ITimeProvider timeProvider); FutureTimestampValidationRule(int timestamp); @Override ValidationResult validate(Transaction tx, ILedger ledger); } | @Test public void success() throws Exception { Transaction tx = Builder.newTransaction(timeProvider).build(networkID, sender); validate(tx); }
@Test public void future_timestamp() throws Exception { expectedException.expect(LifecycleException.class); Transaction tx = Builder.newTransaction(timeProvider).build(networkID, sender); int timestamp = tx.getTimestamp() - 1; Mockito.when(timeProvider.get()).thenReturn(timestamp); validate(tx); } |
TypeValidationRule implements IValidationRule { @Override public ValidationResult validate(Transaction tx, ILedger ledger) { if (allowedTypes.contains(tx.getType())) { return ValidationResult.success; } return ValidationResult.error("Invalid transaction type. Type :" + tx.getType()); } TypeValidationRule(Set<Integer> allowedTypes); @Override ValidationResult validate(Transaction tx, ILedger ledger); } | @Test public void success() throws Exception { Transaction tx = Builder.newTransaction(timeProvider).type(10).build(networkID, sender); validate(tx); }
@Test public void unknown_type() throws Exception { int type = 12345; expectedException.expect(ValidateException.class); expectedException.expectMessage("Invalid transaction type. Type :" + type); Transaction tx = Builder.newTransaction(timeProvider).type(type).build(networkID, sender); validate(tx); } |
ConfirmationsSetValidationRule implements IValidationRule { @Override public ValidationResult validate(Transaction tx, ILedger ledger) { Map<String, Object> confirmations = tx.getConfirmations(); if (confirmations == null) { return ValidationResult.success; } Account sender = ledger.getAccount(tx.getSenderID()); if (sender == null) { return ValidationResult.error("Unknown sender."); } Set<AccountID> accounts = accountHelper.getConfirmingAccounts(sender, timeProvider.get()); if (accounts == null) { accounts = new HashSet<>(); } else { accounts = new HashSet<>(accounts); } if (allowPayer && tx.getPayer() != null) { accounts.add(tx.getPayer()); } for (String id : confirmations.keySet()) { AccountID acc; try { acc = new AccountID(id); } catch (Exception e) { return ValidationResult.error("Invalid format."); } if (!accounts.contains(acc)) { return ValidationResult.error("Account '" + acc.toString() + "' can not sign transaction."); } } return ValidationResult.success; } ConfirmationsSetValidationRule(ITimeProvider timeProvider, IAccountHelper accountHelper); @Override ValidationResult validate(Transaction tx, ILedger ledger); boolean isAllowPayer(); void setAllowPayer(boolean allowPayer); } | @Test public void unset_mfa() throws Exception { expectedException.expect(ValidateException.class); expectedException.expectMessage("can not sign transaction."); Transaction tx = Builder.newTransaction(timeProvider).build(networkID, delegate1, new ISigner[] { sender, delegate2 }); validate(tx); }
@Test public void unspecified_delegate() throws Exception { ISigner unknown = new Signer("33445566778899aabbccddeeff00112233445566778899aabbccddeeff001122"); AccountID id = new AccountID(unknown.getPublicKey()); expectedException.expect(ValidateException.class); expectedException.expectMessage("Account '" + id + "' can not sign transaction."); Transaction tx = Builder.newTransaction(timeProvider).build(networkID, sender, new ISigner[] {unknown}); validate(tx); }
@Test public void mfa_allow_payer() throws Exception { ISigner unknown = new Signer("33445566778899aabbccddeeff00112233445566778899aabbccddeeff001122"); AccountID id = new AccountID(unknown.getPublicKey()); Transaction tx = Builder.newTransaction(timeProvider).payedBy(id).build(networkID, sender, new ISigner[] {unknown}); validate(tx); }
@Test public void unset_mfa_allow_payer() throws Exception { AccountID id = new AccountID(sender.getPublicKey()); Transaction tx = Builder.newTransaction(timeProvider).payedBy(id).build(networkID, delegate1, new ISigner[] { sender }); validate(tx); } |
PayerValidationRule implements IValidationRule { @Override public ValidationResult validate(Transaction tx, ILedger ledger) { if (tx.getPayer() == null) { return ValidationResult.success; } if (tx.getSenderID().equals(tx.getPayer())) { return ValidationResult.error("Invalid payer"); } if (tx.getConfirmations() == null || !tx.getConfirmations().containsKey(tx.getPayer().toString())) { return ValidationResult.error("Payer not confirm"); } return ValidationResult.success; } @Override ValidationResult validate(Transaction tx, ILedger ledger); } | @Test public void payer_success() throws Exception { Transaction tx = Builder.newTransaction(timeProvider) .payedBy(payerAccount) .build(networkID, sender, new ISigner[] {payer}); validate(tx); }
@Test public void no_payer_success() throws Exception { Transaction tx = Builder.newTransaction(timeProvider).build(networkID, sender); validate(tx); }
@Test public void illegal_payer() throws Exception { expectedException.expect(ValidateException.class); expectedException.expectMessage("Invalid payer"); Transaction tx = Builder.newTransaction(timeProvider) .payedBy(new AccountID(sender.getPublicKey())) .build(networkID, sender); validate(tx); }
@Test public void payer_not_confirm() throws Exception { expectedException.expect(ValidateException.class); expectedException.expectMessage("Payer not confirm"); Transaction tx = Builder.newTransaction(timeProvider).payedBy(payerAccount).build(networkID, sender); validate(tx); } |
SignatureValidationRule implements IValidationRule { @Override public ValidationResult validate(Transaction tx, ILedger ledger) { Account sender = ledger.getAccount(tx.getSenderID()); if (sender == null) { return ValidationResult.error("Unknown sender."); } if (!tx.isVerified()) { if (!accountHelper.verifySignature(tx, tx.getSignature(), sender, timeProvider.get())) { return ValidationResult.error(new IllegalSignatureException()); } if (tx.getConfirmations() != null) { for (Map.Entry<String, Object> entry : tx.getConfirmations().entrySet()) { AccountID id; byte[] signature; try { id = new AccountID(entry.getKey()); signature = Format.convert(String.valueOf(entry.getValue())); } catch (Exception e) { return ValidationResult.error("Invalid format."); } if (tx.getSenderID().equals(id)) { return ValidationResult.error("Duplicates sender signature."); } Account account = ledger.getAccount(id); if (account == null) { return ValidationResult.error("Unknown account " + id.toString()); } if (!accountHelper.verifySignature(tx, signature, account, timeProvider.get())) { return ValidationResult.error(new IllegalSignatureException(id.toString())); } } } tx.setVerifiedState(); } return ValidationResult.success; } SignatureValidationRule(ITimeProvider timeProvider, IAccountHelper accountHelper); @Override ValidationResult validate(Transaction tx, ILedger ledger); } | @Test public void success() throws Exception { Transaction tx = Builder.newTransaction(timeProvider).build(networkID, sender); validate(tx); }
@Test public void success_with_confirmations() throws Exception { Transaction tx = Builder.newTransaction(timeProvider).build(networkID, sender, new ISigner[] {delegate1, delegate2}); validate(tx); }
@Test public void sender_unknown() throws Exception { expectedException.expect(ValidateException.class); expectedException.expectMessage("Unknown sender."); Transaction tx = Builder.newTransaction(timeProvider).build(networkID, sender); Mockito.when(ledger.getAccount(tx.getSenderID())).thenReturn(null); validate(tx); }
@Test public void delegate_unknown() throws Exception { AccountID unknownID = new AccountID(delegate2.getPublicKey()); expectedException.expect(ValidateException.class); expectedException.expectMessage("Unknown account " + unknownID.toString()); Mockito.when(ledger.getAccount(ArgumentMatchers.any())).thenAnswer(new Answer<Account>() { @Override public Account answer(InvocationOnMock invocationOnMock) throws Throwable { AccountID id = invocationOnMock.getArgument(0); if (id.equals(unknownID)) { return null; } return (Account) invocationOnMock.callRealMethod(); } }); Transaction tx = Builder.newTransaction(timeProvider).build(networkID, sender, new ISigner[] {delegate1, delegate2}); validate(tx); }
@Test public void illegal_signature() throws Exception { expectedException.expect(ValidateException.class); expectedException.expectMessage("Illegal signature."); Mockito.when(accountHelper.verifySignature(ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers.anyInt())).thenReturn(false); Transaction tx = Builder.newTransaction(timeProvider).build(new BlockID(100500L), sender); validate(tx); }
@Test public void invalid_confirmation() throws Exception { expectedException.expect(ValidateException.class); expectedException.expectMessage("Invalid format."); Transaction tx = Builder.newTransaction(timeProvider).build(networkID, sender); Map<String, Object> map = new HashMap<String, Object>(); map.put("account-id", Format.convert(new byte[64])); tx.setConfirmations(map); validate(tx); }
@Test public void duplicate_confirmation() throws Exception { expectedException.expect(ValidateException.class); expectedException.expectMessage("Duplicates sender signature."); Transaction tx = Builder.newTransaction(timeProvider).build(networkID, sender, new ISigner[] {sender}); validate(tx); }
@Test public void illegal_confirmation() throws Exception { expectedException.expect(IllegalSignatureException.class); Mockito.when(accountHelper.verifySignature(ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers.anyInt())).thenAnswer(new Answer<Boolean>() { @Override public Boolean answer(InvocationOnMock invocationOnMock) throws Throwable { Account account = invocationOnMock.getArgument(2); if (account.getID().equals(new AccountID(delegate2.getPublicKey()))) { return false; } return true; } }); Transaction tx = Builder.newTransaction(timeProvider).build(networkID, sender, new ISigner[] {delegate1, delegate2}); validate(tx); } |
ExpiredTimestampValidationRule implements IValidationRule { @Override public ValidationResult validate(Transaction tx, ILedger ledger) { if (tx.isExpired(timeProvider.get())) { return ValidationResult.error(new LifecycleException()); } return ValidationResult.success; } ExpiredTimestampValidationRule(ITimeProvider timeProvider); ExpiredTimestampValidationRule(int timestamp); @Override ValidationResult validate(Transaction tx, ILedger ledger); } | @Test public void success() throws Exception { Transaction tx = Builder.newTransaction(timeProvider).build(networkID, sender); validate(tx); }
@Test public void expired() throws Exception { expectedException.expect(LifecycleException.class); Transaction tx = Builder.newTransaction(timeProvider).build(networkID, sender); int timestamp = tx.getTimestamp() + tx.getDeadline() + 1; Mockito.when(timeProvider.get()).thenReturn(timestamp); validate(tx); } |
NestedTransactionsValidationRule implements IValidationRule { @Override public ValidationResult validate(Transaction transaction, ILedger ledger) { if (transaction.getNestedTransactions() == null) { return ValidationResult.success; } if (transaction.getNestedTransactions().size() == 0) { return ValidationResult.error("Illegal usage."); } for (Map.Entry<String, Transaction> entry : transaction.getNestedTransactions().entrySet()) { TransactionID id = new TransactionID(entry.getKey()); Transaction nestedTx = entry.getValue(); if (!id.equals(nestedTx.getID())) { return ValidationResult.error("ID does not match transaction."); } if (nestedTx.getTimestamp() > transaction.getTimestamp()) { return ValidationResult.error("Invalid nested transaction. Invalid timestamp."); } AccountID payerID = nestedTx.getPayer(); if (payerID != null && !payerID.equals(transaction.getSenderID())) { return ValidationResult.error("Invalid nested transaction. Invalid payer."); } if (nestedTx.getReference() != null && !transaction.getNestedTransactions().containsKey(nestedTx.getReference().toString())) { return ValidationResult.error("Invalid nested transaction. Invalid reference."); } ValidationResult r = transactionValidator.validate(nestedTx, ledger); if (r.hasError) { return ValidationResult.error("Invalid nested transaction. " + r.cause.getMessage()); } } return ValidationResult.success; } NestedTransactionsValidationRule(Set<Integer> allowedTypes,
ITimeProvider timeProvider,
IAccountHelper accountHelper); @Override ValidationResult validate(Transaction transaction, ILedger ledger); } | @Test public void one_nested() throws Exception { Transaction tx = Builder.newTransaction(timeProvider) .addNested(Builder.newTransaction(timestamp - 1).forFee(0L).build(networkID, signer1)) .build(networkID, signer); validate(tx); }
@Test public void illegal_usage() throws Exception { expectedException.expect(ValidateException.class); expectedException.expectMessage("Illegal usage."); Transaction tx = Builder.newTransaction(timeProvider) .addNested(Builder.newTransaction(timestamp - 1).build(networkID, signer1)) .build(networkID, signer); tx.getNestedTransactions().clear(); validate(tx); }
@Test public void nested_transaction_older_than() throws Exception { expectedException.expect(ValidateException.class); expectedException.expectMessage("Invalid nested transaction. Invalid timestamp."); Transaction tx = Builder.newTransaction(timestamp) .addNested(Builder.newTransaction(timestamp - 1).forFee(0L).build(networkID, signer1)) .addNested(Builder.newTransaction(timestamp + 2).forFee(0L).build(networkID, signer2)) .build(networkID, signer); validate(tx); }
@Test public void nested_transaction_non_zero_fee() throws Exception { expectedException.expect(ValidateException.class); expectedException.expectMessage("Invalid nested transaction. A fee must be equal a zero."); Transaction nestedTx1 = Builder.newTransaction(timestamp - 1).forFee(0L).build(networkID, signer1); Transaction nestedTx2 = Builder.newTransaction(timestamp - 1).refBy(nestedTx1.getID()).build(networkID, signer2); Transaction tx = Builder.newTransaction(timestamp).addNested(nestedTx1).addNested(nestedTx2).build(networkID, signer); validate(tx); }
@Test public void nested_transaction_has_nested_transactions() throws Exception { expectedException.expect(ValidateException.class); expectedException.expectMessage( "Invalid nested transaction. Nested transactions are allowed only at the top level."); Transaction nestedTx1 = Builder.newTransaction(timestamp - 1) .forFee(0L) .addNested(Builder.newTransaction(timestamp).build(networkID, signer)) .build(networkID, signer1); Transaction nestedTx2 = Builder.newTransaction(timestamp - 1).forFee(0L).refBy(nestedTx1.getID()).build(networkID, signer2); Transaction tx = Builder.newTransaction(timestamp).addNested(nestedTx1).addNested(nestedTx2).build(networkID, signer); validate(tx); }
@Test public void success() throws Exception { Transaction nestedTx1 = Builder.newTransaction(timestamp - 1).forFee(0L).build(networkID, signer1); Transaction nestedTx2 = Builder.newTransaction(timestamp - 1).forFee(0L).refBy(nestedTx1.getID()).build(networkID, signer2); Transaction nestedTx3 = Builder.newTransaction(timestamp - 1).forFee(0L).refBy(nestedTx2.getID()).build(networkID, signer1); Transaction tx = Builder.newTransaction(timestamp) .addNested(nestedTx1) .addNested(nestedTx2) .addNested(nestedTx3) .build(networkID, signer); validate(tx); }
@Test public void success_without_nested_transaction() throws Exception { Transaction tx = Builder.newTransaction(timeProvider).build(networkID, signer); validate(tx); }
@Test public void add_payer() throws Exception { Transaction tx = Builder.newTransaction(timeProvider) .addNested(Builder.newTransaction(timestamp - 1) .forFee(0L) .payedBy(new AccountID(signer.getPublicKey())) .build(networkID, signer1)) .addNested(Builder.newTransaction(timestamp).forFee(0L).build(networkID, signer)) .build(networkID, signer); validate(tx); }
@Test public void illegal_payer() throws Exception { expectedException.expect(ValidateException.class); expectedException.expectMessage("Invalid nested transaction. Invalid payer."); Transaction tx = Builder.newTransaction(timeProvider) .addNested(Builder.newTransaction(timestamp - 1) .forFee(0L) .payedBy(new AccountID(signer2.getPublicKey())) .build(networkID, signer1)) .addNested(Builder.newTransaction(timestamp).forFee(0L).build(networkID, signer)) .build(networkID, signer); validate(tx); }
@Test public void illegal_payer_confirmations() throws Exception { AccountID id = new AccountID(signer.getPublicKey()); expectedException.expect(ValidateException.class); expectedException.expectMessage("Invalid nested transaction. Account '" + id + "' can not sign transaction."); Transaction tx = Builder.newTransaction(timeProvider) .addNested(Builder.newTransaction(timestamp - 1) .forFee(0L) .payedBy(id) .build(networkID, signer1, new ISigner[] {signer})) .addNested(Builder.newTransaction(timestamp).forFee(0L).build(networkID, signer)) .build(networkID, signer); validate(tx); }
@Test public void nested_transaction_reference_ok() throws Exception { Transaction nestedTx1 = Builder.newTransaction(timestamp - 1).forFee(0L).build(networkID, signer1); Transaction nestedTx2 = Builder.newTransaction(timestamp - 1).forFee(0L).refBy(nestedTx1.getID()).build(networkID, signer2); Transaction tx = Builder.newTransaction(timestamp).addNested(nestedTx1).addNested(nestedTx2).build(networkID, signer); validate(tx); }
@Test public void nested_transaction_reference_fail() throws Exception { expectedException.expect(ValidateException.class); expectedException.expectMessage("Invalid nested transaction. Invalid reference."); Transaction nestedTx1 = Builder.newTransaction(timestamp - 1).forFee(0L).build(networkID, signer1); Transaction nestedTx2 = Builder.newTransaction(timestamp - 1) .forFee(0L) .refBy(new TransactionID(123L)) .build(networkID, signer2); Transaction tx = Builder.newTransaction(timestamp).addNested(nestedTx1).addNested(nestedTx2).build(networkID, signer); validate(tx); } |
DeadlineValidationRule implements IValidationRule { @Override public ValidationResult validate(Transaction tx, ILedger ledger) { if (tx.getDeadline() < 1 || tx.getDeadline() > Constant.TRANSACTION_MAX_LIFETIME) { return ValidationResult.error(new LifecycleException()); } return ValidationResult.success; } @Override ValidationResult validate(Transaction tx, ILedger ledger); } | @Test public void success() throws Exception { Transaction tx = Builder.newTransaction(timeProvider).build(networkID, sender); validate(tx); }
@Test public void deadline_zero() throws Exception { expectedException.expect(ValidateException.class); expectedException.expectMessage("Invalid timestamp or other params for set the time."); Transaction tx = Builder.newTransaction(timestamp).deadline((short) 0).build(networkID, sender); validate(tx); }
@Test public void deadline_max() throws Exception { expectedException.expect(ValidateException.class); expectedException.expectMessage("Invalid timestamp or other params for set the time."); Transaction tx = Builder.newTransaction(timeProvider) .deadline((short) (Constant.TRANSACTION_MAX_LIFETIME + 1)) .build(networkID, sender); validate(tx); } |
ReferencedTransactionValidationRule implements IValidationRule { @Override public ValidationResult validate(Transaction tx, ILedger ledger) { if (tx.getReference() != null) { return ValidationResult.error("Illegal reference."); } return ValidationResult.success; } @Override ValidationResult validate(Transaction tx, ILedger ledger); } | @Test public void success() throws Exception { Transaction tx = Builder.newTransaction(timeProvider).build(networkID, sender); validate(tx); }
@Test public void success_without_note() throws Exception { expectedException.expect(ValidateException.class); expectedException.expectMessage("Illegal reference."); Transaction tx = Builder.newTransaction(timeProvider).refBy(new TransactionID(12345L)).build(networkID, sender); validate(tx); } |
ConfirmationsValidationRule implements IValidationRule { @Override public ValidationResult validate(Transaction tx, ILedger ledger) { Account sender = ledger.getAccount(tx.getSenderID()); if (sender == null) { return ValidationResult.error("Unknown sender."); } Set<AccountID> accounts = accountHelper.getConfirmingAccounts(sender, timeProvider.get()); if (accounts != null || tx.getConfirmations() != null) { Map<AccountID, Account> set = new HashMap<>(); set.put(tx.getSenderID(), sender); if (tx.getConfirmations() != null) { if (tx.getConfirmations().size() > Constant.TRANSACTION_CONFIRMATIONS_MAX_SIZE) { return ValidationResult.error("Invalid use of the confirmation field."); } for (Map.Entry<String, Object> entry : tx.getConfirmations().entrySet()) { AccountID id; try { id = new AccountID(entry.getKey()); } catch (Exception e) { return ValidationResult.error("Invalid format."); } Account account = ledger.getAccount(id); if (account == null) { return ValidationResult.error("Unknown account " + id.toString()); } set.put(id, account); } } try { if (!accountHelper.validConfirmation(tx, set, timeProvider.get())) { return ValidationResult.error("The quorum is not exist."); } } catch (ValidateException e) { return ValidationResult.error(e); } } return ValidationResult.success; } ConfirmationsValidationRule(ITimeProvider timeProvider, IAccountHelper accountHelper); @Override ValidationResult validate(Transaction tx, ILedger ledger); } | @Test public void unknown_sender() throws Exception { expectedException.expect(ValidateException.class); expectedException.expectMessage("Unknown sender."); Mockito.when(ledger.getAccount(senderAccount.getID())).thenReturn(null); Transaction tx = Builder.newTransaction(timeProvider).build(networkID, sender); validate(tx); }
@Test public void unknown_delegate() throws Exception { expectedException.expect(ValidateException.class); expectedException.expectMessage("Unknown account " + delegate1Account.getID()); Mockito.when(ledger.getAccount(delegate1Account.getID())).thenReturn(null); Transaction tx = Builder.newTransaction(timeProvider).build(networkID, sender, new ISigner[] {delegate1}); validate(tx); }
@Test public void invalid_quorum_without_confirmation() throws Exception { expectedException.expect(ValidateException.class); expectedException.expectMessage("The quorum is not exist."); Transaction tx = Builder.newTransaction(timeProvider).build(networkID, sender, new ISigner[] {}); validate(tx); }
@Test public void invalid_quorum_with_confirmation() throws Exception { expectedException.expect(ValidateException.class); expectedException.expectMessage("The quorum is not exist."); Transaction tx = Builder.newTransaction(timeProvider).build(networkID, sender, new ISigner[] {delegate2}); validate(tx); }
@Test public void quorum_with_confirmation() throws Exception { Transaction tx = Builder.newTransaction(timeProvider).build(networkID, sender, new ISigner[] {delegate1, delegate2}); validate(tx); }
@Test public void quorum_with_partial_confirmation() throws Exception { Transaction tx = Builder.newTransaction(timeProvider).build(networkID, sender, new ISigner[] {delegate1}); validate(tx); }
@Test public void confirmation_limit() throws Exception { expectedException.expect(ValidateException.class); expectedException.expectMessage("Invalid use of the confirmation field."); Random random = new Random(); String alphabet = "0123456789abcdef"; char[] symbols = alphabet.toCharArray(); ISigner[] signers = new ISigner[Constant.TRANSACTION_CONFIRMATIONS_MAX_SIZE + 1]; for (int i = 0; i < Constant.TRANSACTION_CONFIRMATIONS_MAX_SIZE + 1; i++) { char[] buffer = new char[64]; for (int j = 0; j < buffer.length; j++) { buffer[j] = symbols[random.nextInt(symbols.length)]; } signers[i] = new Signer(new String(buffer)); } Transaction tx = Builder.newTransaction(timeProvider).build(networkID, sender, signers); validate(tx); }
@Test public void unspecified_delegate() throws Exception { ISigner unknown = new Signer("33445566778899aabbccddeeff00112233445566778899aabbccddeeff001122"); Account unknownAccount = Mockito.spy(new TestAccount(new AccountID(unknown.getPublicKey()))); ledger.putAccount(unknownAccount); Transaction tx = Builder.newTransaction(timeProvider) .build(networkID, sender, new ISigner[] {unknown, delegate1, delegate2}); validate(tx); } |
EmptyPayerValidationRule implements IValidationRule { @Override public ValidationResult validate(Transaction tx, ILedger ledger) { if (tx.getPayer() != null) { return ValidationResult.error("Forbidden."); } if (tx.hasNestedTransactions()) { for (Transaction transaction : tx.getNestedTransactions().values()) { ValidationResult result = this.validate(transaction, ledger); if (result.hasError) { return result; } } } return ValidationResult.success; } @Override ValidationResult validate(Transaction tx, ILedger ledger); } | @Test public void payer_error() throws Exception { expectedException.expect(ValidateException.class); expectedException.expectMessage("Forbidden."); Transaction tx = Builder.newTransaction(timeProvider) .payedBy(payerAccount) .build(networkID, sender, new ISigner[] {payer}); validate(tx); }
@Test public void payer_success() throws Exception { Transaction tx = Builder.newTransaction(timeProvider).build(networkID, sender); validate(tx); }
@Test public void payer_nested_error() throws Exception { expectedException.expect(ValidateException.class); expectedException.expectMessage("Forbidden."); Transaction tx = Builder.newTransaction(timeProvider) .payedBy(payerAccount) .build(networkID, sender, new ISigner[] {payer}); validate(Builder.newTransaction(timeProvider).addNested(tx).build(networkID, sender)); }
@Test public void payer_nested_success() throws Exception { Transaction tx = Builder.newTransaction(timeProvider).build(networkID, sender); validate(Builder.newTransaction(timeProvider).addNested(tx).build(networkID, sender)); } |
Queue { void append(@NonNull MobileEventJson event) { long now = Time.now(); if (event.userId == null) { event.userId = userIdProvider.getUserId(); } if (this.config.acceptSameEventAfter > 0 && state.lastEvent != null && now < state.lastEvent.time + this.config.acceptSameEventAfter && Utils.eventsAreBasicallyEqual(state.lastEvent, event)) { Log.d(TAG, String.format("Drop duplicate event: %s", event.toString())); return; } Log.d(TAG, String.format("Append event: %s", event.toString())); state.queue.add(event); state.lastEvent = event; if (this.isReadyForUpload(now)) { state.lastUploadTimestamp = now; this.uploadRequester.requestUpload(flush()); } } Queue(String archive,
UserIdProvider userIdProvider,
UploadRequester uploadRequester,
Queue.Config config); } | @Test public void testAppend() throws IOException { Queue.UploadRequester uploadRequester = mock(Queue.UploadRequester.class); MobileEventJson event0 = new MobileEventJson() .withAndroidDeviceProperties(new AndroidDevicePropertiesJson() .withAndroidId("foo0") .withDeviceManufacturer("bar0") .withDeviceModel("baz0") ) .withTime(System.currentTimeMillis()) .withUserId("gary"); MobileEventJson event1 = new MobileEventJson() .withAndroidDeviceProperties(new AndroidDevicePropertiesJson() .withAndroidId("foo1") .withDeviceManufacturer("bar1") .withDeviceModel("baz1") ) .withTime(System.currentTimeMillis()) .withUserId("gary"); MobileEventJson event2 = new MobileEventJson() .withAndroidDeviceProperties(new AndroidDevicePropertiesJson() .withAndroidId("foo2") .withDeviceManufacturer("bar2") .withDeviceModel("baz2") ) .withTime(System.currentTimeMillis()) .withUserId("gary"); Queue queue = new Queue(null, USER_ID_PROVIDER, uploadRequester, new Queue.Config.Builder() .withUploadWhenMoreThan(10) .withUploadWhenOlderThan(TimeUnit.MINUTES.toMillis(1)) .build()); queue.append(event0); verify(uploadRequester).requestUpload(Arrays.asList(event0)); queue.append(event1); queue.append(event2); verifyZeroInteractions(uploadRequester); String archive = queue.archive(); assertEquals(Arrays.asList(event1, event2), queue.flush()); Queue another = new Queue(archive, USER_ID_PROVIDER, uploadRequester, new Queue.Config.Builder() .withUploadWhenMoreThan(10) .build()); assertEquals(Arrays.asList(event1, event2), another.flush()); }
@Test public void testUploadWhenMoreThan() throws IOException { Queue.UploadRequester uploadRequester = mock(Queue.UploadRequester.class); Queue queue = new Queue(null, USER_ID_PROVIDER, uploadRequester, new Queue.Config.Builder() .withUploadWhenMoreThan(1) .withUploadWhenOlderThan(TimeUnit.HOURS.toMillis(1)) .build()); MobileEventJson event = new MobileEventJson() .withAndroidDeviceProperties(new AndroidDevicePropertiesJson() .withAndroidId("foo0") .withDeviceManufacturer("bar0") .withDeviceModel("baz0") ) .withTime(1000L); verifyZeroInteractions(uploadRequester); queue.append(event); verify(uploadRequester).requestUpload(Arrays.asList(event)); queue.append(event); queue.append(event); verify(uploadRequester).requestUpload(Arrays.asList(event, event)); }
@Test public void testUploadWhenOlderThan() throws IOException { Queue.UploadRequester uploadRequester = mock(Queue.UploadRequester.class); Queue queue = new Queue(null, USER_ID_PROVIDER, uploadRequester, new Queue.Config.Builder() .withUploadWhenOlderThan(1) .build()); Time.currentTime = 1000; MobileEventJson event = new MobileEventJson() .withAndroidDeviceProperties(new AndroidDevicePropertiesJson() .withAndroidId("foo0") .withDeviceManufacturer("bar0") .withDeviceModel("baz0") ) .withTime(System.currentTimeMillis()); queue.append(event); verify(uploadRequester).requestUpload(Collections.singletonList(event)); }
@Test public void testUploadFirstEvent() throws IOException { Queue.UploadRequester uploadRequester = mock(Queue.UploadRequester.class); Queue queue = new Queue(null, USER_ID_PROVIDER, uploadRequester, new Queue.Config.Builder() .withUploadWhenMoreThan(5) .withUploadWhenOlderThan(10000) .build()); MobileEventJson event = new MobileEventJson() .withAndroidDeviceProperties(new AndroidDevicePropertiesJson() .withAndroidId("foo0") .withDeviceManufacturer("bar0") .withDeviceModel("baz0") ) .withTime(System.currentTimeMillis()); queue.append(event); verify(uploadRequester).requestUpload(Collections.singletonList(event)); }
@Test public void testUploadEventAfterWait() throws IOException, InterruptedException { Queue.UploadRequester uploadRequester = mock(Queue.UploadRequester.class); Queue queue = new Queue(null, USER_ID_PROVIDER, uploadRequester, new Queue.Config.Builder() .withUploadWhenMoreThan(5) .withUploadWhenOlderThan(1000) .build()); MobileEventJson event = new MobileEventJson() .withAndroidDeviceProperties(new AndroidDevicePropertiesJson() .withAndroidId("foo0") .withDeviceManufacturer("bar0") .withDeviceModel("baz0") ) .withTime(System.currentTimeMillis()); queue.append(event); verify(uploadRequester).requestUpload(Collections.singletonList(event)); reset(uploadRequester); Thread.sleep(2000); queue.append(event); verify(uploadRequester).requestUpload(Collections.singletonList(event)); }
@Test public void testUploadEventWithoutWait() throws IOException { Queue.UploadRequester uploadRequester = mock(Queue.UploadRequester.class); Queue queue = new Queue(null, USER_ID_PROVIDER, uploadRequester, new Queue.Config.Builder() .withUploadWhenMoreThan(5) .withUploadWhenOlderThan(10000) .build()); MobileEventJson event = new MobileEventJson() .withAndroidDeviceProperties(new AndroidDevicePropertiesJson() .withAndroidId("foo0") .withDeviceManufacturer("bar0") .withDeviceModel("baz0") ) .withTime(System.currentTimeMillis()); queue.append(event); verify(uploadRequester).requestUpload(Collections.singletonList(event)); reset(uploadRequester); queue.append(event); verifyZeroInteractions(uploadRequester); } |
Uploader { public void upload(List<MobileEventJson> batch) { try { Request request = makeRequest(batch); if (request != null) { Log.d(TAG, String.format("Uploading batch of size %d", batch.size())); this.doUpload(request, MAX_RETRIES); } } catch (IOException e) { Log.e(TAG, "Encountered IOException in upload", e); } } Uploader(TaskManager taskManager, ConfigProvider configProvider); void upload(List<MobileEventJson> batch); } | @Test public void testUploadOtherErrorExhaustRetries() throws Exception { WireMock.stubFor(makeCall(429)); Uploader bu = new Uploader(taskManager, configProvider); bu.upload(Collections.singletonList(TEST_EVENT)); verify(taskManager, times(1)).schedule(any(Runnable.class), Mockito.eq(0l), Mockito.eq(TimeUnit.SECONDS)); verify(taskManager, times(1)).schedule(any(Runnable.class), Mockito.eq(3l), Mockito.eq(TimeUnit.SECONDS)); verify(taskManager, times(1)).schedule(any(Runnable.class), Mockito.eq(12l), Mockito.eq(TimeUnit.SECONDS)); WireMock.verify(3, WireMock.putRequestedFor(WireMock.urlEqualTo(requestPath))); assertThat(WireMock.findUnmatchedRequests(), Matchers.empty()); }
@Test public void testUploadOtherEventualSuccess() throws Exception { WireMock.stubFor(makeCall(429) .inScenario("default") .whenScenarioStateIs(Scenario.STARTED) .willSetStateTo("failure")); WireMock.stubFor(makeCall(200) .inScenario("default") .whenScenarioStateIs("failure") .willSetStateTo("success") ); Uploader bu = new Uploader(taskManager, configProvider); bu.upload(Collections.singletonList(TEST_EVENT)); WireMock.verify(2, WireMock.putRequestedFor(WireMock.urlEqualTo(requestPath))); assertThat(WireMock.findUnmatchedRequests(), Matchers.empty()); }
@Test public void testUploadNothing() { Uploader bu = new Uploader(taskManager, configProvider); bu.upload(Collections.<MobileEventJson>emptyList()); assertThat(WireMock.findUnmatchedRequests(), Matchers.empty()); }
@Test public void testUpload200() throws Exception { WireMock.stubFor(makeCall(200)); Uploader bu = new Uploader(taskManager, configProvider); bu.upload(Collections.singletonList(TEST_EVENT)); WireMock.verify(1, WireMock.putRequestedFor(WireMock.urlEqualTo(requestPath))); assertThat(WireMock.findUnmatchedRequests(), Matchers.empty()); }
@Test public void testUpload400() throws Exception { WireMock.stubFor(makeCall(400)); Uploader bu = new Uploader(taskManager, configProvider); bu.upload(Collections.singletonList(TEST_EVENT)); WireMock.verify(1, WireMock.putRequestedFor(WireMock.urlEqualTo(requestPath))); assertThat(WireMock.findUnmatchedRequests(), Matchers.empty()); } |
Sift { private Sift() { } private Sift(); static void open(@NonNull Context context,
Config config,
String activityName); static void open(@NonNull Context context, String activityName); static void open(@NonNull Context context, Config config); static void open(@NonNull Context context); static void collect(); static void pause(); static void resume(@NonNull Context context); static void resume(@NonNull Context context, String activityName); static void close(); static synchronized void setUserId(String userId); static synchronized void unsetUserId(); } | @Test public void testSift() throws Exception { MemorySharedPreferences preferences = new MemorySharedPreferences(); SiftImpl sift = new SiftImpl( mockContext(preferences), null, "", false, mockTaskManager()); assertNotNull(sift.getConfig()); assertNull(sift.getConfig().accountId); assertNull(sift.getConfig().beaconKey); assertNotNull(sift.getConfig().serverUrlFormat); assertFalse(sift.getConfig().disallowLocationCollection); assertNull(sift.getUserId()); assertNotNull(sift.getQueue(SiftImpl.DEVICE_PROPERTIES_QUEUE_IDENTIFIER)); assertNull(sift.getQueue("some-queue")); assertNotNull(sift.createQueue("some-queue", new Queue.Config.Builder().build())); try { sift.createQueue("some-queue", new Queue.Config.Builder().build()); fail(); } catch (IllegalStateException e) { assertEquals("Queue exists: some-queue", e.getMessage()); } assertTrue(preferences.fields.isEmpty()); } |
Sift { public static synchronized void unsetUserId() { setUserId(null); } private Sift(); static void open(@NonNull Context context,
Config config,
String activityName); static void open(@NonNull Context context, String activityName); static void open(@NonNull Context context, Config config); static void open(@NonNull Context context); static void collect(); static void pause(); static void resume(@NonNull Context context); static void resume(@NonNull Context context, String activityName); static void close(); static synchronized void setUserId(String userId); static synchronized void unsetUserId(); } | @Test public void testUnsetUserId() throws Exception { MemorySharedPreferences preferences = new MemorySharedPreferences(); SiftImpl sift = new SiftImpl(mockContext(preferences), null, "", false, mockTaskManager()); sift.setUserId("gary"); sift.getQueue(SiftImpl.APP_STATE_QUEUE_IDENTIFIER).append(new MobileEventJson()); sift.getQueue(SiftImpl.APP_STATE_QUEUE_IDENTIFIER).append(new MobileEventJson()); MobileEventJson event = sift.getQueue(SiftImpl.APP_STATE_QUEUE_IDENTIFIER).flush().get(0); assertEquals("gary", event.userId); sift.unsetUserId(); sift.getQueue(SiftImpl.APP_STATE_QUEUE_IDENTIFIER).append(new MobileEventJson()); event = sift.getQueue(SiftImpl.APP_STATE_QUEUE_IDENTIFIER).flush().get(0); assertNull(event.userId); } |
Queue { State unarchive(String archive) { if (archive == null) { return new State(); } try { return Sift.GSON.fromJson(archive, State.class); } catch (JsonSyntaxException e) { Log.d(TAG, "Encountered exception in Queue.State unarchive", e); return new State(); } } Queue(String archive,
UserIdProvider userIdProvider,
UploadRequester uploadRequester,
Queue.Config config); } | @Test public void testUnarchiveLegacyQueueState() throws IOException, NoSuchFieldException, IllegalAccessException { Queue.UploadRequester uploadRequester = mock(Queue.UploadRequester.class); String legacyQueueState = "{\"config\":{\"acceptSameEventAfter\":1,\"uploadWhenMoreThan\":2," + "\"uploadWhenOlderThan\":3},\"queue\":[],\"lastEvent\":{\"time\":1513206382563," + "\"user_id\":\"USER_ID\",\"installation_id\":\"a4c7e6b6cae420e9\"," + "\"android_app_state\":{\"activity_class_name\":\"HelloSift\"," + "\"sdk_version\":\"0.9.7\",\"battery_level\":0.5,\"battery_state\":2," + "\"battery_health\":2,\"plug_state\":1," + "\"network_addresses\":[\"10.0.2.15\",\"fe80::5054:ff:fe12:3456\"]}}," + "\"lastUploadTimestamp\":1513206386326}"; Object o = new Queue(null, USER_ID_PROVIDER, uploadRequester, null) .unarchive(legacyQueueState); Field field = o.getClass().getDeclaredField("config"); field.setAccessible(true); Queue.Config config = (Queue.Config) field.get(o); assertEquals(config, new Queue.Config.Builder() .withAcceptSameEventAfter(1) .withUploadWhenMoreThan(2) .withUploadWhenOlderThan(3) .build() ); field = o.getClass().getDeclaredField("lastEvent"); field.setAccessible(true); MobileEventJson lastEvent = (MobileEventJson) field.get(o); assertEquals(lastEvent, new MobileEventJson() .withTime(1513206382563L) .withUserId("USER_ID") .withInstallationId("a4c7e6b6cae420e9") .withAndroidAppState(new AndroidAppStateJson() .withActivityClassName("HelloSift") .withSdkVersion("0.9.7") .withBatteryLevel(0.5) .withBatteryState(2L) .withBatteryHealth(2L) .withPlugState(1L) .withNetworkAddresses(Arrays.asList("10.0.2.15", "fe80::5054:ff:fe12:3456")) ) ); field = o.getClass().getDeclaredField("lastUploadTimestamp"); field.setAccessible(true); long lastUploadTimestamp = (long) field.get(o); assertEquals(lastUploadTimestamp, 1513206386326L); field = o.getClass().getDeclaredField("queue"); field.setAccessible(true); List queue = (List) field.get(o); assertEquals(queue.size(), 0); } |
DaoTransaction extends DaoIdentifiable { public static DaoTransaction createAndPersist(final DaoInternalAccount from, final DaoAccount to, final BigDecimal amount) throws NotEnoughMoneyException { final Session session = SessionManager.getSessionFactory().getCurrentSession(); final DaoTransaction transaction = new DaoTransaction(from, to, amount); try { session.save(transaction); } catch (final HibernateException e) { session.getTransaction().rollback(); SessionManager.getSessionFactory().getCurrentSession().beginTransaction(); throw e; } return transaction; } private DaoTransaction(final DaoInternalAccount from, final DaoAccount to, final BigDecimal amount); protected DaoTransaction(); static DaoTransaction createAndPersist(final DaoInternalAccount from, final DaoAccount to, final BigDecimal amount); DaoInternalAccount getFrom(); DaoAccount getTo(); BigDecimal getAmount(); Date getCreationDate(); @Override ReturnType accept(final DataClassVisitor<ReturnType> visitor); @Override int hashCode(); @Override boolean equals(final Object obj); } | @Test public void testCreateAndPersist() { SessionManager.beginWorkUnit(); try { yo.getInternalAccount().setAmount(new BigDecimal("200")); fred.getInternalAccount().setAmount(new BigDecimal("200")); DaoTransaction.createAndPersist(yo.getInternalAccount(), tom.getInternalAccount(), new BigDecimal("120")); assertEquals(0, yo.getInternalAccount().getAmount().compareTo(new BigDecimal("80"))); assertEquals(0, tom.getInternalAccount().getAmount().compareTo(new BigDecimal("120"))); SessionManager.flush(); b219.setExternalAccount(DaoExternalAccount.createAndPersist(b219, AccountType.IBAN, "plop")); DaoTransaction.createAndPersist(fred.getInternalAccount(), b219.getExternalAccount(), new BigDecimal("120")); assertEquals(0, fred.getInternalAccount().getAmount().compareTo(new BigDecimal("80"))); assertEquals(0, b219.getExternalAccount().getAmount().compareTo(new BigDecimal("120"))); } catch (final NotEnoughMoneyException e) { fail(); } SessionManager.endWorkUnitAndFlush(); } |
DaoComment extends DaoKudosable implements DaoCommentable { public static DaoComment createAndPersist(final DaoBug father, final DaoTeam team, final DaoMember member, final String text) { final Session session = SessionManager.getSessionFactory().getCurrentSession(); final DaoComment comment = new DaoComment(father, team, member, text); try { session.save(comment); } catch (final HibernateException e) { session.getTransaction().rollback(); SessionManager.getSessionFactory().getCurrentSession().beginTransaction(); throw e; } DaoEvent.createCommentEvent(father.getMilestone().getOffer().getFeature(), EventType.BUG_ADD_COMMENT, father, comment, father.getMilestone().getOffer(), father.getMilestone()); return comment; } private DaoComment(final DaoMember member, final DaoTeam team, final String text); private DaoComment(final DaoBug father, final DaoTeam team, final DaoMember member, final String text); private DaoComment(final DaoFeature father, final DaoTeam team, final DaoMember member, final String text); private DaoComment(final DaoComment father, final DaoTeam team, final DaoMember member, final String text); protected DaoComment(); static DaoCommentable getCommentable(final int id); static Long getCommentCount(Date from, Date to); static DaoComment createAndPersist(final DaoBug father, final DaoTeam team, final DaoMember member, final String text); static DaoComment createAndPersist(final DaoFeature father, final DaoTeam team, final DaoMember member, final String text); static DaoComment createAndPersist(final DaoComment father, final DaoTeam team, final DaoMember member, final String text); void addChildComment(final DaoComment comment); String getText(); void setText(final String content, final DaoMember author); PageIterable<DaoComment> getChildren(); @Override PageIterable<DaoComment> getComments(); @Override DaoComment getLastComment(); @Override void addComment(final DaoComment comment); DaoUserContent getCommented(); DaoComment getFather(); DaoBug getFatherBug(); DaoFeature getFatherFeature(); @Override ReturnType accept(final DataClassVisitor<ReturnType> visitor); @Override int hashCode(); @Override boolean equals(final Object obj); } | @Test public void testCreateAndPersist() { final DaoComment comment = DaoComment.createAndPersist((DaoComment) null, null, DaoMember.getByLogin(yo.getLogin()), "A text"); assertEquals("A text", comment.getText()); try { DaoComment.createAndPersist((DaoComment) null, null, null, "A text"); fail(); } catch (final NonOptionalParameterException e) { assertTrue(true); } try { DaoComment.createAndPersist((DaoComment) null, null, DaoMember.getByLogin(yo.getLogin()), ""); fail(); } catch (final NonOptionalParameterException e) { assertTrue(true); } try { DaoComment.createAndPersist((DaoComment) null, null, DaoMember.getByLogin(yo.getLogin()), null); fail(); } catch (final NonOptionalParameterException e) { assertTrue(true); } } |
DaoComment extends DaoKudosable implements DaoCommentable { public void addChildComment(final DaoComment comment) { if (comment == null) { throw new NonOptionalParameterException(); } if (comment == this) { throw new BadProgrammerException("Cannot add ourself as child comment."); } comment.father = this; this.children.add(comment); } private DaoComment(final DaoMember member, final DaoTeam team, final String text); private DaoComment(final DaoBug father, final DaoTeam team, final DaoMember member, final String text); private DaoComment(final DaoFeature father, final DaoTeam team, final DaoMember member, final String text); private DaoComment(final DaoComment father, final DaoTeam team, final DaoMember member, final String text); protected DaoComment(); static DaoCommentable getCommentable(final int id); static Long getCommentCount(Date from, Date to); static DaoComment createAndPersist(final DaoBug father, final DaoTeam team, final DaoMember member, final String text); static DaoComment createAndPersist(final DaoFeature father, final DaoTeam team, final DaoMember member, final String text); static DaoComment createAndPersist(final DaoComment father, final DaoTeam team, final DaoMember member, final String text); void addChildComment(final DaoComment comment); String getText(); void setText(final String content, final DaoMember author); PageIterable<DaoComment> getChildren(); @Override PageIterable<DaoComment> getComments(); @Override DaoComment getLastComment(); @Override void addComment(final DaoComment comment); DaoUserContent getCommented(); DaoComment getFather(); DaoBug getFatherBug(); DaoFeature getFatherFeature(); @Override ReturnType accept(final DataClassVisitor<ReturnType> visitor); @Override int hashCode(); @Override boolean equals(final Object obj); } | @Test public void testAddChildComment() { final DaoComment comment = DaoComment.createAndPersist((DaoComment) null, null, DaoMember.getByLogin(yo.getLogin()), "A text"); final DaoComment commentChild = DaoComment.createAndPersist(comment, null, DaoMember.getByLogin(fred.getLogin()), "A comment"); comment.addChildComment(commentChild); final DaoComment commentChild1 = DaoComment.createAndPersist(comment, null, DaoMember.getByLogin(yo.getLogin()), "hello"); comment.addChildComment(commentChild1); final DaoComment commentChild2 = DaoComment.createAndPersist(comment, null, DaoMember.getByLogin(tom.getLogin()), "An other text"); comment.addChildComment(commentChild2); final DaoComment commentChildChild = DaoComment.createAndPersist(commentChild1, null, DaoMember.getByLogin(tom.getLogin()), "An other text"); commentChild1.addChildComment(commentChildChild); try { comment.addChildComment(comment); fail(); } catch (final BadProgrammerException e) { assertTrue(true); } try { comment.addChildComment(null); fail(); } catch (final NonOptionalParameterException e) { assertTrue(true); } } |
FeatureImplementation extends Kudosable<DaoFeature> implements Feature { @SuppressWarnings("synthetic-access") public static FeatureImplementation create(final DaoFeature dao) { return new MyCreator().create(dao); } FeatureImplementation(final Member author,
final Team team,
final Language language,
final String title,
final String description,
final Software software); private FeatureImplementation(final DaoFeature dao); @SuppressWarnings("synthetic-access") static FeatureImplementation create(final DaoFeature dao); @Override boolean canAccessComment(final Action action); @Override boolean canAccessContribution(final Action action); @Override boolean canAccessOffer(final Action action); @Override boolean canModify(); @Override Contribution addContribution(final BigDecimal amount, final String comment); @Override void follow(final Member member); @Override Offer addOffer(final BigDecimal amount,
final String description,
final String license,
final Language language,
final Date dateExpire,
final int secondsBeforeValidation); @Override void removeOffer(final Offer offer); @Override Comment addComment(final String text); void unSelectOffer(final Offer offer); boolean validateCurrentMilestone(final boolean force); @Override void cancelDevelopment(); @Override void computeSelectedOffer(); @Override void setFeatureState(final FeatureState featureState); void setFeatureStateUnprotected(final FeatureState featureState); void developmentTimeOut(); @Override void updateDevelopmentState(); void notifyOfferKudos(final Offer offer, final boolean positif); void setOfferIsValidated(); void setMilestoneIsValidated(); void setMilestoneIsRejected(); @Override void setDescription(final String newDescription, final Language language); @Override void setTitle(final String title, final Language language); @Override void setSoftware(final Software software); boolean isDeveloping(); @Override Date getValidationDate(); @Override Long getCommentsCount(); @Override PageIterable<Comment> getComments(); @Deprecated @Override PageIterable<Contribution> getContributions(); @Override PageIterable<Contribution> getContributions(final boolean isCanceled); @Override float getProgression(); @Override float getMemberProgression(final Member author); @Override float getRelativeProgression(final BigDecimal amount); @Override BigDecimal getContribution(); @Override String getTitle(); @Override BigDecimal getContributionMax(); @Override BigDecimal getContributionMin(); @Override BigDecimal getContributionOf(final Member member); @Override Description getDescription(); @Override Software getSoftware(); @Override boolean hasSoftware(); @Override PageIterable<Offer> getOffers(); @Override Offer getSelectedOffer(); @Override Offer getValidatedOffer(); @Override FeatureState getFeatureState(); @Override int countOpenBugs(); @Override PageIterable<Bug> getOpenBugs(); @Override PageIterable<Bug> getClosedBugs(); @Override ReturnType accept(final ModelClassVisitor<ReturnType> visitor); @Override String getTitle(final Locale l); @Override String getDescription(final Locale l); static final int PROGRESSION_PERCENT; } | @Test public void testCreate() { final Feature feature = FeatureImplementation.create(DaoFeature.createAndPersist(memberTom.getDao(), null, DaoDescription.createAndPersist(memberTom.getDao(), null, Language.FR, "title", "description"), DaoSoftware.getByName("VLC"))); assertNotNull(feature); assertNull(FeatureImplementation.create(null)); } |
FeatureImplementation extends Kudosable<DaoFeature> implements Feature { @Override public boolean canAccessComment(final Action action) { return canAccess(new RgtFeature.Comment(), action); } FeatureImplementation(final Member author,
final Team team,
final Language language,
final String title,
final String description,
final Software software); private FeatureImplementation(final DaoFeature dao); @SuppressWarnings("synthetic-access") static FeatureImplementation create(final DaoFeature dao); @Override boolean canAccessComment(final Action action); @Override boolean canAccessContribution(final Action action); @Override boolean canAccessOffer(final Action action); @Override boolean canModify(); @Override Contribution addContribution(final BigDecimal amount, final String comment); @Override void follow(final Member member); @Override Offer addOffer(final BigDecimal amount,
final String description,
final String license,
final Language language,
final Date dateExpire,
final int secondsBeforeValidation); @Override void removeOffer(final Offer offer); @Override Comment addComment(final String text); void unSelectOffer(final Offer offer); boolean validateCurrentMilestone(final boolean force); @Override void cancelDevelopment(); @Override void computeSelectedOffer(); @Override void setFeatureState(final FeatureState featureState); void setFeatureStateUnprotected(final FeatureState featureState); void developmentTimeOut(); @Override void updateDevelopmentState(); void notifyOfferKudos(final Offer offer, final boolean positif); void setOfferIsValidated(); void setMilestoneIsValidated(); void setMilestoneIsRejected(); @Override void setDescription(final String newDescription, final Language language); @Override void setTitle(final String title, final Language language); @Override void setSoftware(final Software software); boolean isDeveloping(); @Override Date getValidationDate(); @Override Long getCommentsCount(); @Override PageIterable<Comment> getComments(); @Deprecated @Override PageIterable<Contribution> getContributions(); @Override PageIterable<Contribution> getContributions(final boolean isCanceled); @Override float getProgression(); @Override float getMemberProgression(final Member author); @Override float getRelativeProgression(final BigDecimal amount); @Override BigDecimal getContribution(); @Override String getTitle(); @Override BigDecimal getContributionMax(); @Override BigDecimal getContributionMin(); @Override BigDecimal getContributionOf(final Member member); @Override Description getDescription(); @Override Software getSoftware(); @Override boolean hasSoftware(); @Override PageIterable<Offer> getOffers(); @Override Offer getSelectedOffer(); @Override Offer getValidatedOffer(); @Override FeatureState getFeatureState(); @Override int countOpenBugs(); @Override PageIterable<Bug> getOpenBugs(); @Override PageIterable<Bug> getClosedBugs(); @Override ReturnType accept(final ModelClassVisitor<ReturnType> visitor); @Override String getTitle(final Locale l); @Override String getDescription(final Locale l); static final int PROGRESSION_PERCENT; } | @Test public void testCanAccessComment() { final Feature feature = createFeatureByThomas(); assertTrue(feature.canAccessComment(Action.READ)); assertFalse(feature.canAccessComment(Action.WRITE)); assertFalse(feature.canAccessComment(Action.DELETE)); AuthToken.authenticate(memeberFred); assertTrue(feature.canAccessComment(Action.READ)); assertTrue(feature.canAccessComment(Action.WRITE)); assertFalse(feature.canAccessComment(Action.DELETE)); AuthToken.authenticate(memberTom); assertTrue(feature.canAccessComment(Action.READ)); assertTrue(feature.canAccessComment(Action.WRITE)); assertFalse(feature.canAccessComment(Action.DELETE)); } |
FeatureImplementation extends Kudosable<DaoFeature> implements Feature { @Override public boolean canAccessContribution(final Action action) { return canAccess(new RgtFeature.Contribute(), action); } FeatureImplementation(final Member author,
final Team team,
final Language language,
final String title,
final String description,
final Software software); private FeatureImplementation(final DaoFeature dao); @SuppressWarnings("synthetic-access") static FeatureImplementation create(final DaoFeature dao); @Override boolean canAccessComment(final Action action); @Override boolean canAccessContribution(final Action action); @Override boolean canAccessOffer(final Action action); @Override boolean canModify(); @Override Contribution addContribution(final BigDecimal amount, final String comment); @Override void follow(final Member member); @Override Offer addOffer(final BigDecimal amount,
final String description,
final String license,
final Language language,
final Date dateExpire,
final int secondsBeforeValidation); @Override void removeOffer(final Offer offer); @Override Comment addComment(final String text); void unSelectOffer(final Offer offer); boolean validateCurrentMilestone(final boolean force); @Override void cancelDevelopment(); @Override void computeSelectedOffer(); @Override void setFeatureState(final FeatureState featureState); void setFeatureStateUnprotected(final FeatureState featureState); void developmentTimeOut(); @Override void updateDevelopmentState(); void notifyOfferKudos(final Offer offer, final boolean positif); void setOfferIsValidated(); void setMilestoneIsValidated(); void setMilestoneIsRejected(); @Override void setDescription(final String newDescription, final Language language); @Override void setTitle(final String title, final Language language); @Override void setSoftware(final Software software); boolean isDeveloping(); @Override Date getValidationDate(); @Override Long getCommentsCount(); @Override PageIterable<Comment> getComments(); @Deprecated @Override PageIterable<Contribution> getContributions(); @Override PageIterable<Contribution> getContributions(final boolean isCanceled); @Override float getProgression(); @Override float getMemberProgression(final Member author); @Override float getRelativeProgression(final BigDecimal amount); @Override BigDecimal getContribution(); @Override String getTitle(); @Override BigDecimal getContributionMax(); @Override BigDecimal getContributionMin(); @Override BigDecimal getContributionOf(final Member member); @Override Description getDescription(); @Override Software getSoftware(); @Override boolean hasSoftware(); @Override PageIterable<Offer> getOffers(); @Override Offer getSelectedOffer(); @Override Offer getValidatedOffer(); @Override FeatureState getFeatureState(); @Override int countOpenBugs(); @Override PageIterable<Bug> getOpenBugs(); @Override PageIterable<Bug> getClosedBugs(); @Override ReturnType accept(final ModelClassVisitor<ReturnType> visitor); @Override String getTitle(final Locale l); @Override String getDescription(final Locale l); static final int PROGRESSION_PERCENT; } | @Test public void testCanAccessContribution() { final Feature feature = createFeatureByThomas(); assertTrue(feature.canAccessContribution(Action.READ)); assertFalse(feature.canAccessContribution(Action.WRITE)); assertFalse(feature.canAccessContribution(Action.DELETE)); AuthToken.authenticate(memberTom); assertTrue(feature.canAccessContribution(Action.READ)); assertTrue(feature.canAccessContribution(Action.WRITE)); assertFalse(feature.canAccessContribution(Action.DELETE)); AuthToken.authenticate(memeberFred); assertTrue(feature.canAccessContribution(Action.READ)); assertTrue(feature.canAccessContribution(Action.WRITE)); assertFalse(feature.canAccessContribution(Action.DELETE)); } |
FeatureImplementation extends Kudosable<DaoFeature> implements Feature { @Override public boolean canAccessOffer(final Action action) { return canAccess(new RgtFeature.Offer(), action); } FeatureImplementation(final Member author,
final Team team,
final Language language,
final String title,
final String description,
final Software software); private FeatureImplementation(final DaoFeature dao); @SuppressWarnings("synthetic-access") static FeatureImplementation create(final DaoFeature dao); @Override boolean canAccessComment(final Action action); @Override boolean canAccessContribution(final Action action); @Override boolean canAccessOffer(final Action action); @Override boolean canModify(); @Override Contribution addContribution(final BigDecimal amount, final String comment); @Override void follow(final Member member); @Override Offer addOffer(final BigDecimal amount,
final String description,
final String license,
final Language language,
final Date dateExpire,
final int secondsBeforeValidation); @Override void removeOffer(final Offer offer); @Override Comment addComment(final String text); void unSelectOffer(final Offer offer); boolean validateCurrentMilestone(final boolean force); @Override void cancelDevelopment(); @Override void computeSelectedOffer(); @Override void setFeatureState(final FeatureState featureState); void setFeatureStateUnprotected(final FeatureState featureState); void developmentTimeOut(); @Override void updateDevelopmentState(); void notifyOfferKudos(final Offer offer, final boolean positif); void setOfferIsValidated(); void setMilestoneIsValidated(); void setMilestoneIsRejected(); @Override void setDescription(final String newDescription, final Language language); @Override void setTitle(final String title, final Language language); @Override void setSoftware(final Software software); boolean isDeveloping(); @Override Date getValidationDate(); @Override Long getCommentsCount(); @Override PageIterable<Comment> getComments(); @Deprecated @Override PageIterable<Contribution> getContributions(); @Override PageIterable<Contribution> getContributions(final boolean isCanceled); @Override float getProgression(); @Override float getMemberProgression(final Member author); @Override float getRelativeProgression(final BigDecimal amount); @Override BigDecimal getContribution(); @Override String getTitle(); @Override BigDecimal getContributionMax(); @Override BigDecimal getContributionMin(); @Override BigDecimal getContributionOf(final Member member); @Override Description getDescription(); @Override Software getSoftware(); @Override boolean hasSoftware(); @Override PageIterable<Offer> getOffers(); @Override Offer getSelectedOffer(); @Override Offer getValidatedOffer(); @Override FeatureState getFeatureState(); @Override int countOpenBugs(); @Override PageIterable<Bug> getOpenBugs(); @Override PageIterable<Bug> getClosedBugs(); @Override ReturnType accept(final ModelClassVisitor<ReturnType> visitor); @Override String getTitle(final Locale l); @Override String getDescription(final Locale l); static final int PROGRESSION_PERCENT; } | @Test public void testCanAccessOffer() { final Feature feature = createFeatureByThomas(); assertTrue(feature.canAccessOffer(Action.READ)); assertFalse(feature.canAccessOffer(Action.WRITE)); assertFalse(feature.canAccessOffer(Action.DELETE)); AuthToken.authenticate(memeberFred); assertTrue(feature.canAccessOffer(Action.READ)); assertTrue(feature.canAccessOffer(Action.WRITE)); assertFalse(feature.canAccessOffer(Action.DELETE)); AuthToken.authenticate(memberTom); assertTrue(feature.canAccessOffer(Action.READ)); assertTrue(feature.canAccessOffer(Action.WRITE)); assertFalse(feature.canAccessOffer(Action.DELETE)); } |
FeatureImplementation extends Kudosable<DaoFeature> implements Feature { @Override public Contribution addContribution(final BigDecimal amount, final String comment) throws NotEnoughMoneyException, UnauthorizedOperationException { tryAccess(new RgtFeature.Contribute(), Action.WRITE); if (AuthToken.getAsTeam() != null) { if (AuthToken.getAsTeam().getUserTeamRight(AuthToken.getMember()).contains(UserTeamRight.BANK)) { Log.model().trace("Doing a contribution in the name of a team: " + AuthToken.getAsTeam().getId()); } else { throw new UnauthorizedOperationException(SpecialCode.TEAM_CONTRIBUTION_WITHOUT_BANK); } } final DaoContribution contribution = getDao().addContribution(AuthToken.getMember().getDao(), DaoGetter.get(AuthToken.getAsTeam()), amount, comment); follow(AuthToken.getMember()); return Contribution.create(contribution); } FeatureImplementation(final Member author,
final Team team,
final Language language,
final String title,
final String description,
final Software software); private FeatureImplementation(final DaoFeature dao); @SuppressWarnings("synthetic-access") static FeatureImplementation create(final DaoFeature dao); @Override boolean canAccessComment(final Action action); @Override boolean canAccessContribution(final Action action); @Override boolean canAccessOffer(final Action action); @Override boolean canModify(); @Override Contribution addContribution(final BigDecimal amount, final String comment); @Override void follow(final Member member); @Override Offer addOffer(final BigDecimal amount,
final String description,
final String license,
final Language language,
final Date dateExpire,
final int secondsBeforeValidation); @Override void removeOffer(final Offer offer); @Override Comment addComment(final String text); void unSelectOffer(final Offer offer); boolean validateCurrentMilestone(final boolean force); @Override void cancelDevelopment(); @Override void computeSelectedOffer(); @Override void setFeatureState(final FeatureState featureState); void setFeatureStateUnprotected(final FeatureState featureState); void developmentTimeOut(); @Override void updateDevelopmentState(); void notifyOfferKudos(final Offer offer, final boolean positif); void setOfferIsValidated(); void setMilestoneIsValidated(); void setMilestoneIsRejected(); @Override void setDescription(final String newDescription, final Language language); @Override void setTitle(final String title, final Language language); @Override void setSoftware(final Software software); boolean isDeveloping(); @Override Date getValidationDate(); @Override Long getCommentsCount(); @Override PageIterable<Comment> getComments(); @Deprecated @Override PageIterable<Contribution> getContributions(); @Override PageIterable<Contribution> getContributions(final boolean isCanceled); @Override float getProgression(); @Override float getMemberProgression(final Member author); @Override float getRelativeProgression(final BigDecimal amount); @Override BigDecimal getContribution(); @Override String getTitle(); @Override BigDecimal getContributionMax(); @Override BigDecimal getContributionMin(); @Override BigDecimal getContributionOf(final Member member); @Override Description getDescription(); @Override Software getSoftware(); @Override boolean hasSoftware(); @Override PageIterable<Offer> getOffers(); @Override Offer getSelectedOffer(); @Override Offer getValidatedOffer(); @Override FeatureState getFeatureState(); @Override int countOpenBugs(); @Override PageIterable<Bug> getOpenBugs(); @Override PageIterable<Bug> getClosedBugs(); @Override ReturnType accept(final ModelClassVisitor<ReturnType> visitor); @Override String getTitle(final Locale l); @Override String getDescription(final Locale l); static final int PROGRESSION_PERCENT; } | @Test public void testAddContribution() { final Feature feature = createFeatureByThomas(); assertEquals(FeatureState.PENDING, feature.getFeatureState()); AuthToken.authenticate(memeberFred); try { feature.addContribution(new BigDecimal("10"), "comment"); } catch (final NotEnoughMoneyException e) { fail(); } catch (final UnauthorizedOperationException e) { fail(); } assertEquals(feature.getContribution(), new BigDecimal("10")); try { feature.addContribution(new BigDecimal("10"), null); } catch (final NotEnoughMoneyException e) { fail(); } catch (final UnauthorizedOperationException e) { fail(); } assertEquals(feature.getContribution(), new BigDecimal("20")); try { feature.addContribution(new BigDecimal("10"), ""); } catch (final NotEnoughMoneyException e) { fail(); } catch (final UnauthorizedOperationException e) { fail(); } assertEquals(feature.getContribution(), new BigDecimal("30")); try { feature.addContribution(null, "comment"); fail(); } catch (final NotEnoughMoneyException e) { fail(); } catch (final UnauthorizedOperationException e) { fail(); } catch (final NonOptionalParameterException e) { assertTrue(true); } assertEquals(feature.getContribution(), new BigDecimal("30")); try { feature.addContribution(new BigDecimal("-10"), "comment"); fail(); } catch (final NotEnoughMoneyException e) { fail(); } catch (final UnauthorizedOperationException e) { fail(); } catch (final BadProgrammerException e) { assertTrue(true); } assertEquals(feature.getContribution(), new BigDecimal("30")); try { feature.addContribution(new BigDecimal("0"), "comment"); fail(); } catch (final NotEnoughMoneyException e) { fail(); } catch (final UnauthorizedOperationException e) { fail(); } catch (final BadProgrammerException e) { assertTrue(true); } assertEquals(feature.getContribution(), new BigDecimal("30")); AuthToken.unAuthenticate(); ; try { feature.addContribution(new BigDecimal("10"), "comment"); fail(); } catch (final NotEnoughMoneyException e) { fail(); } catch (final UnauthorizedOperationException e) { assertTrue(true); } assertEquals(feature.getContribution(), new BigDecimal("30")); AuthToken.authenticate(memberTom); try { feature.addContribution(new BigDecimal("1001"), "comment"); fail(); } catch (final NotEnoughMoneyException e) { assertTrue(true); } catch (final UnauthorizedOperationException e) { fail(); } assertEquals(feature.getContribution(), new BigDecimal("30")); assertEquals(FeatureState.PENDING, feature.getFeatureState()); } |
FeatureImplementation extends Kudosable<DaoFeature> implements Feature { @Override public Offer addOffer(final BigDecimal amount, final String description, final String license, final Language language, final Date dateExpire, final int secondsBeforeValidation) throws UnauthorizedOperationException { tryAccess(new RgtFeature.Offer(), Action.WRITE); final Offer offer = new Offer(AuthToken.getMember(), AuthToken.getAsTeam(), this, amount, description, license, language, dateExpire, secondsBeforeValidation); follow(AuthToken.getMember()); return doAddOffer(offer); } FeatureImplementation(final Member author,
final Team team,
final Language language,
final String title,
final String description,
final Software software); private FeatureImplementation(final DaoFeature dao); @SuppressWarnings("synthetic-access") static FeatureImplementation create(final DaoFeature dao); @Override boolean canAccessComment(final Action action); @Override boolean canAccessContribution(final Action action); @Override boolean canAccessOffer(final Action action); @Override boolean canModify(); @Override Contribution addContribution(final BigDecimal amount, final String comment); @Override void follow(final Member member); @Override Offer addOffer(final BigDecimal amount,
final String description,
final String license,
final Language language,
final Date dateExpire,
final int secondsBeforeValidation); @Override void removeOffer(final Offer offer); @Override Comment addComment(final String text); void unSelectOffer(final Offer offer); boolean validateCurrentMilestone(final boolean force); @Override void cancelDevelopment(); @Override void computeSelectedOffer(); @Override void setFeatureState(final FeatureState featureState); void setFeatureStateUnprotected(final FeatureState featureState); void developmentTimeOut(); @Override void updateDevelopmentState(); void notifyOfferKudos(final Offer offer, final boolean positif); void setOfferIsValidated(); void setMilestoneIsValidated(); void setMilestoneIsRejected(); @Override void setDescription(final String newDescription, final Language language); @Override void setTitle(final String title, final Language language); @Override void setSoftware(final Software software); boolean isDeveloping(); @Override Date getValidationDate(); @Override Long getCommentsCount(); @Override PageIterable<Comment> getComments(); @Deprecated @Override PageIterable<Contribution> getContributions(); @Override PageIterable<Contribution> getContributions(final boolean isCanceled); @Override float getProgression(); @Override float getMemberProgression(final Member author); @Override float getRelativeProgression(final BigDecimal amount); @Override BigDecimal getContribution(); @Override String getTitle(); @Override BigDecimal getContributionMax(); @Override BigDecimal getContributionMin(); @Override BigDecimal getContributionOf(final Member member); @Override Description getDescription(); @Override Software getSoftware(); @Override boolean hasSoftware(); @Override PageIterable<Offer> getOffers(); @Override Offer getSelectedOffer(); @Override Offer getValidatedOffer(); @Override FeatureState getFeatureState(); @Override int countOpenBugs(); @Override PageIterable<Bug> getOpenBugs(); @Override PageIterable<Bug> getClosedBugs(); @Override ReturnType accept(final ModelClassVisitor<ReturnType> visitor); @Override String getTitle(final Locale l); @Override String getDescription(final Locale l); static final int PROGRESSION_PERCENT; } | @Test public void testAddOffer() { final Feature feature = createFeatureByThomas(); assertEquals(FeatureState.PENDING, feature.getFeatureState()); AuthToken.authenticate(memeberFred); assertNull(feature.getSelectedOffer()); assertEquals(0, feature.getOffers().getPageSize()); try { AuthToken.authenticate(memeberFred); feature.addOffer(new BigDecimal("120"), "description", "GNU GPL V3",Language.FR, DateUtils.tomorrow(), 0); } catch (final UnauthorizedOperationException e) { fail(); } assertEquals(FeatureState.PREPARING, feature.getFeatureState()); assertNotNull(feature.getSelectedOffer()); assertEquals(FeatureState.PREPARING, feature.getFeatureState()); } |
FeatureImplementation extends Kudosable<DaoFeature> implements Feature { @Override public void removeOffer(final Offer offer) throws UnauthorizedOperationException { tryAccess(new RgtFeature.Offer(), Action.DELETE); if (getDao().getSelectedOffer().getId() != null && getDao().getSelectedOffer().getId().equals(offer.getId())) { setSelectedOffer(Offer.create(getDao().computeSelectedOffer())); } setStateObject(getStateObject().eventRemoveOffer(offer)); getDao().removeOffer(offer.getDao()); } FeatureImplementation(final Member author,
final Team team,
final Language language,
final String title,
final String description,
final Software software); private FeatureImplementation(final DaoFeature dao); @SuppressWarnings("synthetic-access") static FeatureImplementation create(final DaoFeature dao); @Override boolean canAccessComment(final Action action); @Override boolean canAccessContribution(final Action action); @Override boolean canAccessOffer(final Action action); @Override boolean canModify(); @Override Contribution addContribution(final BigDecimal amount, final String comment); @Override void follow(final Member member); @Override Offer addOffer(final BigDecimal amount,
final String description,
final String license,
final Language language,
final Date dateExpire,
final int secondsBeforeValidation); @Override void removeOffer(final Offer offer); @Override Comment addComment(final String text); void unSelectOffer(final Offer offer); boolean validateCurrentMilestone(final boolean force); @Override void cancelDevelopment(); @Override void computeSelectedOffer(); @Override void setFeatureState(final FeatureState featureState); void setFeatureStateUnprotected(final FeatureState featureState); void developmentTimeOut(); @Override void updateDevelopmentState(); void notifyOfferKudos(final Offer offer, final boolean positif); void setOfferIsValidated(); void setMilestoneIsValidated(); void setMilestoneIsRejected(); @Override void setDescription(final String newDescription, final Language language); @Override void setTitle(final String title, final Language language); @Override void setSoftware(final Software software); boolean isDeveloping(); @Override Date getValidationDate(); @Override Long getCommentsCount(); @Override PageIterable<Comment> getComments(); @Deprecated @Override PageIterable<Contribution> getContributions(); @Override PageIterable<Contribution> getContributions(final boolean isCanceled); @Override float getProgression(); @Override float getMemberProgression(final Member author); @Override float getRelativeProgression(final BigDecimal amount); @Override BigDecimal getContribution(); @Override String getTitle(); @Override BigDecimal getContributionMax(); @Override BigDecimal getContributionMin(); @Override BigDecimal getContributionOf(final Member member); @Override Description getDescription(); @Override Software getSoftware(); @Override boolean hasSoftware(); @Override PageIterable<Offer> getOffers(); @Override Offer getSelectedOffer(); @Override Offer getValidatedOffer(); @Override FeatureState getFeatureState(); @Override int countOpenBugs(); @Override PageIterable<Bug> getOpenBugs(); @Override PageIterable<Bug> getClosedBugs(); @Override ReturnType accept(final ModelClassVisitor<ReturnType> visitor); @Override String getTitle(final Locale l); @Override String getDescription(final Locale l); static final int PROGRESSION_PERCENT; } | @Test public void testRemoveOffer() throws NotEnoughMoneyException, UnauthorizedOperationException, NotFoundException { final Feature feature = createFeatureByThomas(); final DaoMember admin = DaoMember.createAndPersist("admin1", "admin1", "salt", "admin1", Locale.FRANCE); admin.setActivationState(ActivationState.ACTIVE); admin.setRole(Role.ADMIN); assertEquals(FeatureState.PENDING, feature.getFeatureState()); AuthToken.authenticate(memeberFred); feature.addContribution(new BigDecimal("100"), "plop"); assertEquals(FeatureState.PENDING, feature.getFeatureState()); AuthToken.authenticate(memberTom); feature.addOffer(new BigDecimal("120"), "description", "GNU GPL V3", Language.FR, DateUtils.tomorrow(), 0); assertEquals(FeatureState.PREPARING, feature.getFeatureState()); assertNotNull(feature.getSelectedOffer()); try { AuthToken.authenticate(memberTom); feature.removeOffer(feature.getSelectedOffer()); fail(); } catch (final UnauthorizedOperationException e) { assertTrue(true); } try { AuthToken.authenticate(memberAdmin); feature.removeOffer(feature.getSelectedOffer()); assertTrue(true); } catch (final UnauthorizedOperationException e) { fail(); } } |
FeatureImplementation extends Kudosable<DaoFeature> implements Feature { @Override public void cancelDevelopment() throws UnauthorizedOperationException { throwWrongStateExceptionOnNondevelopingState(); getSelectedOffer().tryAccess(new RgtOffer.SelectedOffer(), Action.WRITE); setStateObject(getStateObject().eventDeveloperCanceled()); } FeatureImplementation(final Member author,
final Team team,
final Language language,
final String title,
final String description,
final Software software); private FeatureImplementation(final DaoFeature dao); @SuppressWarnings("synthetic-access") static FeatureImplementation create(final DaoFeature dao); @Override boolean canAccessComment(final Action action); @Override boolean canAccessContribution(final Action action); @Override boolean canAccessOffer(final Action action); @Override boolean canModify(); @Override Contribution addContribution(final BigDecimal amount, final String comment); @Override void follow(final Member member); @Override Offer addOffer(final BigDecimal amount,
final String description,
final String license,
final Language language,
final Date dateExpire,
final int secondsBeforeValidation); @Override void removeOffer(final Offer offer); @Override Comment addComment(final String text); void unSelectOffer(final Offer offer); boolean validateCurrentMilestone(final boolean force); @Override void cancelDevelopment(); @Override void computeSelectedOffer(); @Override void setFeatureState(final FeatureState featureState); void setFeatureStateUnprotected(final FeatureState featureState); void developmentTimeOut(); @Override void updateDevelopmentState(); void notifyOfferKudos(final Offer offer, final boolean positif); void setOfferIsValidated(); void setMilestoneIsValidated(); void setMilestoneIsRejected(); @Override void setDescription(final String newDescription, final Language language); @Override void setTitle(final String title, final Language language); @Override void setSoftware(final Software software); boolean isDeveloping(); @Override Date getValidationDate(); @Override Long getCommentsCount(); @Override PageIterable<Comment> getComments(); @Deprecated @Override PageIterable<Contribution> getContributions(); @Override PageIterable<Contribution> getContributions(final boolean isCanceled); @Override float getProgression(); @Override float getMemberProgression(final Member author); @Override float getRelativeProgression(final BigDecimal amount); @Override BigDecimal getContribution(); @Override String getTitle(); @Override BigDecimal getContributionMax(); @Override BigDecimal getContributionMin(); @Override BigDecimal getContributionOf(final Member member); @Override Description getDescription(); @Override Software getSoftware(); @Override boolean hasSoftware(); @Override PageIterable<Offer> getOffers(); @Override Offer getSelectedOffer(); @Override Offer getValidatedOffer(); @Override FeatureState getFeatureState(); @Override int countOpenBugs(); @Override PageIterable<Bug> getOpenBugs(); @Override PageIterable<Bug> getClosedBugs(); @Override ReturnType accept(final ModelClassVisitor<ReturnType> visitor); @Override String getTitle(final Locale l); @Override String getDescription(final Locale l); static final int PROGRESSION_PERCENT; } | @Test public void testCancelDevelopment() throws NotEnoughMoneyException, UnauthorizedOperationException { final Feature feature = createFeatureAddOffer120AddContribution120BeginDev(); Mockit.setUpMock(DaoFeature.class, new MockFeatureValidationTimeOut()); try { feature.cancelDevelopment(); fail(); } catch (final UnauthorizedOperationException e) { assertTrue(true); } try { AuthToken.authenticate(memberYo); feature.cancelDevelopment(); fail(); } catch (final UnauthorizedOperationException e) { assertTrue(true); } AuthToken.authenticate(memberTom); assertEquals(120, feature.getContribution().intValue()); feature.cancelDevelopment(); assertEquals(0, feature.getContribution().intValue()); assertEquals(FeatureState.DISCARDED, feature.getFeatureState()); Mockit.tearDownMocks(); } |
DaoVersionedString extends DaoIdentifiable { public void addVersion(final String content, final DaoMember author) { this.currentVersion = new DaoStringVersion(content, this, author); versions.add(currentVersion); } private DaoVersionedString(final String content, final DaoMember author); protected DaoVersionedString(); static DaoVersionedString createAndPersist(final String content, final DaoMember author); void addVersion(final String content, final DaoMember author); void useVersion(final DaoStringVersion version); String getContent(); PageIterable<DaoStringVersion> getVersions(); DaoStringVersion getCurrentVersion(); void compact(); @Override ReturnType accept(final DataClassVisitor<ReturnType> visitor); @Override int hashCode(); @Override boolean equals(final Object obj); } | @Test public final void testAddVersion() { final DaoVersionedString str = DaoVersionedString.createAndPersist("plop", fred); str.addVersion("plip", tom); assertEquals(str.getContent(), "plip"); assertEquals(str.getCurrentVersion().getAuthor(), tom); } |
Actor extends Identifiable<T> { public final String getLogin() { return getDao().getLogin(); } protected Actor(final T id); static Actor<?> getActorFromDao(final DaoActor dao); final void setLogin(final String login); final String getLogin(); final Date getDateCreation(); final InternalAccount getInternalAccount(); final ExternalAccount getExternalAccount(); final PageIterable<BankTransaction> getBankTransactions(); PageIterable<Contribution> getContributions(); Contact getContact(); Contact getContactUnprotected(); abstract PageIterable<Contribution> doGetContributions(); PageIterable<MoneyWithdrawal> getMoneyWithdrawals(); abstract PageIterable<MoneyWithdrawal> doGetMoneyWithdrawals(); abstract String getDisplayName(); abstract Image getAvatar(); FollowList getFollowedContent(); final boolean canAccessDateCreation(); final boolean canGetInternalAccount(); final boolean canGetExternalAccount(); final boolean canGetBankTransactionAccount(); final boolean canGetContributions(); final boolean isTeam(); boolean hasInvoicingContact(); boolean hasInvoicingContact(final boolean all); } | @Test public final void testGetLogin() { final Member tom = Member.create(db.getTom()); assertEquals(tom.getLogin(), db.getTom().getLogin()); final Team publicTeam = Team.create(db.getPublicGroup()); assertEquals(publicTeam.getLogin(), db.getPublicGroup().getLogin()); } |
Actor extends Identifiable<T> { public final Date getDateCreation() throws UnauthorizedPublicReadOnlyAccessException { tryAccess(new RgtActor.DateCreation(), Action.READ); return getDao().getDateCreation(); } protected Actor(final T id); static Actor<?> getActorFromDao(final DaoActor dao); final void setLogin(final String login); final String getLogin(); final Date getDateCreation(); final InternalAccount getInternalAccount(); final ExternalAccount getExternalAccount(); final PageIterable<BankTransaction> getBankTransactions(); PageIterable<Contribution> getContributions(); Contact getContact(); Contact getContactUnprotected(); abstract PageIterable<Contribution> doGetContributions(); PageIterable<MoneyWithdrawal> getMoneyWithdrawals(); abstract PageIterable<MoneyWithdrawal> doGetMoneyWithdrawals(); abstract String getDisplayName(); abstract Image getAvatar(); FollowList getFollowedContent(); final boolean canAccessDateCreation(); final boolean canGetInternalAccount(); final boolean canGetExternalAccount(); final boolean canGetBankTransactionAccount(); final boolean canGetContributions(); final boolean isTeam(); boolean hasInvoicingContact(); boolean hasInvoicingContact(final boolean all); } | @Test public final void testGetDateCreation() { final Member tom = Member.create(db.getTom()); try { assertEquals(tom.getDateCreation().getTime(), db.getTom().getDateCreation().getTime()); } catch (final UnauthorizedPublicReadOnlyAccessException e) { fail(); } final Team publicTeam = Team.create(db.getPublicGroup()); try { assertEquals(publicTeam.getDateCreation(), db.getPublicGroup().getDateCreation()); } catch (final UnauthorizedPublicReadOnlyAccessException e) { fail(); } } |
Actor extends Identifiable<T> { public final InternalAccount getInternalAccount() throws UnauthorizedBankDataAccessException { tryAccess(new RgtActor.InternalAccount(), Action.READ); return InternalAccount.create(getDao().getInternalAccount()); } protected Actor(final T id); static Actor<?> getActorFromDao(final DaoActor dao); final void setLogin(final String login); final String getLogin(); final Date getDateCreation(); final InternalAccount getInternalAccount(); final ExternalAccount getExternalAccount(); final PageIterable<BankTransaction> getBankTransactions(); PageIterable<Contribution> getContributions(); Contact getContact(); Contact getContactUnprotected(); abstract PageIterable<Contribution> doGetContributions(); PageIterable<MoneyWithdrawal> getMoneyWithdrawals(); abstract PageIterable<MoneyWithdrawal> doGetMoneyWithdrawals(); abstract String getDisplayName(); abstract Image getAvatar(); FollowList getFollowedContent(); final boolean canAccessDateCreation(); final boolean canGetInternalAccount(); final boolean canGetExternalAccount(); final boolean canGetBankTransactionAccount(); final boolean canGetContributions(); final boolean isTeam(); boolean hasInvoicingContact(); boolean hasInvoicingContact(final boolean all); } | @Test public final void testGetInternalAccount() { final Member tom = Member.create(db.getTom()); try { AuthToken.unAuthenticate(); tom.getInternalAccount(); fail(); } catch (final UnauthorizedOperationException e1) { assertTrue(true); } try { AuthToken.authenticate(memeberFred); tom.getInternalAccount(); fail(); } catch (final UnauthorizedOperationException e1) { assertTrue(true); } try { AuthToken.authenticate(loser); tom.getInternalAccount(); fail(); } catch (final UnauthorizedOperationException e1) { assertTrue(true); } try { AuthToken.authenticate(memberTom); assertEquals(tom.getInternalAccount().getId(), db.getTom().getInternalAccount().getId()); } catch (final UnauthorizedOperationException e) { fail(); } final Team publicTeam = Team.create(db.getPublicGroup()); try { AuthToken.unAuthenticate(); publicTeam.getInternalAccount(); fail(); } catch (final UnauthorizedOperationException e1) { assertTrue(true); } try { AuthToken.authenticate(memberYo); publicTeam.getInternalAccount(); assertTrue(true); } catch (final UnauthorizedOperationException e1) { fail(); } try { AuthToken.authenticate(loser); publicTeam.getInternalAccount(); fail(); } catch (final UnauthorizedOperationException e1) { assertTrue(true); } try { AuthToken.authenticate(memeberFred); publicTeam.getInternalAccount(); fail(); } catch (final UnauthorizedOperationException e1) { assertTrue(true); } try { AuthToken.authenticate(memberTom); assertEquals(publicTeam.getInternalAccount().getId(), db.getPublicGroup().getInternalAccount().getId()); } catch (final UnauthorizedOperationException e) { fail(); } } |
Actor extends Identifiable<T> { public final ExternalAccount getExternalAccount() throws UnauthorizedBankDataAccessException { tryAccess(new RgtActor.ExternalAccount(), Action.READ); return ExternalAccount.create(getDao().getExternalAccount()); } protected Actor(final T id); static Actor<?> getActorFromDao(final DaoActor dao); final void setLogin(final String login); final String getLogin(); final Date getDateCreation(); final InternalAccount getInternalAccount(); final ExternalAccount getExternalAccount(); final PageIterable<BankTransaction> getBankTransactions(); PageIterable<Contribution> getContributions(); Contact getContact(); Contact getContactUnprotected(); abstract PageIterable<Contribution> doGetContributions(); PageIterable<MoneyWithdrawal> getMoneyWithdrawals(); abstract PageIterable<MoneyWithdrawal> doGetMoneyWithdrawals(); abstract String getDisplayName(); abstract Image getAvatar(); FollowList getFollowedContent(); final boolean canAccessDateCreation(); final boolean canGetInternalAccount(); final boolean canGetExternalAccount(); final boolean canGetBankTransactionAccount(); final boolean canGetContributions(); final boolean isTeam(); boolean hasInvoicingContact(); boolean hasInvoicingContact(final boolean all); } | @Test public final void testGetExternalAccount() { final Member tom = Member.create(db.getTom()); try { AuthToken.unAuthenticate(); tom.getExternalAccount(); fail(); } catch (final UnauthorizedOperationException e1) { assertTrue(true); } try { AuthToken.authenticate(memeberFred); tom.getExternalAccount(); fail(); } catch (final UnauthorizedOperationException e1) { assertTrue(true); } try { AuthToken.authenticate(loser); tom.getExternalAccount(); fail(); } catch (final UnauthorizedOperationException e1) { assertTrue(true); } try { AuthToken.authenticate(memberTom); assertEquals(tom.getExternalAccount().getId(), db.getTom().getExternalAccount().getId()); } catch (final UnauthorizedOperationException e) { fail(); } final Team publicTeam = Team.create(db.getPublicGroup()); try { AuthToken.unAuthenticate(); publicTeam.getExternalAccount(); fail(); } catch (final UnauthorizedOperationException e1) { assertTrue(true); } try { AuthToken.authenticate(memberYo); publicTeam.getExternalAccount(); assertTrue(true); } catch (final UnauthorizedOperationException e1) { fail(); } try { AuthToken.authenticate(loser); publicTeam.getExternalAccount(); fail(); } catch (final UnauthorizedOperationException e1) { assertTrue(true); } try { AuthToken.authenticate(memeberFred); publicTeam.getExternalAccount(); fail(); } catch (final UnauthorizedOperationException e1) { assertTrue(true); } try { AuthToken.authenticate(memberTom); assertEquals(publicTeam.getExternalAccount().getId(), db.getPublicGroup().getExternalAccount().getId()); } catch (final UnauthorizedOperationException e) { fail(); } } |
Actor extends Identifiable<T> { public final PageIterable<BankTransaction> getBankTransactions() throws UnauthorizedBankDataAccessException { tryAccess(new RgtActor.BankTransaction(), Action.READ); return new BankTransactionList(getDao().getBankTransactions()); } protected Actor(final T id); static Actor<?> getActorFromDao(final DaoActor dao); final void setLogin(final String login); final String getLogin(); final Date getDateCreation(); final InternalAccount getInternalAccount(); final ExternalAccount getExternalAccount(); final PageIterable<BankTransaction> getBankTransactions(); PageIterable<Contribution> getContributions(); Contact getContact(); Contact getContactUnprotected(); abstract PageIterable<Contribution> doGetContributions(); PageIterable<MoneyWithdrawal> getMoneyWithdrawals(); abstract PageIterable<MoneyWithdrawal> doGetMoneyWithdrawals(); abstract String getDisplayName(); abstract Image getAvatar(); FollowList getFollowedContent(); final boolean canAccessDateCreation(); final boolean canGetInternalAccount(); final boolean canGetExternalAccount(); final boolean canGetBankTransactionAccount(); final boolean canGetContributions(); final boolean isTeam(); boolean hasInvoicingContact(); boolean hasInvoicingContact(final boolean all); } | @Test public final void testGetBankTransactions() { final Member tom = Member.create(db.getTom()); try { AuthToken.unAuthenticate(); tom.getBankTransactions(); fail(); } catch (final UnauthorizedOperationException e1) { assertTrue(true); } try { AuthToken.authenticate(memeberFred); tom.getBankTransactions(); fail(); } catch (final UnauthorizedOperationException e1) { assertTrue(true); } try { AuthToken.authenticate(loser); tom.getBankTransactions(); fail(); } catch (final UnauthorizedOperationException e1) { assertTrue(true); } try { AuthToken.authenticate(memberTom); assertEquals(tom.getBankTransactions().size(), db.getTom().getBankTransactions().size()); } catch (final UnauthorizedOperationException e) { fail(); } final Team publicTeam = Team.create(db.getPublicGroup()); try { AuthToken.unAuthenticate(); publicTeam.getBankTransactions(); fail(); } catch (final UnauthorizedOperationException e1) { assertTrue(true); } try { AuthToken.authenticate(memberYo); publicTeam.getBankTransactions(); assertTrue(true); } catch (final UnauthorizedOperationException e1) { fail(); } try { AuthToken.authenticate(loser); publicTeam.getBankTransactions(); fail(); } catch (final UnauthorizedOperationException e1) { assertTrue(true); } try { AuthToken.authenticate(memeberFred); publicTeam.getBankTransactions(); fail(); } catch (final UnauthorizedOperationException e1) { assertTrue(true); } try { AuthToken.authenticate(memberTom); assertEquals(publicTeam.getBankTransactions().size(), db.getPublicGroup().getBankTransactions().size()); } catch (final UnauthorizedOperationException e) { fail(); } } |
Actor extends Identifiable<T> { public PageIterable<Contribution> getContributions() { return doGetContributions(); } protected Actor(final T id); static Actor<?> getActorFromDao(final DaoActor dao); final void setLogin(final String login); final String getLogin(); final Date getDateCreation(); final InternalAccount getInternalAccount(); final ExternalAccount getExternalAccount(); final PageIterable<BankTransaction> getBankTransactions(); PageIterable<Contribution> getContributions(); Contact getContact(); Contact getContactUnprotected(); abstract PageIterable<Contribution> doGetContributions(); PageIterable<MoneyWithdrawal> getMoneyWithdrawals(); abstract PageIterable<MoneyWithdrawal> doGetMoneyWithdrawals(); abstract String getDisplayName(); abstract Image getAvatar(); FollowList getFollowedContent(); final boolean canAccessDateCreation(); final boolean canGetInternalAccount(); final boolean canGetExternalAccount(); final boolean canGetBankTransactionAccount(); final boolean canGetContributions(); final boolean isTeam(); boolean hasInvoicingContact(); boolean hasInvoicingContact(final boolean all); } | @Test public final void testGetContributions() { final Member tom = Member.create(db.getTom()); assertEquals(tom.getContributions().size(), db.getTom().getContributions(true).size()); final Team publicTeam = Team.create(db.getPublicGroup()); assertEquals(publicTeam.getContributions().size(), db.getPublicGroup().getContributions().size()); } |
Actor extends Identifiable<T> { public abstract String getDisplayName(); protected Actor(final T id); static Actor<?> getActorFromDao(final DaoActor dao); final void setLogin(final String login); final String getLogin(); final Date getDateCreation(); final InternalAccount getInternalAccount(); final ExternalAccount getExternalAccount(); final PageIterable<BankTransaction> getBankTransactions(); PageIterable<Contribution> getContributions(); Contact getContact(); Contact getContactUnprotected(); abstract PageIterable<Contribution> doGetContributions(); PageIterable<MoneyWithdrawal> getMoneyWithdrawals(); abstract PageIterable<MoneyWithdrawal> doGetMoneyWithdrawals(); abstract String getDisplayName(); abstract Image getAvatar(); FollowList getFollowedContent(); final boolean canAccessDateCreation(); final boolean canGetInternalAccount(); final boolean canGetExternalAccount(); final boolean canGetBankTransactionAccount(); final boolean canGetContributions(); final boolean isTeam(); boolean hasInvoicingContact(); boolean hasInvoicingContact(final boolean all); } | @Test public final void testGetDisplayName() { final Member tom = Member.create(db.getTom()); assertEquals(tom.getDisplayName(), db.getTom().getFullname()); } |
Actor extends Identifiable<T> { public final boolean canAccessDateCreation() { return canAccess(new RgtActor.DateCreation(), Action.READ); } protected Actor(final T id); static Actor<?> getActorFromDao(final DaoActor dao); final void setLogin(final String login); final String getLogin(); final Date getDateCreation(); final InternalAccount getInternalAccount(); final ExternalAccount getExternalAccount(); final PageIterable<BankTransaction> getBankTransactions(); PageIterable<Contribution> getContributions(); Contact getContact(); Contact getContactUnprotected(); abstract PageIterable<Contribution> doGetContributions(); PageIterable<MoneyWithdrawal> getMoneyWithdrawals(); abstract PageIterable<MoneyWithdrawal> doGetMoneyWithdrawals(); abstract String getDisplayName(); abstract Image getAvatar(); FollowList getFollowedContent(); final boolean canAccessDateCreation(); final boolean canGetInternalAccount(); final boolean canGetExternalAccount(); final boolean canGetBankTransactionAccount(); final boolean canGetContributions(); final boolean isTeam(); boolean hasInvoicingContact(); boolean hasInvoicingContact(final boolean all); } | @Test public final void testCanAccessDateCreation() { final Member tom = Member.create(db.getTom()); assertTrue(tom.canAccessDateCreation()); } |
Actor extends Identifiable<T> { public final boolean canGetInternalAccount() { return canAccess(new RgtActor.InternalAccount(), Action.READ); } protected Actor(final T id); static Actor<?> getActorFromDao(final DaoActor dao); final void setLogin(final String login); final String getLogin(); final Date getDateCreation(); final InternalAccount getInternalAccount(); final ExternalAccount getExternalAccount(); final PageIterable<BankTransaction> getBankTransactions(); PageIterable<Contribution> getContributions(); Contact getContact(); Contact getContactUnprotected(); abstract PageIterable<Contribution> doGetContributions(); PageIterable<MoneyWithdrawal> getMoneyWithdrawals(); abstract PageIterable<MoneyWithdrawal> doGetMoneyWithdrawals(); abstract String getDisplayName(); abstract Image getAvatar(); FollowList getFollowedContent(); final boolean canAccessDateCreation(); final boolean canGetInternalAccount(); final boolean canGetExternalAccount(); final boolean canGetBankTransactionAccount(); final boolean canGetContributions(); final boolean isTeam(); boolean hasInvoicingContact(); boolean hasInvoicingContact(final boolean all); } | @Test public final void testCanGetInternalAccount() { final Member tom = Member.create(db.getTom()); AuthToken.unAuthenticate(); assertFalse(tom.canGetInternalAccount()); AuthToken.authenticate(memeberFred); assertFalse(tom.canGetInternalAccount()); AuthToken.authenticate(memberTom); assertTrue(tom.canGetInternalAccount()); final Team publicTeam = Team.create(db.getPublicGroup()); AuthToken.unAuthenticate(); assertFalse(publicTeam.canGetInternalAccount()); AuthToken.authenticate(memeberFred); assertFalse(publicTeam.canGetInternalAccount()); AuthToken.authenticate(loser); assertFalse(publicTeam.canGetInternalAccount()); AuthToken.authenticate(memberTom); assertTrue(publicTeam.canGetInternalAccount()); AuthToken.authenticate(memberYo); assertTrue(publicTeam.canGetInternalAccount()); } |
Actor extends Identifiable<T> { public final boolean canGetExternalAccount() { return canAccess(new RgtActor.ExternalAccount(), Action.READ); } protected Actor(final T id); static Actor<?> getActorFromDao(final DaoActor dao); final void setLogin(final String login); final String getLogin(); final Date getDateCreation(); final InternalAccount getInternalAccount(); final ExternalAccount getExternalAccount(); final PageIterable<BankTransaction> getBankTransactions(); PageIterable<Contribution> getContributions(); Contact getContact(); Contact getContactUnprotected(); abstract PageIterable<Contribution> doGetContributions(); PageIterable<MoneyWithdrawal> getMoneyWithdrawals(); abstract PageIterable<MoneyWithdrawal> doGetMoneyWithdrawals(); abstract String getDisplayName(); abstract Image getAvatar(); FollowList getFollowedContent(); final boolean canAccessDateCreation(); final boolean canGetInternalAccount(); final boolean canGetExternalAccount(); final boolean canGetBankTransactionAccount(); final boolean canGetContributions(); final boolean isTeam(); boolean hasInvoicingContact(); boolean hasInvoicingContact(final boolean all); } | @Test public final void testCanGetExternalAccount() { final Member tom = Member.create(db.getTom()); AuthToken.unAuthenticate(); assertFalse(tom.canGetExternalAccount()); AuthToken.authenticate(memeberFred); assertFalse(tom.canGetExternalAccount()); AuthToken.authenticate(memberTom); assertTrue(tom.canGetExternalAccount()); final Team publicTeam = Team.create(db.getPublicGroup()); AuthToken.unAuthenticate(); assertFalse(publicTeam.canGetExternalAccount()); AuthToken.authenticate(memeberFred); assertFalse(publicTeam.canGetExternalAccount()); AuthToken.authenticate(loser); assertFalse(publicTeam.canGetExternalAccount()); AuthToken.authenticate(memberTom); assertTrue(publicTeam.canGetExternalAccount()); AuthToken.authenticate(memberYo); assertTrue(publicTeam.canGetExternalAccount()); } |
DaoVersionedString extends DaoIdentifiable { public void compact() { String previousContent = null; for (final DaoStringVersion version : versions) { if (!version.isCompacted()) { final String savedContent = version.getContent(); if (previousContent != null) { version.compact(previousContent); } previousContent = savedContent; } else { if (previousContent == null) { throw new BadProgrammerException("First string version should never be compacted !"); } previousContent = version.getContentUncompacted(previousContent); } } } private DaoVersionedString(final String content, final DaoMember author); protected DaoVersionedString(); static DaoVersionedString createAndPersist(final String content, final DaoMember author); void addVersion(final String content, final DaoMember author); void useVersion(final DaoStringVersion version); String getContent(); PageIterable<DaoStringVersion> getVersions(); DaoStringVersion getCurrentVersion(); void compact(); @Override ReturnType accept(final DataClassVisitor<ReturnType> visitor); @Override int hashCode(); @Override boolean equals(final Object obj); } | @Test public final void testCompact() { final DaoVersionedString str = DaoVersionedString.createAndPersist("plop", fred); str.addVersion("plop\nplip\n", fred); str.addVersion("plop\nplup\n", fred); str.addVersion("plop\nplup\nplop\ncoucou\nHello\n", fred); str.addVersion("plop\nplup\nplop\ncoucou\n", fred); str.compact(); Iterator<DaoStringVersion> iterator = str.getVersions().iterator(); assertEquals(iterator.next().getContent(), "plop"); assertEquals(iterator.next().getContentUncompacted("plop"), "plop\nplip\n"); assertEquals(iterator.next().getContentUncompacted("plop\nplip\n"), "plop\nplup\n"); assertEquals(iterator.next().getContentUncompacted("plop\nplup\n"), "plop\nplup\nplop\ncoucou\nHello\n"); assertEquals(iterator.next().getContentUncompacted("plop\nplup\nplop\ncoucou\nHello\n"), "plop\nplup\nplop\ncoucou\n"); iterator = str.getVersions().iterator(); assertFalse(iterator.next().isCompacted()); assertTrue(iterator.next().isCompacted()); assertTrue(iterator.next().isCompacted()); assertTrue(iterator.next().isCompacted()); assertTrue(iterator.next().isCompacted()); } |
Actor extends Identifiable<T> { public final boolean canGetBankTransactionAccount() { return canAccess(new RgtActor.BankTransaction(), Action.READ); } protected Actor(final T id); static Actor<?> getActorFromDao(final DaoActor dao); final void setLogin(final String login); final String getLogin(); final Date getDateCreation(); final InternalAccount getInternalAccount(); final ExternalAccount getExternalAccount(); final PageIterable<BankTransaction> getBankTransactions(); PageIterable<Contribution> getContributions(); Contact getContact(); Contact getContactUnprotected(); abstract PageIterable<Contribution> doGetContributions(); PageIterable<MoneyWithdrawal> getMoneyWithdrawals(); abstract PageIterable<MoneyWithdrawal> doGetMoneyWithdrawals(); abstract String getDisplayName(); abstract Image getAvatar(); FollowList getFollowedContent(); final boolean canAccessDateCreation(); final boolean canGetInternalAccount(); final boolean canGetExternalAccount(); final boolean canGetBankTransactionAccount(); final boolean canGetContributions(); final boolean isTeam(); boolean hasInvoicingContact(); boolean hasInvoicingContact(final boolean all); } | @Test public final void testCanGetBankTransactionAccount() { final Member tom = Member.create(db.getTom()); AuthToken.unAuthenticate(); assertFalse(tom.canGetBankTransactionAccount()); AuthToken.authenticate(memeberFred); assertFalse(tom.canGetBankTransactionAccount()); AuthToken.authenticate(memberTom); assertTrue(tom.canGetBankTransactionAccount()); final Team publicTeam = Team.create(db.getPublicGroup()); AuthToken.unAuthenticate(); assertFalse(publicTeam.canGetBankTransactionAccount()); AuthToken.authenticate(memeberFred); assertFalse(publicTeam.canGetBankTransactionAccount()); AuthToken.authenticate(loser); assertFalse(publicTeam.canGetBankTransactionAccount()); AuthToken.authenticate(memberTom); assertTrue(publicTeam.canGetBankTransactionAccount()); AuthToken.authenticate(memberYo); assertTrue(publicTeam.canGetBankTransactionAccount()); } |
Actor extends Identifiable<T> { public final boolean canGetContributions() { return canAccess(new RgtActor.Contribution(), Action.READ); } protected Actor(final T id); static Actor<?> getActorFromDao(final DaoActor dao); final void setLogin(final String login); final String getLogin(); final Date getDateCreation(); final InternalAccount getInternalAccount(); final ExternalAccount getExternalAccount(); final PageIterable<BankTransaction> getBankTransactions(); PageIterable<Contribution> getContributions(); Contact getContact(); Contact getContactUnprotected(); abstract PageIterable<Contribution> doGetContributions(); PageIterable<MoneyWithdrawal> getMoneyWithdrawals(); abstract PageIterable<MoneyWithdrawal> doGetMoneyWithdrawals(); abstract String getDisplayName(); abstract Image getAvatar(); FollowList getFollowedContent(); final boolean canAccessDateCreation(); final boolean canGetInternalAccount(); final boolean canGetExternalAccount(); final boolean canGetBankTransactionAccount(); final boolean canGetContributions(); final boolean isTeam(); boolean hasInvoicingContact(); boolean hasInvoicingContact(final boolean all); } | @Test public final void testCanGetContributions() { final Member tom = Member.create(db.getTom()); AuthToken.unAuthenticate(); assertTrue(tom.canGetContributions()); final Team publicTeam = Team.create(db.getPublicGroup()); AuthToken.unAuthenticate(); assertTrue(publicTeam.canGetContributions()); } |
BankTransaction extends Identifiable<DaoBankTransaction> { public final boolean canGetMessage() { return canAccess(new RgtBankTransaction.Message(), Action.READ); } BankTransaction(final String message,
final String token,
final Actor<?> author,
final BigDecimal value,
final BigDecimal valuePayed,
final String orderReference); BankTransaction(final Actor<?> author, final BigDecimal value, final BigDecimal valuePayed, final String orderReference); private BankTransaction(final DaoBankTransaction dao); static BigDecimal computateAmountToPay(final BigDecimal amount); @SuppressWarnings("synthetic-access") static BankTransaction create(final DaoBankTransaction dao); static BankTransaction getByToken(final String token); BigDecimal getValuePaidUnprotected(); BigDecimal getValueUnprotected(); String getMessage(); BigDecimal getValuePaid(); BigDecimal getValue(); State getState(); State getStateUnprotected(); Date getCreationDate(); Date getModificationDate(); String getReference(); String getReferenceUnprotected(); Actor<?> getAuthor(); Invoice getInvoice(); final boolean canGetMessage(); final boolean canGetValuePaid(); final boolean canGetValue(); final boolean canGetState(); final boolean canGetCreationDate(); final boolean canGetModificationDate(); final boolean canGetReference(); final boolean canGetAuthor(); @Override ReturnType accept(final ModelClassVisitor<ReturnType> visitor); static final BigDecimal COMMISSION_VARIABLE_RATE; static final BigDecimal COMMISSION_FIX_RATE; } | @Test public final void testCanGetMessage() { final BankTransaction bankTransaction = BankTransaction.create(db.getYoBankTransaction()); AuthToken.authenticate(memeberFred); assertFalse(bankTransaction.canGetMessage()); AuthToken.authenticate(memberYo); assertTrue(bankTransaction.canGetMessage()); final BankTransaction groupBankTransaction = BankTransaction.create(db.getPublicGroupBankTransaction()); AuthToken.authenticate(memeberFred); assertFalse(groupBankTransaction.canGetMessage()); AuthToken.authenticate(loser); assertFalse(groupBankTransaction.canGetMessage()); AuthToken.authenticate(memberYo); assertTrue(groupBankTransaction.canGetMessage()); AuthToken.authenticate(memberTom); assertTrue(groupBankTransaction.canGetMessage()); } |
BankTransaction extends Identifiable<DaoBankTransaction> { public final boolean canGetValuePaid() { return canAccess(new RgtBankTransaction.ValuePaid(), Action.READ); } BankTransaction(final String message,
final String token,
final Actor<?> author,
final BigDecimal value,
final BigDecimal valuePayed,
final String orderReference); BankTransaction(final Actor<?> author, final BigDecimal value, final BigDecimal valuePayed, final String orderReference); private BankTransaction(final DaoBankTransaction dao); static BigDecimal computateAmountToPay(final BigDecimal amount); @SuppressWarnings("synthetic-access") static BankTransaction create(final DaoBankTransaction dao); static BankTransaction getByToken(final String token); BigDecimal getValuePaidUnprotected(); BigDecimal getValueUnprotected(); String getMessage(); BigDecimal getValuePaid(); BigDecimal getValue(); State getState(); State getStateUnprotected(); Date getCreationDate(); Date getModificationDate(); String getReference(); String getReferenceUnprotected(); Actor<?> getAuthor(); Invoice getInvoice(); final boolean canGetMessage(); final boolean canGetValuePaid(); final boolean canGetValue(); final boolean canGetState(); final boolean canGetCreationDate(); final boolean canGetModificationDate(); final boolean canGetReference(); final boolean canGetAuthor(); @Override ReturnType accept(final ModelClassVisitor<ReturnType> visitor); static final BigDecimal COMMISSION_VARIABLE_RATE; static final BigDecimal COMMISSION_FIX_RATE; } | @Test public final void testCanGetValuePaid() { final BankTransaction bankTransaction = BankTransaction.create(db.getYoBankTransaction()); AuthToken.authenticate(memeberFred); assertFalse(bankTransaction.canGetValuePaid()); AuthToken.authenticate(memberYo); assertTrue(bankTransaction.canGetValuePaid()); final BankTransaction groupBankTransaction = BankTransaction.create(db.getPublicGroupBankTransaction()); AuthToken.authenticate(memeberFred); assertFalse(groupBankTransaction.canGetValuePaid()); AuthToken.authenticate(loser); assertFalse(groupBankTransaction.canGetValuePaid()); AuthToken.authenticate(memberYo); assertTrue(groupBankTransaction.canGetValuePaid()); AuthToken.authenticate(memberTom); assertTrue(groupBankTransaction.canGetValuePaid()); } |
BankTransaction extends Identifiable<DaoBankTransaction> { public final boolean canGetValue() { return canAccess(new RgtBankTransaction.Value(), Action.READ); } BankTransaction(final String message,
final String token,
final Actor<?> author,
final BigDecimal value,
final BigDecimal valuePayed,
final String orderReference); BankTransaction(final Actor<?> author, final BigDecimal value, final BigDecimal valuePayed, final String orderReference); private BankTransaction(final DaoBankTransaction dao); static BigDecimal computateAmountToPay(final BigDecimal amount); @SuppressWarnings("synthetic-access") static BankTransaction create(final DaoBankTransaction dao); static BankTransaction getByToken(final String token); BigDecimal getValuePaidUnprotected(); BigDecimal getValueUnprotected(); String getMessage(); BigDecimal getValuePaid(); BigDecimal getValue(); State getState(); State getStateUnprotected(); Date getCreationDate(); Date getModificationDate(); String getReference(); String getReferenceUnprotected(); Actor<?> getAuthor(); Invoice getInvoice(); final boolean canGetMessage(); final boolean canGetValuePaid(); final boolean canGetValue(); final boolean canGetState(); final boolean canGetCreationDate(); final boolean canGetModificationDate(); final boolean canGetReference(); final boolean canGetAuthor(); @Override ReturnType accept(final ModelClassVisitor<ReturnType> visitor); static final BigDecimal COMMISSION_VARIABLE_RATE; static final BigDecimal COMMISSION_FIX_RATE; } | @Test public final void testCanGetValue() { final BankTransaction bankTransaction = BankTransaction.create(db.getYoBankTransaction()); AuthToken.authenticate(memeberFred); assertFalse(bankTransaction.canGetValue()); AuthToken.authenticate(memberYo); assertTrue(bankTransaction.canGetValue()); final BankTransaction groupBankTransaction = BankTransaction.create(db.getPublicGroupBankTransaction()); AuthToken.authenticate(memeberFred); assertFalse(groupBankTransaction.canGetValue()); AuthToken.authenticate(loser); assertFalse(groupBankTransaction.canGetValue()); AuthToken.authenticate(memberYo); assertTrue(groupBankTransaction.canGetValue()); AuthToken.authenticate(memberTom); assertTrue(groupBankTransaction.canGetValue()); } |
BankTransaction extends Identifiable<DaoBankTransaction> { public final boolean canGetState() { return canAccess(new RgtBankTransaction.State(), Action.READ); } BankTransaction(final String message,
final String token,
final Actor<?> author,
final BigDecimal value,
final BigDecimal valuePayed,
final String orderReference); BankTransaction(final Actor<?> author, final BigDecimal value, final BigDecimal valuePayed, final String orderReference); private BankTransaction(final DaoBankTransaction dao); static BigDecimal computateAmountToPay(final BigDecimal amount); @SuppressWarnings("synthetic-access") static BankTransaction create(final DaoBankTransaction dao); static BankTransaction getByToken(final String token); BigDecimal getValuePaidUnprotected(); BigDecimal getValueUnprotected(); String getMessage(); BigDecimal getValuePaid(); BigDecimal getValue(); State getState(); State getStateUnprotected(); Date getCreationDate(); Date getModificationDate(); String getReference(); String getReferenceUnprotected(); Actor<?> getAuthor(); Invoice getInvoice(); final boolean canGetMessage(); final boolean canGetValuePaid(); final boolean canGetValue(); final boolean canGetState(); final boolean canGetCreationDate(); final boolean canGetModificationDate(); final boolean canGetReference(); final boolean canGetAuthor(); @Override ReturnType accept(final ModelClassVisitor<ReturnType> visitor); static final BigDecimal COMMISSION_VARIABLE_RATE; static final BigDecimal COMMISSION_FIX_RATE; } | @Test public final void testCanGetState() { final BankTransaction bankTransaction = BankTransaction.create(db.getYoBankTransaction()); AuthToken.authenticate(memeberFred); assertFalse(bankTransaction.canGetState()); AuthToken.authenticate(memberYo); assertTrue(bankTransaction.canGetState()); final BankTransaction groupBankTransaction = BankTransaction.create(db.getPublicGroupBankTransaction()); AuthToken.authenticate(memeberFred); assertFalse(groupBankTransaction.canGetState()); AuthToken.authenticate(loser); assertFalse(groupBankTransaction.canGetState()); AuthToken.authenticate(memberYo); assertTrue(groupBankTransaction.canGetState()); AuthToken.authenticate(memberTom); assertTrue(groupBankTransaction.canGetState()); } |
BankTransaction extends Identifiable<DaoBankTransaction> { public final boolean canGetCreationDate() { return canAccess(new RgtBankTransaction.CreationDate(), Action.READ); } BankTransaction(final String message,
final String token,
final Actor<?> author,
final BigDecimal value,
final BigDecimal valuePayed,
final String orderReference); BankTransaction(final Actor<?> author, final BigDecimal value, final BigDecimal valuePayed, final String orderReference); private BankTransaction(final DaoBankTransaction dao); static BigDecimal computateAmountToPay(final BigDecimal amount); @SuppressWarnings("synthetic-access") static BankTransaction create(final DaoBankTransaction dao); static BankTransaction getByToken(final String token); BigDecimal getValuePaidUnprotected(); BigDecimal getValueUnprotected(); String getMessage(); BigDecimal getValuePaid(); BigDecimal getValue(); State getState(); State getStateUnprotected(); Date getCreationDate(); Date getModificationDate(); String getReference(); String getReferenceUnprotected(); Actor<?> getAuthor(); Invoice getInvoice(); final boolean canGetMessage(); final boolean canGetValuePaid(); final boolean canGetValue(); final boolean canGetState(); final boolean canGetCreationDate(); final boolean canGetModificationDate(); final boolean canGetReference(); final boolean canGetAuthor(); @Override ReturnType accept(final ModelClassVisitor<ReturnType> visitor); static final BigDecimal COMMISSION_VARIABLE_RATE; static final BigDecimal COMMISSION_FIX_RATE; } | @Test public final void testCanGetCreationDate() { final BankTransaction bankTransaction = BankTransaction.create(db.getYoBankTransaction()); AuthToken.authenticate(memeberFred); assertFalse(bankTransaction.canGetCreationDate()); AuthToken.authenticate(memberYo); assertTrue(bankTransaction.canGetCreationDate()); final BankTransaction groupBankTransaction = BankTransaction.create(db.getPublicGroupBankTransaction()); AuthToken.authenticate(memeberFred); assertFalse(groupBankTransaction.canGetCreationDate()); AuthToken.authenticate(loser); assertFalse(groupBankTransaction.canGetCreationDate()); AuthToken.authenticate(memberYo); assertTrue(groupBankTransaction.canGetCreationDate()); AuthToken.authenticate(memberTom); assertTrue(groupBankTransaction.canGetCreationDate()); } |
BankTransaction extends Identifiable<DaoBankTransaction> { public final boolean canGetModificationDate() { return canAccess(new RgtBankTransaction.ModificationDate(), Action.READ); } BankTransaction(final String message,
final String token,
final Actor<?> author,
final BigDecimal value,
final BigDecimal valuePayed,
final String orderReference); BankTransaction(final Actor<?> author, final BigDecimal value, final BigDecimal valuePayed, final String orderReference); private BankTransaction(final DaoBankTransaction dao); static BigDecimal computateAmountToPay(final BigDecimal amount); @SuppressWarnings("synthetic-access") static BankTransaction create(final DaoBankTransaction dao); static BankTransaction getByToken(final String token); BigDecimal getValuePaidUnprotected(); BigDecimal getValueUnprotected(); String getMessage(); BigDecimal getValuePaid(); BigDecimal getValue(); State getState(); State getStateUnprotected(); Date getCreationDate(); Date getModificationDate(); String getReference(); String getReferenceUnprotected(); Actor<?> getAuthor(); Invoice getInvoice(); final boolean canGetMessage(); final boolean canGetValuePaid(); final boolean canGetValue(); final boolean canGetState(); final boolean canGetCreationDate(); final boolean canGetModificationDate(); final boolean canGetReference(); final boolean canGetAuthor(); @Override ReturnType accept(final ModelClassVisitor<ReturnType> visitor); static final BigDecimal COMMISSION_VARIABLE_RATE; static final BigDecimal COMMISSION_FIX_RATE; } | @Test public final void testCanGetModificationDate() { final BankTransaction bankTransaction = BankTransaction.create(db.getYoBankTransaction()); AuthToken.authenticate(memeberFred); assertFalse(bankTransaction.canGetModificationDate()); AuthToken.authenticate(memberYo); assertTrue(bankTransaction.canGetModificationDate()); final BankTransaction groupBankTransaction = BankTransaction.create(db.getPublicGroupBankTransaction()); AuthToken.authenticate(memeberFred); assertFalse(groupBankTransaction.canGetModificationDate()); AuthToken.authenticate(loser); assertFalse(groupBankTransaction.canGetModificationDate()); AuthToken.authenticate(memberYo); assertTrue(groupBankTransaction.canGetModificationDate()); AuthToken.authenticate(memberTom); assertTrue(groupBankTransaction.canGetModificationDate()); } |
BankTransaction extends Identifiable<DaoBankTransaction> { public final boolean canGetReference() { return canAccess(new RgtBankTransaction.Reference(), Action.READ); } BankTransaction(final String message,
final String token,
final Actor<?> author,
final BigDecimal value,
final BigDecimal valuePayed,
final String orderReference); BankTransaction(final Actor<?> author, final BigDecimal value, final BigDecimal valuePayed, final String orderReference); private BankTransaction(final DaoBankTransaction dao); static BigDecimal computateAmountToPay(final BigDecimal amount); @SuppressWarnings("synthetic-access") static BankTransaction create(final DaoBankTransaction dao); static BankTransaction getByToken(final String token); BigDecimal getValuePaidUnprotected(); BigDecimal getValueUnprotected(); String getMessage(); BigDecimal getValuePaid(); BigDecimal getValue(); State getState(); State getStateUnprotected(); Date getCreationDate(); Date getModificationDate(); String getReference(); String getReferenceUnprotected(); Actor<?> getAuthor(); Invoice getInvoice(); final boolean canGetMessage(); final boolean canGetValuePaid(); final boolean canGetValue(); final boolean canGetState(); final boolean canGetCreationDate(); final boolean canGetModificationDate(); final boolean canGetReference(); final boolean canGetAuthor(); @Override ReturnType accept(final ModelClassVisitor<ReturnType> visitor); static final BigDecimal COMMISSION_VARIABLE_RATE; static final BigDecimal COMMISSION_FIX_RATE; } | @Test public final void testCanGetReference() { final BankTransaction bankTransaction = BankTransaction.create(db.getYoBankTransaction()); AuthToken.authenticate(memeberFred); assertFalse(bankTransaction.canGetReference()); AuthToken.authenticate(memberYo); assertTrue(bankTransaction.canGetReference()); final BankTransaction groupBankTransaction = BankTransaction.create(db.getPublicGroupBankTransaction()); AuthToken.authenticate(memeberFred); assertFalse(groupBankTransaction.canGetReference()); AuthToken.authenticate(loser); assertFalse(groupBankTransaction.canGetReference()); AuthToken.authenticate(memberYo); assertTrue(groupBankTransaction.canGetReference()); AuthToken.authenticate(memberTom); assertTrue(groupBankTransaction.canGetReference()); } |
BankTransaction extends Identifiable<DaoBankTransaction> { public final boolean canGetAuthor() { return canAccess(new RgtBankTransaction.Author(), Action.READ); } BankTransaction(final String message,
final String token,
final Actor<?> author,
final BigDecimal value,
final BigDecimal valuePayed,
final String orderReference); BankTransaction(final Actor<?> author, final BigDecimal value, final BigDecimal valuePayed, final String orderReference); private BankTransaction(final DaoBankTransaction dao); static BigDecimal computateAmountToPay(final BigDecimal amount); @SuppressWarnings("synthetic-access") static BankTransaction create(final DaoBankTransaction dao); static BankTransaction getByToken(final String token); BigDecimal getValuePaidUnprotected(); BigDecimal getValueUnprotected(); String getMessage(); BigDecimal getValuePaid(); BigDecimal getValue(); State getState(); State getStateUnprotected(); Date getCreationDate(); Date getModificationDate(); String getReference(); String getReferenceUnprotected(); Actor<?> getAuthor(); Invoice getInvoice(); final boolean canGetMessage(); final boolean canGetValuePaid(); final boolean canGetValue(); final boolean canGetState(); final boolean canGetCreationDate(); final boolean canGetModificationDate(); final boolean canGetReference(); final boolean canGetAuthor(); @Override ReturnType accept(final ModelClassVisitor<ReturnType> visitor); static final BigDecimal COMMISSION_VARIABLE_RATE; static final BigDecimal COMMISSION_FIX_RATE; } | @Test public final void testCanGetAuthor() { final BankTransaction bankTransaction = BankTransaction.create(db.getYoBankTransaction()); AuthToken.authenticate(memeberFred); assertFalse(bankTransaction.canGetAuthor()); AuthToken.authenticate(memberYo); assertTrue(bankTransaction.canGetAuthor()); final BankTransaction groupBankTransaction = BankTransaction.create(db.getPublicGroupBankTransaction()); AuthToken.authenticate(memeberFred); assertFalse(groupBankTransaction.canGetAuthor()); AuthToken.authenticate(loser); assertFalse(groupBankTransaction.canGetAuthor()); AuthToken.authenticate(memberYo); assertTrue(groupBankTransaction.canGetAuthor()); AuthToken.authenticate(memberTom); assertTrue(groupBankTransaction.canGetAuthor()); } |
DaoDescription extends DaoIdentifiable { public static DaoDescription createAndPersist(final DaoMember member, final DaoTeam team, final Language language, final String title, final String description) { final Session session = SessionManager.getSessionFactory().getCurrentSession(); if (member == null || language == null || title == null || title.isEmpty() || description == null || description.isEmpty()) { throw new NonOptionalParameterException(); } final DaoDescription descr = new DaoDescription(member, team, language, title, description); try { session.save(descr); } catch (final HibernateException e) { session.getTransaction().rollback(); SessionManager.getSessionFactory().getCurrentSession().beginTransaction(); throw e; } return descr; } private DaoDescription(final DaoMember member, final DaoTeam team, final Language language, final String title, final String description); protected DaoDescription(); static DaoDescription createAndPersist(final DaoMember member,
final DaoTeam team,
final Language language,
final String title,
final String description); void addTranslation(final DaoMember member, final DaoTeam team, final Language language, final String title, final String description); void setDefaultLanguage(final Language defaultLanguage); DaoTranslation getDefaultTranslation(); PageIterable<DaoTranslation> getTranslations(); DaoTranslation getTranslation(final Language language); Language getDefaultLanguage(); @Override ReturnType accept(final DataClassVisitor<ReturnType> visitor); @Override int hashCode(); @Override boolean equals(final Object obj); } | @Test public void testCreateAndPersist() { DaoDescription.createAndPersist(DaoMember.getByLogin(yo.getLogin()), null, Language.FR, "A title", "a text"); try { DaoDescription.createAndPersist(DaoMember.getByLogin(yo.getLogin()), null, Language.FR, "", "a text"); fail(); } catch (final NonOptionalParameterException e) { assertTrue(true); } try { DaoDescription.createAndPersist(DaoMember.getByLogin(yo.getLogin()), null, Language.FR, "A title", ""); fail(); } catch (final NonOptionalParameterException e) { assertTrue(true); } try { DaoDescription.createAndPersist(DaoMember.getByLogin(yo.getLogin()), null, Language.FR, "A title", null); fail(); } catch (final NonOptionalParameterException e) { assertTrue(true); } try { DaoDescription.createAndPersist(DaoMember.getByLogin(yo.getLogin()), null, Language.FR, null, "a text"); fail(); } catch (final NonOptionalParameterException e) { assertTrue(true); } try { DaoDescription.createAndPersist(DaoMember.getByLogin(yo.getLogin()), null, null, "A title", "a text"); fail(); } catch (final NonOptionalParameterException e) { assertTrue(true); } try { DaoDescription.createAndPersist(null, null, Language.FR, "A title", "a text"); fail(); } catch (final NonOptionalParameterException e) { assertTrue(true); } } |
Account extends Identifiable<T> { public final boolean canAccessTransaction() { return canAccess(new RgtAccount.Transaction(), Action.READ); } protected Account(final T id); final boolean canAccessTransaction(); final boolean canAccessAmount(); final boolean canAccessActor(); final boolean canAccessCreationDate(); final boolean canAccessLastModificationDate(); final Date getLastModificationDate(); final BigDecimal getAmount(); final PageIterable<Transaction> getTransactions(); final Actor<?> getActor(); final Date getCreationDate(); } | @Test public void testCanAccessTransaction() { final InternalAccount tomAccount = InternalAccount.create(db.getTom().getInternalAccount()); AuthToken.unAuthenticate(); assertFalse(tomAccount.canAccessTransaction()); AuthToken.authenticate(memberTom); assertTrue(tomAccount.canAccessTransaction()); AuthToken.authenticate(loser); assertFalse(tomAccount.canAccessTransaction()); final InternalAccount publicGroupAccount = InternalAccount.create(db.getPublicGroup().getInternalAccount()); AuthToken.unAuthenticate(); assertFalse(publicGroupAccount.canAccessTransaction()); AuthToken.authenticate(memberTom); assertTrue(publicGroupAccount.canAccessTransaction()); AuthToken.authenticate(memberYo); assertTrue(publicGroupAccount.canAccessTransaction()); AuthToken.authenticate(memeberFred); assertFalse(publicGroupAccount.canAccessTransaction()); AuthToken.authenticate(loser); assertFalse(publicGroupAccount.canAccessTransaction()); } |
Account extends Identifiable<T> { public final boolean canAccessAmount() { return canAccess(new RgtAccount.Amount(), Action.READ); } protected Account(final T id); final boolean canAccessTransaction(); final boolean canAccessAmount(); final boolean canAccessActor(); final boolean canAccessCreationDate(); final boolean canAccessLastModificationDate(); final Date getLastModificationDate(); final BigDecimal getAmount(); final PageIterable<Transaction> getTransactions(); final Actor<?> getActor(); final Date getCreationDate(); } | @Test public void testCanAccessAmount() { final InternalAccount tomAccount = InternalAccount.create(db.getTom().getInternalAccount()); AuthToken.unAuthenticate(); assertFalse(tomAccount.canAccessAmount()); AuthToken.authenticate(memberTom); assertTrue(tomAccount.canAccessAmount()); AuthToken.authenticate(loser); assertFalse(tomAccount.canAccessAmount()); final InternalAccount publicGroupAccount = InternalAccount.create(db.getPublicGroup().getInternalAccount()); AuthToken.unAuthenticate(); assertFalse(publicGroupAccount.canAccessAmount()); AuthToken.authenticate(memberTom); assertTrue(publicGroupAccount.canAccessAmount()); AuthToken.authenticate(memberYo); assertTrue(publicGroupAccount.canAccessAmount()); AuthToken.authenticate(memeberFred); assertFalse(publicGroupAccount.canAccessAmount()); AuthToken.authenticate(loser); assertFalse(publicGroupAccount.canAccessAmount()); } |
Account extends Identifiable<T> { public final boolean canAccessActor() { return canAccess(new RgtAccount.Actor(), Action.READ); } protected Account(final T id); final boolean canAccessTransaction(); final boolean canAccessAmount(); final boolean canAccessActor(); final boolean canAccessCreationDate(); final boolean canAccessLastModificationDate(); final Date getLastModificationDate(); final BigDecimal getAmount(); final PageIterable<Transaction> getTransactions(); final Actor<?> getActor(); final Date getCreationDate(); } | @Test public void testCanAccessActor() { final InternalAccount tomAccount = InternalAccount.create(db.getTom().getInternalAccount()); AuthToken.unAuthenticate(); assertFalse(tomAccount.canAccessActor()); AuthToken.authenticate(memberTom); assertTrue(tomAccount.canAccessActor()); AuthToken.authenticate(loser); assertFalse(tomAccount.canAccessActor()); final InternalAccount publicGroupAccount = InternalAccount.create(db.getPublicGroup().getInternalAccount()); AuthToken.unAuthenticate(); assertFalse(publicGroupAccount.canAccessActor()); AuthToken.authenticate(memberTom); assertTrue(publicGroupAccount.canAccessActor()); AuthToken.authenticate(memberYo); assertTrue(publicGroupAccount.canAccessActor()); AuthToken.authenticate(memeberFred); assertFalse(publicGroupAccount.canAccessActor()); AuthToken.authenticate(loser); assertFalse(publicGroupAccount.canAccessActor()); } |
Account extends Identifiable<T> { public final boolean canAccessCreationDate() { return canAccess(new RgtAccount.CreationDate(), Action.READ); } protected Account(final T id); final boolean canAccessTransaction(); final boolean canAccessAmount(); final boolean canAccessActor(); final boolean canAccessCreationDate(); final boolean canAccessLastModificationDate(); final Date getLastModificationDate(); final BigDecimal getAmount(); final PageIterable<Transaction> getTransactions(); final Actor<?> getActor(); final Date getCreationDate(); } | @Test public void testCanAccessCreationDate() { final InternalAccount tomAccount = InternalAccount.create(db.getTom().getInternalAccount()); AuthToken.unAuthenticate(); assertFalse(tomAccount.canAccessCreationDate()); AuthToken.authenticate(memberTom); assertTrue(tomAccount.canAccessCreationDate()); AuthToken.authenticate(loser); assertFalse(tomAccount.canAccessCreationDate()); final InternalAccount publicGroupAccount = InternalAccount.create(db.getPublicGroup().getInternalAccount()); AuthToken.unAuthenticate(); assertFalse(publicGroupAccount.canAccessCreationDate()); AuthToken.authenticate(memberTom); assertTrue(publicGroupAccount.canAccessCreationDate()); AuthToken.authenticate(memberYo); assertTrue(publicGroupAccount.canAccessCreationDate()); AuthToken.authenticate(memeberFred); assertFalse(publicGroupAccount.canAccessCreationDate()); AuthToken.authenticate(loser); assertFalse(publicGroupAccount.canAccessCreationDate()); } |
Account extends Identifiable<T> { public final boolean canAccessLastModificationDate() { return canAccess(new RgtAccount.LastModificationDate(), Action.READ); } protected Account(final T id); final boolean canAccessTransaction(); final boolean canAccessAmount(); final boolean canAccessActor(); final boolean canAccessCreationDate(); final boolean canAccessLastModificationDate(); final Date getLastModificationDate(); final BigDecimal getAmount(); final PageIterable<Transaction> getTransactions(); final Actor<?> getActor(); final Date getCreationDate(); } | @Test public void testCanAccessLastModificationDate() { final InternalAccount tomAccount = InternalAccount.create(db.getTom().getInternalAccount()); AuthToken.unAuthenticate(); assertFalse(tomAccount.canAccessLastModificationDate()); AuthToken.authenticate(memberTom); assertTrue(tomAccount.canAccessLastModificationDate()); AuthToken.authenticate(loser); assertFalse(tomAccount.canAccessLastModificationDate()); final InternalAccount publicGroupAccount = InternalAccount.create(db.getPublicGroup().getInternalAccount()); AuthToken.unAuthenticate(); assertFalse(publicGroupAccount.canAccessLastModificationDate()); AuthToken.authenticate(memberTom); assertTrue(publicGroupAccount.canAccessLastModificationDate()); AuthToken.authenticate(memberYo); assertTrue(publicGroupAccount.canAccessLastModificationDate()); AuthToken.authenticate(memeberFred); assertFalse(publicGroupAccount.canAccessLastModificationDate()); AuthToken.authenticate(loser); assertFalse(publicGroupAccount.canAccessLastModificationDate()); } |
Account extends Identifiable<T> { public final Date getLastModificationDate() throws UnauthorizedOperationException { tryAccess(new RgtAccount.LastModificationDate(), Action.READ); return getDao().getLastModificationDate(); } protected Account(final T id); final boolean canAccessTransaction(); final boolean canAccessAmount(); final boolean canAccessActor(); final boolean canAccessCreationDate(); final boolean canAccessLastModificationDate(); final Date getLastModificationDate(); final BigDecimal getAmount(); final PageIterable<Transaction> getTransactions(); final Actor<?> getActor(); final Date getCreationDate(); } | @Test public void testGetLastModificationDate() { final InternalAccount tomAccount = InternalAccount.create(db.getTom().getInternalAccount()); try { AuthToken.unAuthenticate(); tomAccount.getLastModificationDate(); fail(); } catch (final UnauthorizedOperationException e) { assertTrue(true); } try { AuthToken.authenticate(memberTom); tomAccount.getLastModificationDate(); assertEquals(tomAccount.getLastModificationDate(), db.getTom().getInternalAccount().getLastModificationDate()); } catch (final UnauthorizedOperationException e) { fail(); } try { AuthToken.authenticate(loser); tomAccount.getLastModificationDate(); fail(); } catch (final UnauthorizedOperationException e) { assertTrue(true); } final InternalAccount publicGroupAccount = InternalAccount.create(db.getPublicGroup().getInternalAccount()); try { AuthToken.unAuthenticate(); publicGroupAccount.getLastModificationDate(); fail(); } catch (final UnauthorizedOperationException e) { assertTrue(true); } try { AuthToken.authenticate(memberTom); publicGroupAccount.getLastModificationDate(); } catch (final UnauthorizedOperationException e) { fail(); } try { AuthToken.authenticate(memberYo); publicGroupAccount.getLastModificationDate(); } catch (final UnauthorizedOperationException e) { fail(); } try { AuthToken.authenticate(memeberFred); publicGroupAccount.getLastModificationDate(); fail(); } catch (final UnauthorizedOperationException e) { assertTrue(true); } try { AuthToken.authenticate(loser); publicGroupAccount.getLastModificationDate(); fail(); } catch (final UnauthorizedOperationException e) { assertTrue(true); } } |
Account extends Identifiable<T> { public final BigDecimal getAmount() throws UnauthorizedOperationException { tryAccess(new RgtAccount.Amount(), Action.READ); return getDao().getAmount(); } protected Account(final T id); final boolean canAccessTransaction(); final boolean canAccessAmount(); final boolean canAccessActor(); final boolean canAccessCreationDate(); final boolean canAccessLastModificationDate(); final Date getLastModificationDate(); final BigDecimal getAmount(); final PageIterable<Transaction> getTransactions(); final Actor<?> getActor(); final Date getCreationDate(); } | @Test public void testGetAmount() { final InternalAccount tomAccount = InternalAccount.create(db.getTom().getInternalAccount()); try { AuthToken.unAuthenticate(); tomAccount.getAmount(); fail(); } catch (final UnauthorizedOperationException e) { assertTrue(true); } try { AuthToken.authenticate(memberTom); tomAccount.getAmount(); assertEquals(tomAccount.getAmount(), db.getTom().getInternalAccount().getAmount()); } catch (final UnauthorizedOperationException e) { fail(); } try { AuthToken.authenticate(loser); tomAccount.getAmount(); fail(); } catch (final UnauthorizedOperationException e) { assertTrue(true); } final InternalAccount publicGroupAccount = InternalAccount.create(db.getPublicGroup().getInternalAccount()); try { AuthToken.unAuthenticate(); publicGroupAccount.getAmount(); fail(); } catch (final UnauthorizedOperationException e) { assertTrue(true); } try { AuthToken.authenticate(memberTom); publicGroupAccount.getAmount(); } catch (final UnauthorizedOperationException e) { fail(); } try { AuthToken.authenticate(memberYo); publicGroupAccount.getAmount(); } catch (final UnauthorizedOperationException e) { fail(); } try { AuthToken.authenticate(memeberFred); publicGroupAccount.getAmount(); fail(); } catch (final UnauthorizedOperationException e) { assertTrue(true); } try { AuthToken.authenticate(loser); publicGroupAccount.getAmount(); fail(); } catch (final UnauthorizedOperationException e) { assertTrue(true); } } |
Account extends Identifiable<T> { public final PageIterable<Transaction> getTransactions() throws UnauthorizedOperationException { tryAccess(new RgtAccount.Transaction(), Action.READ); return new TransactionList(getDao().getTransactions()); } protected Account(final T id); final boolean canAccessTransaction(); final boolean canAccessAmount(); final boolean canAccessActor(); final boolean canAccessCreationDate(); final boolean canAccessLastModificationDate(); final Date getLastModificationDate(); final BigDecimal getAmount(); final PageIterable<Transaction> getTransactions(); final Actor<?> getActor(); final Date getCreationDate(); } | @Test public void testGetTransactions() { final InternalAccount tomAccount = InternalAccount.create(db.getTom().getInternalAccount()); try { AuthToken.unAuthenticate(); tomAccount.getTransactions(); fail(); } catch (final UnauthorizedOperationException e) { assertTrue(true); } try { AuthToken.authenticate(memberTom); tomAccount.getTransactions(); assertEquals(tomAccount.getTransactions().size(), db.getTom().getInternalAccount().getTransactions().size()); } catch (final UnauthorizedOperationException e) { fail(); } try { AuthToken.authenticate(loser); tomAccount.getTransactions(); fail(); } catch (final UnauthorizedOperationException e) { assertTrue(true); } final InternalAccount publicGroupAccount = InternalAccount.create(db.getPublicGroup().getInternalAccount()); try { AuthToken.unAuthenticate(); publicGroupAccount.getTransactions(); fail(); } catch (final UnauthorizedOperationException e) { assertTrue(true); } try { AuthToken.authenticate(memberTom); publicGroupAccount.getTransactions(); } catch (final UnauthorizedOperationException e) { fail(); } try { AuthToken.authenticate(memberYo); publicGroupAccount.getTransactions(); } catch (final UnauthorizedOperationException e) { fail(); } try { AuthToken.authenticate(memeberFred); publicGroupAccount.getTransactions(); fail(); } catch (final UnauthorizedOperationException e) { assertTrue(true); } try { AuthToken.authenticate(loser); publicGroupAccount.getTransactions(); fail(); } catch (final UnauthorizedOperationException e) { assertTrue(true); } } |
Account extends Identifiable<T> { public final Actor<?> getActor() throws UnauthorizedOperationException { tryAccess(new RgtAccount.Actor(), Action.READ); return getActorUnprotected(); } protected Account(final T id); final boolean canAccessTransaction(); final boolean canAccessAmount(); final boolean canAccessActor(); final boolean canAccessCreationDate(); final boolean canAccessLastModificationDate(); final Date getLastModificationDate(); final BigDecimal getAmount(); final PageIterable<Transaction> getTransactions(); final Actor<?> getActor(); final Date getCreationDate(); } | @Test public void testGetActor() { final InternalAccount tomAccount = InternalAccount.create(db.getTom().getInternalAccount()); try { AuthToken.unAuthenticate(); tomAccount.getActor(); fail(); } catch (final UnauthorizedOperationException e) { assertTrue(true); } try { AuthToken.authenticate(memberTom); tomAccount.getActor(); assertEquals(tomAccount.getActor().getId(), db.getTom().getInternalAccount().getActor().getId()); } catch (final UnauthorizedOperationException e) { fail(); } try { AuthToken.authenticate(loser); tomAccount.getActor(); fail(); } catch (final UnauthorizedOperationException e) { assertTrue(true); } final InternalAccount publicGroupAccount = InternalAccount.create(db.getPublicGroup().getInternalAccount()); try { AuthToken.unAuthenticate(); publicGroupAccount.getActor(); fail(); } catch (final UnauthorizedOperationException e) { assertTrue(true); } try { AuthToken.authenticate(memberTom); publicGroupAccount.getActor(); } catch (final UnauthorizedOperationException e) { fail(); } try { AuthToken.authenticate(memberYo); publicGroupAccount.getActor(); } catch (final UnauthorizedOperationException e) { fail(); } try { AuthToken.authenticate(memeberFred); publicGroupAccount.getActor(); fail(); } catch (final UnauthorizedOperationException e) { assertTrue(true); } try { AuthToken.authenticate(loser); publicGroupAccount.getActor(); fail(); } catch (final UnauthorizedOperationException e) { assertTrue(true); } } |
Account extends Identifiable<T> { public final Date getCreationDate() throws UnauthorizedOperationException { tryAccess(new RgtAccount.CreationDate(), Action.READ); return getDao().getCreationDate(); } protected Account(final T id); final boolean canAccessTransaction(); final boolean canAccessAmount(); final boolean canAccessActor(); final boolean canAccessCreationDate(); final boolean canAccessLastModificationDate(); final Date getLastModificationDate(); final BigDecimal getAmount(); final PageIterable<Transaction> getTransactions(); final Actor<?> getActor(); final Date getCreationDate(); } | @Test public void testGetCreationDate() { final InternalAccount tomAccount = InternalAccount.create(db.getTom().getInternalAccount()); try { AuthToken.unAuthenticate(); tomAccount.getCreationDate(); fail(); } catch (final UnauthorizedOperationException e) { assertTrue(true); } try { AuthToken.authenticate(memberTom); tomAccount.getCreationDate(); assertEquals(tomAccount.getCreationDate(), db.getTom().getInternalAccount().getCreationDate()); } catch (final UnauthorizedOperationException e) { fail(); } try { AuthToken.authenticate(loser); tomAccount.getCreationDate(); fail(); } catch (final UnauthorizedOperationException e) { assertTrue(true); } final InternalAccount publicGroupAccount = InternalAccount.create(db.getPublicGroup().getInternalAccount()); try { AuthToken.unAuthenticate(); publicGroupAccount.getCreationDate(); fail(); } catch (final UnauthorizedOperationException e) { assertTrue(true); } try { AuthToken.authenticate(memberTom); publicGroupAccount.getCreationDate(); } catch (final UnauthorizedOperationException e) { fail(); } try { AuthToken.authenticate(memberYo); publicGroupAccount.getCreationDate(); } catch (final UnauthorizedOperationException e) { fail(); } try { AuthToken.authenticate(memeberFred); publicGroupAccount.getCreationDate(); fail(); } catch (final UnauthorizedOperationException e) { assertTrue(true); } try { AuthToken.authenticate(loser); publicGroupAccount.getCreationDate(); fail(); } catch (final UnauthorizedOperationException e) { assertTrue(true); } } |
DaoUserContent extends DaoIdentifiable { public DaoActor getAuthor() { return asTeam == null ? member : asTeam; } protected DaoUserContent(final DaoMember member, final DaoTeam team); protected DaoUserContent(); DaoMember getMember(); DaoActor getAuthor(); Date getCreationDate(); DaoTeam getAsTeam(); PageIterable<DaoFileMetadata> getFiles(); boolean isDeleted(); void setIsDeleted(final Boolean isDeleted); void addFile(final DaoFileMetadata daoFileMetadata); @Override int hashCode(); @Override boolean equals(final Object obj); } | @Test public void testGetAuthor() { assertEquals(yo, feature.getMember()); } |
Member extends Actor<DaoMember> implements User { public int getKarma() { return getDao().getKarma(); } Member(final String login, final String password, final String email, final Locale locale); Member(final String login, final String password, final String email, final String fullname, final Locale locale); private Member(final DaoMember dao); @SuppressWarnings("synthetic-access") static Member create(final DaoMember dao); void sendInvitation(final Member member, final Team team); boolean acceptInvitation(final JoinTeamInvitation invitation); void refuseInvitation(final JoinTeamInvitation invitation); void kickFromTeam(final Team aTeam, final Member actor); void addToPublicTeam(final Team team); void setPassword(final String password); boolean checkPassword(final String password); void setFullname(final String fullname); void setAvatar(final FileMetadata fileImage); void setDescription(final String userDescription); void setEmail(final String email); void setLocal(final Locale loacle); boolean isActive(); boolean activate(final String activationKey); boolean hasEmailToActivate(); boolean activateEmail(final String activationKey); void setEmailToActivate(final String email); void acceptNewsLetter(final boolean newsletter); FollowFeature followOrGetFeature(final Feature f); boolean isFollowing(final Feature feature); boolean isFollowing(final Software software); boolean isFollowing(final Actor<?> actor); void unfollowFeature(final Feature f); FollowSoftware followOrGetSoftware(final Software s); void unfollowSoftware(final Software s); FollowActor followOrGetActor(final Actor<?> f); void unfollowActor(final Actor<?> a); void setLastWatchedEvents(final Date lastWatchedEvents); void setEmailStrategy(final EmailStrategy emailStrategy); void setGlobalFollow(final boolean globalFollow); void setGlobalFollowWithMail(final boolean globalFollow); Date getLastWatchedEvents(); @Override ActivationState getActivationState(); String getDescription(); EmailStrategy getEmailStrategy(); FollowFeature getFollowFeature(final Feature feature); boolean isGlobalFollow(); boolean isGlobalFollowWithMail(); String getActivationKey(); String getEmailActivationKey(); PageIterable<JoinTeamInvitation> getReceivedInvitation(final State state); PageIterable<JoinTeamInvitation> getSentInvitation(final State state); PageIterable<Team> getTeams(); int getKarma(); PageIterable<Milestone> getMilestoneToInvoice(); PageIterable<Milestone> getMilestoneInvoiced(); PageIterable<Milestone> getMilestones(); PageIterable<UserContent<? extends DaoUserContent>> getHistory(); @Override String getDisplayName(); String getEmail(); String getEmailToActivate(); String getEmailUnprotected(); boolean getNewsletterAccept(); Locale getLocaleUnprotected(); @Override Locale getLocale(); String getFullname(); @Override Image getAvatar(); long getInvitationCount(); PageIterable<Feature> getFeatures(final boolean asMemberOnly); PageIterable<Kudos> getKudos(); @Override PageIterable<Contribution> doGetContributions(); @Override PageIterable<MoneyWithdrawal> doGetMoneyWithdrawals(); PageIterable<Contribution> getContributions(final boolean asMemberOnly); PageIterable<Comment> getComments(final boolean asMemberOnly); PageIterable<Offer> getOffers(final boolean asMemberOnly); PageIterable<Translation> getTranslations(final boolean asMemberOnly); void addToKarma(final int value); Role getRole(); String getResetKey(); PageIterable<ExternalServiceMembership> getExternalServices(); PageIterable<FollowFeature> getFollowedFeatures(); PageIterable<FollowActor> getFollowedActors(); PageIterable<FollowSoftware> getFollowedSoftware(); void addAuthorizedExternalService(final String clientId, final String token, final EnumSet<RightLevel> rights); final boolean canAccessAvatar(final Action action); boolean canGetTeams(); boolean canSetPassword(); boolean canAccessEmail(final Action action); boolean canAccessUserInformations(final Action action); boolean canBeKickFromTeam(final Team aTeam, final Member actor); boolean hasTeamRight(final Team aTeam, final UserTeamRight aRight); Set<UserTeamRight> getTeamRights(final Team g); boolean hasConsultTeamRight(final Team aTeam); boolean hasTalkTeamRight(final Team aTeam); boolean hasInviteTeamRight(final Team aTeam); boolean hasModifyTeamRight(final Team aTeam); boolean hasPromoteTeamRight(final Team aTeam); boolean hasBankTeamRight(final Team aTeam); boolean isInTeam(final Team team); @Override ReturnType accept(final ModelClassVisitor<ReturnType> visitor); } | @Test public void testGetKarma() throws UnauthorizedOperationException { final Member yo = MemberManager.getMemberByLogin("Yoann"); AuthToken.authenticate(memberYo); assertEquals(0, yo.getKarma()); AuthToken.authenticate(memeberFred); assertEquals(0, yo.getKarma()); AuthToken.authenticate(memberTom); assertEquals(0, yo.getKarma()); } |
Member extends Actor<DaoMember> implements User { public void setFullname(final String fullname) throws UnauthorizedPublicAccessException { tryAccess(new RgtMember.FullName(), Action.WRITE); getDao().setFullname(fullname); } Member(final String login, final String password, final String email, final Locale locale); Member(final String login, final String password, final String email, final String fullname, final Locale locale); private Member(final DaoMember dao); @SuppressWarnings("synthetic-access") static Member create(final DaoMember dao); void sendInvitation(final Member member, final Team team); boolean acceptInvitation(final JoinTeamInvitation invitation); void refuseInvitation(final JoinTeamInvitation invitation); void kickFromTeam(final Team aTeam, final Member actor); void addToPublicTeam(final Team team); void setPassword(final String password); boolean checkPassword(final String password); void setFullname(final String fullname); void setAvatar(final FileMetadata fileImage); void setDescription(final String userDescription); void setEmail(final String email); void setLocal(final Locale loacle); boolean isActive(); boolean activate(final String activationKey); boolean hasEmailToActivate(); boolean activateEmail(final String activationKey); void setEmailToActivate(final String email); void acceptNewsLetter(final boolean newsletter); FollowFeature followOrGetFeature(final Feature f); boolean isFollowing(final Feature feature); boolean isFollowing(final Software software); boolean isFollowing(final Actor<?> actor); void unfollowFeature(final Feature f); FollowSoftware followOrGetSoftware(final Software s); void unfollowSoftware(final Software s); FollowActor followOrGetActor(final Actor<?> f); void unfollowActor(final Actor<?> a); void setLastWatchedEvents(final Date lastWatchedEvents); void setEmailStrategy(final EmailStrategy emailStrategy); void setGlobalFollow(final boolean globalFollow); void setGlobalFollowWithMail(final boolean globalFollow); Date getLastWatchedEvents(); @Override ActivationState getActivationState(); String getDescription(); EmailStrategy getEmailStrategy(); FollowFeature getFollowFeature(final Feature feature); boolean isGlobalFollow(); boolean isGlobalFollowWithMail(); String getActivationKey(); String getEmailActivationKey(); PageIterable<JoinTeamInvitation> getReceivedInvitation(final State state); PageIterable<JoinTeamInvitation> getSentInvitation(final State state); PageIterable<Team> getTeams(); int getKarma(); PageIterable<Milestone> getMilestoneToInvoice(); PageIterable<Milestone> getMilestoneInvoiced(); PageIterable<Milestone> getMilestones(); PageIterable<UserContent<? extends DaoUserContent>> getHistory(); @Override String getDisplayName(); String getEmail(); String getEmailToActivate(); String getEmailUnprotected(); boolean getNewsletterAccept(); Locale getLocaleUnprotected(); @Override Locale getLocale(); String getFullname(); @Override Image getAvatar(); long getInvitationCount(); PageIterable<Feature> getFeatures(final boolean asMemberOnly); PageIterable<Kudos> getKudos(); @Override PageIterable<Contribution> doGetContributions(); @Override PageIterable<MoneyWithdrawal> doGetMoneyWithdrawals(); PageIterable<Contribution> getContributions(final boolean asMemberOnly); PageIterable<Comment> getComments(final boolean asMemberOnly); PageIterable<Offer> getOffers(final boolean asMemberOnly); PageIterable<Translation> getTranslations(final boolean asMemberOnly); void addToKarma(final int value); Role getRole(); String getResetKey(); PageIterable<ExternalServiceMembership> getExternalServices(); PageIterable<FollowFeature> getFollowedFeatures(); PageIterable<FollowActor> getFollowedActors(); PageIterable<FollowSoftware> getFollowedSoftware(); void addAuthorizedExternalService(final String clientId, final String token, final EnumSet<RightLevel> rights); final boolean canAccessAvatar(final Action action); boolean canGetTeams(); boolean canSetPassword(); boolean canAccessEmail(final Action action); boolean canAccessUserInformations(final Action action); boolean canBeKickFromTeam(final Team aTeam, final Member actor); boolean hasTeamRight(final Team aTeam, final UserTeamRight aRight); Set<UserTeamRight> getTeamRights(final Team g); boolean hasConsultTeamRight(final Team aTeam); boolean hasTalkTeamRight(final Team aTeam); boolean hasInviteTeamRight(final Team aTeam); boolean hasModifyTeamRight(final Team aTeam); boolean hasPromoteTeamRight(final Team aTeam); boolean hasBankTeamRight(final Team aTeam); boolean isInTeam(final Team team); @Override ReturnType accept(final ModelClassVisitor<ReturnType> visitor); } | @Test public void testSetFullName() throws UnauthorizedOperationException { final Member yo = MemberManager.getMemberByLogin("Yoann"); AuthToken.authenticate(memberYo); assertEquals(0, yo.getKarma()); AuthToken.authenticate(memeberFred); assertEquals(0, yo.getKarma()); AuthToken.authenticate(memberTom); assertEquals(0, yo.getKarma()); }
@Test public void testSetFullname() throws UnauthorizedOperationException { final Member yo = MemberManager.getMemberByLogin("Yoann"); AuthToken.authenticate(memberYo); yo.setFullname("Plénet Yoann"); try { AuthToken.authenticate(memeberFred); yo.setFullname("plop"); fail(); } catch (final Exception e) { assertTrue(true); } assertEquals("Plénet Yoann", yo.getFullname()); } |
Member extends Actor<DaoMember> implements User { public String getFullname() { return getDao().getFullname(); } Member(final String login, final String password, final String email, final Locale locale); Member(final String login, final String password, final String email, final String fullname, final Locale locale); private Member(final DaoMember dao); @SuppressWarnings("synthetic-access") static Member create(final DaoMember dao); void sendInvitation(final Member member, final Team team); boolean acceptInvitation(final JoinTeamInvitation invitation); void refuseInvitation(final JoinTeamInvitation invitation); void kickFromTeam(final Team aTeam, final Member actor); void addToPublicTeam(final Team team); void setPassword(final String password); boolean checkPassword(final String password); void setFullname(final String fullname); void setAvatar(final FileMetadata fileImage); void setDescription(final String userDescription); void setEmail(final String email); void setLocal(final Locale loacle); boolean isActive(); boolean activate(final String activationKey); boolean hasEmailToActivate(); boolean activateEmail(final String activationKey); void setEmailToActivate(final String email); void acceptNewsLetter(final boolean newsletter); FollowFeature followOrGetFeature(final Feature f); boolean isFollowing(final Feature feature); boolean isFollowing(final Software software); boolean isFollowing(final Actor<?> actor); void unfollowFeature(final Feature f); FollowSoftware followOrGetSoftware(final Software s); void unfollowSoftware(final Software s); FollowActor followOrGetActor(final Actor<?> f); void unfollowActor(final Actor<?> a); void setLastWatchedEvents(final Date lastWatchedEvents); void setEmailStrategy(final EmailStrategy emailStrategy); void setGlobalFollow(final boolean globalFollow); void setGlobalFollowWithMail(final boolean globalFollow); Date getLastWatchedEvents(); @Override ActivationState getActivationState(); String getDescription(); EmailStrategy getEmailStrategy(); FollowFeature getFollowFeature(final Feature feature); boolean isGlobalFollow(); boolean isGlobalFollowWithMail(); String getActivationKey(); String getEmailActivationKey(); PageIterable<JoinTeamInvitation> getReceivedInvitation(final State state); PageIterable<JoinTeamInvitation> getSentInvitation(final State state); PageIterable<Team> getTeams(); int getKarma(); PageIterable<Milestone> getMilestoneToInvoice(); PageIterable<Milestone> getMilestoneInvoiced(); PageIterable<Milestone> getMilestones(); PageIterable<UserContent<? extends DaoUserContent>> getHistory(); @Override String getDisplayName(); String getEmail(); String getEmailToActivate(); String getEmailUnprotected(); boolean getNewsletterAccept(); Locale getLocaleUnprotected(); @Override Locale getLocale(); String getFullname(); @Override Image getAvatar(); long getInvitationCount(); PageIterable<Feature> getFeatures(final boolean asMemberOnly); PageIterable<Kudos> getKudos(); @Override PageIterable<Contribution> doGetContributions(); @Override PageIterable<MoneyWithdrawal> doGetMoneyWithdrawals(); PageIterable<Contribution> getContributions(final boolean asMemberOnly); PageIterable<Comment> getComments(final boolean asMemberOnly); PageIterable<Offer> getOffers(final boolean asMemberOnly); PageIterable<Translation> getTranslations(final boolean asMemberOnly); void addToKarma(final int value); Role getRole(); String getResetKey(); PageIterable<ExternalServiceMembership> getExternalServices(); PageIterable<FollowFeature> getFollowedFeatures(); PageIterable<FollowActor> getFollowedActors(); PageIterable<FollowSoftware> getFollowedSoftware(); void addAuthorizedExternalService(final String clientId, final String token, final EnumSet<RightLevel> rights); final boolean canAccessAvatar(final Action action); boolean canGetTeams(); boolean canSetPassword(); boolean canAccessEmail(final Action action); boolean canAccessUserInformations(final Action action); boolean canBeKickFromTeam(final Team aTeam, final Member actor); boolean hasTeamRight(final Team aTeam, final UserTeamRight aRight); Set<UserTeamRight> getTeamRights(final Team g); boolean hasConsultTeamRight(final Team aTeam); boolean hasTalkTeamRight(final Team aTeam); boolean hasInviteTeamRight(final Team aTeam); boolean hasModifyTeamRight(final Team aTeam); boolean hasPromoteTeamRight(final Team aTeam); boolean hasBankTeamRight(final Team aTeam); boolean isInTeam(final Team team); @Override ReturnType accept(final ModelClassVisitor<ReturnType> visitor); } | @Test public void testGetFullname() { final Member yo = MemberManager.getMemberByLogin("Yoann"); AuthToken.authenticate(memberYo); assertEquals("Yoann Plénet", yo.getFullname()); AuthToken.authenticate(memeberFred); assertEquals("Yoann Plénet", yo.getFullname()); AuthToken.authenticate(memberTom); assertEquals("Yoann Plénet", yo.getFullname()); } |
Member extends Actor<DaoMember> implements User { public void setPassword(final String password) throws UnauthorizedPrivateAccessException { tryAccess(new RgtMember.Password(), Action.WRITE); getDao().setPassword(Hash.calculateHash(password, getDao().getSalt())); } Member(final String login, final String password, final String email, final Locale locale); Member(final String login, final String password, final String email, final String fullname, final Locale locale); private Member(final DaoMember dao); @SuppressWarnings("synthetic-access") static Member create(final DaoMember dao); void sendInvitation(final Member member, final Team team); boolean acceptInvitation(final JoinTeamInvitation invitation); void refuseInvitation(final JoinTeamInvitation invitation); void kickFromTeam(final Team aTeam, final Member actor); void addToPublicTeam(final Team team); void setPassword(final String password); boolean checkPassword(final String password); void setFullname(final String fullname); void setAvatar(final FileMetadata fileImage); void setDescription(final String userDescription); void setEmail(final String email); void setLocal(final Locale loacle); boolean isActive(); boolean activate(final String activationKey); boolean hasEmailToActivate(); boolean activateEmail(final String activationKey); void setEmailToActivate(final String email); void acceptNewsLetter(final boolean newsletter); FollowFeature followOrGetFeature(final Feature f); boolean isFollowing(final Feature feature); boolean isFollowing(final Software software); boolean isFollowing(final Actor<?> actor); void unfollowFeature(final Feature f); FollowSoftware followOrGetSoftware(final Software s); void unfollowSoftware(final Software s); FollowActor followOrGetActor(final Actor<?> f); void unfollowActor(final Actor<?> a); void setLastWatchedEvents(final Date lastWatchedEvents); void setEmailStrategy(final EmailStrategy emailStrategy); void setGlobalFollow(final boolean globalFollow); void setGlobalFollowWithMail(final boolean globalFollow); Date getLastWatchedEvents(); @Override ActivationState getActivationState(); String getDescription(); EmailStrategy getEmailStrategy(); FollowFeature getFollowFeature(final Feature feature); boolean isGlobalFollow(); boolean isGlobalFollowWithMail(); String getActivationKey(); String getEmailActivationKey(); PageIterable<JoinTeamInvitation> getReceivedInvitation(final State state); PageIterable<JoinTeamInvitation> getSentInvitation(final State state); PageIterable<Team> getTeams(); int getKarma(); PageIterable<Milestone> getMilestoneToInvoice(); PageIterable<Milestone> getMilestoneInvoiced(); PageIterable<Milestone> getMilestones(); PageIterable<UserContent<? extends DaoUserContent>> getHistory(); @Override String getDisplayName(); String getEmail(); String getEmailToActivate(); String getEmailUnprotected(); boolean getNewsletterAccept(); Locale getLocaleUnprotected(); @Override Locale getLocale(); String getFullname(); @Override Image getAvatar(); long getInvitationCount(); PageIterable<Feature> getFeatures(final boolean asMemberOnly); PageIterable<Kudos> getKudos(); @Override PageIterable<Contribution> doGetContributions(); @Override PageIterable<MoneyWithdrawal> doGetMoneyWithdrawals(); PageIterable<Contribution> getContributions(final boolean asMemberOnly); PageIterable<Comment> getComments(final boolean asMemberOnly); PageIterable<Offer> getOffers(final boolean asMemberOnly); PageIterable<Translation> getTranslations(final boolean asMemberOnly); void addToKarma(final int value); Role getRole(); String getResetKey(); PageIterable<ExternalServiceMembership> getExternalServices(); PageIterable<FollowFeature> getFollowedFeatures(); PageIterable<FollowActor> getFollowedActors(); PageIterable<FollowSoftware> getFollowedSoftware(); void addAuthorizedExternalService(final String clientId, final String token, final EnumSet<RightLevel> rights); final boolean canAccessAvatar(final Action action); boolean canGetTeams(); boolean canSetPassword(); boolean canAccessEmail(final Action action); boolean canAccessUserInformations(final Action action); boolean canBeKickFromTeam(final Team aTeam, final Member actor); boolean hasTeamRight(final Team aTeam, final UserTeamRight aRight); Set<UserTeamRight> getTeamRights(final Team g); boolean hasConsultTeamRight(final Team aTeam); boolean hasTalkTeamRight(final Team aTeam); boolean hasInviteTeamRight(final Team aTeam); boolean hasModifyTeamRight(final Team aTeam); boolean hasPromoteTeamRight(final Team aTeam); boolean hasBankTeamRight(final Team aTeam); boolean isInTeam(final Team team); @Override ReturnType accept(final ModelClassVisitor<ReturnType> visitor); } | @Test public void testSetPassword() throws UnauthorizedOperationException { final Member yo = MemberManager.getMemberByLogin("Yoann"); AuthToken.authenticate(memberYo); yo.setPassword("Coucou"); try { AuthToken.authenticate("Yoann", "Coucou"); } catch (final ElementNotFoundException e) { fail(); } } |
Member extends Actor<DaoMember> implements User { public PageIterable<Feature> getFeatures(final boolean asMemberOnly) { return new FeatureList(getDao().getFeatures(asMemberOnly)); } Member(final String login, final String password, final String email, final Locale locale); Member(final String login, final String password, final String email, final String fullname, final Locale locale); private Member(final DaoMember dao); @SuppressWarnings("synthetic-access") static Member create(final DaoMember dao); void sendInvitation(final Member member, final Team team); boolean acceptInvitation(final JoinTeamInvitation invitation); void refuseInvitation(final JoinTeamInvitation invitation); void kickFromTeam(final Team aTeam, final Member actor); void addToPublicTeam(final Team team); void setPassword(final String password); boolean checkPassword(final String password); void setFullname(final String fullname); void setAvatar(final FileMetadata fileImage); void setDescription(final String userDescription); void setEmail(final String email); void setLocal(final Locale loacle); boolean isActive(); boolean activate(final String activationKey); boolean hasEmailToActivate(); boolean activateEmail(final String activationKey); void setEmailToActivate(final String email); void acceptNewsLetter(final boolean newsletter); FollowFeature followOrGetFeature(final Feature f); boolean isFollowing(final Feature feature); boolean isFollowing(final Software software); boolean isFollowing(final Actor<?> actor); void unfollowFeature(final Feature f); FollowSoftware followOrGetSoftware(final Software s); void unfollowSoftware(final Software s); FollowActor followOrGetActor(final Actor<?> f); void unfollowActor(final Actor<?> a); void setLastWatchedEvents(final Date lastWatchedEvents); void setEmailStrategy(final EmailStrategy emailStrategy); void setGlobalFollow(final boolean globalFollow); void setGlobalFollowWithMail(final boolean globalFollow); Date getLastWatchedEvents(); @Override ActivationState getActivationState(); String getDescription(); EmailStrategy getEmailStrategy(); FollowFeature getFollowFeature(final Feature feature); boolean isGlobalFollow(); boolean isGlobalFollowWithMail(); String getActivationKey(); String getEmailActivationKey(); PageIterable<JoinTeamInvitation> getReceivedInvitation(final State state); PageIterable<JoinTeamInvitation> getSentInvitation(final State state); PageIterable<Team> getTeams(); int getKarma(); PageIterable<Milestone> getMilestoneToInvoice(); PageIterable<Milestone> getMilestoneInvoiced(); PageIterable<Milestone> getMilestones(); PageIterable<UserContent<? extends DaoUserContent>> getHistory(); @Override String getDisplayName(); String getEmail(); String getEmailToActivate(); String getEmailUnprotected(); boolean getNewsletterAccept(); Locale getLocaleUnprotected(); @Override Locale getLocale(); String getFullname(); @Override Image getAvatar(); long getInvitationCount(); PageIterable<Feature> getFeatures(final boolean asMemberOnly); PageIterable<Kudos> getKudos(); @Override PageIterable<Contribution> doGetContributions(); @Override PageIterable<MoneyWithdrawal> doGetMoneyWithdrawals(); PageIterable<Contribution> getContributions(final boolean asMemberOnly); PageIterable<Comment> getComments(final boolean asMemberOnly); PageIterable<Offer> getOffers(final boolean asMemberOnly); PageIterable<Translation> getTranslations(final boolean asMemberOnly); void addToKarma(final int value); Role getRole(); String getResetKey(); PageIterable<ExternalServiceMembership> getExternalServices(); PageIterable<FollowFeature> getFollowedFeatures(); PageIterable<FollowActor> getFollowedActors(); PageIterable<FollowSoftware> getFollowedSoftware(); void addAuthorizedExternalService(final String clientId, final String token, final EnumSet<RightLevel> rights); final boolean canAccessAvatar(final Action action); boolean canGetTeams(); boolean canSetPassword(); boolean canAccessEmail(final Action action); boolean canAccessUserInformations(final Action action); boolean canBeKickFromTeam(final Team aTeam, final Member actor); boolean hasTeamRight(final Team aTeam, final UserTeamRight aRight); Set<UserTeamRight> getTeamRights(final Team g); boolean hasConsultTeamRight(final Team aTeam); boolean hasTalkTeamRight(final Team aTeam); boolean hasInviteTeamRight(final Team aTeam); boolean hasModifyTeamRight(final Team aTeam); boolean hasPromoteTeamRight(final Team aTeam); boolean hasBankTeamRight(final Team aTeam); boolean isInTeam(final Team team); @Override ReturnType accept(final ModelClassVisitor<ReturnType> visitor); } | @Test public void testGetFeatures() { final Member yo = MemberManager.getMemberByLogin("Yoann"); assertEquals("Mon titre", yo.getFeatures(false).iterator().next().getDescription().getTranslationOrDefault(Language.EN).getTitle()); AuthToken.authenticate(memberYo); assertEquals("Mon titre", yo.getFeatures(false).iterator().next().getDescription().getTranslationOrDefault(Language.EN).getTitle()); AuthToken.authenticate(memeberFred); assertEquals("Mon titre", yo.getFeatures(false).iterator().next().getDescription().getTranslationOrDefault(Language.EN).getTitle()); } |
Member extends Actor<DaoMember> implements User { public PageIterable<Kudos> getKudos() throws UnauthorizedPrivateAccessException { tryAccess(new RgtMember.Kudos(), Action.READ); return new KudosList(getDao().getKudos()); } Member(final String login, final String password, final String email, final Locale locale); Member(final String login, final String password, final String email, final String fullname, final Locale locale); private Member(final DaoMember dao); @SuppressWarnings("synthetic-access") static Member create(final DaoMember dao); void sendInvitation(final Member member, final Team team); boolean acceptInvitation(final JoinTeamInvitation invitation); void refuseInvitation(final JoinTeamInvitation invitation); void kickFromTeam(final Team aTeam, final Member actor); void addToPublicTeam(final Team team); void setPassword(final String password); boolean checkPassword(final String password); void setFullname(final String fullname); void setAvatar(final FileMetadata fileImage); void setDescription(final String userDescription); void setEmail(final String email); void setLocal(final Locale loacle); boolean isActive(); boolean activate(final String activationKey); boolean hasEmailToActivate(); boolean activateEmail(final String activationKey); void setEmailToActivate(final String email); void acceptNewsLetter(final boolean newsletter); FollowFeature followOrGetFeature(final Feature f); boolean isFollowing(final Feature feature); boolean isFollowing(final Software software); boolean isFollowing(final Actor<?> actor); void unfollowFeature(final Feature f); FollowSoftware followOrGetSoftware(final Software s); void unfollowSoftware(final Software s); FollowActor followOrGetActor(final Actor<?> f); void unfollowActor(final Actor<?> a); void setLastWatchedEvents(final Date lastWatchedEvents); void setEmailStrategy(final EmailStrategy emailStrategy); void setGlobalFollow(final boolean globalFollow); void setGlobalFollowWithMail(final boolean globalFollow); Date getLastWatchedEvents(); @Override ActivationState getActivationState(); String getDescription(); EmailStrategy getEmailStrategy(); FollowFeature getFollowFeature(final Feature feature); boolean isGlobalFollow(); boolean isGlobalFollowWithMail(); String getActivationKey(); String getEmailActivationKey(); PageIterable<JoinTeamInvitation> getReceivedInvitation(final State state); PageIterable<JoinTeamInvitation> getSentInvitation(final State state); PageIterable<Team> getTeams(); int getKarma(); PageIterable<Milestone> getMilestoneToInvoice(); PageIterable<Milestone> getMilestoneInvoiced(); PageIterable<Milestone> getMilestones(); PageIterable<UserContent<? extends DaoUserContent>> getHistory(); @Override String getDisplayName(); String getEmail(); String getEmailToActivate(); String getEmailUnprotected(); boolean getNewsletterAccept(); Locale getLocaleUnprotected(); @Override Locale getLocale(); String getFullname(); @Override Image getAvatar(); long getInvitationCount(); PageIterable<Feature> getFeatures(final boolean asMemberOnly); PageIterable<Kudos> getKudos(); @Override PageIterable<Contribution> doGetContributions(); @Override PageIterable<MoneyWithdrawal> doGetMoneyWithdrawals(); PageIterable<Contribution> getContributions(final boolean asMemberOnly); PageIterable<Comment> getComments(final boolean asMemberOnly); PageIterable<Offer> getOffers(final boolean asMemberOnly); PageIterable<Translation> getTranslations(final boolean asMemberOnly); void addToKarma(final int value); Role getRole(); String getResetKey(); PageIterable<ExternalServiceMembership> getExternalServices(); PageIterable<FollowFeature> getFollowedFeatures(); PageIterable<FollowActor> getFollowedActors(); PageIterable<FollowSoftware> getFollowedSoftware(); void addAuthorizedExternalService(final String clientId, final String token, final EnumSet<RightLevel> rights); final boolean canAccessAvatar(final Action action); boolean canGetTeams(); boolean canSetPassword(); boolean canAccessEmail(final Action action); boolean canAccessUserInformations(final Action action); boolean canBeKickFromTeam(final Team aTeam, final Member actor); boolean hasTeamRight(final Team aTeam, final UserTeamRight aRight); Set<UserTeamRight> getTeamRights(final Team g); boolean hasConsultTeamRight(final Team aTeam); boolean hasTalkTeamRight(final Team aTeam); boolean hasInviteTeamRight(final Team aTeam); boolean hasModifyTeamRight(final Team aTeam); boolean hasPromoteTeamRight(final Team aTeam); boolean hasBankTeamRight(final Team aTeam); boolean isInTeam(final Team team); @Override ReturnType accept(final ModelClassVisitor<ReturnType> visitor); } | @Test public void testGetKudos() { final Member yo = MemberManager.getMemberByLogin("Yoann"); try { assertEquals(1, yo.getKudos().size()); fail(); } catch (final UnauthorizedPrivateAccessException e) { assertTrue(true); } try { AuthToken.authenticate(memberYo); assertEquals(1, yo.getKudos().size()); } catch (final UnauthorizedPrivateAccessException e) { fail(); } try { AuthToken.authenticate(memeberFred); assertEquals(1, yo.getKudos().size()); fail(); } catch (final UnauthorizedPrivateAccessException e) { assertTrue(true); } } |
DaoFeature extends DaoKudosable implements DaoCommentable { public static DaoFeature createAndPersist(final DaoMember member, final DaoTeam team, final DaoDescription description, final DaoSoftware software) { final Session session = SessionManager.getSessionFactory().getCurrentSession(); final DaoFeature feature = new DaoFeature(member, team, description, software); try { session.save(feature); } catch (final HibernateException e) { session.getTransaction().rollback(); SessionManager.getSessionFactory().getCurrentSession().beginTransaction(); throw e; } DaoEvent.createFeatureEvent(feature, EventType.CREATE_FEATURE); return feature; } private DaoFeature(final DaoMember member, final DaoTeam team, final DaoDescription description, final DaoSoftware software); protected DaoFeature(); static DaoFeature createAndPersist(final DaoMember member, final DaoTeam team, final DaoDescription description, final DaoSoftware software); void setSoftware(final DaoSoftware soft); @Override void addComment(final DaoComment comment); DaoContribution addContribution(final DaoMember member, final DaoTeam team, final BigDecimal amount, final String comment); void addOffer(final DaoOffer offer); void removeOffer(final DaoOffer offer); DaoOffer computeSelectedOffer(); void setSelectedOffer(final DaoOffer selectedOffer); void setValidationDate(final Date validationDate); void setFeatureState(final FeatureState featureState); void setDescription(final String newDescription, final Language language); void setTitle(final String title, final Language language); @Field(store = Store.YES, index = Index.UN_TOKENIZED) float getProgress(); List<DaoFollowFeature> getFollowers(); DaoDescription getDescription(); PageIterable<DaoOffer> getOffers(); FeatureState getFeatureState(); PageIterable<DaoContribution> getContributions(); PageIterable<DaoContribution> getContributions(final boolean isCanceled); Long getCommentsCount(); @Override PageIterable<DaoComment> getComments(); @Override DaoComment getLastComment(); DaoOffer getSelectedOffer(); BigDecimal getContribution(); BigDecimal getContributionMin(); BigDecimal getContributionMax(); BigDecimal getContributionAvg(); BigDecimal getContributionOf(final DaoMember member); Date getValidationDate(); DaoSoftware getSoftware(); int countOpenBugs(); PageIterable<DaoBug> getOpenBugs(); PageIterable<DaoBug> getClosedBugs(); static PageIterable<DaoFeature> getAllByCreationDate(); @Override ReturnType accept(final DataClassVisitor<ReturnType> visitor); @Override int hashCode(); @Override boolean equals(final Object obj); static final int PROGRESSION_PERCENT; } | @Test public void testCreateFeature() { final DaoFeature feature = DaoFeature.createAndPersist(yo, null, DaoDescription.createAndPersist(yo, null, Language.FR, "Ma super demande !", "Ceci est la descption de ma demande :) "), project); assertEquals(feature, yo.getFeatures(false).iterator().next()); }
@Test public void testRetrieveFeature() { final DaoFeature feature = DaoFeature.createAndPersist(yo, null, DaoDescription.createAndPersist(yo, null, Language.FR, "Ma super demande !", "Ceci est la descption de ma demande :) "), project); assertEquals(feature, DBRequests.getAll(DaoFeature.class).iterator().next()); assertEquals(yo, feature.getMember()); } |
DaoFeature extends DaoKudosable implements DaoCommentable { public DaoContribution addContribution(final DaoMember member, final DaoTeam team, final BigDecimal amount, final String comment) throws NotEnoughMoneyException { if (amount == null) { throw new NonOptionalParameterException(); } if (amount.compareTo(BigDecimal.ZERO) <= 0) { Log.data().fatal("Cannot create a contribution with this amount " + amount.toEngineeringString() + " by member " + member.getId()); throw new BadProgrammerException("The amount of a contribution cannot be <= 0.", null); } if (comment != null && comment.length() > DaoContribution.COMMENT_MAX_LENGTH) { Log.data().fatal("The comment of a contribution must be <= 140 chars long."); throw new BadProgrammerException("Comments length of Contribution must be < 140.", null); } if (team != null && !team.getUserTeamRight(member).contains(UserTeamRight.BANK)) { throw new BadProgrammerException("This member cannot contribute as a team."); } final DaoContribution newContribution = new DaoContribution(member, team, this, amount, comment); this.contributions.add(newContribution); this.contribution = this.contribution.add(amount); return newContribution; } private DaoFeature(final DaoMember member, final DaoTeam team, final DaoDescription description, final DaoSoftware software); protected DaoFeature(); static DaoFeature createAndPersist(final DaoMember member, final DaoTeam team, final DaoDescription description, final DaoSoftware software); void setSoftware(final DaoSoftware soft); @Override void addComment(final DaoComment comment); DaoContribution addContribution(final DaoMember member, final DaoTeam team, final BigDecimal amount, final String comment); void addOffer(final DaoOffer offer); void removeOffer(final DaoOffer offer); DaoOffer computeSelectedOffer(); void setSelectedOffer(final DaoOffer selectedOffer); void setValidationDate(final Date validationDate); void setFeatureState(final FeatureState featureState); void setDescription(final String newDescription, final Language language); void setTitle(final String title, final Language language); @Field(store = Store.YES, index = Index.UN_TOKENIZED) float getProgress(); List<DaoFollowFeature> getFollowers(); DaoDescription getDescription(); PageIterable<DaoOffer> getOffers(); FeatureState getFeatureState(); PageIterable<DaoContribution> getContributions(); PageIterable<DaoContribution> getContributions(final boolean isCanceled); Long getCommentsCount(); @Override PageIterable<DaoComment> getComments(); @Override DaoComment getLastComment(); DaoOffer getSelectedOffer(); BigDecimal getContribution(); BigDecimal getContributionMin(); BigDecimal getContributionMax(); BigDecimal getContributionAvg(); BigDecimal getContributionOf(final DaoMember member); Date getValidationDate(); DaoSoftware getSoftware(); int countOpenBugs(); PageIterable<DaoBug> getOpenBugs(); PageIterable<DaoBug> getClosedBugs(); static PageIterable<DaoFeature> getAllByCreationDate(); @Override ReturnType accept(final DataClassVisitor<ReturnType> visitor); @Override int hashCode(); @Override boolean equals(final Object obj); static final int PROGRESSION_PERCENT; } | @Test public void testAddContribution() throws Throwable { DaoFeature feature = DaoFeature.createAndPersist(yo, null, DaoDescription.createAndPersist(yo, null, Language.FR, "Ma super demande !", "Ceci est la descption de ma demande :) "), project); fred.getInternalAccount().setAmount(new BigDecimal("100")); yo.getInternalAccount().setAmount(new BigDecimal("100")); feature.addContribution(fred, null, new BigDecimal("25.00"), "Contribution"); feature.addContribution(yo, null, new BigDecimal("18.00"), "I'm so generous"); feature = DBRequests.getById(DaoFeature.class, feature.getId()); assertEquals(2, feature.getContributions().size()); assertEquals(0, fred.getInternalAccount().getBlocked().compareTo(new BigDecimal("25"))); assertEquals(0, fred.getInternalAccount().getAmount().compareTo(new BigDecimal("75"))); assertEquals(0, yo.getInternalAccount().getBlocked().compareTo(new BigDecimal("18"))); assertEquals(0, yo.getInternalAccount().getAmount().compareTo(new BigDecimal("82"))); super.closeDB(); super.createDB(); } |
DaoFeature extends DaoKudosable implements DaoCommentable { public void addOffer(final DaoOffer offer) { this.offers.add(offer); DaoEvent.createOfferEvent(this, EventType.ADD_OFFER, offer); } private DaoFeature(final DaoMember member, final DaoTeam team, final DaoDescription description, final DaoSoftware software); protected DaoFeature(); static DaoFeature createAndPersist(final DaoMember member, final DaoTeam team, final DaoDescription description, final DaoSoftware software); void setSoftware(final DaoSoftware soft); @Override void addComment(final DaoComment comment); DaoContribution addContribution(final DaoMember member, final DaoTeam team, final BigDecimal amount, final String comment); void addOffer(final DaoOffer offer); void removeOffer(final DaoOffer offer); DaoOffer computeSelectedOffer(); void setSelectedOffer(final DaoOffer selectedOffer); void setValidationDate(final Date validationDate); void setFeatureState(final FeatureState featureState); void setDescription(final String newDescription, final Language language); void setTitle(final String title, final Language language); @Field(store = Store.YES, index = Index.UN_TOKENIZED) float getProgress(); List<DaoFollowFeature> getFollowers(); DaoDescription getDescription(); PageIterable<DaoOffer> getOffers(); FeatureState getFeatureState(); PageIterable<DaoContribution> getContributions(); PageIterable<DaoContribution> getContributions(final boolean isCanceled); Long getCommentsCount(); @Override PageIterable<DaoComment> getComments(); @Override DaoComment getLastComment(); DaoOffer getSelectedOffer(); BigDecimal getContribution(); BigDecimal getContributionMin(); BigDecimal getContributionMax(); BigDecimal getContributionAvg(); BigDecimal getContributionOf(final DaoMember member); Date getValidationDate(); DaoSoftware getSoftware(); int countOpenBugs(); PageIterable<DaoBug> getOpenBugs(); PageIterable<DaoBug> getClosedBugs(); static PageIterable<DaoFeature> getAllByCreationDate(); @Override ReturnType accept(final DataClassVisitor<ReturnType> visitor); @Override int hashCode(); @Override boolean equals(final Object obj); static final int PROGRESSION_PERCENT; } | @Test public void testAddOffer() { DaoFeature feature = DaoFeature.createAndPersist(yo, null, DaoDescription.createAndPersist(yo, null, Language.FR, "Ma super demande !", "Ceci est la descption de ma demande :) "), project); feature = DBRequests.getById(DaoFeature.class, feature.getId()); feature.addOffer(createOffer(feature)); assertEquals(1, feature.getOffers().size()); } |
DaoFeature extends DaoKudosable implements DaoCommentable { @Override public void addComment(final DaoComment comment) { this.comments.add(comment); } private DaoFeature(final DaoMember member, final DaoTeam team, final DaoDescription description, final DaoSoftware software); protected DaoFeature(); static DaoFeature createAndPersist(final DaoMember member, final DaoTeam team, final DaoDescription description, final DaoSoftware software); void setSoftware(final DaoSoftware soft); @Override void addComment(final DaoComment comment); DaoContribution addContribution(final DaoMember member, final DaoTeam team, final BigDecimal amount, final String comment); void addOffer(final DaoOffer offer); void removeOffer(final DaoOffer offer); DaoOffer computeSelectedOffer(); void setSelectedOffer(final DaoOffer selectedOffer); void setValidationDate(final Date validationDate); void setFeatureState(final FeatureState featureState); void setDescription(final String newDescription, final Language language); void setTitle(final String title, final Language language); @Field(store = Store.YES, index = Index.UN_TOKENIZED) float getProgress(); List<DaoFollowFeature> getFollowers(); DaoDescription getDescription(); PageIterable<DaoOffer> getOffers(); FeatureState getFeatureState(); PageIterable<DaoContribution> getContributions(); PageIterable<DaoContribution> getContributions(final boolean isCanceled); Long getCommentsCount(); @Override PageIterable<DaoComment> getComments(); @Override DaoComment getLastComment(); DaoOffer getSelectedOffer(); BigDecimal getContribution(); BigDecimal getContributionMin(); BigDecimal getContributionMax(); BigDecimal getContributionAvg(); BigDecimal getContributionOf(final DaoMember member); Date getValidationDate(); DaoSoftware getSoftware(); int countOpenBugs(); PageIterable<DaoBug> getOpenBugs(); PageIterable<DaoBug> getClosedBugs(); static PageIterable<DaoFeature> getAllByCreationDate(); @Override ReturnType accept(final DataClassVisitor<ReturnType> visitor); @Override int hashCode(); @Override boolean equals(final Object obj); static final int PROGRESSION_PERCENT; } | @Test public void testAddComment() throws Throwable { DaoFeature feature = DaoFeature.createAndPersist(yo, null, DaoDescription.createAndPersist(yo, null, Language.FR, "Ma super demande !", "Ceci est la descption de ma demande :) "), project); feature.addComment(DaoComment.createAndPersist(feature, null, yo, "4")); feature.addComment(DaoComment.createAndPersist(feature, null, yo, "3")); feature.addComment(DaoComment.createAndPersist(feature, null, yo, "2")); feature.addComment(DaoComment.createAndPersist(feature, null, yo, "1")); feature = DBRequests.getById(DaoFeature.class, feature.getId()); assertEquals(4, feature.getComments().size()); } |
JsonToElementParser { public List<Element> createWebItems(InputStream in) { List<Element> items = newArrayList(); DocumentFactory factory = DocumentFactory.getInstance(); try { if (in == null) { return emptyList(); } final String content = StringUtils.join(IOUtils.readLines(in), "\n"); JSONArray root = new JSONArray(stripComments(content)); for (int x=0; x<root.length(); x++) { Element element = factory.createElement("scoped-web-item"); element.addAttribute("key", "item-" + x); JSONObject item = root.getJSONObject(x); if (!item.isNull("section")) { element.addAttribute("section", item.getString("section")); } if (!item.isNull("label")) { element.addElement("label").setText(item.getString("label")); } if (hasLink(item)) { Element link = element.addElement("link"); link.setText(getLink(item)); if (!item.isNull("cssId")) { link.addAttribute("linkId", item.getString("cssId")); } } if (!item.isNull("cssName")) { element.addElement("styleClass").setText(item.getString("cssName")); } if (!item.isNull("weight")) { element.addAttribute("weight", item.getString("weight")); } if (!item.isNull("tooltip")) { element.addElement("tooltip").setText(item.getString("tooltip")); } if (!item.isNull("icon")) { JSONObject iconJson = item.getJSONObject("icon"); Element iconE = element.addElement("icon"); if (!iconJson.isNull("width")) { iconE.addAttribute("width", iconJson.getString("width")); } if (!iconJson.isNull("height")) { iconE.addAttribute("height", iconJson.getString("height")); } if (hasLink(iconJson)) { iconE.addElement("link").setText(getLink(iconJson)); } } items.add(element); } } catch (IOException e) { throw new PluginOperationFailedException("Unable to read ui/web-items.json", e, null); } catch (JSONException e) { throw new PluginOperationFailedException("Unable to parse ui/web-items.json: " + e.getMessage(), e, null); } finally { IOUtils.closeQuietly(in); } return items; } List<Element> createWebItems(InputStream in); } | @Test public void testMinimal() { List<Element> list = jsonToElementParser.createWebItems(new ByteArrayInputStream("\n[{\"section\":\"foo\",\"weight\":40}\n]".getBytes())); assertNotNull(list); assertEquals(1, list.size()); assertEquals("foo", list.get(0).attributeValue("section")); }
@Test public void testMinimalNoComment() { List<Element> list = jsonToElementParser.createWebItems(new ByteArrayInputStream("[{\"section\":\"foo\",\"weight\":40}\n]".getBytes())); assertNotNull(list); assertEquals(1, list.size()); assertEquals("foo", list.get(0).attributeValue("section")); } |
JsDocParser { public static JsDoc parse(String moduleId, String content) { if (content == null) { return EMPTY_JSDOC; } if (content.startsWith("/**")) { final String noStars = stripStars(content); Iterable<String> tokens = filter(asList(noStars.split("(?:^|[\\r\\n])\\s*@")), new Predicate<String>() { public boolean apply(String input) { return input.trim().length() > 0; } }); ListMultimap<String,String> tags = ArrayListMultimap.create(); int x = 0; for (String token : tokens) { if (x++ == 0 && !noStars.startsWith("@")) { tags.put(DESCRIPTION, token.trim()); } else { int spacePos = token.indexOf(' '); if (spacePos > -1) { String value = token.substring(spacePos + 1); StringBuilder sb = new StringBuilder(); for (String line : value.split("(?:\\r\\n)|\\r|\\n")) { sb.append(line.trim()).append(" "); } tags.put(token.substring(0, spacePos).toLowerCase(), sb.toString().trim()); } else { tags.put(token.toLowerCase(), token.toLowerCase()); } } } Map<String,Collection<String>> attributes = tags.asMap(); Collection<String> descriptions = attributes.remove(DESCRIPTION); return new JsDoc(descriptions != null ? descriptions.iterator().next() : null, attributes); } else { log.debug("Module '{}' doesn't start with /** so not parsed as a jsdoc comment", moduleId); return EMPTY_JSDOC; } } static JsDoc parse(String moduleId, String content); static final JsDoc EMPTY_JSDOC; } | @Test public void testExtractAttributesMultiline() { JsDoc doc = JsDocParser.parse("foo", ""); assertEquals("bar jim", doc.getAttribute("foo")); } |
KeyExtractor { public static String extractFromFilename(String fileName) { String name = stripExtension(fileName); Matcher m = TEMP_FILENAME_WITH_VERSION.matcher(name); if (m.matches()) { return m.group(1); } else { m = UPLOADED_FILENAME_WITH_VERSION.matcher(name); if (m.matches()) { return m.group(1); } } return name; } static String extractFromFilename(String fileName); static File createExtractableTempFile(String key, String suffix); static final String SPEAKEASY_KEY_SEPARATOR; } | @Test public void testKeyFromFilename() { assertEquals("foo", KeyExtractor.extractFromFilename("foo")); assertEquals("foo", KeyExtractor.extractFromFilename("foo.zip")); assertEquals("foo", KeyExtractor.extractFromFilename("foo.jar")); assertEquals("foo", KeyExtractor.extractFromFilename("foo-1.zip")); assertEquals("foo", KeyExtractor.extractFromFilename("foo-1-bar-2.zip")); assertEquals("foo", KeyExtractor.extractFromFilename("foo-1.0.zip")); assertEquals("foo-bar", KeyExtractor.extractFromFilename("foo-bar.zip")); }
@Test public void testKeyFromTempFilename() { assertEquals("foo", KeyExtractor.extractFromFilename("foo----speakeasy-bar")); assertEquals("foo", KeyExtractor.extractFromFilename("foo----speakeasy-bar.zip")); assertEquals("foo-1", KeyExtractor.extractFromFilename("foo-1----speakeasy-jim.jar")); } |
RepositoryDirectoryUtil { public static List<String> getEntries(File root) { return walk(root.toURI(), root); } static List<String> getEntries(File root); static List<String> walk(URI root, File dir); } | @Test public void testGetEntries() throws IOException { final File dir = tmp.newFolder("names"); new File(dir, "foo.txt").createNewFile(); new File(dir, "a/b").mkdirs(); new File(dir, "a/bar.txt").createNewFile(); new File(dir, "c").mkdirs(); assertEquals(newArrayList("a/", "a/b/", "a/bar.txt", "c/", "foo.txt"), RepositoryDirectoryUtil.getEntries(dir)); } |
JsDocParser { static String stripStars(String jsDoc) { String noStartOrEndStars = jsDoc != null ? jsDoc.replaceAll("^\\/\\*\\*|\\*\\/$", "") : ""; String result = Pattern.compile("^\\s*\\* ?", Pattern.MULTILINE).matcher(noStartOrEndStars).replaceAll(""); return result.trim(); } static JsDoc parse(String moduleId, String content); static final JsDoc EMPTY_JSDOC; } | @Test public void testStripStarsJsDocMultilineComment() { assertEquals("foo", JsDocParser.stripStars("")); }
@Test public void testStripStarsJsDocMultilineCommentWithStars() { assertEquals("foo", JsDocParser.stripStars("")); }
@Test public void testStripStarsJsDocMultilineCommentWithSpaceStars() { assertEquals("foo", JsDocParser.stripStars("")); }
@Test public void testStripStarsJsDocOneLineComment() { assertEquals("foo", JsDocParser.stripStars("")); } |
JsDocParser { static Map<String,String> extractAttributes(String jsDocWithNoStars) { return null; } static JsDoc parse(String moduleId, String content); static final JsDoc EMPTY_JSDOC; } | @Test public void testExtractAttributes() { JsDoc doc = JsDocParser.parse("foo", ""); assertEquals("Desc", doc.getDescription()); assertEquals("bar", doc.getAttribute("foo")); assertEquals("jim bob", doc.getAttribute("baz")); } |
VersionUtils { public static Optional<SentinelVersion> parseVersion(String s) { if (StringUtil.isBlank(s)) { return Optional.empty(); } try { String versionFull = s; SentinelVersion version = new SentinelVersion(); int index = versionFull.indexOf("-"); if (index == 0) { return Optional.empty(); } if (index == versionFull.length() - 1) { } else if (index > 0) { version.setPostfix(versionFull.substring(index + 1)); } if (index >= 0) { versionFull = versionFull.substring(0, index); } int segment = 0; int[] ver = new int[3]; while (segment < ver.length) { index = versionFull.indexOf('.'); if (index < 0) { if (versionFull.length() > 0) { ver[segment] = Integer.valueOf(versionFull); } break; } ver[segment] = Integer.valueOf(versionFull.substring(0, index)); versionFull = versionFull.substring(index + 1); segment ++; } if (ver[0] < 1) { return Optional.empty(); } else { return Optional.of(version .setMajorVersion(ver[0]) .setMinorVersion(ver[1]) .setFixVersion(ver[2])); } } catch (Exception ex) { return Optional.empty(); } } private VersionUtils(); static Optional<SentinelVersion> parseVersion(String s); } | @Test public void test() { Optional<SentinelVersion> version = VersionUtils.parseVersion("1.2.3"); assertTrue(version.isPresent()); assertEquals(1, version.get().getMajorVersion()); assertEquals(2, version.get().getMinorVersion()); assertEquals(3, version.get().getFixVersion()); assertNull(version.get().getPostfix()); version = VersionUtils.parseVersion("1.2"); assertTrue(version.isPresent()); assertEquals(1, version.get().getMajorVersion()); assertEquals(2, version.get().getMinorVersion()); assertEquals(0, version.get().getFixVersion()); assertNull(version.get().getPostfix()); version = VersionUtils.parseVersion("1."); assertTrue(version.isPresent()); assertEquals(1, version.get().getMajorVersion()); assertEquals(0, version.get().getMinorVersion()); assertEquals(0, version.get().getFixVersion()); assertNull(version.get().getPostfix()); version = VersionUtils.parseVersion("1.2."); assertTrue(version.isPresent()); assertEquals(1, version.get().getMajorVersion()); assertEquals(2, version.get().getMinorVersion()); assertEquals(0, version.get().getFixVersion()); assertNull(version.get().getPostfix()); version = VersionUtils.parseVersion("1.2.3."); assertTrue(version.isPresent()); assertEquals(1, version.get().getMajorVersion()); assertEquals(2, version.get().getMinorVersion()); assertEquals(3, version.get().getFixVersion()); assertNull(version.get().getPostfix()); version = VersionUtils.parseVersion("1.2.3.4"); assertTrue(version.isPresent()); assertEquals(1, version.get().getMajorVersion()); assertEquals(2, version.get().getMinorVersion()); assertEquals(3, version.get().getFixVersion()); assertNull(version.get().getPostfix()); version = VersionUtils.parseVersion("1"); assertTrue(version.isPresent()); assertEquals(1, version.get().getMajorVersion()); assertEquals(0, version.get().getMinorVersion()); assertEquals(0, version.get().getFixVersion()); assertNull(version.get().getPostfix()); version = VersionUtils.parseVersion("1.2.3-"); assertTrue(version.isPresent()); assertEquals(1, version.get().getMajorVersion()); assertEquals(2, version.get().getMinorVersion()); assertEquals(3, version.get().getFixVersion()); assertNull(version.get().getPostfix()); version = VersionUtils.parseVersion("-"); assertFalse(version.isPresent()); version = VersionUtils.parseVersion("-t"); assertFalse(version.isPresent()); version = VersionUtils.parseVersion(""); assertFalse(version.isPresent()); version = VersionUtils.parseVersion(null); assertFalse(version.isPresent()); version = VersionUtils.parseVersion("1.2.3-SNAPSHOTS"); assertTrue(version.isPresent()); assertEquals(1, version.get().getMajorVersion()); assertEquals(2, version.get().getMinorVersion()); assertEquals(3, version.get().getFixVersion()); assertEquals("SNAPSHOTS", version.get().getPostfix()); } |
DashboardConfig { protected static int getConfigInt(String name, int defaultVal, int minVal) { if (cacheMap.containsKey(name)) { return (int)cacheMap.get(name); } int val = NumberUtils.toInt(getConfig(name)); if (val == 0) { val = defaultVal; } else if (val < minVal) { val = minVal; } cacheMap.put(name, val); return val; } static String getAuthUsername(); static String getAuthPassword(); static int getHideAppNoMachineMillis(); static int getRemoveAppNoMachineMillis(); static int getAutoRemoveMachineMillis(); static int getUnhealthyMachineMillis(); static void clearCache(); static final int DEFAULT_MACHINE_HEALTHY_TIMEOUT_MS; static final String CONFIG_AUTH_USERNAME; static final String CONFIG_AUTH_PASSWORD; static final String CONFIG_HIDE_APP_NO_MACHINE_MILLIS; static final String CONFIG_REMOVE_APP_NO_MACHINE_MILLIS; static final String CONFIG_UNHEALTHY_MACHINE_MILLIS; static final String CONFIG_AUTO_REMOVE_MACHINE_MILLIS; } | @Test public void testGetConfigInt() { DashboardConfig.clearCache(); assertEquals(0, DashboardConfig.getConfigInt("t", 0, 10)); DashboardConfig.clearCache(); assertEquals(1, DashboardConfig.getConfigInt("t", 1, 10)); System.setProperty("t", "asdf"); DashboardConfig.clearCache(); assertEquals(0, DashboardConfig.getConfigInt("t", 0, 10)); System.setProperty("t", ""); DashboardConfig.clearCache(); assertEquals(0, DashboardConfig.getConfigInt("t", 0, 10)); System.setProperty("t", "2"); DashboardConfig.clearCache(); assertEquals(2, DashboardConfig.getConfigInt("t", 0, 1)); DashboardConfig.clearCache(); assertEquals(10, DashboardConfig.getConfigInt("t", 0, 10)); DashboardConfig.clearCache(); assertEquals(2, DashboardConfig.getConfigInt("t", 0, -1)); environmentVariables.set("t", "20"); DashboardConfig.clearCache(); assertEquals(20, DashboardConfig.getConfigInt("t", 0, 10)); environmentVariables.set("t", "20dddd"); DashboardConfig.clearCache(); assertEquals(0, DashboardConfig.getConfigInt("t", 0, 10)); environmentVariables.set("t", ""); DashboardConfig.clearCache(); assertEquals(10, DashboardConfig.getConfigInt("t", 0, 10)); DashboardConfig.clearCache(); assertEquals(2, DashboardConfig.getConfigInt("t", 0, 1)); System.setProperty("t", "666"); DashboardConfig.clearCache(); assertEquals(666, DashboardConfig.getConfigInt("t", 0, 1)); System.setProperty("t", "777"); assertEquals(666, DashboardConfig.getConfigInt("t", 0, 1)); System.setProperty("t", "555"); assertEquals(666, DashboardConfig.getConfigInt("t", 0, 1)); } |
InMemoryMetricsRepository implements MetricsRepository<MetricEntity> { @Override public void save(MetricEntity entity) { if (entity == null || StringUtil.isBlank(entity.getApp())) { return; } readWriteLock.writeLock().lock(); try { allMetrics.computeIfAbsent(entity.getApp(), e -> new HashMap<>(16)) .computeIfAbsent(entity.getResource(), e -> new LinkedHashMap<Long, MetricEntity>() { @Override protected boolean removeEldestEntry(Entry<Long, MetricEntity> eldest) { return eldest.getKey() < TimeUtil.currentTimeMillis() - MAX_METRIC_LIVE_TIME_MS; } }).put(entity.getTimestamp().getTime(), entity); } finally { readWriteLock.writeLock().unlock(); } } @Override void save(MetricEntity entity); @Override void saveAll(Iterable<MetricEntity> metrics); @Override List<MetricEntity> queryByAppAndResourceBetween(String app, String resource,
long startTime, long endTime); @Override List<String> listResourcesOfApp(String app); } | @Test public void testSave() { MetricEntity entry = new MetricEntity(); entry.setApp("testSave"); entry.setResource("testResource"); entry.setTimestamp(new Date(System.currentTimeMillis())); entry.setPassQps(1L); entry.setExceptionQps(1L); entry.setBlockQps(0L); entry.setSuccessQps(1L); inMemoryMetricsRepository.save(entry); List<String> resources = inMemoryMetricsRepository.listResourcesOfApp("testSave"); Assert.assertTrue(resources.size() == 1 && "testResource".equals(resources.get(0))); } |
InMemoryMetricsRepository implements MetricsRepository<MetricEntity> { @Override public void saveAll(Iterable<MetricEntity> metrics) { if (metrics == null) { return; } readWriteLock.writeLock().lock(); try { metrics.forEach(this::save); } finally { readWriteLock.writeLock().unlock(); } } @Override void save(MetricEntity entity); @Override void saveAll(Iterable<MetricEntity> metrics); @Override List<MetricEntity> queryByAppAndResourceBetween(String app, String resource,
long startTime, long endTime); @Override List<String> listResourcesOfApp(String app); } | @Test public void testSaveAll() { List<MetricEntity> entities = new ArrayList<>(10000); for (int i = 0; i < 10000; i++) { MetricEntity entry = new MetricEntity(); entry.setApp("testSaveAll"); entry.setResource("testResource" + i); entry.setTimestamp(new Date(System.currentTimeMillis())); entry.setPassQps(1L); entry.setExceptionQps(1L); entry.setBlockQps(0L); entry.setSuccessQps(1L); entities.add(entry); } inMemoryMetricsRepository.saveAll(entities); List<String> result = inMemoryMetricsRepository.listResourcesOfApp("testSaveAll"); Assert.assertTrue(result.size() == entities.size()); } |
InMemoryMetricsRepository implements MetricsRepository<MetricEntity> { @Override public List<String> listResourcesOfApp(String app) { List<String> results = new ArrayList<>(); if (StringUtil.isBlank(app)) { return results; } Map<String, LinkedHashMap<Long, MetricEntity>> resourceMap = allMetrics.get(app); if (resourceMap == null) { return results; } final long minTimeMs = System.currentTimeMillis() - 1000 * 60; Map<String, MetricEntity> resourceCount = new ConcurrentHashMap<>(32); readWriteLock.readLock().lock(); try { for (Entry<String, LinkedHashMap<Long, MetricEntity>> resourceMetrics : resourceMap.entrySet()) { for (Entry<Long, MetricEntity> metrics : resourceMetrics.getValue().entrySet()) { if (metrics.getKey() < minTimeMs) { continue; } MetricEntity newEntity = metrics.getValue(); if (resourceCount.containsKey(resourceMetrics.getKey())) { MetricEntity oldEntity = resourceCount.get(resourceMetrics.getKey()); oldEntity.addPassQps(newEntity.getPassQps()); oldEntity.addRtAndSuccessQps(newEntity.getRt(), newEntity.getSuccessQps()); oldEntity.addBlockQps(newEntity.getBlockQps()); oldEntity.addExceptionQps(newEntity.getExceptionQps()); oldEntity.addCount(1); } else { resourceCount.put(resourceMetrics.getKey(), MetricEntity.copyOf(newEntity)); } } } return resourceCount.entrySet() .stream() .sorted((o1, o2) -> { MetricEntity e1 = o1.getValue(); MetricEntity e2 = o2.getValue(); int t = e2.getBlockQps().compareTo(e1.getBlockQps()); if (t != 0) { return t; } return e2.getPassQps().compareTo(e1.getPassQps()); }) .map(Entry::getKey) .collect(Collectors.toList()); } finally { readWriteLock.readLock().unlock(); } } @Override void save(MetricEntity entity); @Override void saveAll(Iterable<MetricEntity> metrics); @Override List<MetricEntity> queryByAppAndResourceBetween(String app, String resource,
long startTime, long endTime); @Override List<String> listResourcesOfApp(String app); } | @Test public void testConcurrentPutAndGet() { List<CompletableFuture> futures = new ArrayList<>(10000); final CyclicBarrier cyclicBarrier = new CyclicBarrier(8); for (int j = 0; j < 10000; j++) { final int finalJ = j; futures.add(CompletableFuture.runAsync(() -> { try { cyclicBarrier.await(); if (finalJ % 2 == 0) { batchSave(); } else { inMemoryMetricsRepository.listResourcesOfApp(DEFAULT_APP); } } catch (InterruptedException | BrokenBarrierException e) { e.printStackTrace(); } }, executorService) ); } CompletableFuture all = CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])); try { all.get(10, TimeUnit.SECONDS); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.getCause().printStackTrace(); if (e.getCause() instanceof ConcurrentModificationException) { fail("concurrent error occurred"); } else { fail("unexpected exception"); } } catch (TimeoutException e) { fail("allOf future timeout"); } } |
SentinelApiClient { protected static HttpUriRequest postRequest(String url, Map<String, String> params, boolean supportEnhancedContentType) { HttpPost httpPost = new HttpPost(url); if (params != null && params.size() > 0) { List<NameValuePair> list = new ArrayList<>(params.size()); for (Entry<String, String> entry : params.entrySet()) { list.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); } httpPost.setEntity(new UrlEncodedFormEntity(list, Consts.UTF_8)); if (!supportEnhancedContentType) { httpPost.setHeader(HTTP_HEADER_CONTENT_TYPE, HTTP_HEADER_CONTENT_TYPE_URLENCODED); } } return httpPost; } SentinelApiClient(); void close(); List<NodeVo> fetchResourceOfMachine(String ip, int port, String type); List<NodeVo> fetchClusterNodeOfMachine(String ip, int port, boolean includeZero); List<FlowRuleEntity> fetchFlowRuleOfMachine(String app, String ip, int port); List<DegradeRuleEntity> fetchDegradeRuleOfMachine(String app, String ip, int port); List<SystemRuleEntity> fetchSystemRuleOfMachine(String app, String ip, int port); CompletableFuture<List<ParamFlowRuleEntity>> fetchParamFlowRulesOfMachine(String app, String ip, int port); List<AuthorityRuleEntity> fetchAuthorityRulesOfMachine(String app, String ip, int port); boolean setFlowRuleOfMachine(String app, String ip, int port, List<FlowRuleEntity> rules); CompletableFuture<Void> setFlowRuleOfMachineAsync(String app, String ip, int port, List<FlowRuleEntity> rules); boolean setDegradeRuleOfMachine(String app, String ip, int port, List<DegradeRuleEntity> rules); boolean setSystemRuleOfMachine(String app, String ip, int port, List<SystemRuleEntity> rules); boolean setAuthorityRuleOfMachine(String app, String ip, int port, List<AuthorityRuleEntity> rules); CompletableFuture<Void> setParamFlowRuleOfMachine(String app, String ip, int port, List<ParamFlowRuleEntity> rules); CompletableFuture<ClusterStateSimpleEntity> fetchClusterMode(String ip, int port); CompletableFuture<Void> modifyClusterMode(String ip, int port, int mode); CompletableFuture<ClusterClientInfoVO> fetchClusterClientInfoAndConfig(String ip, int port); CompletableFuture<Void> modifyClusterClientConfig(String app, String ip, int port, ClusterClientConfig config); CompletableFuture<Void> modifyClusterServerFlowConfig(String app, String ip, int port, ServerFlowConfig config); CompletableFuture<Void> modifyClusterServerTransportConfig(String app, String ip, int port, ServerTransportConfig config); CompletableFuture<Void> modifyClusterServerNamespaceSet(String app, String ip, int port, Set<String> set); CompletableFuture<ClusterServerStateVO> fetchClusterServerBasicInfo(String ip, int port); CompletableFuture<List<ApiDefinitionEntity>> fetchApis(String app, String ip, int port); boolean modifyApis(String app, String ip, int port, List<ApiDefinitionEntity> apis); CompletableFuture<List<GatewayFlowRuleEntity>> fetchGatewayFlowRules(String app, String ip, int port); boolean modifyGatewayFlowRules(String app, String ip, int port, List<GatewayFlowRuleEntity> rules); } | @Test public void postRequest() throws HttpException, IOException { RequestContent processor = new RequestContent(); Map<String, String> params = new HashMap<String, String>(); params.put("a", "1"); params.put("b", "2+"); params.put("c", "3 "); HttpUriRequest request; request = SentinelApiClient.postRequest("/test", params, false); assertNotNull(request); processor.process(request, null); assertNotNull(request.getFirstHeader("Content-Type")); assertEquals("application/x-www-form-urlencoded", request.getFirstHeader("Content-Type").getValue()); request = SentinelApiClient.postRequest("/test", params, true); assertNotNull(request); processor.process(request, null); assertNotNull(request.getFirstHeader("Content-Type")); assertEquals("application/x-www-form-urlencoded; charset=UTF-8", request.getFirstHeader("Content-Type").getValue()); } |
SentinelVersion { public boolean greaterThan(SentinelVersion version) { if (version == null) { return true; } return getFullVersion() > version.getFullVersion(); } SentinelVersion(); SentinelVersion(int major, int minor, int fix); SentinelVersion(int major, int minor, int fix, String postfix); int getFullVersion(); int getMajorVersion(); SentinelVersion setMajorVersion(int majorVersion); int getMinorVersion(); SentinelVersion setMinorVersion(int minorVersion); int getFixVersion(); SentinelVersion setFixVersion(int fixVersion); String getPostfix(); SentinelVersion setPostfix(String postfix); boolean greaterThan(SentinelVersion version); boolean greaterOrEqual(SentinelVersion version); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); } | @Test public void testGreater() { assertTrue(new SentinelVersion(2, 0, 0).greaterThan(new SentinelVersion(1, 0, 0))); assertTrue(new SentinelVersion(1, 1, 0).greaterThan(new SentinelVersion(1, 0, 0))); assertTrue(new SentinelVersion(1, 1, 2).greaterThan(new SentinelVersion(1, 1, 0))); assertTrue(new SentinelVersion(1, 1, 4).greaterThan(new SentinelVersion(1, 1, 3))); assertFalse(new SentinelVersion(1, 0, 0).greaterThan(new SentinelVersion(1, 0, 0))); assertFalse(new SentinelVersion(1, 0, 0).greaterThan(new SentinelVersion(1, 1, 0))); assertFalse(new SentinelVersion(1, 1, 3).greaterThan(new SentinelVersion(1, 1, 3))); assertFalse(new SentinelVersion(1, 1, 2).greaterThan(new SentinelVersion(1, 1, 3))); assertFalse(new SentinelVersion(1, 0, 0, "").greaterThan(new SentinelVersion(1, 0, 0))); assertTrue(new SentinelVersion(1, 0, 1).greaterThan(new SentinelVersion(1, 0, 0))); assertTrue(new SentinelVersion(1, 0, 1, "a").greaterThan(new SentinelVersion(1, 0, 0, "b"))); assertFalse(new SentinelVersion(1, 0, 0, "b").greaterThan(new SentinelVersion(1, 0, 0, "a"))); } |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.