method2testcases stringlengths 118 3.08k |
|---|
### Question:
ShardDataSourceCreateHelper { public Long getShardId() { return shardId; } ShardDataSourceCreateHelper(DatabaseManager databaseManager); ShardDataSourceCreateHelper(DatabaseManager databaseManager, Long shardId); Long getShardId(); String getShardName(); TransactionalDataSource getShardDb(); ShardDataSourceCreateHelper createUninitializedDataSource(); String checkGenerateShardName(); static final int MAX_CACHE_SIZE; static final int MAX_CONNECTIONS; static final int MAX_MEMORY_ROWS; }### Answer:
@Test void getShardId() { createHelper = new ShardDataSourceCreateHelper(extension.getDatabaseManager(), null); createHelper.createUninitializedDataSource(); long shardId = createHelper.getShardId(); assertEquals(3, shardId); } |
### Question:
ShardDataSourceCreateHelper { public String getShardName() { return shardName; } ShardDataSourceCreateHelper(DatabaseManager databaseManager); ShardDataSourceCreateHelper(DatabaseManager databaseManager, Long shardId); Long getShardId(); String getShardName(); TransactionalDataSource getShardDb(); ShardDataSourceCreateHelper createUninitializedDataSource(); String checkGenerateShardName(); static final int MAX_CACHE_SIZE; static final int MAX_CONNECTIONS; static final int MAX_MEMORY_ROWS; }### Answer:
@Test void getShardName() { createHelper = new ShardDataSourceCreateHelper(extension.getDatabaseManager(), 1L); createHelper.createUninitializedDataSource(); String shardName = createHelper.getShardName(); assertEquals("apl-blockchain-shard-1-chain-b5d7b697-f359-4ce5-a619-fa34b6fb01a5", shardName); } |
### Question:
ShardDataSourceCreateHelper { public TransactionalDataSource getShardDb() { return shardDb; } ShardDataSourceCreateHelper(DatabaseManager databaseManager); ShardDataSourceCreateHelper(DatabaseManager databaseManager, Long shardId); Long getShardId(); String getShardName(); TransactionalDataSource getShardDb(); ShardDataSourceCreateHelper createUninitializedDataSource(); String checkGenerateShardName(); static final int MAX_CACHE_SIZE; static final int MAX_CONNECTIONS; static final int MAX_MEMORY_ROWS; }### Answer:
@Test void getShardDb() { createHelper = new ShardDataSourceCreateHelper(extension.getDatabaseManager(), 2L); createHelper.createUninitializedDataSource(); TransactionalDataSource transactionalDataSource = createHelper.getShardDb(); assertNotNull(transactionalDataSource); } |
### Question:
PeerAddress implements Comparable { private void fromString(String addr) { if (addr == null || addr.isEmpty()) { addr = "localhost"; } try { String a = addr.toLowerCase(); if (!a.startsWith("http")) { a = "http: } URL u = new URL(a); hostName = u.getHost(); setHost(hostName); port = u.getPort(); if (port == -1) { port = Constants.DEFAULT_PEER_PORT; } } catch (MalformedURLException ex) { valid = false; } } PeerAddress(int port, String host); PeerAddress(); PeerAddress(String hostWithPort); String formatIP6Address(String addr); String getHost(); Integer getPort(); final void setPort(Integer port); String getAddrWithPort(); InetAddress getInetAddress(); String getHostName(); boolean isLocal(); @Override int compareTo(Object t); boolean isValid(); @Override String toString(); }### Answer:
@Test public void testFromString() throws MalformedURLException, UnknownHostException { PeerAddress a = new PeerAddress("192.168.0.1"); int port = a.getPort(); String hp = a.getAddrWithPort(); assertEquals(hp, "192.168.0.1" + ":" + Integer.toString(Constants.DEFAULT_PEER_PORT)); assertEquals(port, Constants.DEFAULT_PEER_PORT); a = new PeerAddress("[fe80::d166:519e:5758:d24a]"); hp = a.getAddrWithPort(); assertEquals(hp, "[fe80:0:0:0:d166:519e:5758:d24a]" + ":" + Integer.toString(Constants.DEFAULT_PEER_PORT)); } |
### Question:
TimeLimiterServiceImpl implements TimeLimiterService { @Override public TimeLimiter acquireLimiter(String name) { Preconditions.checkState(started, MESSAGE_THE_SERVICE_IS_SHUT_DOWN); LimiterEntry limiter = allocatedLimiters.get(name); if (limiter == null) { limiter = createLimiterEntry(name); allocatedLimiters.put(name, limiter); } return limiter.limiter; } TimeLimiterServiceImpl(); @Override TimeLimiter acquireLimiter(String name); @Override void shutdown(); ExecutorService getExecutor(String name); static final String MESSAGE_THE_SERVICE_IS_SHUT_DOWN; }### Answer:
@Test void acquireLimiter() { String name = "FIRST_LIMITER"; assertNull(limiterService.getExecutor(name)); TimeLimiter limiter = limiterService.acquireLimiter(name); assertNotNull(limiter); assertNotNull(limiterService.getExecutor(name)); assertEquals(limiter, limiterService.acquireLimiter(name)); } |
### Question:
TimeLimiterServiceImpl implements TimeLimiterService { @Override public void shutdown() { if (started) { started = false; Enumeration<String> keys = allocatedLimiters.keys(); Collections.asList(keys).forEach(name -> Tasks.shutdownExecutor(name, allocatedLimiters.get(name).executor, 5)); } else { log.warn("The service is already shut down."); } } TimeLimiterServiceImpl(); @Override TimeLimiter acquireLimiter(String name); @Override void shutdown(); ExecutorService getExecutor(String name); static final String MESSAGE_THE_SERVICE_IS_SHUT_DOWN; }### Answer:
@Test void shutdown() { String name = "FIRST_LIMITER"; TimeLimiter limiter = limiterService.acquireLimiter(name); assertNotNull(limiter); limiterService.shutdown(); ExecutorService executor = limiterService.getExecutor(name); assertNotNull(executor); assertTrue(executor.isShutdown()); } |
### Question:
TrimObserver { public void onTrimConfigUpdated(@Observes @TrimConfigUpdated TrimConfig trimConfig) { log.info("Set trim to {} ", trimConfig.isEnableTrim()); this.trimDerivedTablesEnabled = trimConfig.isEnableTrim(); if (trimConfig.isClearTrimQueue()) { synchronized (lock) { trimHeights.clear(); } } } @Inject TrimObserver(TrimService trimService, BlockchainConfig blockchainConfig,
PropertiesHolder propertiesHolder, Random random,
Blockchain blockchain); void onTrimConfigUpdated(@Observes @TrimConfigUpdated TrimConfig trimConfig); void onBlockScanned(@Observes @BlockEvent(BlockEventType.BLOCK_SCANNED) Block block); int onBlockPushed(@Observes @BlockEvent(BlockEventType.BLOCK_PUSHED) Block block); }### Answer:
@Test void testOnTrimConfigUpdated() { doReturn(5000).when(config).getShardingFrequency(); assertTrue(observer.isTrimDerivedTablesEnabled()); fireBlockPushed(5000); fireBlockPushed(6000); assertEquals(2, observer.getTrimHeights().size()); trimEvent.select(new AnnotationLiteral<TrimConfigUpdated>() { }).fire(new TrimConfig(false, true)); assertFalse(observer.isTrimDerivedTablesEnabled()); assertEquals(0, observer.getTrimHeights().size()); trimEvent.select(new AnnotationLiteral<TrimConfigUpdated>() { }).fire(new TrimConfig(true, false)); assertTrue(observer.isTrimDerivedTablesEnabled()); } |
### Question:
TrimObserver { List<Integer> getTrimHeights() { synchronized (lock) { return new ArrayList<>(trimHeights); } } @Inject TrimObserver(TrimService trimService, BlockchainConfig blockchainConfig,
PropertiesHolder propertiesHolder, Random random,
Blockchain blockchain); void onTrimConfigUpdated(@Observes @TrimConfigUpdated TrimConfig trimConfig); void onBlockScanned(@Observes @BlockEvent(BlockEventType.BLOCK_SCANNED) Block block); int onBlockPushed(@Observes @BlockEvent(BlockEventType.BLOCK_PUSHED) Block block); }### Answer:
@Test void testOnBlockPushedWithDisabledTrim() throws InterruptedException { doReturn(5000).when(config).getShardingFrequency(); fireBlockPushed(4998); fireBlockPushed(4999); fireBlockPushed(5000); fireBlockPushed(6000); assertEquals(2, observer.getTrimHeights().size()); doAnswer(invocation -> { trimEvent.select(new AnnotationLiteral<TrimConfigUpdated>() { }).fire(new TrimConfig(false, false)); return null; }).when(trimService).trimDerivedTables(5000, true); Thread.sleep(4000); verify(trimService, times(1)).isTrimming(); trimEvent.select(new AnnotationLiteral<TrimConfigUpdated>() { }).fire(new TrimConfig(true, false)); } |
### Question:
TrimDao { public TrimEntry get() { try (Connection con = databaseManager.getDataSource().getConnection(); PreparedStatement pstmt = con.prepareStatement("SELECT * FROM trim"); ResultSet rs = pstmt.executeQuery()) { if (rs.next()) { return new TrimEntry(rs.getLong("db_id"), rs.getInt("height"), rs.getBoolean("done")); } else { return null; } } catch (SQLException e) { throw new RuntimeException(e.toString(), e); } } @Inject TrimDao(DatabaseManager databaseManager); TrimEntry save(TrimEntry trimEntry); TrimEntry get(); void clear(); int count(); }### Answer:
@Test void testGet() { TrimEntry entry = dao.get(); assertEquals(new TrimEntry(1L, 1000, true), entry); } |
### Question:
TrimDao { public void clear() { try (Connection con = databaseManager.getDataSource().getConnection(); PreparedStatement pstmt = con.prepareStatement("DELETE FROM trim"); ) { pstmt.executeUpdate(); } catch (SQLException e) { throw new RuntimeException(e.toString(), e); } } @Inject TrimDao(DatabaseManager databaseManager); TrimEntry save(TrimEntry trimEntry); TrimEntry get(); void clear(); int count(); }### Answer:
@Test void testClear() { dao.clear(); int count = dao.count(); assertEquals(0, count); assertNull(dao.get()); } |
### Question:
TrimService { public int getLastTrimHeight() { TrimEntry trimEntry = trimDao.get(); return trimEntry == null ? 0 : Math.max(trimEntry.getHeight() - maxRollback, 0); } @Inject TrimService(DatabaseManager databaseManager,
DerivedTablesRegistry derivedDbTablesRegistry,
GlobalSync globalSync,
TimeService timeService,
Event<TrimData> trimEvent,
Event<TrimConfig> trimConfigEvent,
TrimDao trimDao,
@Property(value = "apl.maxRollback", defaultValue = "720") int maxRollback
); int getLastTrimHeight(); void init(int height, int shardInitialBlockHeight); void trimDerivedTables(int height, boolean async); void doTrimDerivedTablesOnBlockchainHeight(int blockchainHeight, boolean async); void resetTrim(); void resetTrim(int height); int doTrimDerivedTablesOnHeightLocked(int height, boolean isSharding); void updateTrimConfig(boolean enableTrim, boolean clearQueue); boolean isTrimming(); void waitTrimming(); }### Answer:
@Test void testGetLastTrimHeightWhenTrimEntryIsNull() { int lastTrimHeight = trimService.getLastTrimHeight(); assertEquals(0, lastTrimHeight); }
@Test void testGetLastTrimHeightWhenTrimEntryIsNotNull() { doReturn(new TrimEntry(1L, 3000, true)).when(trimDao).get(); int lastTrimHeight = trimService.getLastTrimHeight(); assertEquals(2000, lastTrimHeight); } |
### Question:
TrimService { public void resetTrim() { resetTrim(0); } @Inject TrimService(DatabaseManager databaseManager,
DerivedTablesRegistry derivedDbTablesRegistry,
GlobalSync globalSync,
TimeService timeService,
Event<TrimData> trimEvent,
Event<TrimConfig> trimConfigEvent,
TrimDao trimDao,
@Property(value = "apl.maxRollback", defaultValue = "720") int maxRollback
); int getLastTrimHeight(); void init(int height, int shardInitialBlockHeight); void trimDerivedTables(int height, boolean async); void doTrimDerivedTablesOnBlockchainHeight(int blockchainHeight, boolean async); void resetTrim(); void resetTrim(int height); int doTrimDerivedTablesOnHeightLocked(int height, boolean isSharding); void updateTrimConfig(boolean enableTrim, boolean clearQueue); boolean isTrimming(); void waitTrimming(); }### Answer:
@Test void testResetTrim() { trimService.resetTrim(); verify(trimDao).clear(); }
@Test void testResetTrimToHeight() { trimService.resetTrim(2000); verify(trimDao).clear(); verify(trimDao).save(new TrimEntry(null, 2000, true)); } |
### Question:
AplAppStatus { public String durableTaskStart(String name, String description, boolean isCritical) { return this.durableTaskStart(name, description, isCritical, 0.0); } @Inject AplAppStatus(); String durableTaskStart(String name, String description, boolean isCritical); String durableTaskStart(String name, String description, boolean isCritical, Double percentComplete); synchronized String durableTaskUpdate(String taskId, Double percentComplete, String message); synchronized String durableTaskUpdate(String taskId, Double percentComplete, String message, int keepPrevMessages); synchronized void durableTaskUpdate(String taskId, Double percentComplete, String message, int keepPrevMessages, Double offset); synchronized double durableTaskUpdate(String taskId, String message, double addPercents); synchronized void durableTaskPaused(String taskId, String message); synchronized void durableTaskContinue(String taskId, String message); synchronized void durableTaskFinished(String taskId, boolean isCancelled, String message); synchronized void clearFinished(Long secondsAgo); Collection<DurableTaskInfo> getTasksList(); synchronized Optional<DurableTaskInfo> findTaskByName(String taskName); double durableTaskUpdateAddPercents(String taskId, Double percentIncreaseValue); }### Answer:
@Test void durableTaskStart() { String taskId = status.durableTaskStart("name1", "descr1", true); assertNotNull(taskId); taskId = status.durableTaskStart("name1", "descr1", true, 100.0); assertNotNull(taskId); } |
### Question:
AplAppStatus { public synchronized String durableTaskUpdate(String taskId, Double percentComplete, String message) { return durableTaskUpdate(taskId, percentComplete, message, -1); } @Inject AplAppStatus(); String durableTaskStart(String name, String description, boolean isCritical); String durableTaskStart(String name, String description, boolean isCritical, Double percentComplete); synchronized String durableTaskUpdate(String taskId, Double percentComplete, String message); synchronized String durableTaskUpdate(String taskId, Double percentComplete, String message, int keepPrevMessages); synchronized void durableTaskUpdate(String taskId, Double percentComplete, String message, int keepPrevMessages, Double offset); synchronized double durableTaskUpdate(String taskId, String message, double addPercents); synchronized void durableTaskPaused(String taskId, String message); synchronized void durableTaskContinue(String taskId, String message); synchronized void durableTaskFinished(String taskId, boolean isCancelled, String message); synchronized void clearFinished(Long secondsAgo); Collection<DurableTaskInfo> getTasksList(); synchronized Optional<DurableTaskInfo> findTaskByName(String taskName); double durableTaskUpdateAddPercents(String taskId, Double percentIncreaseValue); }### Answer:
@Test void durableTaskUpdate() { String taskId = status.durableTaskStart("name1", "descr1", true, 10.0); assertNotNull(taskId); String result = status.durableTaskUpdate(taskId, 50.0, "new msg"); assertEquals(taskId, result); result = status.durableTaskUpdate(taskId, 60.0, null); assertEquals(taskId, result); Double completeResult = status.durableTaskUpdateAddPercents(taskId, 1.0); assertEquals(61.0, completeResult); completeResult = status.durableTaskUpdateAddPercents(taskId, 1.2); assertEquals(62.2, completeResult); completeResult = status.durableTaskUpdateAddPercents(taskId, 1.05); assertEquals(63.25, completeResult); } |
### Question:
AplAppStatus { public Collection<DurableTaskInfo> getTasksList() { return tasks.values(); } @Inject AplAppStatus(); String durableTaskStart(String name, String description, boolean isCritical); String durableTaskStart(String name, String description, boolean isCritical, Double percentComplete); synchronized String durableTaskUpdate(String taskId, Double percentComplete, String message); synchronized String durableTaskUpdate(String taskId, Double percentComplete, String message, int keepPrevMessages); synchronized void durableTaskUpdate(String taskId, Double percentComplete, String message, int keepPrevMessages, Double offset); synchronized double durableTaskUpdate(String taskId, String message, double addPercents); synchronized void durableTaskPaused(String taskId, String message); synchronized void durableTaskContinue(String taskId, String message); synchronized void durableTaskFinished(String taskId, boolean isCancelled, String message); synchronized void clearFinished(Long secondsAgo); Collection<DurableTaskInfo> getTasksList(); synchronized Optional<DurableTaskInfo> findTaskByName(String taskName); double durableTaskUpdateAddPercents(String taskId, Double percentIncreaseValue); }### Answer:
@Test void getTasksList() { String taskId = status.durableTaskStart("name1", "descr1", true); assertNotNull(taskId); taskId = status.durableTaskStart("name1", "descr1", true); assertNotNull(taskId); taskId = status.durableTaskStart("name1", "descr1", false); assertNotNull(taskId); assertEquals(3, status.getTasksList().size()); } |
### Question:
AplAppStatus { public synchronized Optional<DurableTaskInfo> findTaskByName(String taskName) { Objects.requireNonNull(taskName, "taskName is NULL"); for (DurableTaskInfo taskInfo : tasks.values()) { if (taskInfo.getName() != null && !taskInfo.getName().isEmpty() && taskInfo.getName().contains(taskName)) { return Optional.of(taskInfo); } } return Optional.empty(); } @Inject AplAppStatus(); String durableTaskStart(String name, String description, boolean isCritical); String durableTaskStart(String name, String description, boolean isCritical, Double percentComplete); synchronized String durableTaskUpdate(String taskId, Double percentComplete, String message); synchronized String durableTaskUpdate(String taskId, Double percentComplete, String message, int keepPrevMessages); synchronized void durableTaskUpdate(String taskId, Double percentComplete, String message, int keepPrevMessages, Double offset); synchronized double durableTaskUpdate(String taskId, String message, double addPercents); synchronized void durableTaskPaused(String taskId, String message); synchronized void durableTaskContinue(String taskId, String message); synchronized void durableTaskFinished(String taskId, boolean isCancelled, String message); synchronized void clearFinished(Long secondsAgo); Collection<DurableTaskInfo> getTasksList(); synchronized Optional<DurableTaskInfo> findTaskByName(String taskName); double durableTaskUpdateAddPercents(String taskId, Double percentIncreaseValue); }### Answer:
@Test void findTaskByName() { String taskId = status.durableTaskStart("sharding", "descr1", true); assertNotNull(taskId); Optional<DurableTaskInfo> taskInfo = status.findTaskByName("sharding"); assertNotNull(taskInfo); assertTrue(taskInfo.isPresent()); assertEquals("sharding", taskInfo.get().getName()); } |
### Question:
PhasingApprovedResultTable extends EntityDbTable<PhasingApprovalResult> { public PhasingApprovalResult get(long id) { return get(KEY_FACTORY.newKey(id)); } PhasingApprovedResultTable(); @Override PhasingApprovalResult load(Connection con, ResultSet rs, DbKey dbKey); PhasingApprovalResult get(long id); @Override void save(Connection con, PhasingApprovalResult phasingPollResult); }### Answer:
@Test void testInsertNew() { DbUtils.inTransaction(extension, (con) -> table.insert(data.NEW_RESULT)); PhasingApprovalResult phasingApprovalResult = table.get(data.NEW_RESULT.getPhasingTx()); assertEquals(data.NEW_RESULT, phasingApprovalResult); }
@Test void testGetById() { PhasingApprovalResult result = table.get(data.RESULT_1.getPhasingTx()); assertEquals(data.RESULT_1, result); } |
### Question:
PhasingVoteTable extends EntityDbTable<PhasingVote> { public PhasingVote get(long phasedTransactionId, long voterId) { return get(KEY_FACTORY.newKey(phasedTransactionId, voterId)); } PhasingVoteTable(); @Override PhasingVote load(Connection con, ResultSet rs, DbKey dbKey); @Override void save(Connection con, PhasingVote vote); PhasingVote get(long phasedTransactionId, long voterId); List<PhasingVote> get(long phasingTransactionId); }### Answer:
@Test void testGetByPhasingIdAndVoterId() { PhasingVote phasingVote = table.get(ptd.POLL_1_VOTE_0.getPhasedTransactionId(), ptd.POLL_1_VOTE_0.getVoterId()); assertEquals(ptd.POLL_1_VOTE_0, phasingVote); }
@Test void getByPhasingId() { List<PhasingVote> phasingVotes = table.get(ptd.POLL_1_VOTE_1.getPhasedTransactionId()); assertEquals(phasingVotes, List.of(ptd.POLL_1_VOTE_1, ptd.POLL_1_VOTE_0)); }
@Test void testInsert() { DbUtils.inTransaction(extension, (con) -> table.insert(ptd.NEW_VOTE)); List<PhasingVote> phasingVotes = table.get(ptd.POLL_1.getId()); assertEquals(phasingVotes, List.of(ptd.POLL_1_VOTE_1, ptd.POLL_1_VOTE_0, ptd.NEW_VOTE)); } |
### Question:
PhasingPollVoterTable extends ValuesDbTable<PhasingPollVoter> { public List<PhasingPollVoter> get(long pollId) { return get(KEY_FACTORY.newKey(pollId)); } @Inject PhasingPollVoterTable(Blockchain blockchain); List<PhasingPollVoter> get(long pollId); @Override PhasingPollVoter load(Connection con, ResultSet rs, DbKey dbKey); @Override void save(Connection con, PhasingPollVoter voter); DbIterator<Transaction> getVoterPhasedTransactions(long voterId, int from, int to); }### Answer:
@Test void testGetVotersForPollWithoutVoters() { List<PhasingPollVoter> pollVoters = table.get(ptd.POLL_2.getId()); assertTrue(pollVoters.isEmpty(), "Poll voters should not exist for poll2"); } |
### Question:
PhasingPollTable extends EntityDbTable<PhasingPoll> { public int getAllPhasedTransactionsCount() throws SQLException { try (Connection con = getDatabaseManager().getDataSource().getConnection(); @DatabaseSpecificDml(DmlMarker.NAMED_SUB_SELECT) PreparedStatement pstmt = con.prepareStatement("select count(*) from (select id from phasing_poll UNION select id from phasing_poll_result)")) { try (ResultSet rs = pstmt.executeQuery()) { rs.next(); return rs.getInt(1); } } } @Inject PhasingPollTable(Blockchain blockchain); @Override PhasingPoll load(Connection con, ResultSet rs, DbKey dbKey); PhasingPoll get(long id); @Override void save(Connection con, PhasingPoll poll); List<Transaction> getFinishingTransactions(int height); List<Transaction> getFinishingTransactionsByTime(int startTime, int finishTime); long getSenderPhasedTransactionFees(long accountId, int height); DbIterator<Transaction> getHoldingPhasedTransactions(long holdingId, VoteWeighting.VotingModel votingModel,
long accountId, boolean withoutWhitelist, int from, int to, int height); DbIterator<Transaction> getAccountPhasedTransactions(long accountId, int from, int to, int height); int getAccountPhasedTransactionCount(long accountId, int height); int getAllPhasedTransactionsCount(); List<TransactionDbInfo> getActivePhasedTransactionDbIds(int height); boolean isTransactionPhased(long id); @Override void trim(int height); }### Answer:
@Test void testGetAllPhasedTransactionsCount() throws SQLException { int count = table.getAllPhasedTransactionsCount(); assertEquals(ptd.NUMBER_OF_PHASED_TRANSACTIONS, count); } |
### Question:
PhasingPollTable extends EntityDbTable<PhasingPoll> { public PhasingPoll get(long id) { return get(KEY_FACTORY.newKey(id)); } @Inject PhasingPollTable(Blockchain blockchain); @Override PhasingPoll load(Connection con, ResultSet rs, DbKey dbKey); PhasingPoll get(long id); @Override void save(Connection con, PhasingPoll poll); List<Transaction> getFinishingTransactions(int height); List<Transaction> getFinishingTransactionsByTime(int startTime, int finishTime); long getSenderPhasedTransactionFees(long accountId, int height); DbIterator<Transaction> getHoldingPhasedTransactions(long holdingId, VoteWeighting.VotingModel votingModel,
long accountId, boolean withoutWhitelist, int from, int to, int height); DbIterator<Transaction> getAccountPhasedTransactions(long accountId, int from, int to, int height); int getAccountPhasedTransactionCount(long accountId, int height); int getAllPhasedTransactionsCount(); List<TransactionDbInfo> getActivePhasedTransactionDbIds(int height); boolean isTransactionPhased(long id); @Override void trim(int height); }### Answer:
@Test void testGetById() { PhasingPoll phasingPoll = table.get(ptd.POLL_2.getId()); assertEquals(ptd.POLL_2, phasingPoll); }
@Test void testGetByIdNotExist() { PhasingPoll phasingPoll = table.get(1); assertNull(phasingPoll); } |
### Question:
ShardImporter { public void importShardByFileId(ShardPresentData shardPresentData) { importShard(shardPresentData, List.of()); log.debug("Before updating BlockchainProcessor from Shard data and RESUME block downloading..."); BlockchainProcessor blockchainProcessor = CDI.current().select(BlockchainProcessor.class).get(); blockchain.update(); blockchainProcessor.resumeBlockchainDownloading(); } @Inject ShardImporter(ShardDao shardDao, BlockchainConfig blockchainConfig, GenesisImporter genesisImporter, Blockchain blockchain, DerivedTablesRegistry derivedTablesRegistry, CsvImporter csvImporter, Zip zipComponent, DataTagDao dataTagDao, DownloadableFilesManager downloadableFilesManager, AplAppStatus aplAppStatus); void importShardByFileId(ShardPresentData shardPresentData); void importLastShard(int height); boolean canImport(int height); void importShard(ShardPresentData shardPresentData, List<String> excludedTables); }### Answer:
@Test void importShardByFileIdFaile() { assertThrows(NullPointerException.class, () -> shardImporter.importShardByFileId( new ShardPresentData(null, "fileId", List.of())) ); }
@Test void testImportByFileId() { doReturn(Paths.get("")).when(downloadableFilesManager).mapFileIdToLocalPath("fileId"); doReturn(true).when(zipComponent).extract(Paths.get("").toAbsolutePath().toString(), csvImporter.getDataExportPath().toAbsolutePath().toString(), true); doNothing().when(genesisImporter).importGenesisJson(true); doReturn(List.of()).when(derivedTablesRegistry).getDerivedTableNames(); doReturn(mock(Shard.class)).when(shardDao).getLastShard(); shardImporter.importShardByFileId(new ShardPresentData(null, "fileId", List.of())); verify(blockchain).update(); verify(blockchainProcessor).resumeBlockchainDownloading(); verify(aplAppStatus).durableTaskFinished(null, false, "Shard data import"); } |
### Question:
PrevBlockInfoExtractor { public PrevBlockData extractPrevBlockData(int height, int limit) { return PrevBlockData.builder() .generatorIds(Convert.toObjectLongArray(extractObjects(height, limit, "generator_id"))) .prevBlockTimeouts(Convert.toObjectIntArray(extractObjects(height, limit, "timeout"))) .prevBlockTimestamps(Convert.toObjectIntArray(extractObjects(height, limit, "timestamp"))) .build(); } @Inject PrevBlockInfoExtractor(DatabaseManager databaseManager); PrevBlockData extractPrevBlockData(int height, int limit); }### Answer:
@Test void testGetIdsBeforeGenesisHeight() { PrevBlockData prevBlockData = extractor.extractPrevBlockData(0, Integer.MAX_VALUE); assertEquals(0, prevBlockData.getGeneratorIds().length); assertEquals(0, prevBlockData.getPrevBlockTimeouts().length); assertEquals(0, prevBlockData.getPrevBlockTimestamps().length); }
@Test void testGetIdsBeforeLastBlockHeight() { PrevBlockData prevBlockData = extractor.extractPrevBlockData(BlockTestData.BLOCK_10_HEIGHT, 3); assertArrayEquals(new Long[]{BlockTestData.BLOCK_9_GENERATOR, BlockTestData.BLOCK_8_GENERATOR, BlockTestData.BLOCK_7_GENERATOR}, prevBlockData.getGeneratorIds()); assertArrayEquals(new Integer[]{BlockTestData.BLOCK_9_TIMESTAMP, BlockTestData.BLOCK_8_TIMESTAMP, BlockTestData.BLOCK_7_TIMESTAMP}, prevBlockData.getPrevBlockTimestamps()); assertArrayEquals(new Integer[]{BlockTestData.BLOCK_9_TIMEOUT, BlockTestData.BLOCK_8_TIMEOUT, BlockTestData.BLOCK_7_TIMEOUT}, prevBlockData.getPrevBlockTimeouts()); } |
### Question:
MerkleTree { public List<Node> getNodes() { return nodes; } MerkleTree(MessageDigest digest); MerkleTree(MessageDigest digest, List<byte[]> dataList); List<Node> getNodes(); List<Node> getLeaves(); Node getRoot(); void appendLeaf(Node node); void appendLeaves(Node[] nodes); void appendLeaf(byte[] value); void appendLeaves(byte[][] values); void appendHashedLeaves(byte[][] hashes); @Override boolean equals(Object o); }### Answer:
@Test public void testCreateEmptyTree() { MerkleTree tree = new MerkleTree(sha256()); List<Node> nodes = tree.getNodes(); Assertions.assertEquals(0, nodes.size()); } |
### Question:
MerkleTree { public void appendLeaf(Node node) { int size = nodes.size(); if (size <= 2) { nodes.add(node); if (size == 0) { nodes.add(new Node(node.getValue())); } else { updateHash(0); } } else { int parentIndex = getParentIndex(size); Node nodeToReplace = nodes.get(parentIndex); Node emptyNode = new Node(null); nodes.set(parentIndex, emptyNode); nodes.add(nodeToReplace); nodes.add(node); updateHash(parentIndex); } } MerkleTree(MessageDigest digest); MerkleTree(MessageDigest digest, List<byte[]> dataList); List<Node> getNodes(); List<Node> getLeaves(); Node getRoot(); void appendLeaf(Node node); void appendLeaves(Node[] nodes); void appendLeaf(byte[] value); void appendLeaves(byte[][] values); void appendHashedLeaves(byte[][] hashes); @Override boolean equals(Object o); }### Answer:
@Test public void testAppendAndBuildTreesEquals() { int counter = 1_000; List<byte[]> bytesToAdd = new ArrayList<>(); MerkleTree appendTree = new MerkleTree(sha256()); Random random = new Random(); while (counter-- > 0) { byte[] bytes = new byte[256]; random.nextBytes(bytes); bytesToAdd.add(bytes); appendTree.appendLeaf(bytes); } MerkleTree builtTree = new MerkleTree(sha256(), bytesToAdd); Assertions.assertEquals(appendTree, builtTree); } |
### Question:
ShardNameHelper { public String getShardNameByShardId(Long shardId, UUID chainId) { if (shardId == null || shardId < 0) { throw new IllegalArgumentException("'shardId' should have positive value, but " + shardId + " was supplied"); } Objects.requireNonNull(chainId, "chainID must be set"); String result = String.format(SHARD_NAME_PATTERN, shardId, chainId.toString()); log.debug(result); return result; } ShardNameHelper(); String getShardNameByShardId(Long shardId, UUID chainId); String getFullShardId(Long shardId, UUID chainId); String getFullShardPrunId(Long shardId, UUID chainId); String getCoreShardArchiveNameByShardId(Long shardId, UUID chainId); String getPrunableShardArchiveNameByShardId(Long shardId, UUID chainId); }### Answer:
@Test void getShardName() { ShardNameHelper shardNameHelper = new ShardNameHelper(); String result = shardNameHelper.getShardNameByShardId(001L, chainId); assertEquals("apl-blockchain-shard-1-chain-b5d7b697-f359-4ce5-a619-fa34b6fb01a5", result); result = shardNameHelper.getShardNameByShardId(2001L, chainId); assertEquals("apl-blockchain-shard-2001-chain-b5d7b697-f359-4ce5-a619-fa34b6fb01a5", result); } |
### Question:
ShardNameHelper { public String getCoreShardArchiveNameByShardId(Long shardId, UUID chainId) { return getShardArchiveNameByShardId(SHARD_CORE_ARCHIVE_NAME_PATTERN, shardId, chainId); } ShardNameHelper(); String getShardNameByShardId(Long shardId, UUID chainId); String getFullShardId(Long shardId, UUID chainId); String getFullShardPrunId(Long shardId, UUID chainId); String getCoreShardArchiveNameByShardId(Long shardId, UUID chainId); String getPrunableShardArchiveNameByShardId(Long shardId, UUID chainId); }### Answer:
@Test void getCoreShardArchiveName() { ShardNameHelper shardNameHelper = new ShardNameHelper(); String result = shardNameHelper.getCoreShardArchiveNameByShardId(001L, chainId); assertEquals("apl-blockchain-shard-1-chain-b5d7b697-f359-4ce5-a619-fa34b6fb01a5.zip", result); result = shardNameHelper.getCoreShardArchiveNameByShardId(2001L, chainId); assertEquals("apl-blockchain-shard-2001-chain-b5d7b697-f359-4ce5-a619-fa34b6fb01a5.zip", result); } |
### Question:
ShardNameHelper { public String getPrunableShardArchiveNameByShardId(Long shardId, UUID chainId) { return getShardArchiveNameByShardId(SHARD_PRUNABLE_ARCHIVE_NAME_PATTERN, shardId, chainId); } ShardNameHelper(); String getShardNameByShardId(Long shardId, UUID chainId); String getFullShardId(Long shardId, UUID chainId); String getFullShardPrunId(Long shardId, UUID chainId); String getCoreShardArchiveNameByShardId(Long shardId, UUID chainId); String getPrunableShardArchiveNameByShardId(Long shardId, UUID chainId); }### Answer:
@Test void getPrunableShardArchiveName() { ShardNameHelper shardNameHelper = new ShardNameHelper(); String result = shardNameHelper.getPrunableShardArchiveNameByShardId(001L, chainId); assertEquals("apl-blockchain-shardprun-1-chain-b5d7b697-f359-4ce5-a619-fa34b6fb01a5.zip", result); result = shardNameHelper.getPrunableShardArchiveNameByShardId(2001L, chainId); assertEquals("apl-blockchain-shardprun-2001-chain-b5d7b697-f359-4ce5-a619-fa34b6fb01a5.zip", result); } |
### Question:
ShardNameHelper { public String getFullShardPrunId(Long shardId, UUID chainId) { String result = String.format(SHARD_PRUN_ID_PATTERN, shardId, chainId.toString()); return result; } ShardNameHelper(); String getShardNameByShardId(Long shardId, UUID chainId); String getFullShardId(Long shardId, UUID chainId); String getFullShardPrunId(Long shardId, UUID chainId); String getCoreShardArchiveNameByShardId(Long shardId, UUID chainId); String getPrunableShardArchiveNameByShardId(Long shardId, UUID chainId); }### Answer:
@Test void getFullPrunableShardId() { ShardNameHelper shardNameHelper = new ShardNameHelper(); String result = shardNameHelper.getFullShardPrunId(001L, chainId); assertEquals("shardprun::1;chain::b5d7b697-f359-4ce5-a619-fa34b6fb01a5", result); result = shardNameHelper.getFullShardPrunId(2001L, chainId); assertEquals("shardprun::2001;chain::b5d7b697-f359-4ce5-a619-fa34b6fb01a5", result); } |
### Question:
ShardService { public List<Shard> getAllShards() { return shardDao.getAllShard(); } @Inject ShardService(ShardDao shardDao, BlockchainProcessor blockchainProcessor, Blockchain blockchain,
DirProvider dirProvider, Zip zip, DatabaseManager databaseManager,
BlockchainConfig blockchainConfig, ShardRecoveryDao shardRecoveryDao,
ShardMigrationExecutor shardMigrationExecutor, AplAppStatus aplAppStatus,
PropertiesHolder propertiesHolder, Event<TrimConfig> trimEvent, GlobalSync globalSync,
TrimService trimService, Event<DbHotSwapConfig> dbEvent); List<Shard> getAllCompletedShards(); List<Shard> getAllCompletedOrArchivedShards(); List<Shard> getAllShards(); boolean isSharding(); void setSharding(boolean sharding); boolean reset(long shardId); void recoverSharding(); MigrateState performSharding(int minRollbackHeight, long shardId, MigrateState initialState); CompletableFuture<MigrateState> tryCreateShardAsync(int lastTrimBlockHeight, int blockchainHeight); @Transactional void saveShardRecoveryAndShard(long nextShardId, int lastTrimBlockHeight, int blockchainHeight); Shard getLastShard(); List<Shard> getShardsByBlockHeightRange(int heightFrom, int heightTo); final static long LOWER_SHARDING_MEMORY_LIMIT; }### Answer:
@Test void testGetAllShards() { doReturn(List.of()).when(shardDao).getAllShard(); List<Shard> allShards = shardService.getAllShards(); assertEquals(List.of(), allShards); verify(shardDao).getAllShard(); } |
### Question:
ShardService { public List<Shard> getAllCompletedShards() { return shardDao.getAllCompletedShards(); } @Inject ShardService(ShardDao shardDao, BlockchainProcessor blockchainProcessor, Blockchain blockchain,
DirProvider dirProvider, Zip zip, DatabaseManager databaseManager,
BlockchainConfig blockchainConfig, ShardRecoveryDao shardRecoveryDao,
ShardMigrationExecutor shardMigrationExecutor, AplAppStatus aplAppStatus,
PropertiesHolder propertiesHolder, Event<TrimConfig> trimEvent, GlobalSync globalSync,
TrimService trimService, Event<DbHotSwapConfig> dbEvent); List<Shard> getAllCompletedShards(); List<Shard> getAllCompletedOrArchivedShards(); List<Shard> getAllShards(); boolean isSharding(); void setSharding(boolean sharding); boolean reset(long shardId); void recoverSharding(); MigrateState performSharding(int minRollbackHeight, long shardId, MigrateState initialState); CompletableFuture<MigrateState> tryCreateShardAsync(int lastTrimBlockHeight, int blockchainHeight); @Transactional void saveShardRecoveryAndShard(long nextShardId, int lastTrimBlockHeight, int blockchainHeight); Shard getLastShard(); List<Shard> getShardsByBlockHeightRange(int heightFrom, int heightTo); final static long LOWER_SHARDING_MEMORY_LIMIT; }### Answer:
@Test void testAllCompletedShards() { doReturn(List.of()).when(shardDao).getAllCompletedShards(); List<Shard> allShards = shardService.getAllCompletedShards(); assertEquals(List.of(), allShards); verify(shardDao).getAllCompletedShards(); } |
### Question:
ShardService { public List<Shard> getAllCompletedOrArchivedShards() { return shardDao.getAllCompletedOrArchivedShards(); } @Inject ShardService(ShardDao shardDao, BlockchainProcessor blockchainProcessor, Blockchain blockchain,
DirProvider dirProvider, Zip zip, DatabaseManager databaseManager,
BlockchainConfig blockchainConfig, ShardRecoveryDao shardRecoveryDao,
ShardMigrationExecutor shardMigrationExecutor, AplAppStatus aplAppStatus,
PropertiesHolder propertiesHolder, Event<TrimConfig> trimEvent, GlobalSync globalSync,
TrimService trimService, Event<DbHotSwapConfig> dbEvent); List<Shard> getAllCompletedShards(); List<Shard> getAllCompletedOrArchivedShards(); List<Shard> getAllShards(); boolean isSharding(); void setSharding(boolean sharding); boolean reset(long shardId); void recoverSharding(); MigrateState performSharding(int minRollbackHeight, long shardId, MigrateState initialState); CompletableFuture<MigrateState> tryCreateShardAsync(int lastTrimBlockHeight, int blockchainHeight); @Transactional void saveShardRecoveryAndShard(long nextShardId, int lastTrimBlockHeight, int blockchainHeight); Shard getLastShard(); List<Shard> getShardsByBlockHeightRange(int heightFrom, int heightTo); final static long LOWER_SHARDING_MEMORY_LIMIT; }### Answer:
@Test void testAllCompletedOrArchivedShards() { List<Shard> expected = List.of(new Shard(1L, 20), new Shard(2L, 30)); doReturn(expected).when(shardDao).getAllCompletedOrArchivedShards(); List<Shard> allShards = shardService.getAllCompletedOrArchivedShards(); assertEquals(expected, allShards); verify(shardDao).getAllCompletedOrArchivedShards(); } |
### Question:
TradeServiceImpl implements TradeService { @Override public Stream<Trade> getAllTrades(int from, int to) { return converter.convert(tradeTable.getAll(from, to)); } TradeServiceImpl(
final DatabaseManager databaseManager,
final Blockchain blockchain,
final TradeTable tradeTable,
final IteratorToStreamConverter<Trade> converter
); @Inject TradeServiceImpl(
final DatabaseManager databaseManager,
final Blockchain blockchain,
final TradeTable tradeTable
); @Override Stream<Trade> getAllTrades(int from, int to); @Override int getCount(); @Override Trade getTrade(long askOrderId, long bidOrderId); @Override Stream<Trade> getAssetTrades(long assetId, int from, int to); @Override List<Trade> getLastTrades(long[] assetIds); @Override Stream<Trade> getAccountTrades(long accountId, int from, int to); @Override Stream<Trade> getAccountAssetTrades(long accountId, long assetId, int from, int to); @Override Stream<Trade> getAskOrderTrades(long askOrderId, int from, int to); @Override Stream<Trade> getBidOrderTrades(long bidOrderId, int from, int to); @Override int getTradeCount(long assetId); @Override Trade addTrade(long assetId, AskOrder askOrder, BidOrder bidOrder); }### Answer:
@Test void shouldGetAllTrades() { final int from = 0; final int to = 100; @SuppressWarnings("unchecked") final DbIterator<Trade> dbIterator = mock(DbIterator.class); when(tradeTable.getAll(from, to)).thenReturn(dbIterator); final Trade trade = mock(Trade.class); final Stream<Trade> tradesExpected = Stream.of(trade); when(converter.convert(dbIterator)).thenReturn(tradesExpected); final Stream<Trade> tradesActual = tradeService.getAllTrades(from, to); assertEquals(tradesExpected, tradesActual); } |
### Question:
TradeServiceImpl implements TradeService { @Override public int getCount() { return tradeTable.getCount(); } TradeServiceImpl(
final DatabaseManager databaseManager,
final Blockchain blockchain,
final TradeTable tradeTable,
final IteratorToStreamConverter<Trade> converter
); @Inject TradeServiceImpl(
final DatabaseManager databaseManager,
final Blockchain blockchain,
final TradeTable tradeTable
); @Override Stream<Trade> getAllTrades(int from, int to); @Override int getCount(); @Override Trade getTrade(long askOrderId, long bidOrderId); @Override Stream<Trade> getAssetTrades(long assetId, int from, int to); @Override List<Trade> getLastTrades(long[] assetIds); @Override Stream<Trade> getAccountTrades(long accountId, int from, int to); @Override Stream<Trade> getAccountAssetTrades(long accountId, long assetId, int from, int to); @Override Stream<Trade> getAskOrderTrades(long askOrderId, int from, int to); @Override Stream<Trade> getBidOrderTrades(long bidOrderId, int from, int to); @Override int getTradeCount(long assetId); @Override Trade addTrade(long assetId, AskOrder askOrder, BidOrder bidOrder); }### Answer:
@Test void shouldGetCount() { final int count = 100; when(tradeTable.getCount()).thenReturn(100); final int countActual = tradeService.getCount(); assertEquals(count, countActual); } |
### Question:
TradeServiceImpl implements TradeService { @Override public Trade getTrade(long askOrderId, long bidOrderId) { return tradeTable.getTrade(askOrderId, bidOrderId); } TradeServiceImpl(
final DatabaseManager databaseManager,
final Blockchain blockchain,
final TradeTable tradeTable,
final IteratorToStreamConverter<Trade> converter
); @Inject TradeServiceImpl(
final DatabaseManager databaseManager,
final Blockchain blockchain,
final TradeTable tradeTable
); @Override Stream<Trade> getAllTrades(int from, int to); @Override int getCount(); @Override Trade getTrade(long askOrderId, long bidOrderId); @Override Stream<Trade> getAssetTrades(long assetId, int from, int to); @Override List<Trade> getLastTrades(long[] assetIds); @Override Stream<Trade> getAccountTrades(long accountId, int from, int to); @Override Stream<Trade> getAccountAssetTrades(long accountId, long assetId, int from, int to); @Override Stream<Trade> getAskOrderTrades(long askOrderId, int from, int to); @Override Stream<Trade> getBidOrderTrades(long bidOrderId, int from, int to); @Override int getTradeCount(long assetId); @Override Trade addTrade(long assetId, AskOrder askOrder, BidOrder bidOrder); }### Answer:
@Test void shouldGetTrade() { final long askOrderId = 1L; final long bidOrderId = 2L; final Trade trade = mock(Trade.class); when(tradeTable.getTrade(askOrderId, bidOrderId)).thenReturn(trade); final Trade tradeActual = tradeService.getTrade(askOrderId, bidOrderId); assertEquals(trade, tradeActual); } |
### Question:
TradeServiceImpl implements TradeService { @Override public List<Trade> getLastTrades(long[] assetIds) { final TransactionalDataSource dataSource = databaseManager.getDataSource(); return tradeTable.getLastTrades(dataSource, assetIds); } TradeServiceImpl(
final DatabaseManager databaseManager,
final Blockchain blockchain,
final TradeTable tradeTable,
final IteratorToStreamConverter<Trade> converter
); @Inject TradeServiceImpl(
final DatabaseManager databaseManager,
final Blockchain blockchain,
final TradeTable tradeTable
); @Override Stream<Trade> getAllTrades(int from, int to); @Override int getCount(); @Override Trade getTrade(long askOrderId, long bidOrderId); @Override Stream<Trade> getAssetTrades(long assetId, int from, int to); @Override List<Trade> getLastTrades(long[] assetIds); @Override Stream<Trade> getAccountTrades(long accountId, int from, int to); @Override Stream<Trade> getAccountAssetTrades(long accountId, long assetId, int from, int to); @Override Stream<Trade> getAskOrderTrades(long askOrderId, int from, int to); @Override Stream<Trade> getBidOrderTrades(long bidOrderId, int from, int to); @Override int getTradeCount(long assetId); @Override Trade addTrade(long assetId, AskOrder askOrder, BidOrder bidOrder); }### Answer:
@Test void shouldGetLastTrades() { final long[] assetIds = new long[]{1}; final Trade trade = mock(Trade.class); final TransactionalDataSource dataSource = mock(TransactionalDataSource.class); when(databaseManager.getDataSource()).thenReturn(dataSource); final List<Trade> tradesExpected = List.of(trade); when(tradeTable.getLastTrades(dataSource, assetIds)).thenReturn(tradesExpected); final List<Trade> tradesActual = tradeService.getLastTrades(assetIds); assertEquals(tradesExpected, tradesActual); } |
### Question:
BidOrderServiceImpl implements OrderService<BidOrder, ColoredCoinsBidOrderPlacement> { @Override public int getCount() { return bidOrderTable.getCount(); } BidOrderServiceImpl(
final DatabaseManager databaseManager,
final BidOrderTable bidOrderTable,
final Blockchain blockchain,
final IteratorToStreamConverter<BidOrder> converter
); @Inject BidOrderServiceImpl(
final DatabaseManager databaseManager,
final BidOrderTable bidOrderTable,
final Blockchain blockchain
); @Override int getCount(); @Override BidOrder getOrder(long orderId); @Override Stream<BidOrder> getAll(int from, int to); @Override Stream<BidOrder> getOrdersByAccount(long accountId, int from, int to); @Override Stream<BidOrder> getOrdersByAccountAsset(final long accountId, final long assetId, int from, int to); @Override Stream<BidOrder> getSortedOrders(long assetId, int from, int to); @Override BidOrder getNextOrder(long assetId); @Override void addOrder(Transaction transaction, ColoredCoinsBidOrderPlacement attachment); @Override void removeOrder(long orderId); @Override void updateQuantityATU(long quantityATU, BidOrder orderBid); }### Answer:
@Test void shouldGetCount() { final int count = 1; when(bidOrderTable.getCount()).thenReturn(count); final int countActual = orderService.getCount(); assertEquals(count, countActual); } |
### Question:
BidOrderServiceImpl implements OrderService<BidOrder, ColoredCoinsBidOrderPlacement> { @Override public BidOrder getOrder(long orderId) { return bidOrderTable.getBidOrder(orderId); } BidOrderServiceImpl(
final DatabaseManager databaseManager,
final BidOrderTable bidOrderTable,
final Blockchain blockchain,
final IteratorToStreamConverter<BidOrder> converter
); @Inject BidOrderServiceImpl(
final DatabaseManager databaseManager,
final BidOrderTable bidOrderTable,
final Blockchain blockchain
); @Override int getCount(); @Override BidOrder getOrder(long orderId); @Override Stream<BidOrder> getAll(int from, int to); @Override Stream<BidOrder> getOrdersByAccount(long accountId, int from, int to); @Override Stream<BidOrder> getOrdersByAccountAsset(final long accountId, final long assetId, int from, int to); @Override Stream<BidOrder> getSortedOrders(long assetId, int from, int to); @Override BidOrder getNextOrder(long assetId); @Override void addOrder(Transaction transaction, ColoredCoinsBidOrderPlacement attachment); @Override void removeOrder(long orderId); @Override void updateQuantityATU(long quantityATU, BidOrder orderBid); }### Answer:
@Test void shouldGetOrder() { long orderId = 1L; final BidOrder order = mock(BidOrder.class); when(bidOrderTable.getBidOrder(orderId)).thenReturn(order); final BidOrder orderActual = orderService.getOrder(orderId); assertEquals(order, orderActual); } |
### Question:
BidOrderServiceImpl implements OrderService<BidOrder, ColoredCoinsBidOrderPlacement> { @Override public Stream<BidOrder> getAll(int from, int to) { return converter.convert(bidOrderTable.getAll(from, to)); } BidOrderServiceImpl(
final DatabaseManager databaseManager,
final BidOrderTable bidOrderTable,
final Blockchain blockchain,
final IteratorToStreamConverter<BidOrder> converter
); @Inject BidOrderServiceImpl(
final DatabaseManager databaseManager,
final BidOrderTable bidOrderTable,
final Blockchain blockchain
); @Override int getCount(); @Override BidOrder getOrder(long orderId); @Override Stream<BidOrder> getAll(int from, int to); @Override Stream<BidOrder> getOrdersByAccount(long accountId, int from, int to); @Override Stream<BidOrder> getOrdersByAccountAsset(final long accountId, final long assetId, int from, int to); @Override Stream<BidOrder> getSortedOrders(long assetId, int from, int to); @Override BidOrder getNextOrder(long assetId); @Override void addOrder(Transaction transaction, ColoredCoinsBidOrderPlacement attachment); @Override void removeOrder(long orderId); @Override void updateQuantityATU(long quantityATU, BidOrder orderBid); }### Answer:
@Test void shouldGetAll() { final BidOrder order = mock(BidOrder.class); int from = 0; int to = 100; @SuppressWarnings("unchecked") final DbIterator<BidOrder> dbIterator = mock(DbIterator.class); when(bidOrderTable.getAll(from, to)).thenReturn(dbIterator); final Stream<BidOrder> streamExpected = Stream.of(order); when(converter.convert(dbIterator)).thenReturn(streamExpected); final Stream<BidOrder> streamActual = orderService.getAll(from, to); assertEquals(streamExpected, streamActual); } |
### Question:
BidOrderServiceImpl implements OrderService<BidOrder, ColoredCoinsBidOrderPlacement> { @Override public BidOrder getNextOrder(long assetId) { final TransactionalDataSource dataSource = databaseManager.getDataSource(); return bidOrderTable.getNextOrder(dataSource, assetId); } BidOrderServiceImpl(
final DatabaseManager databaseManager,
final BidOrderTable bidOrderTable,
final Blockchain blockchain,
final IteratorToStreamConverter<BidOrder> converter
); @Inject BidOrderServiceImpl(
final DatabaseManager databaseManager,
final BidOrderTable bidOrderTable,
final Blockchain blockchain
); @Override int getCount(); @Override BidOrder getOrder(long orderId); @Override Stream<BidOrder> getAll(int from, int to); @Override Stream<BidOrder> getOrdersByAccount(long accountId, int from, int to); @Override Stream<BidOrder> getOrdersByAccountAsset(final long accountId, final long assetId, int from, int to); @Override Stream<BidOrder> getSortedOrders(long assetId, int from, int to); @Override BidOrder getNextOrder(long assetId); @Override void addOrder(Transaction transaction, ColoredCoinsBidOrderPlacement attachment); @Override void removeOrder(long orderId); @Override void updateQuantityATU(long quantityATU, BidOrder orderBid); }### Answer:
@Test void shouldGetNextOrder() { final long assetId = 10L; final TransactionalDataSource dataSource = mock(TransactionalDataSource.class); final BidOrder order = mock(BidOrder.class); when(databaseManager.getDataSource()).thenReturn(dataSource); when(bidOrderTable.getNextOrder(dataSource, assetId)).thenReturn(order); final BidOrder orderActual = orderService.getNextOrder(assetId); assertEquals(order, orderActual); } |
### Question:
BidOrderServiceImpl implements OrderService<BidOrder, ColoredCoinsBidOrderPlacement> { @Override public void addOrder(Transaction transaction, ColoredCoinsBidOrderPlacement attachment) { final BidOrder order = new BidOrder(transaction, attachment, blockchain.getHeight()); log.trace(">> addOrder() bidOrder={}", order); bidOrderTable.insert(order); } BidOrderServiceImpl(
final DatabaseManager databaseManager,
final BidOrderTable bidOrderTable,
final Blockchain blockchain,
final IteratorToStreamConverter<BidOrder> converter
); @Inject BidOrderServiceImpl(
final DatabaseManager databaseManager,
final BidOrderTable bidOrderTable,
final Blockchain blockchain
); @Override int getCount(); @Override BidOrder getOrder(long orderId); @Override Stream<BidOrder> getAll(int from, int to); @Override Stream<BidOrder> getOrdersByAccount(long accountId, int from, int to); @Override Stream<BidOrder> getOrdersByAccountAsset(final long accountId, final long assetId, int from, int to); @Override Stream<BidOrder> getSortedOrders(long assetId, int from, int to); @Override BidOrder getNextOrder(long assetId); @Override void addOrder(Transaction transaction, ColoredCoinsBidOrderPlacement attachment); @Override void removeOrder(long orderId); @Override void updateQuantityATU(long quantityATU, BidOrder orderBid); }### Answer:
@Test void shouldAddOrder() { final Transaction transaction = mock(Transaction.class); final ColoredCoinsBidOrderPlacement attachment = mock(ColoredCoinsBidOrderPlacement.class); final long txId = 10L; when(transaction.getId()).thenReturn(txId); final int height = 1040; when(blockchain.getHeight()).thenReturn(height); final BidOrder order = new BidOrder(transaction, attachment, blockchain.getHeight()); orderService.addOrder(transaction, attachment); verify(bidOrderTable).insert(eq(order)); } |
### Question:
BidOrderServiceImpl implements OrderService<BidOrder, ColoredCoinsBidOrderPlacement> { @Override public void removeOrder(long orderId) { int height = blockchain.getHeight(); BidOrder order = getOrder(orderId); order.setHeight(height); boolean result = bidOrderTable.deleteAtHeight(order, height); log.trace("<< removeOrder() result={}, bidOrderId={}, height={}", result, orderId, height); } BidOrderServiceImpl(
final DatabaseManager databaseManager,
final BidOrderTable bidOrderTable,
final Blockchain blockchain,
final IteratorToStreamConverter<BidOrder> converter
); @Inject BidOrderServiceImpl(
final DatabaseManager databaseManager,
final BidOrderTable bidOrderTable,
final Blockchain blockchain
); @Override int getCount(); @Override BidOrder getOrder(long orderId); @Override Stream<BidOrder> getAll(int from, int to); @Override Stream<BidOrder> getOrdersByAccount(long accountId, int from, int to); @Override Stream<BidOrder> getOrdersByAccountAsset(final long accountId, final long assetId, int from, int to); @Override Stream<BidOrder> getSortedOrders(long assetId, int from, int to); @Override BidOrder getNextOrder(long assetId); @Override void addOrder(Transaction transaction, ColoredCoinsBidOrderPlacement attachment); @Override void removeOrder(long orderId); @Override void updateQuantityATU(long quantityATU, BidOrder orderBid); }### Answer:
@Test void removeOrder() { final long orderId = 10L; final BidOrder order = mock(BidOrder.class); when(bidOrderTable.getBidOrder(orderId)).thenReturn(order); final int height = 1040; when(blockchain.getHeight()).thenReturn(height); orderService.removeOrder(orderId); verify(bidOrderTable).deleteAtHeight(order, height); } |
### Question:
BidOrderServiceImpl implements OrderService<BidOrder, ColoredCoinsBidOrderPlacement> { @Override public void updateQuantityATU(long quantityATU, BidOrder orderBid) { orderBid.setQuantityATU(quantityATU); int height = blockchain.getHeight(); orderBid.setHeight(height); insertOrDeleteOrder(bidOrderTable, quantityATU, orderBid, height); } BidOrderServiceImpl(
final DatabaseManager databaseManager,
final BidOrderTable bidOrderTable,
final Blockchain blockchain,
final IteratorToStreamConverter<BidOrder> converter
); @Inject BidOrderServiceImpl(
final DatabaseManager databaseManager,
final BidOrderTable bidOrderTable,
final Blockchain blockchain
); @Override int getCount(); @Override BidOrder getOrder(long orderId); @Override Stream<BidOrder> getAll(int from, int to); @Override Stream<BidOrder> getOrdersByAccount(long accountId, int from, int to); @Override Stream<BidOrder> getOrdersByAccountAsset(final long accountId, final long assetId, int from, int to); @Override Stream<BidOrder> getSortedOrders(long assetId, int from, int to); @Override BidOrder getNextOrder(long assetId); @Override void addOrder(Transaction transaction, ColoredCoinsBidOrderPlacement attachment); @Override void removeOrder(long orderId); @Override void updateQuantityATU(long quantityATU, BidOrder orderBid); }### Answer:
@Test void updateQuantityATU() { final long quantityATU = 300; final BidOrder order = mock(BidOrder.class); final int height = 1040; when(blockchain.getHeight()).thenReturn(height); doNothing().when(orderService).insertOrDeleteOrder(bidOrderTable, quantityATU, order, height); orderService.updateQuantityATU(quantityATU, order); verify(orderService).insertOrDeleteOrder(bidOrderTable, quantityATU, order, height); } |
### Question:
AskOrderServiceImpl implements OrderService<AskOrder, ColoredCoinsAskOrderPlacement> { @Override public int getCount() { return askOrderTable.getCount(); } AskOrderServiceImpl(
final DatabaseManager databaseManager,
final AskOrderTable orderAskTable,
final Blockchain blockchain,
final IteratorToStreamConverter<AskOrder> converter
); @Inject AskOrderServiceImpl(
final DatabaseManager databaseManager,
final AskOrderTable orderAskTable,
final Blockchain blockchain
); @Override int getCount(); @Override AskOrder getOrder(long orderId); @Override Stream<AskOrder> getAll(int from, int to); @Override Stream<AskOrder> getOrdersByAccount(long accountId, int from, int to); @Override Stream<AskOrder> getOrdersByAccountAsset(final long accountId, final long assetId, int from, int to); @Override Stream<AskOrder> getSortedOrders(long assetId, int from, int to); @Override AskOrder getNextOrder(long assetId); @Override void addOrder(Transaction transaction, ColoredCoinsAskOrderPlacement attachment); @Override void removeOrder(long orderId); @Override void updateQuantityATU(long quantityATU, AskOrder orderAsk); }### Answer:
@Test void shouldGetCount() { final int count = 1; when(askOrderTable.getCount()).thenReturn(count); final int countActual = orderService.getCount(); assertEquals(count, countActual); } |
### Question:
AskOrderServiceImpl implements OrderService<AskOrder, ColoredCoinsAskOrderPlacement> { @Override public AskOrder getOrder(long orderId) { return askOrderTable.getAskOrder(orderId); } AskOrderServiceImpl(
final DatabaseManager databaseManager,
final AskOrderTable orderAskTable,
final Blockchain blockchain,
final IteratorToStreamConverter<AskOrder> converter
); @Inject AskOrderServiceImpl(
final DatabaseManager databaseManager,
final AskOrderTable orderAskTable,
final Blockchain blockchain
); @Override int getCount(); @Override AskOrder getOrder(long orderId); @Override Stream<AskOrder> getAll(int from, int to); @Override Stream<AskOrder> getOrdersByAccount(long accountId, int from, int to); @Override Stream<AskOrder> getOrdersByAccountAsset(final long accountId, final long assetId, int from, int to); @Override Stream<AskOrder> getSortedOrders(long assetId, int from, int to); @Override AskOrder getNextOrder(long assetId); @Override void addOrder(Transaction transaction, ColoredCoinsAskOrderPlacement attachment); @Override void removeOrder(long orderId); @Override void updateQuantityATU(long quantityATU, AskOrder orderAsk); }### Answer:
@Test void shouldGetOrder() { long orderId = 1L; final AskOrder order = mock(AskOrder.class); when(askOrderTable.getAskOrder(orderId)).thenReturn(order); final AskOrder orderActual = orderService.getOrder(orderId); assertEquals(order, orderActual); } |
### Question:
AskOrderServiceImpl implements OrderService<AskOrder, ColoredCoinsAskOrderPlacement> { @Override public Stream<AskOrder> getAll(int from, int to) { return converter.convert(askOrderTable.getAll(from, to)); } AskOrderServiceImpl(
final DatabaseManager databaseManager,
final AskOrderTable orderAskTable,
final Blockchain blockchain,
final IteratorToStreamConverter<AskOrder> converter
); @Inject AskOrderServiceImpl(
final DatabaseManager databaseManager,
final AskOrderTable orderAskTable,
final Blockchain blockchain
); @Override int getCount(); @Override AskOrder getOrder(long orderId); @Override Stream<AskOrder> getAll(int from, int to); @Override Stream<AskOrder> getOrdersByAccount(long accountId, int from, int to); @Override Stream<AskOrder> getOrdersByAccountAsset(final long accountId, final long assetId, int from, int to); @Override Stream<AskOrder> getSortedOrders(long assetId, int from, int to); @Override AskOrder getNextOrder(long assetId); @Override void addOrder(Transaction transaction, ColoredCoinsAskOrderPlacement attachment); @Override void removeOrder(long orderId); @Override void updateQuantityATU(long quantityATU, AskOrder orderAsk); }### Answer:
@Test void shouldGetAll() { final AskOrder order = mock(AskOrder.class); int from = 0; int to = 100; @SuppressWarnings("unchecked") final DbIterator<AskOrder> dbIterator = mock(DbIterator.class); when(askOrderTable.getAll(from, to)).thenReturn(dbIterator); final Stream<AskOrder> streamExpected = Stream.of(order); when(converter.convert(dbIterator)).thenReturn(streamExpected); final Stream<AskOrder> streamActual = orderService.getAll(from, to); assertEquals(streamExpected, streamActual); } |
### Question:
AskOrderServiceImpl implements OrderService<AskOrder, ColoredCoinsAskOrderPlacement> { @Override public AskOrder getNextOrder(long assetId) { final TransactionalDataSource dataSource = databaseManager.getDataSource(); return askOrderTable.getNextOrder(dataSource, assetId); } AskOrderServiceImpl(
final DatabaseManager databaseManager,
final AskOrderTable orderAskTable,
final Blockchain blockchain,
final IteratorToStreamConverter<AskOrder> converter
); @Inject AskOrderServiceImpl(
final DatabaseManager databaseManager,
final AskOrderTable orderAskTable,
final Blockchain blockchain
); @Override int getCount(); @Override AskOrder getOrder(long orderId); @Override Stream<AskOrder> getAll(int from, int to); @Override Stream<AskOrder> getOrdersByAccount(long accountId, int from, int to); @Override Stream<AskOrder> getOrdersByAccountAsset(final long accountId, final long assetId, int from, int to); @Override Stream<AskOrder> getSortedOrders(long assetId, int from, int to); @Override AskOrder getNextOrder(long assetId); @Override void addOrder(Transaction transaction, ColoredCoinsAskOrderPlacement attachment); @Override void removeOrder(long orderId); @Override void updateQuantityATU(long quantityATU, AskOrder orderAsk); }### Answer:
@Test void shouldGetNextOrder() { final long assetId = 10L; final TransactionalDataSource dataSource = mock(TransactionalDataSource.class); final AskOrder order = mock(AskOrder.class); when(databaseManager.getDataSource()).thenReturn(dataSource); when(askOrderTable.getNextOrder(dataSource, assetId)).thenReturn(order); final AskOrder orderActual = orderService.getNextOrder(assetId); assertEquals(order, orderActual); } |
### Question:
AskOrderServiceImpl implements OrderService<AskOrder, ColoredCoinsAskOrderPlacement> { @Override public void addOrder(Transaction transaction, ColoredCoinsAskOrderPlacement attachment) { final AskOrder order = new AskOrder(transaction, attachment, blockchain.getHeight()); log.trace(">> addOrder() askOrder={}", order); askOrderTable.insert(order); } AskOrderServiceImpl(
final DatabaseManager databaseManager,
final AskOrderTable orderAskTable,
final Blockchain blockchain,
final IteratorToStreamConverter<AskOrder> converter
); @Inject AskOrderServiceImpl(
final DatabaseManager databaseManager,
final AskOrderTable orderAskTable,
final Blockchain blockchain
); @Override int getCount(); @Override AskOrder getOrder(long orderId); @Override Stream<AskOrder> getAll(int from, int to); @Override Stream<AskOrder> getOrdersByAccount(long accountId, int from, int to); @Override Stream<AskOrder> getOrdersByAccountAsset(final long accountId, final long assetId, int from, int to); @Override Stream<AskOrder> getSortedOrders(long assetId, int from, int to); @Override AskOrder getNextOrder(long assetId); @Override void addOrder(Transaction transaction, ColoredCoinsAskOrderPlacement attachment); @Override void removeOrder(long orderId); @Override void updateQuantityATU(long quantityATU, AskOrder orderAsk); }### Answer:
@Test void shouldAddOrder() { final Transaction transaction = mock(Transaction.class); final ColoredCoinsAskOrderPlacement attachment = mock(ColoredCoinsAskOrderPlacement.class); final long txId = 10L; when(transaction.getId()).thenReturn(txId); final int height = 1040; when(blockchain.getHeight()).thenReturn(height); final AskOrder order = new AskOrder(transaction, attachment, blockchain.getHeight()); orderService.addOrder(transaction, attachment); verify(askOrderTable).insert(eq(order)); } |
### Question:
AskOrderServiceImpl implements OrderService<AskOrder, ColoredCoinsAskOrderPlacement> { @Override public void removeOrder(long orderId) { int height = blockchain.getHeight(); AskOrder order = getOrder(orderId); order.setHeight(height); boolean result = askOrderTable.deleteAtHeight(order, height); log.trace(">> removeOrder() result={}, askOrderId={}, height={}", result, orderId, height); } AskOrderServiceImpl(
final DatabaseManager databaseManager,
final AskOrderTable orderAskTable,
final Blockchain blockchain,
final IteratorToStreamConverter<AskOrder> converter
); @Inject AskOrderServiceImpl(
final DatabaseManager databaseManager,
final AskOrderTable orderAskTable,
final Blockchain blockchain
); @Override int getCount(); @Override AskOrder getOrder(long orderId); @Override Stream<AskOrder> getAll(int from, int to); @Override Stream<AskOrder> getOrdersByAccount(long accountId, int from, int to); @Override Stream<AskOrder> getOrdersByAccountAsset(final long accountId, final long assetId, int from, int to); @Override Stream<AskOrder> getSortedOrders(long assetId, int from, int to); @Override AskOrder getNextOrder(long assetId); @Override void addOrder(Transaction transaction, ColoredCoinsAskOrderPlacement attachment); @Override void removeOrder(long orderId); @Override void updateQuantityATU(long quantityATU, AskOrder orderAsk); }### Answer:
@Test void removeOrder() { final long orderId = 10L; final AskOrder order = mock(AskOrder.class); when(askOrderTable.getAskOrder(orderId)).thenReturn(order); final int height = 1040; when(blockchain.getHeight()).thenReturn(height); orderService.removeOrder(orderId); verify(askOrderTable).deleteAtHeight(order, height); } |
### Question:
AskOrderServiceImpl implements OrderService<AskOrder, ColoredCoinsAskOrderPlacement> { @Override public void updateQuantityATU(long quantityATU, AskOrder orderAsk) { orderAsk.setQuantityATU(quantityATU); int height = blockchain.getHeight(); orderAsk.setHeight(height); insertOrDeleteOrder(askOrderTable, quantityATU, orderAsk, height); } AskOrderServiceImpl(
final DatabaseManager databaseManager,
final AskOrderTable orderAskTable,
final Blockchain blockchain,
final IteratorToStreamConverter<AskOrder> converter
); @Inject AskOrderServiceImpl(
final DatabaseManager databaseManager,
final AskOrderTable orderAskTable,
final Blockchain blockchain
); @Override int getCount(); @Override AskOrder getOrder(long orderId); @Override Stream<AskOrder> getAll(int from, int to); @Override Stream<AskOrder> getOrdersByAccount(long accountId, int from, int to); @Override Stream<AskOrder> getOrdersByAccountAsset(final long accountId, final long assetId, int from, int to); @Override Stream<AskOrder> getSortedOrders(long assetId, int from, int to); @Override AskOrder getNextOrder(long assetId); @Override void addOrder(Transaction transaction, ColoredCoinsAskOrderPlacement attachment); @Override void removeOrder(long orderId); @Override void updateQuantityATU(long quantityATU, AskOrder orderAsk); }### Answer:
@Test void updateQuantityATU() { final long quantityATU = 300; final AskOrder order = mock(AskOrder.class); final int height = 1040; when(blockchain.getHeight()).thenReturn(height); doNothing().when(orderService).insertOrDeleteOrder(askOrderTable, quantityATU, order, height); orderService.updateQuantityATU(quantityATU, order); verify(orderService).insertOrDeleteOrder(askOrderTable, quantityATU, order, height); } |
### Question:
DGSPublicFeedbackTable extends ValuesDbTable<DGSPublicFeedback> { public List<DGSPublicFeedback> get(long id) { return get(KEY_FACTORY.newKey(id)); } protected DGSPublicFeedbackTable(); @Override DGSPublicFeedback load(Connection connection, ResultSet rs, DbKey dbKey); @Override void save(Connection con, DGSPublicFeedback feedback); List<DGSPublicFeedback> get(long id); }### Answer:
@Test void testGetByPurchaseId() { List<DGSPublicFeedback> feedbacks = table.get(dtd.PUBLIC_FEEDBACK_12.getId()); assertEquals(List.of(dtd.PUBLIC_FEEDBACK_11, dtd.PUBLIC_FEEDBACK_12, dtd.PUBLIC_FEEDBACK_13), feedbacks); }
@Test void testGetDeletedByPurchaseId() { List<DGSPublicFeedback> feedbacks = table.get(dtd.PUBLIC_FEEDBACK_8.getId()); assertEquals(0, feedbacks.size()); }
@Test void testNonexistentById() { List<DGSPublicFeedback> feedbacks = table.get(-1); assertEquals(0, feedbacks.size()); } |
### Question:
DGSTagTable extends EntityDbTable<DGSTag> { public DGSTag get(String tagValue) { return get(KEY_FACTORY.newKey(tagValue)); } DGSTagTable(); @Override DGSTag load(Connection con, ResultSet rs, DbKey dbKey); @Override void save(Connection con, DGSTag tag); DGSTag get(String tagValue); @Override String defaultSort(); static final String TABLE_NAME; }### Answer:
@Test void testGetByTag() { DGSTag dgsTag = table.get(dtd.TAG_10.getTag()); assertEquals(dtd.TAG_10, dgsTag); }
@Test void testGetDeletedTag() { DGSTag dgsTag = table.get(dtd.TAG_8.getTag()); assertNull(dgsTag); }
@Test void testGetByNonexistentTag() { DGSTag dgsTag = table.get(""); assertNull(dgsTag); } |
### Question:
TaggedDataTimestampDao extends EntityDbTable<TaggedDataTimestamp> { public DbKey newDbKey(TaggedDataTimestamp dataTimestamp) { return timestampKeyFactory.newKey(dataTimestamp.getId()); } TaggedDataTimestampDao(); DbKey newDbKey(TaggedDataTimestamp dataTimestamp); @Override TaggedDataTimestamp load(Connection con, ResultSet rs, DbKey dbKey); void save(Connection con, TaggedDataTimestamp dataTimestamp); }### Answer:
@Test void getDataStampById() { DbKey dbKey = dataTimestampDao.newDbKey(tagtd.TagDTsmp_1); TaggedDataTimestamp stamp = dataTimestampDao.get(dbKey); assertNotNull(stamp); assertEquals(stamp.getId(), tagtd.TagDTsmp_1.getId()); } |
### Question:
DataTagDao extends EntityDbTable<DataTag> { public DbKey newDbKey(DataTag dataTag) { return tagDbKeyFactory.newKey(dataTag.getTag()); } @Inject DataTagDao(); DbKey newDbKey(DataTag dataTag); void add(TaggedData taggedData); void add(String[] tags, int height); @Override boolean isScanSafe(); void add(TaggedData taggedData, int height); void delete(Map<String, Integer> expiredTags); int getDataTagCount(); DbIterator<DataTag> getAllTags(int from, int to); DbIterator<DataTag> getTagsLike(String prefix, int from, int to); @Override DataTag load(Connection con, ResultSet rs, DbKey dbKey); @Override void save(Connection con, DataTag dataTag); @Override String defaultSort(); }### Answer:
@Test void getDataTagById() { DbKey dbKey = dataTagDao.newDbKey(tagtd.dataTag_1); DataTag result = dataTagDao.get(dbKey); assertNotNull(result); assertEquals(result.getTag(), tagtd.dataTag_1.getTag()); } |
### Question:
DataTagDao extends EntityDbTable<DataTag> { public void add(TaggedData taggedData) { add(taggedData.getParsedTags(), taggedData.getHeight()); } @Inject DataTagDao(); DbKey newDbKey(DataTag dataTag); void add(TaggedData taggedData); void add(String[] tags, int height); @Override boolean isScanSafe(); void add(TaggedData taggedData, int height); void delete(Map<String, Integer> expiredTags); int getDataTagCount(); DbIterator<DataTag> getAllTags(int from, int to); DbIterator<DataTag> getTagsLike(String prefix, int from, int to); @Override DataTag load(Connection con, ResultSet rs, DbKey dbKey); @Override void save(Connection con, DataTag dataTag); @Override String defaultSort(); }### Answer:
@Test void testAdd() { TaggedData taggedData = mock(TaggedData.class); doReturn(1_000_000).when(taggedData).getHeight(); doReturn(new String[]{tagtd.dataTag_1.getTag(), "newTag"}).when(taggedData).getParsedTags(); DbUtils.inTransaction(extension, (con) -> dataTagDao.add(taggedData)); List<DataTag> dataTags = CollectionUtil.toList(dataTagDao.getAllTags(0, 4)); DataTag updatedDataTag = new DataTag(tagtd.dataTag_1.getTag(), 1_000_000, tagtd.dataTag_1.getCount() + 1); updatedDataTag.setLatest(true); updatedDataTag.setDbId(41); DataTag newTag = new DataTag("newTag", 1_000_000, 1); newTag.setLatest(true); newTag.setDbId(42); tagtd.dataTag_4.setDbId(40); List<DataTag> expected = List.of( updatedDataTag, newTag, tagtd.dataTag_4 ); assertEquals(expected, dataTags); } |
### Question:
ShardInfoDownloader { public void processAllPeersShardingInfo() { shardInfoByPeers.entrySet().removeIf( entry -> (entry.getValue().isShardingOff == true) ); shardInfoByPeers.keySet().forEach((pa) -> { processPeerShardingInfo(pa, shardInfoByPeers.get(pa)); }); log.debug("ShardingInfo requesting result {}", sortedByIdShards); sortedByIdShards.keySet().forEach((idx) -> { shardsDesisons.put(idx, checkShard(idx)); }); } @Inject ShardInfoDownloader(PeersService peers); void setShardInfoByPeers(Map<String, ShardingInfo> testData); void processAllPeersShardingInfo(); boolean processPeerShardingInfo(String pa, ShardingInfo si); ShardingInfo getShardingInfoFromPeer(String addr); Map<String, ShardingInfo> getShardInfoFromPeers(); ShardInfo getShardInfo(Long shardId); double getShardWeight(Long shardId); Map<Long, Double> getShardRelativeWeights(); static final String SHARD_ID_ENV; }### Answer:
@Test public void testProcessAllPeersShardingInfo() { downloader.setShardInfoByPeers(shardInfoByPeers_ALL_GOOD); downloader.processAllPeersShardingInfo(); int size = downloader.getGoodPeersMap().size(); assertEquals(3, size); } |
### Question:
ShardInfoDownloader { public boolean processPeerShardingInfo(String pa, ShardingInfo si) { Objects.requireNonNull(pa, "peerAddress is NULL"); Objects.requireNonNull(si, "shardInfo is NULL"); boolean haveShard = false; log.trace("shardInfo = {}", si); if (si != null) { for (ShardInfo s : si.shards) { if (myChainId.equals(UUID.fromString(s.chainId))) { haveShard = true; synchronized (this) { Set<String> ps = shardsPeers.get(s.shardId); if (ps == null) { ps = new HashSet<>(); shardsPeers.put(s.shardId, ps); } ps.add(pa); Set<ShardInfo> rs = sortedByIdShards.get(s.shardId); if (rs == null) { rs = new HashSet<>(); sortedByIdShards.put(s.shardId, rs); } rs.add(s); } } } } return haveShard; } @Inject ShardInfoDownloader(PeersService peers); void setShardInfoByPeers(Map<String, ShardingInfo> testData); void processAllPeersShardingInfo(); boolean processPeerShardingInfo(String pa, ShardingInfo si); ShardingInfo getShardingInfoFromPeer(String addr); Map<String, ShardingInfo> getShardInfoFromPeers(); ShardInfo getShardInfo(Long shardId); double getShardWeight(Long shardId); Map<Long, Double> getShardRelativeWeights(); static final String SHARD_ID_ENV; }### Answer:
@Test public void testProcessPeerShardingInfo() { downloader.setShardInfoByPeers(shardInfoByPeers_ALL_GOOD); downloader.processAllPeersShardingInfo(); String pa = "1"; ShardingInfo si = shardInfoByPeers_ALL_GOOD.get(pa); boolean expResult = true; boolean result = downloader.processPeerShardingInfo(pa, si); assertEquals(expResult, result); } |
### Question:
ShardInfoDownloader { public ShardingInfo getShardingInfoFromPeer(String addr) { int attempts = 3; if (StringUtils.isBlank(addr)) { String error = String.format("address is EMPTY or NULL : '%s'", addr); log.error(error); throw new RuntimeException(error); } ShardingInfo res = null; Peer p = peers.findOrCreatePeer(null, addr, true); if (p != null) { if (tryConnectToPeer(p, attempts)) { PeerClient pc = new PeerClient(p); res = pc.getShardingInfo(); } else { log.debug("FAILED to connect to peer: {} after '{}' attempts", addr, attempts); } } else { log.debug("Can not create peer: {}", addr); } return res; } @Inject ShardInfoDownloader(PeersService peers); void setShardInfoByPeers(Map<String, ShardingInfo> testData); void processAllPeersShardingInfo(); boolean processPeerShardingInfo(String pa, ShardingInfo si); ShardingInfo getShardingInfoFromPeer(String addr); Map<String, ShardingInfo> getShardInfoFromPeers(); ShardInfo getShardInfo(Long shardId); double getShardWeight(Long shardId); Map<Long, Double> getShardRelativeWeights(); static final String SHARD_ID_ENV; }### Answer:
@Test public void testGetShardingInfoFromPeer() { } |
### Question:
ShardInfoDownloader { public ShardInfo getShardInfo(Long shardId) { Objects.requireNonNull(shardId, "shardId is NULL"); ShardInfo res = null; if (goodPeersMap.isEmpty()) { return res; } Set<PeerFileHashSum> goodShardPeers = goodPeersMap.get(shardId); if (goodShardPeers == null || goodShardPeers.isEmpty()) { return res; } PeerFileHashSum pfhs = goodShardPeers.iterator().next(); if (pfhs == null) { return res; } String peerId = pfhs.getPeerId(); ShardingInfo srdInfo = shardInfoByPeers.get(peerId); for (ShardInfo si : srdInfo.getShards()) { if (si.shardId.longValue() == shardId.longValue()) { res = si; break; } } return res; } @Inject ShardInfoDownloader(PeersService peers); void setShardInfoByPeers(Map<String, ShardingInfo> testData); void processAllPeersShardingInfo(); boolean processPeerShardingInfo(String pa, ShardingInfo si); ShardingInfo getShardingInfoFromPeer(String addr); Map<String, ShardingInfo> getShardInfoFromPeers(); ShardInfo getShardInfo(Long shardId); double getShardWeight(Long shardId); Map<Long, Double> getShardRelativeWeights(); static final String SHARD_ID_ENV; }### Answer:
@Test public void testGetShardInfo() { Long shardId = 1L; downloader.setShardInfoByPeers(shardInfoByPeers_ALL_GOOD); downloader.processAllPeersShardingInfo(); ShardInfo expResult = shardInfoByPeers_ALL_GOOD.get("1").getShards().get(2); ShardInfo result = downloader.getShardInfo(shardId); assertEquals(expResult, result); } |
### Question:
ShardInfoDownloader { public double getShardWeight(Long shardId) { Objects.requireNonNull(shardId, "shardId is NULL"); double res = 0.0D; int allPeersNumber = shardInfoByPeers.size(); Set<PeerFileHashSum> goodPeers = goodPeersMap.get(shardId); int goodPeersNumber = (goodPeers == null ? 0 : goodPeers.size()); Set<PeerFileHashSum> badPeers = badPeersMap.get(shardId); int badPeersNumber = (badPeers == null ? 0 : badPeers.size()); int noShardPeersNumber = allPeersNumber - (goodPeersNumber + badPeersNumber); res = (1.0 * goodPeersNumber - 1.0 * badPeersNumber - 1.0 * noShardPeersNumber) / allPeersNumber; return res; } @Inject ShardInfoDownloader(PeersService peers); void setShardInfoByPeers(Map<String, ShardingInfo> testData); void processAllPeersShardingInfo(); boolean processPeerShardingInfo(String pa, ShardingInfo si); ShardingInfo getShardingInfoFromPeer(String addr); Map<String, ShardingInfo> getShardInfoFromPeers(); ShardInfo getShardInfo(Long shardId); double getShardWeight(Long shardId); Map<Long, Double> getShardRelativeWeights(); static final String SHARD_ID_ENV; }### Answer:
@Test public void testGetShardWeight() { downloader.setShardInfoByPeers(shardInfoByPeers_ALL_GOOD); downloader.processAllPeersShardingInfo(); double expResult = 0.7; for (long i = 1; i <= downloader.getShardsDesisons().size(); i++) { double result = downloader.getShardWeight(i); assertEquals(result > expResult, true); log.debug("Shard: {} weight: {}", i, result); } } |
### Question:
ShardInfoDownloader { public Map<Long, Double> getShardRelativeWeights() { Map<Long, Double> res = new HashMap<>(); if (sortedByIdShards.isEmpty()) { return res; } for (Long shardId : sortedByIdShards.keySet()) { Double k = 1.0 * shardId / sortedByIdShards.keySet().size(); Double weight = getShardWeight(shardId) * k; res.put(shardId, weight); } Long predefined = readManuallyDefinedShardId(); if (predefined != null) { boolean exists = res.get(predefined) != null; if (exists) { res.replace(predefined, 20.0D); log.info("Downloading of shard {} is forced by enviromnent variable", predefined); } else { log.info("Shard ID {} predefined in environment variable is not usable or does not exist", predefined); } } return res; } @Inject ShardInfoDownloader(PeersService peers); void setShardInfoByPeers(Map<String, ShardingInfo> testData); void processAllPeersShardingInfo(); boolean processPeerShardingInfo(String pa, ShardingInfo si); ShardingInfo getShardingInfoFromPeer(String addr); Map<String, ShardingInfo> getShardInfoFromPeers(); ShardInfo getShardInfo(Long shardId); double getShardWeight(Long shardId); Map<Long, Double> getShardRelativeWeights(); static final String SHARD_ID_ENV; }### Answer:
@Test public void testGetShardRelativeWeights() { downloader.setShardInfoByPeers(shardInfoByPeers_ALL_GOOD); downloader.processAllPeersShardingInfo(); Map<Long, Double> result = downloader.getShardRelativeWeights(); int size = result.size(); result.keySet().forEach((id) -> { log.debug("Shard: {} RelWeight: {}", id, result.get(id)); }); assertEquals(size, 3); } |
### Question:
BlockchainConfig { public HeightConfig getCurrentConfig() { return currentConfig; } BlockchainConfig(); BlockchainConfig(Chain chain, PropertiesHolder holder); void updateChain(Chain chain, int minPrunableLifetime, int maxPrunableLifetime); HeightConfig getConfigAtHeight(int targetHeight); String getProjectName(); String getAccountPrefix(); String getCoinSymbol(); int getLeasingDelay(); int getMinPrunableLifetime(); short getShufflingProcessingDeadline(); long getLastKnownBlock(); long getUnconfirmedPoolDepositAtm(); long getShufflingDepositAtm(); int getGuaranteedBalanceConfirmations(); boolean isEnablePruning(); int getMaxPrunableLifetime(); Integer getDexPendingOrdersReopeningHeight(); Integer getDexExpiredContractWithFinishedPhasingHeightAndStep3(); HeightConfig getCurrentConfig(); void setCurrentConfig(HeightConfig currentConfig); Chain getChain(); Optional<HeightConfig> getPreviousConfig(); boolean isJustUpdated(); void resetJustUpdated(); }### Answer:
@Test void testCreateBlockchainConfig() { BlockchainConfig blockchainConfig = new BlockchainConfig(chain, new PropertiesHolder()); assertEquals(new HeightConfig(bp1), blockchainConfig.getCurrentConfig()); } |
### Question:
ApolloCertificate extends CertBase { public AuthorityID getAuthorityId() { return cert_attr.getAuthorityId(); } ApolloCertificate(X509Certificate certificate); static ApolloCertificate loadPEMFromPath(String path); static ApolloCertificate loadPEMFromStream(InputStream is); BigInteger getApolloId(); AuthorityID getAuthorityId(); String getCN(); String getOrganization(); String getOrganizationUnit(); String getCountry(); String getCity(); String getCertificatePurpose(); List<String> getIPAddresses(); List<String> getDNSNames(); String getStateOrProvince(); String getEmail(); String fromList(List<String> sl); List<String> fromString(String l); @Override String toString(); String getPEM(); boolean isValid(Date date); BigInteger getSerial(); CertAttributes getIssuerAttrinutes(); boolean verify(); }### Answer:
@Test public void testGetAuthorityId() { AuthorityID result = acert.getAuthorityId(); assertEquals(5139, result.getActorType()); } |
### Question:
ApolloCertificate extends CertBase { public String getCN() { return cert_attr.getCn(); } ApolloCertificate(X509Certificate certificate); static ApolloCertificate loadPEMFromPath(String path); static ApolloCertificate loadPEMFromStream(InputStream is); BigInteger getApolloId(); AuthorityID getAuthorityId(); String getCN(); String getOrganization(); String getOrganizationUnit(); String getCountry(); String getCity(); String getCertificatePurpose(); List<String> getIPAddresses(); List<String> getDNSNames(); String getStateOrProvince(); String getEmail(); String fromList(List<String> sl); List<String> fromString(String l); @Override String toString(); String getPEM(); boolean isValid(Date date); BigInteger getSerial(); CertAttributes getIssuerAttrinutes(); boolean verify(); }### Answer:
@Test public void testGetCN() { String result = acert.getCN(); assertEquals("al.cn.ua", result); } |
### Question:
ApolloCertificate extends CertBase { public String getOrganization() { return cert_attr.getO(); } ApolloCertificate(X509Certificate certificate); static ApolloCertificate loadPEMFromPath(String path); static ApolloCertificate loadPEMFromStream(InputStream is); BigInteger getApolloId(); AuthorityID getAuthorityId(); String getCN(); String getOrganization(); String getOrganizationUnit(); String getCountry(); String getCity(); String getCertificatePurpose(); List<String> getIPAddresses(); List<String> getDNSNames(); String getStateOrProvince(); String getEmail(); String fromList(List<String> sl); List<String> fromString(String l); @Override String toString(); String getPEM(); boolean isValid(Date date); BigInteger getSerial(); CertAttributes getIssuerAttrinutes(); boolean verify(); }### Answer:
@Test public void testGetOrganization() { String expResult = "FirstBridge"; String result = acert.getOrganization(); assertEquals(expResult, result); } |
### Question:
ApolloCertificate extends CertBase { public String getOrganizationUnit() { return cert_attr.getOu(); } ApolloCertificate(X509Certificate certificate); static ApolloCertificate loadPEMFromPath(String path); static ApolloCertificate loadPEMFromStream(InputStream is); BigInteger getApolloId(); AuthorityID getAuthorityId(); String getCN(); String getOrganization(); String getOrganizationUnit(); String getCountry(); String getCity(); String getCertificatePurpose(); List<String> getIPAddresses(); List<String> getDNSNames(); String getStateOrProvince(); String getEmail(); String fromList(List<String> sl); List<String> fromString(String l); @Override String toString(); String getPEM(); boolean isValid(Date date); BigInteger getSerial(); CertAttributes getIssuerAttrinutes(); boolean verify(); }### Answer:
@Test public void testGetOrganizationUnit() { String expResult = "FB-cn"; String result = acert.getOrganizationUnit(); assertEquals(expResult, result); } |
### Question:
ApolloCertificate extends CertBase { public String getCountry() { return cert_attr.getCountry(); } ApolloCertificate(X509Certificate certificate); static ApolloCertificate loadPEMFromPath(String path); static ApolloCertificate loadPEMFromStream(InputStream is); BigInteger getApolloId(); AuthorityID getAuthorityId(); String getCN(); String getOrganization(); String getOrganizationUnit(); String getCountry(); String getCity(); String getCertificatePurpose(); List<String> getIPAddresses(); List<String> getDNSNames(); String getStateOrProvince(); String getEmail(); String fromList(List<String> sl); List<String> fromString(String l); @Override String toString(); String getPEM(); boolean isValid(Date date); BigInteger getSerial(); CertAttributes getIssuerAttrinutes(); boolean verify(); }### Answer:
@Test public void testGetCountry() { String expResult = "UA"; String result = acert.getCountry(); assertEquals(expResult, result); } |
### Question:
ApolloCertificate extends CertBase { public String getCity() { return cert_attr.getCity(); } ApolloCertificate(X509Certificate certificate); static ApolloCertificate loadPEMFromPath(String path); static ApolloCertificate loadPEMFromStream(InputStream is); BigInteger getApolloId(); AuthorityID getAuthorityId(); String getCN(); String getOrganization(); String getOrganizationUnit(); String getCountry(); String getCity(); String getCertificatePurpose(); List<String> getIPAddresses(); List<String> getDNSNames(); String getStateOrProvince(); String getEmail(); String fromList(List<String> sl); List<String> fromString(String l); @Override String toString(); String getPEM(); boolean isValid(Date date); BigInteger getSerial(); CertAttributes getIssuerAttrinutes(); boolean verify(); }### Answer:
@Test public void testGetCity() { String expResult = "Chernigiv"; String result = acert.getCity(); assertEquals(expResult, result); } |
### Question:
ApolloCertificate extends CertBase { public String getCertificatePurpose() { return "Node"; } ApolloCertificate(X509Certificate certificate); static ApolloCertificate loadPEMFromPath(String path); static ApolloCertificate loadPEMFromStream(InputStream is); BigInteger getApolloId(); AuthorityID getAuthorityId(); String getCN(); String getOrganization(); String getOrganizationUnit(); String getCountry(); String getCity(); String getCertificatePurpose(); List<String> getIPAddresses(); List<String> getDNSNames(); String getStateOrProvince(); String getEmail(); String fromList(List<String> sl); List<String> fromString(String l); @Override String toString(); String getPEM(); boolean isValid(Date date); BigInteger getSerial(); CertAttributes getIssuerAttrinutes(); boolean verify(); }### Answer:
@Test public void testGetCertificatePurpose() { String expResult = "Node"; String result = acert.getCertificatePurpose(); assertEquals(expResult, result); } |
### Question:
ApolloCertificate extends CertBase { public List<String> getIPAddresses() { return cert_attr.IpAddresses(); } ApolloCertificate(X509Certificate certificate); static ApolloCertificate loadPEMFromPath(String path); static ApolloCertificate loadPEMFromStream(InputStream is); BigInteger getApolloId(); AuthorityID getAuthorityId(); String getCN(); String getOrganization(); String getOrganizationUnit(); String getCountry(); String getCity(); String getCertificatePurpose(); List<String> getIPAddresses(); List<String> getDNSNames(); String getStateOrProvince(); String getEmail(); String fromList(List<String> sl); List<String> fromString(String l); @Override String toString(); String getPEM(); boolean isValid(Date date); BigInteger getSerial(); CertAttributes getIssuerAttrinutes(); boolean verify(); }### Answer:
@Test public void testGetIPAddresses() { List<String> expResult = null; List<String> result = acert.getIPAddresses(); assertEquals(expResult, result); } |
### Question:
ApolloCertificate extends CertBase { public List<String> getDNSNames() { return null; } ApolloCertificate(X509Certificate certificate); static ApolloCertificate loadPEMFromPath(String path); static ApolloCertificate loadPEMFromStream(InputStream is); BigInteger getApolloId(); AuthorityID getAuthorityId(); String getCN(); String getOrganization(); String getOrganizationUnit(); String getCountry(); String getCity(); String getCertificatePurpose(); List<String> getIPAddresses(); List<String> getDNSNames(); String getStateOrProvince(); String getEmail(); String fromList(List<String> sl); List<String> fromString(String l); @Override String toString(); String getPEM(); boolean isValid(Date date); BigInteger getSerial(); CertAttributes getIssuerAttrinutes(); boolean verify(); }### Answer:
@Test public void testGetDNSNames() { List<String> expResult = null; List<String> result = acert.getDNSNames(); assertEquals(expResult, result); } |
### Question:
ApolloCertificate extends CertBase { public String getStateOrProvince() { return null; } ApolloCertificate(X509Certificate certificate); static ApolloCertificate loadPEMFromPath(String path); static ApolloCertificate loadPEMFromStream(InputStream is); BigInteger getApolloId(); AuthorityID getAuthorityId(); String getCN(); String getOrganization(); String getOrganizationUnit(); String getCountry(); String getCity(); String getCertificatePurpose(); List<String> getIPAddresses(); List<String> getDNSNames(); String getStateOrProvince(); String getEmail(); String fromList(List<String> sl); List<String> fromString(String l); @Override String toString(); String getPEM(); boolean isValid(Date date); BigInteger getSerial(); CertAttributes getIssuerAttrinutes(); boolean verify(); }### Answer:
@Test public void testGetStateOrProvince() { String expResult = null; String result = acert.getStateOrProvince(); assertEquals(expResult, result); } |
### Question:
ApolloCertificate extends CertBase { public String getEmail() { return cert_attr.geteMail(); } ApolloCertificate(X509Certificate certificate); static ApolloCertificate loadPEMFromPath(String path); static ApolloCertificate loadPEMFromStream(InputStream is); BigInteger getApolloId(); AuthorityID getAuthorityId(); String getCN(); String getOrganization(); String getOrganizationUnit(); String getCountry(); String getCity(); String getCertificatePurpose(); List<String> getIPAddresses(); List<String> getDNSNames(); String getStateOrProvince(); String getEmail(); String fromList(List<String> sl); List<String> fromString(String l); @Override String toString(); String getPEM(); boolean isValid(Date date); BigInteger getSerial(); CertAttributes getIssuerAttrinutes(); boolean verify(); }### Answer:
@Test public void testGetEmail() { String expResult = "alukin@gmail.com"; String result = acert.getEmail(); assertEquals(expResult, result); } |
### Question:
ApolloCertificate extends CertBase { public String getPEM() { String res = ""; KeyWriter kw = new KeyWriterImpl(); try { res = kw.getX509CertificatePEM(certificate); } catch (IOException ex) { log.error("Can not get certificate PEM", ex); } return res; } ApolloCertificate(X509Certificate certificate); static ApolloCertificate loadPEMFromPath(String path); static ApolloCertificate loadPEMFromStream(InputStream is); BigInteger getApolloId(); AuthorityID getAuthorityId(); String getCN(); String getOrganization(); String getOrganizationUnit(); String getCountry(); String getCity(); String getCertificatePurpose(); List<String> getIPAddresses(); List<String> getDNSNames(); String getStateOrProvince(); String getEmail(); String fromList(List<String> sl); List<String> fromString(String l); @Override String toString(); String getPEM(); boolean isValid(Date date); BigInteger getSerial(); CertAttributes getIssuerAttrinutes(); boolean verify(); }### Answer:
@Test public void testGetPEM() { String result = acert.getPEM(); assertEquals(true, result.startsWith("-----BEGIN CERTIFICATE----")); } |
### Question:
ApolloCertificate extends CertBase { public boolean isValid(Date date) { boolean dateOK = false; Date start = certificate.getNotBefore(); Date end = certificate.getNotAfter(); if (date != null && start != null && end != null) { if (date.after(start) && date.before(end)) { dateOK = true; } else { dateOK = false; } } return dateOK; } ApolloCertificate(X509Certificate certificate); static ApolloCertificate loadPEMFromPath(String path); static ApolloCertificate loadPEMFromStream(InputStream is); BigInteger getApolloId(); AuthorityID getAuthorityId(); String getCN(); String getOrganization(); String getOrganizationUnit(); String getCountry(); String getCity(); String getCertificatePurpose(); List<String> getIPAddresses(); List<String> getDNSNames(); String getStateOrProvince(); String getEmail(); String fromList(List<String> sl); List<String> fromString(String l); @Override String toString(); String getPEM(); boolean isValid(Date date); BigInteger getSerial(); CertAttributes getIssuerAttrinutes(); boolean verify(); }### Answer:
@Test public void testIsValid() { Date date = null; boolean expResult = false; boolean result = acert.isValid(date); assertEquals(expResult, result); } |
### Question:
ApolloCertificate extends CertBase { public BigInteger getSerial() { return certificate.getSerialNumber(); } ApolloCertificate(X509Certificate certificate); static ApolloCertificate loadPEMFromPath(String path); static ApolloCertificate loadPEMFromStream(InputStream is); BigInteger getApolloId(); AuthorityID getAuthorityId(); String getCN(); String getOrganization(); String getOrganizationUnit(); String getCountry(); String getCity(); String getCertificatePurpose(); List<String> getIPAddresses(); List<String> getDNSNames(); String getStateOrProvince(); String getEmail(); String fromList(List<String> sl); List<String> fromString(String l); @Override String toString(); String getPEM(); boolean isValid(Date date); BigInteger getSerial(); CertAttributes getIssuerAttrinutes(); boolean verify(); }### Answer:
@Test public void testGetSerial() { BigInteger result = acert.getSerial(); BigInteger expResult = BigInteger.valueOf(1582313240538L); assertEquals(expResult, result); } |
### Question:
ThreadUtils { public static String lastStacktrace() { return lastStacktrace(Thread.currentThread().getStackTrace()); } private ThreadUtils(); static void sleep(long millis); static void sleep(long time, TimeUnit timeUnit); static String last3Stacktrace(); static String last5Stacktrace(); static String lastStacktrace(); static String lastStacktrace(StackTraceElement[] stackTraceElements); static String lastStacktrace(StackTraceElement[] stackTraceElements, int elementNumber); static String getStacktraceSpec(StackTraceElement element); static String getStackTrace(Throwable exception); static String getStackTraceSilently(Throwable exception); }### Answer:
@Test void lastStacktrace() { StackTraceElement[] stack = Thread.currentThread().getStackTrace(); int length = stack.length; String result0 = ThreadUtils.lastStacktrace(); assertNotNull(result0); String result = ThreadUtils.lastStacktrace(stack, length); assertNotNull(result); assertTrue(result.length() < result0.length()); String result2 = ThreadUtils.lastStacktrace(stack, length + 10); assertNotNull(result2); assertEquals(result, result2); String result3 = ThreadUtils.lastStacktrace(stack, length - 2); assertNotNull(result3); assertTrue(result3.length() < result.length()); } |
### Question:
ThreadUtils { public static String getStacktraceSpec(StackTraceElement element) { String className = element.getClassName(); return className.substring(className.lastIndexOf(".") + 1) + "." + element.getMethodName() + ":" + element.getLineNumber(); } private ThreadUtils(); static void sleep(long millis); static void sleep(long time, TimeUnit timeUnit); static String last3Stacktrace(); static String last5Stacktrace(); static String lastStacktrace(); static String lastStacktrace(StackTraceElement[] stackTraceElements); static String lastStacktrace(StackTraceElement[] stackTraceElements, int elementNumber); static String getStacktraceSpec(StackTraceElement element); static String getStackTrace(Throwable exception); static String getStackTraceSilently(Throwable exception); }### Answer:
@Test void getStacktraceSpec() { StackTraceElement element = Thread.currentThread().getStackTrace()[0]; String result = ThreadUtils.getStacktraceSpec(element); assertNotNull(result); assertTrue(result.contains(".")); assertTrue(result.contains(":")); } |
### Question:
PathSpecification { public static PathSpecification fromSpecString(String pathSpec) { PathSpecification res = new PathSpecification(); res.pathSpec = pathSpec; String[] elements = pathSpec.split("/"); int bracePos = pathSpec.indexOf("{"); if (bracePos > 0) { res.prefix = pathSpec.substring(0, bracePos - 1); for (String element : elements) { if (element.startsWith("{")) { if (element.endsWith("}")) { res.paramNames.add(element.substring(1, element.length() - 1)); } else { log.error("Missing brace in path element {} of path sepce: {}", element, pathSpec); res.paramNames.add(element.substring(1, element.length())); } } } } else { res.prefix = pathSpec; } return res; } PathSpecification(); static PathSpecification fromSpecString(String pathSpec); boolean matches(String path); Map<String, String> parseParams(String path); public String prefix; public List<String> paramNames; public String pathSpec; }### Answer:
@Test public void testFromSpecString() { String pathSpec1 = "/test/one/{param1}/{param2}"; PathSpecification result1 = PathSpecification.fromSpecString(pathSpec1); assertEquals("/test/one", result1.prefix); assertEquals("param1", result1.paramNames.get(0)); assertEquals("param2", result1.paramNames.get(1)); String pathSpec2 = "/test/two/one"; PathSpecification result2 = PathSpecification.fromSpecString(pathSpec2); assertEquals("/test/two/one", result2.prefix); assertEquals(0, result2.paramNames.size()); String pathSpec3 = "/test/one/{param1/{param2}"; PathSpecification result3 = PathSpecification.fromSpecString(pathSpec3); assertEquals("/test/one", result3.prefix); assertEquals("param1", result3.paramNames.get(0)); assertEquals("param2", result3.paramNames.get(1)); } |
### Question:
PathSpecification { public boolean matches(String path) { boolean res = false; int len = prefix.length(); if (path.length() >= len) { String matching = path.substring(0, len); if (matching.equals(prefix)) { res = true; } } return res; } PathSpecification(); static PathSpecification fromSpecString(String pathSpec); boolean matches(String path); Map<String, String> parseParams(String path); public String prefix; public List<String> paramNames; public String pathSpec; }### Answer:
@Test public void testMatches() { String pathSpec = "/test/one/{param1}/{param2}"; PathSpecification ps = PathSpecification.fromSpecString(pathSpec); boolean result1 = ps.matches("/test/one/1"); assertEquals(true,result1); boolean result2 = ps.matches("/test/one/1/2/3"); assertEquals(true,result2); } |
### Question:
PathSpecification { public Map<String, String> parseParams(String path) { Map<String, String> res = new HashMap<>(); String params = path.substring(prefix.length()); if (!params.isEmpty()) { String[] elements = params.split("/"); int start = 0; if (elements.length > 0) { if (elements[0].isEmpty()) { start = 1; } } for (int i = start; i < elements.length; i++) { if (i >= paramNames.size() + start) { break; } res.put(paramNames.get(i - start), elements[i]); } } return res; } PathSpecification(); static PathSpecification fromSpecString(String pathSpec); boolean matches(String path); Map<String, String> parseParams(String path); public String prefix; public List<String> paramNames; public String pathSpec; }### Answer:
@Test public void testParseParams() { String pathSpec = "/test/one/{param1}/{param2}"; PathSpecification ps = PathSpecification.fromSpecString(pathSpec); Map<String,String> params = ps.parseParams("/test/one/1"); assertEquals("1", params.get("param1")); assertEquals(null, params.get("param2")); Map<String,String> params1 = ps.parseParams("/test/one/1/2"); assertEquals("1", params1.get("param1")); assertEquals("2", params1.get("param2")); Map<String,String> params2 = ps.parseParams("test/one/1/2"); assertEquals("1", params1.get("param1")); assertEquals("2", params1.get("param2")); } |
### Question:
FileUtils { public static boolean deleteFileIfExistsQuietly(Path file) { try { return Files.deleteIfExists(file); } catch (IOException e) { log.error("Unable to delete file {}, cause: {}", file, e.getMessage()); } return false; } private FileUtils(); static boolean deleteFileIfExistsQuietly(Path file); static boolean deleteFileIfExistsAndHandleException(Path file, Consumer<IOException> handler); static boolean deleteFileIfExists(Path file); static void clearDirectorySilently(Path directory); static void deleteFilesByPattern(Path directory, String[] suffixes, String[] names); static void deleteFilesByFilter(Path directory, Predicate<Path> predicate); static long countElementsOfDirectory(Path directory); }### Answer:
@Test void deleteFileIfExistsQuietly() throws IOException { Path file = temporaryFolderExtension.newFile("file").toPath(); FileUtils.deleteFileIfExistsQuietly(file); assertFalse(Files.exists(file)); }
@Test void deleteFileIfExistsWithException() throws IOException { Path directory = temporaryFolderExtension.newFolder().toPath(); Files.createFile(directory.resolve("file.txt")); FileUtils.deleteFileIfExistsQuietly(directory); assertTrue(Files.exists(directory)); } |
### Question:
FileUtils { public static boolean deleteFileIfExistsAndHandleException(Path file, Consumer<IOException> handler) { try { return Files.deleteIfExists(file); } catch (IOException e) { handler.accept(e); } return false; } private FileUtils(); static boolean deleteFileIfExistsQuietly(Path file); static boolean deleteFileIfExistsAndHandleException(Path file, Consumer<IOException> handler); static boolean deleteFileIfExists(Path file); static void clearDirectorySilently(Path directory); static void deleteFilesByPattern(Path directory, String[] suffixes, String[] names); static void deleteFilesByFilter(Path directory, Predicate<Path> predicate); static long countElementsOfDirectory(Path directory); }### Answer:
@Test void deleteFileIfExistsAndHandleException() throws IOException { Path directory = temporaryFolderExtension.newFolder().toPath(); Files.createFile(directory.resolve("file.txt")); boolean result = FileUtils.deleteFileIfExistsAndHandleException(directory, (e) -> assertEquals(DirectoryNotEmptyException.class, e.getClass())); assertFalse(result); assertTrue(Files.exists(directory)); } |
### Question:
UpdaterUtil { public static Set<Certificate> readCertificates(Set<Path> certificateFilesPaths) throws CertificateException, IOException { return certificates; } private UpdaterUtil(); static void init(boolean useDebugCerts); static Set<CertificatePair> buildCertificatePairs(String certificateDirectory, String firstCertificatePrefix,
String secondCertificatePrefix, String certificateSuffix); static Set<Certificate> readCertificates(Set<Path> certificateFilesPaths); static Certificate readCertificate(String certificateFileName); static Certificate readCertificate(Path certificatePath); static String getStringRepresentation(Certificate cert); static Set<Certificate> readCertificates(String directory, String prefix, String suffix); static Set<Certificate> readCertificates(String directory, String suffix, String... prefixes); static Set<Path> findFiles(Path directory, String prefix, String suffix); static Set<Path> findFiles(String directory, String suffix, String... prefixes); static DoubleByteArrayTuple split(byte[] arr); static Stream<Path> walk(String path); static URL getResource(String resource); static byte[] concatArrays(byte[] arr1, byte[] arr2); }### Answer:
@Test public void testReadCertificates() throws Exception { String[] files = new String[]{"cert1", "cert2", "cert3"}; createCertificateMocksForFiles(certificateFactoryMock, files); Set<Certificate> result = UpdaterUtil.readCertificates(createPathStream(files).collect(Collectors.toSet())); assertNotNull(result); assertEquals(result.size(), files.length); HashSet<String> filenames = new HashSet<>(Arrays.asList(files)); for (Certificate certificate : result) { assertTrue(filenames.contains(certificate.toString().replace(CERTIFICATE_MOCK_PREFIX, ""))); } } |
### Question:
NtpTime { public long getTime() { return System.currentTimeMillis() + timeOffset; } NtpTime(); long getTime(); @PostConstruct void start(); @PreDestroy void shutdown(); }### Answer:
@Test void getTimeTest() { ntpTime = new NtpTime(); ntpTime.start(); long freshTime = ntpTime.getTime(); assertTrue(freshTime > currentTime); log.info("now : long = {} / formatted = {}", freshTime, dateFormat.format(freshTime)); } |
### Question:
AnonymouslyEncryptedData { public static AnonymouslyEncryptedData encrypt(byte[] plaintext, byte[] secretBytes, byte[] theirPublicKey, byte[] nonce) { byte[] keySeed = Crypto.getKeySeed(secretBytes, theirPublicKey, nonce); byte[] myPrivateKey = Crypto.getPrivateKey(keySeed); byte[] myPublicKey = Crypto.getPublicKey(keySeed); byte[] sharedKey = Crypto.getSharedKey(myPrivateKey, theirPublicKey); byte[] data = Crypto.aesGCMEncrypt(plaintext, sharedKey); return new AnonymouslyEncryptedData(data, myPublicKey); } AnonymouslyEncryptedData(byte[] data, byte[] publicKey); static AnonymouslyEncryptedData encrypt(byte[] plaintext, byte[] secretBytes, byte[] theirPublicKey, byte[] nonce); static AnonymouslyEncryptedData readEncryptedData(ByteBuffer buffer, int length, int maxLength); static AnonymouslyEncryptedData readEncryptedData(byte[] bytes); byte[] decrypt(byte[] secretBytes); byte[] decrypt(byte[] keySeed, byte[] theirPublicKey); byte[] getData(); byte[] getPublicKey(); int getSize(); byte[] getBytes(); @Override String toString(); }### Answer:
@Test public void testEncrypt() throws IOException { byte[] plaintext = plain_data; byte[] theirPublicKey = Crypto.getPublicKey(secretPhraseB); AnonymouslyEncryptedData result_enc = AnonymouslyEncryptedData.encrypt(plaintext, secretPhraseA.getBytes(), theirPublicKey, nonce1); byte[] plain_res = result_enc.decrypt(secretPhraseB.getBytes()); assertArrayEquals(plaintext, plain_res); writeToFile(ByteBuffer.wrap(result_enc.getBytes()), TST_OUT_DIR+OUT_FILE_ENCRYPTED); } |
### Question:
EncryptedData { public static EncryptedData encrypt(byte[] plaintext, byte[] keySeed, byte[] theirPublicKey) { if (plaintext.length == 0) { return EMPTY_DATA; } byte[] nonce = new byte[32]; Crypto.getSecureRandom().nextBytes(nonce); byte[] sharedKey = Crypto.getSharedKey(Crypto.getPrivateKey(keySeed), theirPublicKey, nonce); byte[] data = Crypto.aesEncrypt(plaintext, sharedKey); return new EncryptedData(data, nonce); } EncryptedData(byte[] data, byte[] nonce); static EncryptedData encrypt(byte[] plaintext, byte[] keySeed, byte[] theirPublicKey); static EncryptedData readEncryptedData(ByteBuffer buffer, int length, int maxLength); static EncryptedData readEncryptedData(byte[] bytes); static int getEncryptedDataLength(byte[] plaintext); static int getEncryptedSize(byte[] plaintext); byte[] decrypt(byte[] keySeed, byte[] theirPublicKey); byte[] getData(); byte[] getNonce(); int getSize(); byte[] getBytes(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); static final EncryptedData EMPTY_DATA; }### Answer:
@Test public void testEncrypt() throws IOException { byte[] plaintext = plain_data; byte[] keySeed = Crypto.getKeySeed(secretPhraseA); byte[] theirPublicKey = Crypto.getPublicKey(secretPhraseB); EncryptedData result_enc = EncryptedData.encrypt(plaintext, keySeed, theirPublicKey); byte[] plain_res = result_enc.decrypt(keySeed, theirPublicKey); assertArrayEquals(plaintext, plain_res); writeToFile(ByteBuffer.wrap(result_enc.getBytes()), TST_OUT_DIR+OUT_FILE_ENCRYPTED); } |
### Question:
ImageBuilder { public TargetPlatformSpec prepare(TargetPlatformSpec inputSpec) { try { List<Path> platformArtifacts = install(Arrays.asList(inputSpec.getDependencies()),TargetPlatformSpec.platformPath(targetBase)); Path specArtifact = Files.createDirectories(TargetPlatformSpec.configuration(targetBase)).resolve(BLOB_FILENAME); writeBlob(inputSpec,specArtifact); return inputSpec; }catch (Exception e) { throw new RuntimeException("Problem!",e); } } ImageBuilder( Path targetBase); TargetPlatformSpec prepare(TargetPlatformSpec inputSpec); void assembleJar(Path output, URI launcher, TargetPlatformSpec inputSpec); TargetPlatformSpec findSpec(List<URI> c); }### Answer:
@Test void testInstallDependenciesFromSpec() throws IOException { FileSystem fs = Jimfs.newFileSystem(Configuration.unix()); Path inputs = Files.createDirectories(fs.getPath("/").resolve("INPUTS")); Path p1 = Files.write(inputs.resolve("DATA1"),"data1".getBytes(StandardCharsets.UTF_8)); Path p2 = Files.write(inputs.resolve("DATA2"),"data2".getBytes(StandardCharsets.UTF_8)); Path base = fs.getPath("/SOMEWHERE/ELSE"); ImageBuilder imageBuilder = new ImageBuilder(base); TargetPlatformSpec spec = new TargetPlatformSpec(); spec.setDependencies(new Dependency[] { dependency("foo1", p1.toUri()), dependency("foo2", p2.toUri()) }); TargetPlatformSpec result = imageBuilder.prepare(spec); Path root = fs.getPath("/"); assertThat(TargetPlatformSpec.platformPath(base).resolve("foo1.jar")).exists(); assertThat(TargetPlatformSpec.platformPath(base).resolve("foo2.jar")).exists(); assertThat(spec.getDependencies()[0].getLocation()).isEqualTo(URI.create("file: assertThat(spec.getDependencies()[1].getLocation()).isEqualTo(URI.create("file: } |
### Question:
UserPresenter { public void getUserName() { disposable = nameRepository .getName() .timeout(2, TimeUnit.SECONDS) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe( name -> { listener.onUserNameLoaded(name); if (BuildConfig.DEBUG) { logger.info(String.format("Name loaded: %s", name)); } }, error -> listener.onGettingUserNameError(error.getMessage())); } UserPresenter(Listener listener, NameRepository nameRepository, Logger logger); void getUserName(); void stopLoading(); }### Answer:
@Test public void getUserName() { presenter.getUserName(); timeoutRule.getTestScheduler().advanceTimeBy(TIMEOUT_SEC - 1, TimeUnit.SECONDS); nameObservable.onNext(NAME); verify(listener).onUserNameLoaded(NAME); }
@Test public void getUserName_timeout() { presenter.getUserName(); timeoutRule.getTestScheduler().advanceTimeBy(TIMEOUT_SEC + 1, TimeUnit.SECONDS); nameObservable.onNext(NAME); verify(listener).onGettingUserNameError(any()); } |
### Question:
NameRepository { public Single<String> getName() { return Single.create( emitter -> { Gson gson = new Gson(); emitter.onSuccess(gson.fromJson(fileReader.readFile(), User.class).name); }); } NameRepository(FileReader fileReader); Single<String> getName(); }### Answer:
@Test public void getName() { TestObserver<String> observer = nameRepository.getName().test(); observer.assertValue("Sasha"); } |
### Question:
DelegatingContentHandlerImpl implements FileContentReferenceHandler { @Override public boolean isAvailable() { for (ContentReferenceHandler delegate : delegates) { if (!delegate.isAvailable()) { return false; } } return true; } void setDelegates(List<ContentReferenceHandler> delegates); @Override boolean isContentReferenceSupported(ContentReference contentReference); @Override boolean isContentReferenceExists(ContentReference contentReference); @Override ContentReference createContentReference(String fileName, String mediaType); @Override InputStream getInputStream(ContentReference contentReference, boolean waitForAvailability); @Override long putInputStream(InputStream sourceInputStream, ContentReference targetContentReference); @Override long putFile(File sourceFile, ContentReference targetContentReference); @Override void delete(ContentReference contentReference); @Override boolean isAvailable(); @Override File getFile(ContentReference contentReference, boolean waitForTransfer); }### Answer:
@Test public void testIsAvailable() { assertTrue(delegatingHandler.isAvailable()); ((FileContentReferenceHandlerImpl) handlerA).setFileProvider(null); assertFalse(delegatingHandler.isAvailable()); } |
### Question:
DelegatingContentHandlerImpl implements FileContentReferenceHandler { @Override public boolean isContentReferenceSupported(ContentReference contentReference) { for (ContentReferenceHandler delegate : delegates) { if (delegate.isContentReferenceSupported(contentReference)) { return true; } } return false; } void setDelegates(List<ContentReferenceHandler> delegates); @Override boolean isContentReferenceSupported(ContentReference contentReference); @Override boolean isContentReferenceExists(ContentReference contentReference); @Override ContentReference createContentReference(String fileName, String mediaType); @Override InputStream getInputStream(ContentReference contentReference, boolean waitForAvailability); @Override long putInputStream(InputStream sourceInputStream, ContentReference targetContentReference); @Override long putFile(File sourceFile, ContentReference targetContentReference); @Override void delete(ContentReference contentReference); @Override boolean isAvailable(); @Override File getFile(ContentReference contentReference, boolean waitForTransfer); }### Answer:
@Test public void testIsContentReferenceSupported() { assertTrue(delegatingHandler.isContentReferenceSupported(contentReferenceFile1a)); assertTrue(delegatingHandler.isContentReferenceSupported(contentReferenceFile1b)); assertFalse(delegatingHandler.isContentReferenceSupported(contentReferenceFile1c)); } |
### Question:
DelegatingContentHandlerImpl implements FileContentReferenceHandler { @Override public boolean isContentReferenceExists(ContentReference contentReference) { ContentReferenceHandler delegate = getDelegate(contentReference); return delegate.isContentReferenceExists(contentReference); } void setDelegates(List<ContentReferenceHandler> delegates); @Override boolean isContentReferenceSupported(ContentReference contentReference); @Override boolean isContentReferenceExists(ContentReference contentReference); @Override ContentReference createContentReference(String fileName, String mediaType); @Override InputStream getInputStream(ContentReference contentReference, boolean waitForAvailability); @Override long putInputStream(InputStream sourceInputStream, ContentReference targetContentReference); @Override long putFile(File sourceFile, ContentReference targetContentReference); @Override void delete(ContentReference contentReference); @Override boolean isAvailable(); @Override File getFile(ContentReference contentReference, boolean waitForTransfer); }### Answer:
@Test public void testIsContentReferenceExists() { assertTrue(delegatingHandler.isContentReferenceExists(contentReferenceFile1a)); assertTrue(delegatingHandler.isContentReferenceExists(contentReferenceFile1b)); thrown.expect(UnsupportedOperationException.class); delegatingHandler.isContentReferenceExists(contentReferenceFile1c); } |
### Question:
DelegatingContentHandlerImpl implements FileContentReferenceHandler { @Override public ContentReference createContentReference(String fileName, String mediaType) throws ContentIOException { throw new UnsupportedOperationException( "createContentReference not supported for " + this.getClass().getSimpleName()); } void setDelegates(List<ContentReferenceHandler> delegates); @Override boolean isContentReferenceSupported(ContentReference contentReference); @Override boolean isContentReferenceExists(ContentReference contentReference); @Override ContentReference createContentReference(String fileName, String mediaType); @Override InputStream getInputStream(ContentReference contentReference, boolean waitForAvailability); @Override long putInputStream(InputStream sourceInputStream, ContentReference targetContentReference); @Override long putFile(File sourceFile, ContentReference targetContentReference); @Override void delete(ContentReference contentReference); @Override boolean isAvailable(); @Override File getFile(ContentReference contentReference, boolean waitForTransfer); }### Answer:
@Test public void testCreateContentReference() { thrown.expect(UnsupportedOperationException.class); delegatingHandler.createContentReference("testCreate.txt", "text/plain"); } |
### Question:
DelegatingContentHandlerImpl implements FileContentReferenceHandler { @Override public File getFile(ContentReference contentReference, boolean waitForTransfer) throws ContentIOException, InterruptedException { ContentReferenceHandler delegate = getDelegate(contentReference); if (!(FileContentReferenceHandler.class.isAssignableFrom(delegate.getClass()))) { throw new UnsupportedOperationException( delegate.getClass().getSimpleName() + " does not implement " + FileContentReferenceHandler.class.getSimpleName()); } return ((FileContentReferenceHandler) delegate).getFile(contentReference, waitForTransfer); } void setDelegates(List<ContentReferenceHandler> delegates); @Override boolean isContentReferenceSupported(ContentReference contentReference); @Override boolean isContentReferenceExists(ContentReference contentReference); @Override ContentReference createContentReference(String fileName, String mediaType); @Override InputStream getInputStream(ContentReference contentReference, boolean waitForAvailability); @Override long putInputStream(InputStream sourceInputStream, ContentReference targetContentReference); @Override long putFile(File sourceFile, ContentReference targetContentReference); @Override void delete(ContentReference contentReference); @Override boolean isAvailable(); @Override File getFile(ContentReference contentReference, boolean waitForTransfer); }### Answer:
@Test public void testGetFile() throws Exception { File sourceFile = delegatingHandler.getFile(contentReferenceFile1a, false); assertTrue(sourceFile.exists()); }
@Test public void testNonFileDelegate() throws Exception { MockEmptyContentReferenceHandlerImpl handlerC = new MockEmptyContentReferenceHandlerImpl(); ArrayList<ContentReferenceHandler> delegates = new ArrayList<ContentReferenceHandler>(); delegates.add(handlerA); delegates.add(handlerB); delegates.add(handlerC); ContentReference contentReference = new ContentReference("mock: thrown.expect(UnsupportedOperationException.class); delegatingHandler.getFile(contentReference, false); } |
### Question:
DelegatingContentHandlerImpl implements FileContentReferenceHandler { @Override public InputStream getInputStream(ContentReference contentReference, boolean waitForAvailability) throws ContentIOException, InterruptedException { ContentReferenceHandler delegate = getDelegate(contentReference); return delegate.getInputStream(contentReference, waitForAvailability); } void setDelegates(List<ContentReferenceHandler> delegates); @Override boolean isContentReferenceSupported(ContentReference contentReference); @Override boolean isContentReferenceExists(ContentReference contentReference); @Override ContentReference createContentReference(String fileName, String mediaType); @Override InputStream getInputStream(ContentReference contentReference, boolean waitForAvailability); @Override long putInputStream(InputStream sourceInputStream, ContentReference targetContentReference); @Override long putFile(File sourceFile, ContentReference targetContentReference); @Override void delete(ContentReference contentReference); @Override boolean isAvailable(); @Override File getFile(ContentReference contentReference, boolean waitForTransfer); }### Answer:
@Test public void testGetInputStream() throws Exception { InputStream sourceInputStream = delegatingHandler.getInputStream(contentReferenceFile1a, false); assertEquals(15, sourceInputStream.available()); } |
### Question:
DelegatingContentHandlerImpl implements FileContentReferenceHandler { @Override public long putFile(File sourceFile, ContentReference targetContentReference) throws ContentIOException { ContentReferenceHandler delegate = getDelegate(targetContentReference); return delegate.putFile(sourceFile, targetContentReference); } void setDelegates(List<ContentReferenceHandler> delegates); @Override boolean isContentReferenceSupported(ContentReference contentReference); @Override boolean isContentReferenceExists(ContentReference contentReference); @Override ContentReference createContentReference(String fileName, String mediaType); @Override InputStream getInputStream(ContentReference contentReference, boolean waitForAvailability); @Override long putInputStream(InputStream sourceInputStream, ContentReference targetContentReference); @Override long putFile(File sourceFile, ContentReference targetContentReference); @Override void delete(ContentReference contentReference); @Override boolean isAvailable(); @Override File getFile(ContentReference contentReference, boolean waitForTransfer); }### Answer:
@Test public void testPutFile() throws Exception { File sourceFile = new File(this.getClass().getResource( "/content-handler-a/file-a-1.txt").toURI()); String targetFolder = "/content-handler-a"; ContentReference targetContentReference = getTextReference(targetFolder); targetContentReference.setUri(targetContentReference.getUri() + "/file-a-3.txt"); delegatingHandler.putFile(sourceFile, targetContentReference); File targetFile = new File(new URI(targetContentReference.getUri())); assertTrue(targetFile.exists()); } |
### Question:
DelegatingContentHandlerImpl implements FileContentReferenceHandler { @Override public long putInputStream(InputStream sourceInputStream, ContentReference targetContentReference) throws ContentIOException { ContentReferenceHandler delegate = getDelegate(targetContentReference); return delegate.putInputStream(sourceInputStream, targetContentReference); } void setDelegates(List<ContentReferenceHandler> delegates); @Override boolean isContentReferenceSupported(ContentReference contentReference); @Override boolean isContentReferenceExists(ContentReference contentReference); @Override ContentReference createContentReference(String fileName, String mediaType); @Override InputStream getInputStream(ContentReference contentReference, boolean waitForAvailability); @Override long putInputStream(InputStream sourceInputStream, ContentReference targetContentReference); @Override long putFile(File sourceFile, ContentReference targetContentReference); @Override void delete(ContentReference contentReference); @Override boolean isAvailable(); @Override File getFile(ContentReference contentReference, boolean waitForTransfer); }### Answer:
@Test public void testPutInputStream() throws Exception { InputStream sourceInputStream = (this.getClass().getResourceAsStream( "/content-handler-a/file-a-1.txt")); String targetFolder = "/content-handler-a"; ContentReference targetContentReference = getTextReference(targetFolder); targetContentReference.setUri(targetContentReference.getUri() + "/file-a-4.txt"); delegatingHandler.putInputStream(sourceInputStream, targetContentReference); File targetFile = new File(new URI(targetContentReference.getUri())); assertTrue(targetFile.exists()); } |
### Question:
DelegatingContentHandlerImpl implements FileContentReferenceHandler { @Override public void delete(ContentReference contentReference) throws ContentIOException { ContentReferenceHandler delegate = getDelegate(contentReference); delegate.delete(contentReference); } void setDelegates(List<ContentReferenceHandler> delegates); @Override boolean isContentReferenceSupported(ContentReference contentReference); @Override boolean isContentReferenceExists(ContentReference contentReference); @Override ContentReference createContentReference(String fileName, String mediaType); @Override InputStream getInputStream(ContentReference contentReference, boolean waitForAvailability); @Override long putInputStream(InputStream sourceInputStream, ContentReference targetContentReference); @Override long putFile(File sourceFile, ContentReference targetContentReference); @Override void delete(ContentReference contentReference); @Override boolean isAvailable(); @Override File getFile(ContentReference contentReference, boolean waitForTransfer); }### Answer:
@Test public void testDelete() throws Exception { File sourceFile = new File(this.getClass().getResource( "/content-handler-b/file-b-1.txt").toURI()); ContentReference targetContentReferenceToDelete = getTextReference("/content-handler-b"); targetContentReferenceToDelete.setUri(targetContentReferenceToDelete.getUri() + "/file-b-3.txt"); delegatingHandler.putFile(sourceFile, targetContentReferenceToDelete); File fileToDelete = new File(new URI(targetContentReferenceToDelete.getUri())); assertTrue(fileToDelete.exists()); delegatingHandler.delete(targetContentReferenceToDelete); assertFalse(fileToDelete.exists()); } |
### Question:
TimecodeUtils { public static String convertSecondsToTimecode(float totalSeconds) { return convertSecondsToTimecode(totalSeconds, 3); } static String convertSecondsToTimecode(float totalSeconds); static String convertSecondsToTimecode(float totalSeconds, int decimalScale); static float convertTimecodeToSeconds(String timecode); }### Answer:
@Test public void testSecondsToTimecode() { float seconds = 50f; assertEquals("00:00:50.000", TimecodeUtils.convertSecondsToTimecode(seconds)); seconds = 70f; assertEquals("00:01:10.000", TimecodeUtils.convertSecondsToTimecode(seconds)); seconds = 5f; assertEquals("00:00:05.000", TimecodeUtils.convertSecondsToTimecode(seconds)); seconds = 5.011f; assertEquals("00:00:05.011", TimecodeUtils.convertSecondsToTimecode(seconds)); seconds = (60*60*2) + (60*11) + 22.123f; assertEquals("02:11:22.123", TimecodeUtils.convertSecondsToTimecode(seconds)); seconds = 5f; assertEquals("00:00:05.0", TimecodeUtils.convertSecondsToTimecode(seconds, 1)); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.