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.ma...
@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...
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; } @Overrid...
@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."); Tr...
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().equ...
@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 voi...
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 && transac...
@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 { ISi...
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(ac...
@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.t...
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)...
@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 Reg...
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 = ...
@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 getWe...
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 (!color...
@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 ColoredCoinPrope...
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 getGen...
@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 ge...
@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 ...
@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(); ExecutionCo...
@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("Snapsho...
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"))) { bencodeSt...
@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:TYP...
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()...
@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 = Build...
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."); Transacti...
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.suc...
@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.newT...
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 timePro...
@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...
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> a...
@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 transa...
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 (se...
@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 unsp...
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 ...
@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(networkI...
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,...
@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, delega...
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 time...
@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)...
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("...
@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(Validate...
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 Va...
@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 se...
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, IL...
@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...
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.getConfirmingAccou...
@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(t...
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()) { Validatio...
@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_succ...
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(stat...
@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") ) ....
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); } } ...
@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));...
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(...
@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...
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 Co...
@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())...
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 userIdPr...
@Test public void testUnarchiveLegacyQueueState() throws IOException, NoSuchFieldException, IllegalAccessException { Queue.UploadRequester uploadRequester = mock(Queue.UploadRequester.class); String legacyQueueState = "{\"config\":{\"acceptSameEventAfter\":1,\"uploadWhenMoreThan\":2," + "\"uploadWhenOlderThan\":3},\"qu...
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 DaoT...
@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...
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, te...
@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 NonOpti...
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....
@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.addChildCommen...
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, ...
@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(FeatureImplementa...
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, fi...
@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.canAccessComme...
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, ...
@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(feat...
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 ...
@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....
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) ...
@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 (fina...
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 RgtFe...
@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); f...
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.getI...
@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.ACTIV...
FeatureImplementation extends Kudosable<DaoFeature> implements Feature { @Override public void cancelDevelopment() throws UnauthorizedOperationException { throwWrongStateExceptionOnNondevelopingState(); getSelectedOffer().tryAccess(new RgtOffer.SelectedOffer(), Action.WRITE); setStateObject(getStateObject().eventDevelo...
@Test public void testCancelDevelopment() throws NotEnoughMoneyException, UnauthorizedOperationException { final Feature feature = createFeatureAddOffer120AddContribution120BeginDev(); Mockit.setUpMock(DaoFeature.class, new MockFeatureValidationTimeOut()); try { feature.cancelDevelopment(); fail(); } catch (final Unaut...
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(...
@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(); fi...
@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 St...
@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()); t...
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 DaoAc...
@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(); } cat...
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 DaoAc...
@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(); } cat...
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<?> getActorFr...
@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(); } ...
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 g...
@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().getCont...
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 ge...
@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(); ...
@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(...
@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.canGetInternalAccoun...
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(...
@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.canGetExternalAccoun...
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 = saved...
@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...
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 getDateCr...
@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...
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(); fi...
@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, ...
@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...
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, ...
@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 BankTrans...
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, ...
@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 group...
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, ...
@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 group...
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, ...
@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 extends Identifiable<DaoBankTransaction> { public final boolean canGetModificationDate() { return canAccess(new RgtBankTransaction.ModificationDate(), Action.READ); } BankTransaction(final String message, final String token, final Actor<?> author, ...
@Test public final void testCanGetModificationDate() { final BankTransaction bankTransaction = BankTransaction.create(db.getYoBankTransaction()); AuthToken.authenticate(memeberFred); assertFalse(bankTransaction.canGetModificationDate()); AuthToken.authenticate(memberYo); assertTrue(bankTransaction.canGetModificationDat...
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, ...
@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 BankTrans...
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, ...
@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 gr...
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 == nu...
@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) { ...
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(); fin...
@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...
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...
@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); assert...
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 c...
@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); assertFal...
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(); f...
@Test public void testCanAccessCreationDate() { final InternalAccount tomAccount = InternalAccount.create(db.getTom().getInternalAccount()); AuthToken.unAuthenticate(); assertFalse(tomAccount.canAccessCreationDate()); AuthToken.authenticate(memberTom); assertTrue(tomAccount.canAccessCreationDate()); AuthToken.authentic...
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 canAccessC...
@Test public void testCanAccessLastModificationDate() { final InternalAccount tomAccount = InternalAccount.create(db.getTom().getInternalAccount()); AuthToken.unAuthenticate(); assertFalse(tomAccount.canAccessLastModificationDate()); AuthToken.authenticate(memberTom); assertTrue(tomAccount.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 canAccessA...
@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.authentica...
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 canAccessActo...
@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.ge...
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 b...
@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); t...
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()...
@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.getA...
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 c...
@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); t...
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<Dao...
@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 ...
@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...
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); Me...
@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,...
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);...
@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 P...
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, fina...
@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 pass...
@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...
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); Mem...
@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 Unau...
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...
@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 ...
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(BigDecima...
@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.getInter...
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); p...
@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(f...
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...
@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")); fea...
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(st...
@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 testMinimalNoCom...
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 app...
@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;...
@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("fo...
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"), Reposi...
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, Stri...
@Test public void testStripStarsJsDocMultilineComment() { assertEquals("foo", JsDocParser.stripStars("")); } @Test public void testStripStarsJsDocMultilineCommentWithStars() { assertEquals("foo", JsDocParser.stripStars("")); } @Test public void testStripStarsJsDocMultilineCommentWithSpaceStars() { assertEquals("foo", J...
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 == versionFu...
@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()); ...
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 va...
@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.getConfi...
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(ent...
@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(e...
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(MetricEnti...
@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.set...
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 (resourceM...
@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) { bat...
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 : pa...
@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", pa...
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(); i...
@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, ...