method2testcases
stringlengths 118
6.63k
|
---|
### Question:
ArgumentPasrser { public void parseArgs(String[] args) throws ArgumentParserException { Namespace parsedArgs = parser.parseArgs(args); if (parsedArgs.get("subcommand") == Subcommand.local) { localCommand(parsedArgs); } if (parsedArgs.get("subcommand") == Subcommand.node) { nodeCommand(parsedArgs); } } ArgumentPasrser(FileVisitor<Path> visitor); void parseArgs(String[] args); }### Answer:
@Test(expected = ArgumentParserException.class) public void testParseArgsInvalidOption() throws Exception { cut.parseArgs(new String[] { LOCAL_SUBCOMMAND, "--foo" }); }
@Test public void testParseArgsUpdateOption() throws Exception { cut.parseArgs(new String[] { LOCAL_SUBCOMMAND, "--update", "foo" }); }
@Test public void testParseArgsNodeOption() throws Exception { cut.parseArgs(new String[] { NODE_SUBCOMMAND, "--port", "123" }); } |
### Question:
ProgressCalc { public double totalProgressPercent() { if (foundFiles.getCount() == 0) { return 0; } else { return (PERCENT_100 / foundFiles.getCount()) * (processedFiles.getCount() + failedFiles.getCount()); } } ProgressCalc(MetricRegistry metrics); double totalProgressPercent(); double corruptPercent(); @Override String toString(); static final String METRIC_NAME_FOUND; static final String METRIC_NAME_PROCESSED; static final String METRIC_NAME_FAILED; static final String METRIC_NAME_FILES_PER_SECOND; }### Answer:
@Test public void testTotalProgressPercent() throws Exception { assertThat(cut.totalProgressPercent(), closeTo(TOTAL_PROGRESS_PERCENT, ALLOWED_COMAPRE_ERROR)); }
@Test public void testTotalProgressPercentWithNoFiles() throws Exception { setCounter(ProgressCalc.METRIC_NAME_FOUND, 0); setCounter(ProgressCalc.METRIC_NAME_PROCESSED, 0); assertThat(cut.totalProgressPercent(), is(0.0)); } |
### Question:
HashAttribute { public String getTimestampFQN() { return timestampFQN; } HashAttribute(String hashName); boolean areAttributesValid(Path path); long readHash(Path path); void writeHash(Path path, long hash); void markCorrupted(Path path); boolean isCorrupted(Path path); String getHashFQN(); String getTimestampFQN(); String getCorruptNameFQN(); }### Answer:
@Test public void testGetTimestampFQN() throws Exception { assertThat(cut.getTimestampFQN(), is(ExtendedAttribute.createName("timestamp", TEST_HASH_NAME))); } |
### Question:
ProgressCalc { public double corruptPercent() { if (foundFiles.getCount() == 0) { return 0; } else { return (PERCENT_100 / foundFiles.getCount()) * failedFiles.getCount(); } } ProgressCalc(MetricRegistry metrics); double totalProgressPercent(); double corruptPercent(); @Override String toString(); static final String METRIC_NAME_FOUND; static final String METRIC_NAME_PROCESSED; static final String METRIC_NAME_FAILED; static final String METRIC_NAME_FILES_PER_SECOND; }### Answer:
@Test public void testCorruptPercent() throws Exception { assertThat(cut.corruptPercent(), closeTo(CORRUPT_PERCENT, ALLOWED_COMAPRE_ERROR)); }
@Test public void testCorruptPercentWithNoFiles() throws Exception { setCounter(ProgressCalc.METRIC_NAME_FOUND, 0); setCounter(ProgressCalc.METRIC_NAME_FAILED, 0); assertThat(cut.corruptPercent(), is(0.0)); } |
### Question:
ProgressCalc { @Override public String toString() { return String.format("Total progress: %.2f%%, corrupt images: %.2f%%, files per second processed: %.2f", totalProgressPercent(), corruptPercent(), filesPerSecond.getMeanRate()); } ProgressCalc(MetricRegistry metrics); double totalProgressPercent(); double corruptPercent(); @Override String toString(); static final String METRIC_NAME_FOUND; static final String METRIC_NAME_PROCESSED; static final String METRIC_NAME_FAILED; static final String METRIC_NAME_FILES_PER_SECOND; }### Answer:
@Test public void testToString() throws Exception { assertThat(cut.toString(), is("Total progress: 23.81%, corrupt images: 9.52%, files per second processed: 0.00")); } |
### Question:
MessageFactory { public ClientMessage hashRequestMessage(byte[] resizedImage, UUID uuid) { ClientMessage message = session.createMessage(true); message.getBodyBuffer().writeLong(uuid.getMostSignificantBits()); message.getBodyBuffer().writeLong(uuid.getLeastSignificantBits()); message.getBodyBuffer().writeBytes(resizedImage); return message; } MessageFactory(ClientSession session); ClientMessage hashRequestMessage(byte[] resizedImage, UUID uuid); ClientMessage resultMessage(long hash, long most, long least); ClientMessage corruptMessage(Path path); ClientMessage pendingImageQuery(); ClientMessage pendingImageResponse(List<PendingHashImage> pendingImages); ClientMessage trackPath(Path path, UUID uuid); ClientMessage eaUpdate(Path path, long hash); ClientMessage resizeRequest(Path path, InputStream is); }### Answer:
@Test public void testHashRequestMessageTrackingId() throws Exception { ClientMessage result = cut.hashRequestMessage(IMAGE_DATA, UUID); UUID id = new UUID(result.getBodyBuffer().readLong(), result.getBodyBuffer().readLong()); assertThat(id, is(UUID)); }
@Test public void testHashRequestMessageImageData() throws Exception { ClientMessage result = cut.hashRequestMessage(IMAGE_DATA, UUID); result.getBodyBuffer().readLong(); result.getBodyBuffer().readLong(); byte[] data = new byte[IMAGE_DATA.length]; result.getBodyBuffer().readBytes(data); assertArrayEquals(data, IMAGE_DATA); }
@Test public void testHashRequestMessageImageSize() throws Exception { ClientMessage result = cut.hashRequestMessage(IMAGE_DATA, UUID); result.getBodyBuffer().readLong(); result.getBodyBuffer().readLong(); byte[] data = new byte[result.getBodySize()]; result.getBodyBuffer().readBytes(data); assertArrayEquals(data, IMAGE_DATA); } |
### Question:
MessageFactory { public ClientMessage resultMessage(long hash, long most, long least) { ClientMessage message = session.createMessage(true); setTaskType(message, TaskType.result); ActiveMQBuffer buffer = message.getBodyBuffer(); buffer.writeLong(most); buffer.writeLong(least); buffer.writeLong(hash); return message; } MessageFactory(ClientSession session); ClientMessage hashRequestMessage(byte[] resizedImage, UUID uuid); ClientMessage resultMessage(long hash, long most, long least); ClientMessage corruptMessage(Path path); ClientMessage pendingImageQuery(); ClientMessage pendingImageResponse(List<PendingHashImage> pendingImages); ClientMessage trackPath(Path path, UUID uuid); ClientMessage eaUpdate(Path path, long hash); ClientMessage resizeRequest(Path path, InputStream is); }### Answer:
@Test public void testResultMessageTask() throws Exception { ClientMessage result = cut.resultMessage(HASH, UUID.getMostSignificantBits(), UUID.getLeastSignificantBits()); assertThat(result.getStringProperty(MessageProperty.task.toString()), is(TaskType.result.toString())); }
@Test public void testResultMessageUuid() throws Exception { ClientMessage result = cut.resultMessage(HASH, UUID.getMostSignificantBits(), UUID.getLeastSignificantBits()); UUID id = new UUID(result.getBodyBuffer().readLong(), result.getBodyBuffer().readLong()); assertThat(id, is(UUID)); }
@Test public void testResultMessageHash() throws Exception { ClientMessage result = cut.resultMessage(HASH, UUID.getMostSignificantBits(), UUID.getLeastSignificantBits()); result.getBodyBuffer().readLong(); result.getBodyBuffer().readLong(); long hash = result.getBodyBuffer().readLong(); assertThat(hash, is(HASH)); } |
### Question:
MessageFactory { public ClientMessage pendingImageQuery() { ClientMessage message = session.createMessage(false); message.putStringProperty(MessageProperty.repository_query.toString(), QueryType.pending.toString()); return message; } MessageFactory(ClientSession session); ClientMessage hashRequestMessage(byte[] resizedImage, UUID uuid); ClientMessage resultMessage(long hash, long most, long least); ClientMessage corruptMessage(Path path); ClientMessage pendingImageQuery(); ClientMessage pendingImageResponse(List<PendingHashImage> pendingImages); ClientMessage trackPath(Path path, UUID uuid); ClientMessage eaUpdate(Path path, long hash); ClientMessage resizeRequest(Path path, InputStream is); }### Answer:
@Test public void testPendingImageQuery() throws Exception { ClientMessage result = cut.pendingImageQuery(); assertThat(result.getStringProperty(MessageFactory.MessageProperty.repository_query.toString()), is(MessageFactory.QueryType.pending.toString())); } |
### Question:
HashAttribute { public void markCorrupted(Path path) throws IOException { ExtendedAttribute.setExtendedAttribute(path, corruptNameFQN, ""); } HashAttribute(String hashName); boolean areAttributesValid(Path path); long readHash(Path path); void writeHash(Path path, long hash); void markCorrupted(Path path); boolean isCorrupted(Path path); String getHashFQN(); String getTimestampFQN(); String getCorruptNameFQN(); }### Answer:
@Test public void testMarkCorrupted() throws Exception { cut.markCorrupted(tempFile); assertThat(ExtendedAttribute.isExtendedAttributeSet(tempFile, cut.getCorruptNameFQN()), is(true)); } |
### Question:
MessageFactory { public ClientMessage pendingImageResponse(List<PendingHashImage> pendingImages) throws IOException { List<String> pendingPaths = new LinkedList<String>(); for (PendingHashImage p : pendingImages) { pendingPaths.add(p.getPath()); } try (ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos)) { ClientMessage message = session.createMessage(false); oos.writeObject(pendingPaths); message.writeBodyBufferBytes(baos.toByteArray()); return message; } } MessageFactory(ClientSession session); ClientMessage hashRequestMessage(byte[] resizedImage, UUID uuid); ClientMessage resultMessage(long hash, long most, long least); ClientMessage corruptMessage(Path path); ClientMessage pendingImageQuery(); ClientMessage pendingImageResponse(List<PendingHashImage> pendingImages); ClientMessage trackPath(Path path, UUID uuid); ClientMessage eaUpdate(Path path, long hash); ClientMessage resizeRequest(Path path, InputStream is); }### Answer:
@Test public void testPendingImageResponse() throws Exception { ClientMessage result = cut.pendingImageResponse(Arrays.asList(new PendingHashImage(PATH, UUID))); assertThat(result.getBodySize(), is(EXPECTED_MESSAGE_SIZE)); } |
### Question:
MessageFactory { public ClientMessage corruptMessage(Path path) { ClientMessage message = session.createMessage(true); message.putStringProperty(MessageProperty.path.toString(), path.toString()); message.putStringProperty(MessageProperty.task.toString(), TaskType.corr.toString()); return message; } MessageFactory(ClientSession session); ClientMessage hashRequestMessage(byte[] resizedImage, UUID uuid); ClientMessage resultMessage(long hash, long most, long least); ClientMessage corruptMessage(Path path); ClientMessage pendingImageQuery(); ClientMessage pendingImageResponse(List<PendingHashImage> pendingImages); ClientMessage trackPath(Path path, UUID uuid); ClientMessage eaUpdate(Path path, long hash); ClientMessage resizeRequest(Path path, InputStream is); }### Answer:
@Test public void testCorruptMessagePath() throws Exception { ClientMessage result = cut.corruptMessage(PATH); assertThat(result.getStringProperty(MessageProperty.path.toString()), is(PATH.toString())); }
@Test public void testCorruptMessageTask() throws Exception { ClientMessage result = cut.corruptMessage(PATH); assertThat(result.getStringProperty(MessageProperty.task.toString()), is(TaskType.corr.toString())); } |
### Question:
MessageFactory { public ClientMessage eaUpdate(Path path, long hash) { ClientMessage message = session.createMessage(true); setTaskType(message, TaskType.eaupdate); setPath(message, path); message.getBodyBuffer().writeLong(hash); return message; } MessageFactory(ClientSession session); ClientMessage hashRequestMessage(byte[] resizedImage, UUID uuid); ClientMessage resultMessage(long hash, long most, long least); ClientMessage corruptMessage(Path path); ClientMessage pendingImageQuery(); ClientMessage pendingImageResponse(List<PendingHashImage> pendingImages); ClientMessage trackPath(Path path, UUID uuid); ClientMessage eaUpdate(Path path, long hash); ClientMessage resizeRequest(Path path, InputStream is); }### Answer:
@Test public void testEaUpdatePath() throws Exception { ClientMessage result = cut.eaUpdate(PATH, HASH); assertThat(result.getStringProperty(MessageProperty.path.toString()), is(PATH.toString())); }
@Test public void testEaUpdateHash() throws Exception { ClientMessage result = cut.eaUpdate(PATH, HASH); assertThat(result.getBodyBuffer().readLong(), is(HASH)); }
@Test public void testEaUpdateTask() throws Exception { ClientMessage result = cut.eaUpdate(PATH, HASH); assertThat(result.getStringProperty(MessageProperty.task.toString()), is(TaskType.eaupdate.toString())); } |
### Question:
MessageFactory { public ClientMessage resizeRequest(Path path, InputStream is) throws IOException { ClientMessage message = session.createMessage(true); copyInputStreamToMessage(is, message); setTaskType(message, TaskType.hash); setPath(message, path); return message; } MessageFactory(ClientSession session); ClientMessage hashRequestMessage(byte[] resizedImage, UUID uuid); ClientMessage resultMessage(long hash, long most, long least); ClientMessage corruptMessage(Path path); ClientMessage pendingImageQuery(); ClientMessage pendingImageResponse(List<PendingHashImage> pendingImages); ClientMessage trackPath(Path path, UUID uuid); ClientMessage eaUpdate(Path path, long hash); ClientMessage resizeRequest(Path path, InputStream is); }### Answer:
@Test public void testResizeRequestPath() throws Exception { ClientMessage result = cut.resizeRequest(PATH, is); assertThat(result.getStringProperty(MessageProperty.path.toString()), is(PATH.toString())); }
@Test public void testResizeRequestTask() throws Exception { ClientMessage result = cut.resizeRequest(PATH, is); assertThat(result.getStringProperty(MessageProperty.task.toString()), is(TaskType.hash.toString())); } |
### Question:
MessageFactory { public ClientMessage trackPath(Path path, UUID uuid) { ClientMessage message = session.createMessage(false); setTaskType(message, TaskType.track); setPath(message, path); message.getBodyBuffer().writeLong(uuid.getMostSignificantBits()); message.getBodyBuffer().writeLong(uuid.getLeastSignificantBits()); return message; } MessageFactory(ClientSession session); ClientMessage hashRequestMessage(byte[] resizedImage, UUID uuid); ClientMessage resultMessage(long hash, long most, long least); ClientMessage corruptMessage(Path path); ClientMessage pendingImageQuery(); ClientMessage pendingImageResponse(List<PendingHashImage> pendingImages); ClientMessage trackPath(Path path, UUID uuid); ClientMessage eaUpdate(Path path, long hash); ClientMessage resizeRequest(Path path, InputStream is); }### Answer:
@Test public void testTrackPathPathProperty() throws Exception { ClientMessage result = cut.trackPath(PATH, UUID); assertThat(result.getStringProperty(MessageProperty.path.toString()), is(PATH.toString())); }
@Test public void testTrackPathTaskProperty() throws Exception { ClientMessage result = cut.trackPath(PATH, UUID); assertThat(result.getStringProperty(MessageProperty.task.toString()), is(TaskType.track.toString())); }
@Test public void testTrackPathMessageBody() throws Exception { ClientMessage result = cut.trackPath(PATH, UUID); long most = result.getBodyBuffer().readLong(); long least = result.getBodyBuffer().readLong(); assertThat(new UUID(most, least), is(UUID)); } |
### Question:
HashAttribute { public String getCorruptNameFQN() { return corruptNameFQN; } HashAttribute(String hashName); boolean areAttributesValid(Path path); long readHash(Path path); void writeHash(Path path, long hash); void markCorrupted(Path path); boolean isCorrupted(Path path); String getHashFQN(); String getTimestampFQN(); String getCorruptNameFQN(); }### Answer:
@Test public void testGetCorruptNameFQN() throws Exception { assertThat(cut.getCorruptNameFQN(), is(ExtendedAttribute.createName("corrupt"))); } |
### Question:
QueueToDatabaseTransaction implements CollectedMessageConsumer { @Override public void onDrain(List<ClientMessage> messages) { try { transactionManager.callInTransaction(new Callable<Void>() { @Override public Void call() throws Exception { onCall(messages); return null; } }); } catch (SQLException e) { LOGGER.warn("Failed to store {} messages: {}", messages.size(), e.toString(), e.getCause()); try { session.rollback(); } catch (ActiveMQException mqException) { String message = "Failed to rollback message transaction"; LOGGER.error(message, mqException); throw new RuntimeException(message, mqException); } } } QueueToDatabaseTransaction(ClientSession transactedSession, TransactionManager transactionManager,
String eaQueueName, PendingHashImageRepository pendingRepository,
ImageRepository imageRepository, MetricRegistry metrics); @Inject QueueToDatabaseTransaction(@Named("transacted") ClientSession transactedSession,
TransactionManager transactionManager, PendingHashImageRepository pendingRepository,
ImageRepository imageRepository, MetricRegistry metrics); @Override void onDrain(List<ClientMessage> messages); static final String METRIC_NAME_PENDING_MESSAGES_MISSING; static final String METRIC_NAME_PENDING_MESSAGES; static final String METRIC_NAME_PROCESSED_IMAGES; }### Answer:
@Test public void testOnDrainInTransaction() throws Exception { cut.onDrain(messages); verify(transactionManager).callInTransaction(any()); }
@Test public void testMessageRollbackOnDatabaseFailure() throws Exception { when(transactionManager.callInTransaction(any())) .thenThrow(new SQLException(EXCEPTION_MESSAGE)); cut.onDrain(messages); verify(session).rollback(); }
@Test(expected = RuntimeException.class) public void testMessageRollbackFailure() throws Exception { when(transactionManager.callInTransaction(any())).thenThrow(new SQLException(EXCEPTION_MESSAGE)); Mockito.doThrow(new ActiveMQException()).when(session).rollback(); cut.onDrain(messages); } |
### Question:
QueueToDatabaseTransaction implements CollectedMessageConsumer { protected void onCall(List<ClientMessage> messages) throws RepositoryException, ActiveMQException { for (ClientMessage message : messages) { processMessage(message); message.acknowledge(); } session.commit(); } QueueToDatabaseTransaction(ClientSession transactedSession, TransactionManager transactionManager,
String eaQueueName, PendingHashImageRepository pendingRepository,
ImageRepository imageRepository, MetricRegistry metrics); @Inject QueueToDatabaseTransaction(@Named("transacted") ClientSession transactedSession,
TransactionManager transactionManager, PendingHashImageRepository pendingRepository,
ImageRepository imageRepository, MetricRegistry metrics); @Override void onDrain(List<ClientMessage> messages); static final String METRIC_NAME_PENDING_MESSAGES_MISSING; static final String METRIC_NAME_PENDING_MESSAGES; static final String METRIC_NAME_PROCESSED_IMAGES; }### Answer:
@Test public void testOnCallMessageAcknowledge() throws Exception { cut.onCall(messages); verify(message, times(TEST_MESSAGE_SIZE)).acknowledge(); }
@Test public void testOnCallPendingQuery() throws Exception { cut.onCall(messages); verify(pendingRepository).getByUUID(UUID_MOST, UUID_LEAST); }
@Test public void testOnCallPendingMessageMissing() throws Exception { when(pendingRepository.getByUUID(UUID_MOST, UUID_LEAST)).thenReturn(null); cut.onCall(messages); assertThat( metrics.getCounters().get(QueueToDatabaseTransaction.METRIC_NAME_PENDING_MESSAGES_MISSING).getCount(), is((long) TEST_MESSAGE_SIZE)); }
@Test public void testOnCallPendingMessagesDecrement() throws Exception { cut.onCall(messages); assertThat(metrics.getCounters().get(QueueToDatabaseTransaction.METRIC_NAME_PENDING_MESSAGES).getCount(), is(-1L)); }
@Test public void testOnCallProcessedMessagesIncrement() throws Exception { cut.onCall(messages); assertThat(metrics.getMeters().get(QueueToDatabaseTransaction.METRIC_NAME_PROCESSED_IMAGES).getCount(), is(1L)); }
@Test public void testOnCallResultStored() throws Exception { cut.onCall(messages); verify(imageRepository).store(eq(new ImageRecord(PATH, HASH))); }
@Test public void testOnCallPendingRemoved() throws Exception { cut.onCall(messages); verify(pendingRepository).remove(new PendingHashImage(PATH, UUID_MOST, UUID_LEAST)); }
@Test public void testOnCallEAupdateSent() throws Exception { cut.onCall(messages); verify(producer).send(sendMessage); } |
### Question:
HashAttribute { public boolean isCorrupted(Path path) throws IOException { return ExtendedAttribute.isExtendedAttributeSet(path, corruptNameFQN); } HashAttribute(String hashName); boolean areAttributesValid(Path path); long readHash(Path path); void writeHash(Path path, long hash); void markCorrupted(Path path); boolean isCorrupted(Path path); String getHashFQN(); String getTimestampFQN(); String getCorruptNameFQN(); }### Answer:
@Test public void testIsCorruptedNotSet() throws Exception { assertThat(cut.isCorrupted(tempFile), is(false)); } |
### Question:
ResizerNode implements MessageHandler, Node { @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(ResizerNode.class.getSimpleName()).append(" {").append(identity.toString()).append("}"); return sb.toString(); } @Inject ResizerNode(ClientSession session, ImageResizer resizer, MetricRegistry metrics); protected ResizerNode(ClientSession session, ImageResizer resizer, String requestAddress, String resultAddress,
QueryMessage queryMessage, MetricRegistry metrics); @Override void onMessage(ClientMessage message); @Override void stop(); @Override String toString(); static final String METRIC_NAME_RESIZE_MESSAGES; static final String METRIC_NAME_RESIZE_DURATION; static final String METRIC_NAME_PENDING_CACHE_HIT; static final String METRIC_NAME_PENDING_CACHE_MISS; static final String METRIC_NAME_IMAGE_SIZE; static final String METRIC_NAME_BUFFER_RESIZE; }### Answer:
@Test public void testValidImageNotCorrupt() throws Exception { producer.send(message); await().atMost(MESSAGE_TIMEOUT).until(hashRequests::size, is(1)); ClientMessage response = hashRequests.get(0); assertThat(response.containsProperty(MessageProperty.task.toString()), is(false)); }
@Test public void testValidImageTrackSent() throws Exception { producer.send(message); await().atMost(MESSAGE_TIMEOUT).until(results::size, is(1)); ClientMessage response = results.get(0); assertThat(response.getStringProperty(MessageProperty.task.toString()), is(TaskType.track.toString())); }
@Test public void testCorruptImageDataTaskProperty() throws Exception { when(resizer.resize(nullable(BufferedImage.class))).thenThrow(new IIOException("")); producer.send(message); await().atMost(MESSAGE_TIMEOUT).until(eaUpdates::size, is(1)); ClientMessage response = eaUpdates.get(0); assertThat(response.getStringProperty(MessageProperty.task.toString()), is(TaskType.corr.toString())); }
@Test public void testCorruptImageDataPathProperty() throws Exception { when(resizer.resize(nullable(BufferedImage.class))).thenThrow(new IIOException("")); producer.send(message); await().atMost(MESSAGE_TIMEOUT).until(eaUpdates::size, is(1)); ClientMessage response = eaUpdates.get(0); assertThat(response.getStringProperty(MessageProperty.path.toString()), is(PATH_NEW)); }
@Test public void testGIFerrorUnknownBlock() throws Exception { when(resizer.resize(nullable(BufferedImage.class))).thenThrow(new IOException("Unknown block")); producer.send(message); await().atMost(MESSAGE_TIMEOUT).until(eaUpdates::size, is(1)); ClientMessage response = eaUpdates.get(0); assertThat(response.getStringProperty(MessageProperty.task.toString()), is(TaskType.corr.toString())); }
@Test public void testGIFerrorInvalidHeader() throws Exception { when(resizer.resize(nullable(BufferedImage.class))).thenThrow(new IOException("Invalid GIF header")); producer.send(message); await().atMost(MESSAGE_TIMEOUT).until(eaUpdates::size, is(1)); ClientMessage response = eaUpdates.get(0); assertThat(response.getStringProperty(MessageProperty.task.toString()), is(TaskType.corr.toString())); }
@Test public void testToStringStart() throws Exception { assertThat(cut.toString(), startsWith("ResizerNode {")); }
@Test public void testToStringEnd() throws Exception { assertThat(cut.toString(), endsWith("}")); } |
### Question:
ResizerNode implements MessageHandler, Node { protected void allocateNewBuffer(int messageSize) { messageBuffer = ByteBuffer.allocateDirect(calcNewBufferSize(messageSize)); } @Inject ResizerNode(ClientSession session, ImageResizer resizer, MetricRegistry metrics); protected ResizerNode(ClientSession session, ImageResizer resizer, String requestAddress, String resultAddress,
QueryMessage queryMessage, MetricRegistry metrics); @Override void onMessage(ClientMessage message); @Override void stop(); @Override String toString(); static final String METRIC_NAME_RESIZE_MESSAGES; static final String METRIC_NAME_RESIZE_DURATION; static final String METRIC_NAME_PENDING_CACHE_HIT; static final String METRIC_NAME_PENDING_CACHE_MISS; static final String METRIC_NAME_IMAGE_SIZE; static final String METRIC_NAME_BUFFER_RESIZE; }### Answer:
@Test public void testBufferResize() throws Exception { for (byte i = 0; i < BUFFER_TEST_DATA_SIZE; i++) { message.getBodyBuffer().writeByte(i); } cut.allocateNewBuffer(1); producer.send(message); await().atMost(MESSAGE_TIMEOUT).until(() -> metrics.getCounters().get(ResizerNode.METRIC_NAME_BUFFER_RESIZE).getCount(), is(1L)); } |
### Question:
ResizerNode implements MessageHandler, Node { @Override public void onMessage(ClientMessage message) { String pathPropterty = null; resizeRequests.mark(); Context resizeTimeContext = resizeDuration.time(); try { pathPropterty = message.getStringProperty(MessageProperty.path.toString()); LOGGER.debug("Resize request for image {}", pathPropterty); if (pendingCache.getIfPresent(pathPropterty) != null) { LOGGER.trace("{} found in cache, skipping...", pathPropterty); pendingCacheHit.mark(); return; } else { pendingCacheMiss.mark(); } checkBufferCapacity(message.getBodySize()); messageBuffer.limit(message.getBodySize()); imageSize.update(message.getBodySize()); messageBuffer.rewind(); message.getBodyBuffer().readBytes(messageBuffer); messageBuffer.rewind(); Path path = Paths.get(pathPropterty); Path filename = path.getFileName(); InputStream is = new ByteBufferInputstream(messageBuffer); if (filename != null && filename.toString().toLowerCase().endsWith(".gif")) { GifImage gi = GifDecoder.read(is); is = new ByteArrayInputStream(ImageUtil.imageToBytes(gi.getFrame(0))); } BufferedImage originalImage = ImageIO.read(is); byte[] resizedImageData = resizer.resize(originalImage); UUID uuid = UUID.randomUUID(); ClientMessage trackMessage = messageFactory.trackPath(path, uuid); producer.send(QueueAddress.RESULT.toString(), trackMessage); LOGGER.trace("Sent tracking message for {} with UUID {}", pathPropterty, uuid); ClientMessage response = messageFactory.hashRequestMessage(resizedImageData, uuid); LOGGER.trace("Sending hash request with id {} instead of path {}", uuid, path); producer.send(response); pendingCache.put(pathPropterty, DUMMY); resizeTimeContext.stop(); } catch (ActiveMQException e) { LOGGER.error("Failed to send message: {}", e.toString()); } catch (IIOException | ArrayIndexOutOfBoundsException ie) { markImageCorrupt(pathPropterty); } catch (IOException e) { if (isImageError(e.getMessage())) { markImageCorrupt(pathPropterty); } else { LOGGER.error("Failed to process image: {}", e.toString()); } } catch (Exception e) { LOGGER.error("Unhandled exception: {}", e.toString()); LOGGER.debug("", e); } } @Inject ResizerNode(ClientSession session, ImageResizer resizer, MetricRegistry metrics); protected ResizerNode(ClientSession session, ImageResizer resizer, String requestAddress, String resultAddress,
QueryMessage queryMessage, MetricRegistry metrics); @Override void onMessage(ClientMessage message); @Override void stop(); @Override String toString(); static final String METRIC_NAME_RESIZE_MESSAGES; static final String METRIC_NAME_RESIZE_DURATION; static final String METRIC_NAME_PENDING_CACHE_HIT; static final String METRIC_NAME_PENDING_CACHE_MISS; static final String METRIC_NAME_IMAGE_SIZE; static final String METRIC_NAME_BUFFER_RESIZE; }### Answer:
@Test public void testImageSizeHistogramCount() throws Exception { message = new MessageFactory(session).resizeRequest(Paths.get(PATH_NEW), is); for (byte i = 0; i < BUFFER_TEST_DATA_SIZE; i++) { message.getBodyBuffer().writeByte(i); } cut.onMessage(message); assertThat(metrics.getHistograms().get(ResizerNode.METRIC_NAME_IMAGE_SIZE).getCount(), is(1L)); }
@Test public void testImageSizeHistogramSize() throws Exception { message = new MessageFactory(session).resizeRequest(Paths.get(PATH_NEW), is); for (byte i = 0; i < BUFFER_TEST_DATA_SIZE; i++) { message.getBodyBuffer().writeByte(i); } cut.onMessage(message); assertThat(metrics.getHistograms().get(ResizerNode.METRIC_NAME_IMAGE_SIZE).getSnapshot().getMean(), is((double) BUFFER_TEST_DATA_SIZE)); } |
### Question:
ByteBufferInputstream extends InputStream { @Override public int read() throws IOException { if (buffer.hasRemaining()) { return buffer.get() & 0xFF; } else { return -1; } } ByteBufferInputstream(ByteBuffer buffer); @Override int read(); @Override int available(); }### Answer:
@Test public void testReadFirstByte() throws Exception { assertThat(input.read(), is(2)); }
@Test public void testReadAllData() throws Exception { byte[] read = new byte[TEST_DATA.length]; input.read(read); assertThat(read, is(TEST_DATA)); }
@Test public void testReadAllDataByteRead() throws Exception { byte[] read = new byte[BUFFER_CAPACITY *2]; int actualRead = input.read(read); assertThat(actualRead, is(TEST_DATA.length)); }
@Test public void testReadAllDataBuffered() throws Exception { byte[] read = new byte[TEST_DATA.length]; BufferedInputStream bis = new BufferedInputStream(input); bis.read(read); assertThat(read, is(TEST_DATA)); } |
### Question:
MessageCollector { private void onDrain() { ImmutableList<ClientMessage> immutable; LOGGER.trace("Draining {} collected messsages...", collectedMessages.size()); synchronized (collectedMessages) { immutable = ImmutableList.copyOf(collectedMessages); collectedMessages.clear(); } for (CollectedMessageConsumer drain : consumers) { drain.onDrain(immutable); } } MessageCollector(int collectedMessageThreshold, CollectedMessageConsumer... consumers); void addMessage(ClientMessage message); void drain(); }### Answer:
@Test public void testAddMessageAboveThreshold() throws Exception { addNumberOfMessages(MESSAGE_THRESHOLD); verify(collector).onDrain(anyListOf(ClientMessage.class)); }
@Test public void testAddMessageReTrigger() throws Exception { addNumberOfMessages(2 * MESSAGE_THRESHOLD); verify(collector, times(2)).onDrain(anyListOf(ClientMessage.class)); } |
### Question:
TaskMessageHandler implements MessageHandler { @Override public void onMessage(ClientMessage msg) { try { if (isTaskType(msg, TaskType.track)) { String path = msg.getStringProperty(MessageProperty.path.toString()); long most = msg.getBodyBuffer().readLong(); long least = msg.getBodyBuffer().readLong(); if (LOGGER.isTraceEnabled()) { LOGGER.trace("Tracking new path {} with UUID {}", path, new UUID(most, least)); } pendingMessages.inc(); pendingRepository.store(new PendingHashImage(path, most, least)); } else { LOGGER.error("Unhandled message: {}", msg); } } catch (RepositoryException e) { String cause = "unknown"; if(e.getCause() != null) { cause = e.getCause().toString(); } LOGGER.warn("Failed to store result message: {}, cause:{}", e.toString(), cause); } } @Inject TaskMessageHandler(PendingHashImageRepository pendingRepository, ImageRepository imageRepository,
MetricRegistry metrics); @Deprecated TaskMessageHandler(PendingHashImageRepository pendingRepository, ImageRepository imageRepository,
ClientSession session, MetricRegistry metrics); @Deprecated TaskMessageHandler(PendingHashImageRepository pendingRepository, ImageRepository imageRepository,
ClientSession session, String eaUpdateAddress, MetricRegistry metrics); TaskMessageHandler(PendingHashImageRepository pendingRepository, ImageRepository imageRepository,
String eaUpdateAddress, MetricRegistry metrics); @Override void onMessage(ClientMessage msg); static final String METRIC_NAME_PENDING_MESSAGES; }### Answer:
@Test public void testMetricPendingMessagesTrack() throws Exception { ClientMessage message = messageFactory.trackPath(Paths.get(TEST_PATH), UUID); cut.onMessage(message); assertThat(metrics.getCounters().get(TaskMessageHandler.METRIC_NAME_PENDING_MESSAGES).getCount(), is(1L)); } |
### Question:
ResultMessageSink implements Node { @Override public void stop() { LOGGER.info("Stopping {}", WORKER_THREAD_NAME); sink.interrupt(); try { sink.join(); } catch (InterruptedException ie) { LOGGER.warn("Interrupted while wating for sink to terminate: {}", ie.toString()); } try { consumer.close(); } catch (ActiveMQException e) { LOGGER.warn("Failed to close consumer: {}", e.toString()); } } ResultMessageSink(ClientSession transactedSession, MessageCollector collector, String resultQueueName,
long messageIdleTimeout); ResultMessageSink(ClientSession transactedSession, MessageCollector collector); @Override void stop(); }### Answer:
@Test public void testStop() throws Exception { cut.stop(); verify(collector, timeout(VERIFY_TIMEOUT)).drain(); verify(consumer).close(); }
@Test(timeout = TEST_TIMEOUT) public void testDrainOnNoMessage() throws Exception { cut.stop(); Mockito.reset(collector); when(consumer.receive(anyLong())).thenReturn(null); cut = new ResultMessageSink(session, collector); verify(collector, timeout(VERIFY_TIMEOUT).atLeastOnce()).drain(); verify(collector, never()).addMessage(message); }
@Test public void testMessageReadFailure() throws Exception { cut.stop(); Mockito.reset(collector); when(consumer.receive(anyLong())).thenThrow(new ActiveMQException("test")); cut = new ResultMessageSink(session, collector); verify(collector, atMost(1)).drain(); verify(collector, never()).addMessage(any(ClientMessage.class)); } |
### Question:
HasherNode implements MessageHandler, Node { @Override public void onMessage(ClientMessage message) { hashRequests.mark(); Context hashTimeContext = hashDuration.time(); try { long most = message.getBodyBuffer().readLong(); long least = message.getBodyBuffer().readLong(); if (LOGGER.isTraceEnabled()) { LOGGER.trace("Got hash request with UUID {}, size {}", new UUID(most, least), message.getBodySize()); } checkBufferCapacity(message.getBodySize()); buffer.limit(message.getBodySize()); LOGGER.trace("Reading resized image with size {}", message.getBodySize()); buffer.rewind(); message.getBodyBuffer().readBytes(buffer); buffer.rewind(); long hash = doHash(ImageIO.read(new ByteBufferInputstream(buffer))); ClientMessage response = messageFactory.resultMessage(hash, most, least); producer.send(response); if (LOGGER.isTraceEnabled()) { LOGGER.trace("Sent result for request with UUID {} to {}", new UUID(most, least), producer.getAddress()); } hashTimeContext.stop(); } catch (ActiveMQException e) { LOGGER.error("Failed to process message: {}", e.toString()); } catch (Exception e) { LOGGER.error("Failed to process image: {}", e.toString()); } } HasherNode(ClientSession session, ImagePHash hasher, String requestAddress, String resultAddress,
MetricRegistry metrics); @Override void stop(); @Override String toString(); @Override void onMessage(ClientMessage message); static final String METRIC_NAME_HASH_MESSAGES; static final String METRIC_NAME_HASH_DURATION; static final String METRIC_NAME_BUFFER_RESIZE; }### Answer:
@Test public void testBufferResize() throws Exception { hashRequestMessage = messageFactory.hashRequestMessage(new byte[LARGE_DATA_SIZE], TEST_UUID); cut.onMessage(hashRequestMessage); assertThat(metrics.getMeters().get(HasherNode.METRIC_NAME_BUFFER_RESIZE).getCount(), is(1L)); }
@Test public void testHashDuration() throws Exception { cut.onMessage(hashRequestMessage); assertThat(metrics.getTimers().get(HasherNode.METRIC_NAME_HASH_DURATION).getSnapshot().getMean(), is(not(0.0))); }
@Test public void testHashDurationOnFailure() throws Exception { Mockito.reset(hasher); when(hasher.getLongHash(nullable(BufferedImage.class))).thenThrow(new IOException("Testing")); cut.onMessage(hashRequestMessage); assertThat(metrics.getTimers().get(HasherNode.METRIC_NAME_HASH_DURATION).getSnapshot().getMean(), is(0.0)); } |
### Question:
HasherNode implements MessageHandler, Node { @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(HasherNode.class.getSimpleName()).append(" {").append(identity.toString()).append("}"); return sb.toString(); } HasherNode(ClientSession session, ImagePHash hasher, String requestAddress, String resultAddress,
MetricRegistry metrics); @Override void stop(); @Override String toString(); @Override void onMessage(ClientMessage message); static final String METRIC_NAME_HASH_MESSAGES; static final String METRIC_NAME_HASH_DURATION; static final String METRIC_NAME_BUFFER_RESIZE; }### Answer:
@Test public void testToStringStart() throws Exception { assertThat(cut.toString(), startsWith("HasherNode {")); }
@Test public void testToStringEnd() throws Exception { assertThat(cut.toString(), endsWith("}")); } |
### Question:
HasherNode implements MessageHandler, Node { @Override public void stop() { LOGGER.info("Stopping {}...", this.toString()); MessagingUtil.silentClose(consumer); MessagingUtil.silentClose(producer); MessagingUtil.silentClose(session); } HasherNode(ClientSession session, ImagePHash hasher, String requestAddress, String resultAddress,
MetricRegistry metrics); @Override void stop(); @Override String toString(); @Override void onMessage(ClientMessage message); static final String METRIC_NAME_HASH_MESSAGES; static final String METRIC_NAME_HASH_DURATION; static final String METRIC_NAME_BUFFER_RESIZE; }### Answer:
@Test public void testStop() throws Exception { cut.stop(); assertThat(session.isClosed(), is(true)); } |
### Question:
RepositoryNode implements MessageHandler, Node { @Override public String toString() { return RepositoryNode.class.getSimpleName(); } RepositoryNode(ClientSession session, String queryAddress, String taskAddress,
PendingHashImageRepository pendingRepository, ImageRepository imageRepository,
TaskMessageHandler taskMessageHandler, MetricRegistry metrics); @Inject RepositoryNode(@Named("normal") ClientSession session, PendingHashImageRepository pendingRepository,
TaskMessageHandler taskMessageHandler, MetricRegistry metrics); @Override void onMessage(ClientMessage message); @Override void stop(); @Override String toString(); }### Answer:
@Test public void testQueryPending() throws Exception { List<String> pending = queryMessage.pendingImagePaths(); assertThat(pending, hasItem(PATH.toString())); }
@Test public void testToString() throws Exception { assertThat(cut.toString(), is("RepositoryNode")); } |
### Question:
StorageNode implements MessageHandler, Node { public boolean processFile(Path path) { LOGGER.trace("Processing {}", path); if (isAlreadySent(path)) { LOGGER.trace("File {} has already been sent, ignoring...", path); return true; } try (InputStream bis = new BufferedInputStream(Files.newInputStream(path))) { ClientMessage request = messageFactory.resizeRequest(path, bis); producer.send(request); sentRequests.put(path, 0); LOGGER.trace("Sent resize request for {}", path); return true; } catch (IOException e) { LOGGER.warn("Failed to access file {}: {}", path, e.toString()); } catch (ActiveMQException e) { LOGGER.warn("Failed to send resize request for {}: {}", path, e.toString()); } return false; } StorageNode(ClientSession session, ExtendedAttributeQuery eaQuery, HashAttribute hashAttribute, List<Path> pendingPaths,
String resizeAddress, String eaUpdateAddress); @Inject StorageNode(@Named("normal") ClientSession session, ExtendedAttributeQuery eaQuery,
HashAttribute hashAttribute, @Named("pending") List<Path> pendingPaths); @Override void onMessage(ClientMessage message); boolean processFile(Path path); @Override void stop(); @Override String toString(); }### Answer:
@Test public void testProcessFile() throws Exception { cut.processFile(testFile); await().until(messages::size, is(1)); ClientMessage message = messages.get(0); assertThat(message.getStringProperty(MessageProperty.path.toString()), is(testFile.toString())); }
@Test public void testProcessFileSkipDuplicateCached() throws Exception { cut.processFile(cachedFile); await().pollDelay(1, TimeUnit.SECONDS).until(messages::size, is(0)); } |
### Question:
StorageNode implements MessageHandler, Node { @Override public String toString() { return StorageNode.class.getSimpleName(); } StorageNode(ClientSession session, ExtendedAttributeQuery eaQuery, HashAttribute hashAttribute, List<Path> pendingPaths,
String resizeAddress, String eaUpdateAddress); @Inject StorageNode(@Named("normal") ClientSession session, ExtendedAttributeQuery eaQuery,
HashAttribute hashAttribute, @Named("pending") List<Path> pendingPaths); @Override void onMessage(ClientMessage message); boolean processFile(Path path); @Override void stop(); @Override String toString(); }### Answer:
@Test public void testToString() throws Exception { assertThat(cut.toString(), is("StorageNode")); } |
### Question:
ByteBufferInputstream extends InputStream { @Override public int available() throws IOException { return buffer.remaining(); } ByteBufferInputstream(ByteBuffer buffer); @Override int read(); @Override int available(); }### Answer:
@Test public void testAvailable() throws Exception { assertThat(input.available(), is(TEST_DATA.length)); } |
### Question:
ImageFileFilter implements Filter<Path> { @Override public boolean accept(Path entry) throws IOException { return extFilter.accept(entry); } ImageFileFilter(); @Override boolean accept(Path entry); }### Answer:
@Test public void testJpg() throws Exception { assertThat(cut.accept(createFile("foo.jpg")), is(true)); }
@Test public void testJpeg() throws Exception { assertThat(cut.accept(createFile("foo.jpeg")), is(true)); }
@Test public void testPng() throws Exception { assertThat(cut.accept(createFile("foo.png")), is(true)); }
@Test public void testGif() throws Exception { assertThat(cut.accept(createFile("foo.gif")), is(true)); }
@Test public void testNonLowerCase() throws Exception { assertThat(cut.accept(createFile("foo.Jpg")), is(true)); }
@Test public void testNonImageExtension() throws Exception { assertThat(cut.accept(createFile("foo.txt")), is(false)); } |
### Question:
ImageUtil { public static BufferedImage loadImage(Path path) throws IOException { try (InputStream is = new BufferedInputStream(Files.newInputStream(path))) { BufferedImage bi; try { bi = ImageIO.read(is); } catch (ArrayIndexOutOfBoundsException e) { bi = GifDecoder.read(is).getFrame(0); } return bi; } } static BufferedImage bytesToImage(byte[] data); static byte[] imageToBytes(BufferedImage image); static BufferedImage loadImage(Path path); }### Answer:
@Test public void testLoadImageJpg() throws Exception { BufferedImage image = ImageUtil.loadImage(jpgPath); assertThat(image.getHeight(), is(IMAGE_SIZE)); assertThat(image.getWidth(), is(IMAGE_SIZE)); }
@Test public void testLoadImageGif() throws Exception { BufferedImage image = ImageUtil.loadImage(gifPath); assertThat(image.getHeight(), is(IMAGE_SIZE)); assertThat(image.getWidth(), is(IMAGE_SIZE)); } |
### Question:
Statistics { public void incrementFailedFiles() { dispatchEvent(StatisticsEvent.FAILED_FILES, failedFiles.incrementAndGet()); } int getFoundFiles(); void incrementFoundFiles(); int getProcessedFiles(); void incrementProcessedFiles(); int getFailedFiles(); void incrementFailedFiles(); int getSkippedFiles(); void incrementSkippedFiles(); void reset(); void addStatisticsListener(StatisticsChangedListener listener); void removeStatisticsListener(StatisticsChangedListener listener); }### Answer:
@Test public void testIncrementFailedFilesEvent() throws Exception { cut.incrementFailedFiles(); verify(listener).statisticsChangedEvent(eq(StatisticsEvent.FAILED_FILES), eq(1)); } |
### Question:
Statistics { public void incrementFoundFiles() { dispatchEvent(StatisticsEvent.FOUND_FILES, foundFiles.incrementAndGet()); } int getFoundFiles(); void incrementFoundFiles(); int getProcessedFiles(); void incrementProcessedFiles(); int getFailedFiles(); void incrementFailedFiles(); int getSkippedFiles(); void incrementSkippedFiles(); void reset(); void addStatisticsListener(StatisticsChangedListener listener); void removeStatisticsListener(StatisticsChangedListener listener); }### Answer:
@Test public void testIncrementFoundFilesEvent() throws Exception { cut.incrementFoundFiles(); verify(listener).statisticsChangedEvent(eq(StatisticsEvent.FOUND_FILES), eq(1)); } |
### Question:
Statistics { public void incrementProcessedFiles() { dispatchEvent(StatisticsEvent.PROCESSED_FILES, processedFiles.incrementAndGet()); } int getFoundFiles(); void incrementFoundFiles(); int getProcessedFiles(); void incrementProcessedFiles(); int getFailedFiles(); void incrementFailedFiles(); int getSkippedFiles(); void incrementSkippedFiles(); void reset(); void addStatisticsListener(StatisticsChangedListener listener); void removeStatisticsListener(StatisticsChangedListener listener); }### Answer:
@Test public void testIncrementProcessedFilesFiles() throws Exception { cut.incrementProcessedFiles(); verify(listener).statisticsChangedEvent(eq(StatisticsEvent.PROCESSED_FILES), eq(1)); } |
### Question:
Statistics { public void incrementSkippedFiles() { dispatchEvent(StatisticsEvent.SKIPPED_FILES, skippedFiles.incrementAndGet()); } int getFoundFiles(); void incrementFoundFiles(); int getProcessedFiles(); void incrementProcessedFiles(); int getFailedFiles(); void incrementFailedFiles(); int getSkippedFiles(); void incrementSkippedFiles(); void reset(); void addStatisticsListener(StatisticsChangedListener listener); void removeStatisticsListener(StatisticsChangedListener listener); }### Answer:
@Test public void testIncrementSkippedFilesEvent() throws Exception { cut.incrementSkippedFiles(); verify(listener).statisticsChangedEvent(eq(StatisticsEvent.SKIPPED_FILES), eq(1)); } |
### Question:
Statistics { public void removeStatisticsListener(StatisticsChangedListener listener) { statisticsChangedListners.remove(listener); } int getFoundFiles(); void incrementFoundFiles(); int getProcessedFiles(); void incrementProcessedFiles(); int getFailedFiles(); void incrementFailedFiles(); int getSkippedFiles(); void incrementSkippedFiles(); void reset(); void addStatisticsListener(StatisticsChangedListener listener); void removeStatisticsListener(StatisticsChangedListener listener); }### Answer:
@Test public void testRemoveStatisticsListener() throws Exception { cut.removeStatisticsListener(listener); cut.incrementFailedFiles(); cut.incrementFoundFiles(); cut.incrementProcessedFiles(); cut.incrementSkippedFiles(); verifyZeroInteractions(listener); } |
### Question:
GroupList { public void remove(Result result) { Collection<ResultGroup> groupsToRemoveFrom = resultsToGroups.removeAll(result); LOGGER.debug("Removing {} from {} group(s).", result, groupsToRemoveFrom.size()); for (ResultGroup g : groupsToRemoveFrom) { g.remove(result, false); checkAndremoveEmptyGroup(g); } } GroupList(); GroupList(DefaultListModel<ResultGroup> mappedListModel); void populateList(Collection<ResultGroup> groupsToAdd); int groupCount(); void remove(Result result); ResultGroup getGroup(long hash); List<ResultGroup> getAllGroups(); void setMappedListModel(DefaultListModel<ResultGroup> mappedListeModel); ResultGroup nextGroup(ResultGroup currentGroup); ResultGroup previousGroup(ResultGroup currentGroup); }### Answer:
@Test public void testRemoveViaGroup() throws Exception { Result result = new Result(groupB, recordC); assertThat(groupB.getResults(), hasItem(result)); groupA.remove(result); assertThat(groupB.getResults(), not(hasItem(result))); }
@Test public void testEmptyGroupRemovedFromGui() throws Exception { cut = new GroupList(dlm); initGroupList(); groupA.remove(new Result(groupA, recordC)); groupA.remove(new Result(groupA, recordA)); assertThat(dlm.contains(groupA), is(false)); } |
### Question:
GroupList { public int groupCount() { return groups.size(); } GroupList(); GroupList(DefaultListModel<ResultGroup> mappedListModel); void populateList(Collection<ResultGroup> groupsToAdd); int groupCount(); void remove(Result result); ResultGroup getGroup(long hash); List<ResultGroup> getAllGroups(); void setMappedListModel(DefaultListModel<ResultGroup> mappedListeModel); ResultGroup nextGroup(ResultGroup currentGroup); ResultGroup previousGroup(ResultGroup currentGroup); }### Answer:
@Test public void testGroupCount() throws Exception { assertThat(cut.groupCount(), is(2)); } |
### Question:
GroupList { public ResultGroup getGroup(long hash) throws IllegalArgumentException { ResultGroup group = hashToGroup.get(hash); if (group == null) { throw new IllegalArgumentException("Query for unknown hash"); } return group; } GroupList(); GroupList(DefaultListModel<ResultGroup> mappedListModel); void populateList(Collection<ResultGroup> groupsToAdd); int groupCount(); void remove(Result result); ResultGroup getGroup(long hash); List<ResultGroup> getAllGroups(); void setMappedListModel(DefaultListModel<ResultGroup> mappedListeModel); ResultGroup nextGroup(ResultGroup currentGroup); ResultGroup previousGroup(ResultGroup currentGroup); }### Answer:
@Test public void testGetGroup() throws Exception { assertThat(cut.getGroup(HASH_A), is(groupA)); }
@Test(expected = IllegalArgumentException.class) public void testGetInvalidHash() throws Exception { cut.getGroup(-1); } |
### Question:
GroupList { public ResultGroup previousGroup(ResultGroup currentGroup) { int index = groups.indexOf(currentGroup); index = boundsCheckedIndex(--index); return groups.get(index); } GroupList(); GroupList(DefaultListModel<ResultGroup> mappedListModel); void populateList(Collection<ResultGroup> groupsToAdd); int groupCount(); void remove(Result result); ResultGroup getGroup(long hash); List<ResultGroup> getAllGroups(); void setMappedListModel(DefaultListModel<ResultGroup> mappedListeModel); ResultGroup nextGroup(ResultGroup currentGroup); ResultGroup previousGroup(ResultGroup currentGroup); }### Answer:
@Test public void testPreviousGroup() throws Exception { assertThat(cut.previousGroup(groupB), is(groupA)); }
@Test public void testPreviousGroupWithFirstGroup() throws Exception { assertThat(cut.previousGroup(groupA), is(groupA)); }
@Test public void testPreviousGroupWithUnknownGroup() throws Exception { assertThat(cut.previousGroup(groupUnknown), is(groupA)); } |
### Question:
GroupList { public ResultGroup nextGroup(ResultGroup currentGroup) { int index = groups.indexOf(currentGroup); index = boundsCheckedIndex(++index); return groups.get(index); } GroupList(); GroupList(DefaultListModel<ResultGroup> mappedListModel); void populateList(Collection<ResultGroup> groupsToAdd); int groupCount(); void remove(Result result); ResultGroup getGroup(long hash); List<ResultGroup> getAllGroups(); void setMappedListModel(DefaultListModel<ResultGroup> mappedListeModel); ResultGroup nextGroup(ResultGroup currentGroup); ResultGroup previousGroup(ResultGroup currentGroup); }### Answer:
@Test public void testNextGroup() throws Exception { assertThat(cut.nextGroup(groupA), is(groupB)); }
@Test public void testNextGroupWithLastGroup() throws Exception { assertThat(cut.nextGroup(groupB), is(groupB)); }
@Test public void testNextGroupWithUnknownGroup() throws Exception { assertThat(cut.nextGroup(groupUnknown), is(groupA)); } |
### Question:
Result { public ImageRecord getImageRecord() { return imageRecord; } Result(ResultGroup parentGroup, ImageRecord imageRecord); ImageRecord getImageRecord(); void remove(); @Override String toString(); @Override final int hashCode(); @Override final boolean equals(Object obj); }### Answer:
@Test public void testGetImageRecord() throws Exception { assertThat(cut.getImageRecord(), is(imageRecord)); } |
### Question:
StringUtil { public static String sanitizeTag(String tagFromGui) { if (tagFromGui == null || "".equals(tagFromGui)) { return MATCH_ALL_TAGS; } return tagFromGui; } private StringUtil(); static String sanitizeTag(String tagFromGui); static final String MATCH_ALL_TAGS; }### Answer:
@Test public void testSanitizeTag() throws Exception { assertThat(StringUtil.sanitizeTag(TEST_TAG), is(TEST_TAG)); }
@Test public void testSanitizeTagNull() throws Exception { assertThat(StringUtil.sanitizeTag(null), is(StringUtil.MATCH_ALL_TAGS)); }
@Test public void testSanitizeTagEmpty() throws Exception { assertThat(StringUtil.sanitizeTag(""), is(StringUtil.MATCH_ALL_TAGS)); } |
### Question:
Result { public void remove() { LOGGER.debug("Removing result {}", this); parentGroup.remove(this); } Result(ResultGroup parentGroup, ImageRecord imageRecord); ImageRecord getImageRecord(); void remove(); @Override String toString(); @Override final int hashCode(); @Override final boolean equals(Object obj); }### Answer:
@Test public void testRemoveResult() throws Exception { cut.remove(); verify(parentGroup).remove(cut); } |
### Question:
ResultGroup { public long getHash() { return hash; } ResultGroup(GroupList parent, long hash, Collection<ImageRecord> records); long getHash(); List<Result> getResults(); boolean remove(Result result); boolean remove(Result result, boolean notifyParent); @Override String toString(); boolean hasResults(); @Override final int hashCode(); @Override final boolean equals(Object obj); }### Answer:
@Test public void testGetHash() throws Exception { assertThat(cut.getHash(), is(HASH)); } |
### Question:
ResultGroup { public List<Result> getResults() { return results; } ResultGroup(GroupList parent, long hash, Collection<ImageRecord> records); long getHash(); List<Result> getResults(); boolean remove(Result result); boolean remove(Result result, boolean notifyParent); @Override String toString(); boolean hasResults(); @Override final int hashCode(); @Override final boolean equals(Object obj); }### Answer:
@Test public void testGetResults() throws Exception { assertThat(cut.getResults(), hasItems(resultA, new Result(cut, recordB))); } |
### Question:
ResultGroup { public boolean remove(Result result) { return remove(result, true); } ResultGroup(GroupList parent, long hash, Collection<ImageRecord> records); long getHash(); List<Result> getResults(); boolean remove(Result result); boolean remove(Result result, boolean notifyParent); @Override String toString(); boolean hasResults(); @Override final int hashCode(); @Override final boolean equals(Object obj); }### Answer:
@Test public void testRemove() throws Exception { assertThat(cut.remove(resultA), is(true)); }
@Test public void testRemoveNonExistingResult() throws Exception { cut.remove(resultA); assertThat(cut.remove(resultA), is(false)); }
@Test public void testNotifyParentOnResultRemoval() throws Exception { cut.remove(resultA); verify(parent).remove(resultA); }
@Test public void testRemoveWithoutNotification() throws Exception { cut.remove(resultA, false); verify(parent, never()).remove(resultA); } |
### Question:
ResultGroup { public boolean hasResults() { return !results.isEmpty(); } ResultGroup(GroupList parent, long hash, Collection<ImageRecord> records); long getHash(); List<Result> getResults(); boolean remove(Result result); boolean remove(Result result, boolean notifyParent); @Override String toString(); boolean hasResults(); @Override final int hashCode(); @Override final boolean equals(Object obj); }### Answer:
@Test public void testHasResults() throws Exception { assertThat(cut.hasResults(), is(true)); } |
### Question:
ResultGroup { @Override public String toString() { return String.format("%d (%d)", this.hash, results.size()); } ResultGroup(GroupList parent, long hash, Collection<ImageRecord> records); long getHash(); List<Result> getResults(); boolean remove(Result result); boolean remove(Result result, boolean notifyParent); @Override String toString(); boolean hasResults(); @Override final int hashCode(); @Override final boolean equals(Object obj); }### Answer:
@Test public void testToString() throws Exception { assertThat(cut.toString(), is("42 (2)")); } |
### Question:
ImageRecord implements Comparable<ImageRecord> { public String getPath() { return path; } @Deprecated ImageRecord(); ImageRecord(String path, long pHash); String getPath(); long getpHash(); @Override int hashCode(); @Override boolean equals(Object obj); @Override int compareTo(ImageRecord o); @Override String toString(); static final String PATH_COLUMN_NAME; }### Answer:
@Test public void testGetPath() throws Exception { assertThat(imageRecord.getPath(), is("foo")); } |
### Question:
ImageRecord implements Comparable<ImageRecord> { public long getpHash() { return pHash; } @Deprecated ImageRecord(); ImageRecord(String path, long pHash); String getPath(); long getpHash(); @Override int hashCode(); @Override boolean equals(Object obj); @Override int compareTo(ImageRecord o); @Override String toString(); static final String PATH_COLUMN_NAME; }### Answer:
@Test public void testGetpHash() throws Exception { assertThat(imageRecord.getpHash(), is(42L)); } |
### Question:
ImageRecord implements Comparable<ImageRecord> { @Override public int compareTo(ImageRecord o) { if (o == null) { throw new NullPointerException(); } if (this.pHash == o.getpHash()) { return 0; } else if (this.getpHash() > o.pHash) { return 1; } else { return -1; } } @Deprecated ImageRecord(); ImageRecord(String path, long pHash); String getPath(); long getpHash(); @Override int hashCode(); @Override boolean equals(Object obj); @Override int compareTo(ImageRecord o); @Override String toString(); static final String PATH_COLUMN_NAME; }### Answer:
@Test public void testCompareToSelf() throws Exception { assertThat(imageRecord.compareTo(imageRecord), is(0)); }
@Test(expected = NullPointerException.class) public void testCompareToNull() throws Exception { imageRecord.compareTo(null); }
@Test public void testCompareToBigger() throws Exception { assertThat(imageRecord.compareTo(new ImageRecord("bar", 55)), is(-1)); }
@Test public void testCompareToSmaller() throws Exception { assertThat(imageRecord.compareTo(new ImageRecord("bar", 7)), is(1)); }
@Test public void testCompareToEqual() throws Exception { assertThat(imageRecord.compareTo(new ImageRecord("bar", 42)), is(0)); } |
### Question:
ImageRecord implements Comparable<ImageRecord> { @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; ImageRecord other = (ImageRecord) obj; if (pHash != other.pHash) return false; if (path == null) { if (other.path != null) return false; } else if (!path.equals(other.path)) return false; return true; } @Deprecated ImageRecord(); ImageRecord(String path, long pHash); String getPath(); long getpHash(); @Override int hashCode(); @Override boolean equals(Object obj); @Override int compareTo(ImageRecord o); @Override String toString(); static final String PATH_COLUMN_NAME; }### Answer:
@Test public void testEquals() throws Exception { EqualsVerifier.forClass(ImageRecord.class).suppress(Warning.NONFINAL_FIELDS).verify(); } |
### Question:
ImageRecord implements Comparable<ImageRecord> { @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("ImageRecord"); sb.append("{"); sb.append("path:"); sb.append(path); sb.append(","); sb.append("hash:"); sb.append(pHash); sb.append("}"); return sb.toString(); } @Deprecated ImageRecord(); ImageRecord(String path, long pHash); String getPath(); long getpHash(); @Override int hashCode(); @Override boolean equals(Object obj); @Override int compareTo(ImageRecord o); @Override String toString(); static final String PATH_COLUMN_NAME; }### Answer:
@Test public void testToString() throws Exception { assertThat(imageRecord.toString(), is(EXPECTED_TO_STRING)); } |
### Question:
BadFileRecord { public String getPath() { return path; } @Deprecated BadFileRecord(); BadFileRecord(Path path); String getPath(); }### Answer:
@Test public void testGetPath() throws Exception { assertThat(badFileRecord.getPath(), is("bad")); } |
### Question:
RepositoryException extends Exception { public final String getMessage() { return message; } RepositoryException(String message, Throwable cause); RepositoryException(String message); final String getMessage(); final Throwable getCause(); }### Answer:
@Test public void testRepositoryExceptionStringThrowableMessage() throws Exception { cut = new RepositoryException(TEST_MESSAGE, testException); assertThat(cut.getMessage(), is(TEST_MESSAGE)); }
@Test public void testRepositoryExceptionStringMessage() throws Exception { cut = new RepositoryException(TEST_MESSAGE); assertThat(cut.getMessage(), is(TEST_MESSAGE)); } |
### Question:
RepositoryException extends Exception { public final Throwable getCause() { return cause; } RepositoryException(String message, Throwable cause); RepositoryException(String message); final String getMessage(); final Throwable getCause(); }### Answer:
@Test public void testRepositoryExceptionStringThrowableCause() throws Exception { cut = new RepositoryException(TEST_MESSAGE, testException); assertThat(cut.getCause(), is(testException)); }
@Test public void testRepositoryExceptionStringCause() throws Exception { cut = new RepositoryException(TEST_MESSAGE); assertThat(cut.getCause(), nullValue()); } |
### Question:
OrmliteRepositoryFactory implements RepositoryFactory { @Override public FilterRepository buildFilterRepository() throws RepositoryException { return new OrmliteFilterRepository(filterRecordDao, thumbnailDao); } @Inject OrmliteRepositoryFactory(Database database); @Override FilterRepository buildFilterRepository(); @Override ImageRepository buildImageRepository(); @Override TagRepository buildTagRepository(); @Override PendingHashImageRepository buildPendingHashImageRepository(); @Override IgnoreRepository buildIgnoreRepository(); }### Answer:
@Test public void testBuildFilterRepository() throws Exception { FilterRepository fr = cut.buildFilterRepository(); fr.store(new FilterRecord(0, new Tag(TEST_STRING))); } |
### Question:
OrmliteRepositoryFactory implements RepositoryFactory { @Override public ImageRepository buildImageRepository() throws RepositoryException { return new OrmliteImageRepository(imageRecordDao, ignoreDao); } @Inject OrmliteRepositoryFactory(Database database); @Override FilterRepository buildFilterRepository(); @Override ImageRepository buildImageRepository(); @Override TagRepository buildTagRepository(); @Override PendingHashImageRepository buildPendingHashImageRepository(); @Override IgnoreRepository buildIgnoreRepository(); }### Answer:
@Test public void testBuildImageRepository() throws Exception { ImageRepository ir = cut.buildImageRepository(); ir.store(new ImageRecord(TEST_STRING, 0)); } |
### Question:
OrmliteRepositoryFactory implements RepositoryFactory { @Override public TagRepository buildTagRepository() throws RepositoryException { return new OrmliteTagRepository(tagDao); } @Inject OrmliteRepositoryFactory(Database database); @Override FilterRepository buildFilterRepository(); @Override ImageRepository buildImageRepository(); @Override TagRepository buildTagRepository(); @Override PendingHashImageRepository buildPendingHashImageRepository(); @Override IgnoreRepository buildIgnoreRepository(); }### Answer:
@Test public void testBuildTagRepository() throws Exception { TagRepository tr = cut.buildTagRepository(); tr.store(new Tag(TEST_STRING)); } |
### Question:
OrmliteRepositoryFactory implements RepositoryFactory { @Override public PendingHashImageRepository buildPendingHashImageRepository() throws RepositoryException { return new OrmlitePendingHashImage(pendingDao); } @Inject OrmliteRepositoryFactory(Database database); @Override FilterRepository buildFilterRepository(); @Override ImageRepository buildImageRepository(); @Override TagRepository buildTagRepository(); @Override PendingHashImageRepository buildPendingHashImageRepository(); @Override IgnoreRepository buildIgnoreRepository(); }### Answer:
@Test public void testBuildPendingImageRepository() throws Exception { PendingHashImageRepository phir = cut.buildPendingHashImageRepository(); phir.store(new PendingHashImage(TEST_STRING, 0, 0)); } |
### Question:
OrmliteRepositoryFactory implements RepositoryFactory { @Override public IgnoreRepository buildIgnoreRepository() throws RepositoryException { return new OrmliteIgnoreRepository(ignoreDao); } @Inject OrmliteRepositoryFactory(Database database); @Override FilterRepository buildFilterRepository(); @Override ImageRepository buildImageRepository(); @Override TagRepository buildTagRepository(); @Override PendingHashImageRepository buildPendingHashImageRepository(); @Override IgnoreRepository buildIgnoreRepository(); }### Answer:
@Test public void testBuildIgnoreRepository() throws Exception { IgnoreRepository ir = cut.buildIgnoreRepository(); ir.store(new IgnoreRecord(new ImageRecord(TEST_STRING, 0))); } |
### Question:
OrmlitePendingHashImage implements PendingHashImageRepository { @Override public synchronized boolean store(PendingHashImage image) throws RepositoryException { try { if (pendingDao.queryForMatchingArgs(image).isEmpty()) { pendingDao.create(image); return true; } else { return false; } } catch (SQLException e) { throw new RepositoryException("Failed to store entry", e); } } OrmlitePendingHashImage(Dao<PendingHashImage, Integer> pendingDao); @Override synchronized boolean store(PendingHashImage image); @Override boolean exists(PendingHashImage image); @Override List<PendingHashImage> getAll(); @Override PendingHashImage getByUUID(long most, long least); @Override void remove(PendingHashImage image); }### Answer:
@Test public void testStoreQueryDatabase() throws Exception { cut.store(newEntry); assertThat(dao.queryForMatchingArgs(newEntry), hasSize(1)); }
@Test public void testStoreReturnValue() throws Exception { assertThat(cut.store(newEntry), is(true)); }
@Test public void testStoreDuplicate() throws Exception { assertThat(cut.store(existingEntry), is(false)); } |
### Question:
ExtendedAttribute implements ExtendedAttributeQuery { public static boolean supportsExtendedAttributes(Path path) { try { return Files.getFileStore(path).supportsFileAttributeView(UserDefinedFileAttributeView.class); } catch (IOException e) { LOGGER.debug("Failed to check extended attributes via FileStore ({}) for {}, falling back to write test...", e.toString(), path); return checkSupportWithWrite(path); } } static String createName(String... names); static boolean supportsExtendedAttributes(Path path); static void deleteExtendedAttribute(Path path, String name); static void setExtendedAttribute(Path path, String name, String value); static void setExtendedAttribute(Path path, String name, ByteBuffer value); static ByteBuffer readExtendedAttribute(Path path, String name); static String readExtendedAttributeAsString(Path path, String name); static boolean isExtendedAttributeSet(Path path, String name); @Override boolean isEaSupported(Path path); static final String SIMILARIMAGE_NAMESPACE; }### Answer:
@Test public void testSupportsExtendedAttributes() throws Exception { assertThat(ExtendedAttribute.supportsExtendedAttributes(tempFile), is(true)); }
@Test public void testSupportsExtendedAttributesNoFile() throws Exception { assertThat(ExtendedAttribute.supportsExtendedAttributes(Jimfs.newFileSystem().getPath("noEAsupport")), is(false)); } |
### Question:
OrmlitePendingHashImage implements PendingHashImageRepository { @Override public boolean exists(PendingHashImage image) throws RepositoryException { try { if (pendingDao.refresh(image) == 0) { return !pendingDao.queryForMatching(image).isEmpty(); } else { return true; } } catch (SQLException e) { throw new RepositoryException("Failed to lookup entry", e); } } OrmlitePendingHashImage(Dao<PendingHashImage, Integer> pendingDao); @Override synchronized boolean store(PendingHashImage image); @Override boolean exists(PendingHashImage image); @Override List<PendingHashImage> getAll(); @Override PendingHashImage getByUUID(long most, long least); @Override void remove(PendingHashImage image); }### Answer:
@Test public void testExistsById() throws Exception { assertThat(cut.exists(existingEntry), is(true)); }
@Test public void testExistsByPath() throws Exception { assertThat(cut.exists(new PendingHashImage(EXISTING_PATH, UUID_EXISTING)), is(true)); }
@Test public void testExistsNotFound() throws Exception { assertThat(cut.exists(newEntry), is(false)); } |
### Question:
OrmlitePendingHashImage implements PendingHashImageRepository { @Override public List<PendingHashImage> getAll() throws RepositoryException { try { return pendingDao.queryForAll(); } catch (SQLException e) { throw new RepositoryException("Failed to query for all entries", e); } } OrmlitePendingHashImage(Dao<PendingHashImage, Integer> pendingDao); @Override synchronized boolean store(PendingHashImage image); @Override boolean exists(PendingHashImage image); @Override List<PendingHashImage> getAll(); @Override PendingHashImage getByUUID(long most, long least); @Override void remove(PendingHashImage image); }### Answer:
@Test public void testGetAll() throws Exception { dao.create(newEntry); assertThat(cut.getAll(), containsInAnyOrder(newEntry, existingEntry)); } |
### Question:
OrmlitePendingHashImage implements PendingHashImageRepository { @Override public PendingHashImage getByUUID(long most, long least) throws RepositoryException { try { synchronized (uuidQuery) { mostParam.setValue(most); leastParam.setValue(least); return pendingDao.queryForFirst(uuidQuery); } } catch (SQLException e) { throw new RepositoryException("Failed to get entry by id", e); } } OrmlitePendingHashImage(Dao<PendingHashImage, Integer> pendingDao); @Override synchronized boolean store(PendingHashImage image); @Override boolean exists(PendingHashImage image); @Override List<PendingHashImage> getAll(); @Override PendingHashImage getByUUID(long most, long least); @Override void remove(PendingHashImage image); }### Answer:
@Test public void testGetByUuidNonExisting() throws Exception { assertThat(cut.getByUUID(UUID_NEW.getMostSignificantBits(), UUID_NEW.getLeastSignificantBits()), is(nullValue())); }
@Test public void testGetByUuidExisting() throws Exception { assertThat(cut.getByUUID(UUID_EXISTING.getMostSignificantBits(), UUID_EXISTING.getLeastSignificantBits()), is(existingEntry)); } |
### Question:
OrmlitePendingHashImage implements PendingHashImageRepository { @Override public void remove(PendingHashImage image) throws RepositoryException { try { pendingDao.delete(image); } catch (SQLException e) { throw new RepositoryException("Failed to remove entry", e); } } OrmlitePendingHashImage(Dao<PendingHashImage, Integer> pendingDao); @Override synchronized boolean store(PendingHashImage image); @Override boolean exists(PendingHashImage image); @Override List<PendingHashImage> getAll(); @Override PendingHashImage getByUUID(long most, long least); @Override void remove(PendingHashImage image); }### Answer:
@Test public void testRemove() throws Exception { assertThat(dao.queryForSameId(existingEntry), is(notNullValue())); cut.remove(existingEntry); assertThat(dao.queryForSameId(existingEntry), is(nullValue())); } |
### Question:
OrmliteImageRepository implements ImageRepository { @Override public void store(ImageRecord image) throws RepositoryException { try { imageDao.createOrUpdate(image); } catch (SQLException e) { throw new RepositoryException("Failed to store image", e); } } OrmliteImageRepository(Dao<ImageRecord, String> imageDao, Dao<IgnoreRecord, String> ignoreDao); @Override void store(ImageRecord image); @Override List<ImageRecord> getByHash(long hash); @Override ImageRecord getByPath(Path path); @Override synchronized List<ImageRecord> startsWithPath(Path directory); @Override void remove(ImageRecord image); @Override void remove(Collection<ImageRecord> images); @Override List<ImageRecord> getAll(); @Override List<ImageRecord> getAllWithoutIgnored(); @Override List<ImageRecord> getAllWithoutIgnored(Path directory); }### Answer:
@Test public void testStore() throws Exception { cut.store(imageNew); assertThat(imageDao.queryForId(pathNew), is(imageNew)); } |
### Question:
SeedPeers implements PeerDiscovery { public InetSocketAddress getPeer() throws PeerDiscoveryException { try { return nextPeer(); } catch (UnknownHostException e) { throw new PeerDiscoveryException(e); } } SeedPeers(NetworkParameters params); InetSocketAddress getPeer(); InetSocketAddress[] getPeers(long timeoutValue, TimeUnit timeoutUnit); void shutdown(); static int[] seedAddrs; }### Answer:
@Test public void getPeer_one() throws Exception{ SeedPeers seedPeers = new SeedPeers(NetworkParameters.prodNet()); assertThat(seedPeers.getPeer(), notNullValue()); }
@Test public void getPeer_all() throws Exception{ SeedPeers seedPeers = new SeedPeers(NetworkParameters.prodNet()); for(int i = 0; i < SeedPeers.seedAddrs.length; ++i){ assertThat("Failed on index: "+i, seedPeers.getPeer(), notNullValue()); } assertThat(seedPeers.getPeer(), equalTo(null)); } |
### Question:
Address extends VersionedChecksummedBytes { public byte[] getHash160() { return bytes; } Address(NetworkParameters params, byte[] hash160); Address(NetworkParameters params, String address); byte[] getHash160(); NetworkParameters getParameters(); static NetworkParameters getParametersFromAddress(String address); static final int LENGTH; }### Answer:
@Test public void decoding() throws Exception { Address a = new Address(testParams, "n4eA2nbYqErp7H6jebchxAN59DmNpksexv"); assertEquals("fda79a24e50ff70ff42f7d89585da5bd19d9e5cc", Utils.bytesToHexString(a.getHash160())); Address b = new Address(prodParams, "LQz2pJYaeqntA9BFB8rDX5AL2TTKGd5AuN"); assertEquals("3f2ebb6c8d88e586b551303d2c29eba15518d8d1", Utils.bytesToHexString(b.getHash160())); } |
### Question:
Address extends VersionedChecksummedBytes { public static NetworkParameters getParametersFromAddress(String address) throws AddressFormatException { try { return new Address(null, address).getParameters(); } catch (WrongNetworkException e) { throw new RuntimeException(e); } } Address(NetworkParameters params, byte[] hash160); Address(NetworkParameters params, String address); byte[] getHash160(); NetworkParameters getParameters(); static NetworkParameters getParametersFromAddress(String address); static final int LENGTH; }### Answer:
@Test public void getNetwork() throws Exception { NetworkParameters params = Address.getParametersFromAddress("LQz2pJYaeqntA9BFB8rDX5AL2TTKGd5AuN"); assertEquals(NetworkParameters.prodNet().getId(), params.getId()); params = Address.getParametersFromAddress("n4eA2nbYqErp7H6jebchxAN59DmNpksexv"); assertEquals(NetworkParameters.testNet().getId(), params.getId()); } |
### Question:
Block extends Message { public BigInteger getWork() throws VerificationException { BigInteger target = getDifficultyTargetAsInteger(); return LARGEST_HASH.divide(target.add(BigInteger.ONE)); } Block(NetworkParameters params); Block(NetworkParameters params, byte[] payloadBytes); Block(NetworkParameters params, byte[] payloadBytes, boolean parseLazy, boolean parseRetain, int length); BigInteger getBlockInflation(int height); int getOptimalEncodingMessageSize(); void ensureParsed(); void ensureParsedHeader(); void ensureParsedTransactions(); byte[] litecoinSerialize(); String getHashAsString(); String getScryptHashAsString(); Sha256Hash getHash(); Sha256Hash getScryptHash(); BigInteger getWork(); Block cloneAsHeader(); @Override String toString(); BigInteger getDifficultyTargetAsInteger(); void verifyHeader(); void verifyTransactions(); void verify(); @Override boolean equals(Object o); @Override int hashCode(); Sha256Hash getMerkleRoot(); void addTransaction(Transaction t); long getVersion(); Sha256Hash getPrevBlockHash(); long getTimeSeconds(); Date getTime(); long getDifficultyTarget(); long getNonce(); List<Transaction> getTransactions(); Block createNextBlock(Address to, TransactionOutPoint prevOut); Block createNextBlock(Address to, BigInteger value); Block createNextBlock(Address to); Block createNextBlockWithCoinbase(byte[] pubKey, BigInteger coinbaseValue); static final int HEADER_SIZE; static final int MAX_BLOCK_SIZE; static final int MAX_BLOCK_SIGOPS; }### Answer:
@Test public void testWork() throws Exception { BigInteger work = params.genesisBlock.getWork(); assertEquals(BigInteger.valueOf(536879104L), work); } |
### Question:
Block extends Message { public Date getTime() { return new Date(getTimeSeconds()*1000); } Block(NetworkParameters params); Block(NetworkParameters params, byte[] payloadBytes); Block(NetworkParameters params, byte[] payloadBytes, boolean parseLazy, boolean parseRetain, int length); BigInteger getBlockInflation(int height); int getOptimalEncodingMessageSize(); void ensureParsed(); void ensureParsedHeader(); void ensureParsedTransactions(); byte[] litecoinSerialize(); String getHashAsString(); String getScryptHashAsString(); Sha256Hash getHash(); Sha256Hash getScryptHash(); BigInteger getWork(); Block cloneAsHeader(); @Override String toString(); BigInteger getDifficultyTargetAsInteger(); void verifyHeader(); void verifyTransactions(); void verify(); @Override boolean equals(Object o); @Override int hashCode(); Sha256Hash getMerkleRoot(); void addTransaction(Transaction t); long getVersion(); Sha256Hash getPrevBlockHash(); long getTimeSeconds(); Date getTime(); long getDifficultyTarget(); long getNonce(); List<Transaction> getTransactions(); Block createNextBlock(Address to, TransactionOutPoint prevOut); Block createNextBlock(Address to, BigInteger value); Block createNextBlock(Address to); Block createNextBlockWithCoinbase(byte[] pubKey, BigInteger coinbaseValue); static final int HEADER_SIZE; static final int MAX_BLOCK_SIZE; static final int MAX_BLOCK_SIGOPS; }### Answer:
@SuppressWarnings("deprecation") @Test public void testDate() throws Exception { Block block = new Block(params, blockBytes); assertEquals("4 Nov 2010 16:06:04 GMT", block.getTime().toGMTString()); } |
### Question:
Block extends Message { public void verify() throws VerificationException { verifyHeader(); verifyTransactions(); } Block(NetworkParameters params); Block(NetworkParameters params, byte[] payloadBytes); Block(NetworkParameters params, byte[] payloadBytes, boolean parseLazy, boolean parseRetain, int length); BigInteger getBlockInflation(int height); int getOptimalEncodingMessageSize(); void ensureParsed(); void ensureParsedHeader(); void ensureParsedTransactions(); byte[] litecoinSerialize(); String getHashAsString(); String getScryptHashAsString(); Sha256Hash getHash(); Sha256Hash getScryptHash(); BigInteger getWork(); Block cloneAsHeader(); @Override String toString(); BigInteger getDifficultyTargetAsInteger(); void verifyHeader(); void verifyTransactions(); void verify(); @Override boolean equals(Object o); @Override int hashCode(); Sha256Hash getMerkleRoot(); void addTransaction(Transaction t); long getVersion(); Sha256Hash getPrevBlockHash(); long getTimeSeconds(); Date getTime(); long getDifficultyTarget(); long getNonce(); List<Transaction> getTransactions(); Block createNextBlock(Address to, TransactionOutPoint prevOut); Block createNextBlock(Address to, BigInteger value); Block createNextBlock(Address to); Block createNextBlockWithCoinbase(byte[] pubKey, BigInteger coinbaseValue); static final int HEADER_SIZE; static final int MAX_BLOCK_SIZE; static final int MAX_BLOCK_SIGOPS; }### Answer:
@Test public void testBadTransactions() throws Exception { Block block = new Block(params, blockBytes); Transaction tx1 = block.transactions.get(0); Transaction tx2 = block.transactions.get(1); block.transactions.set(0, tx2); block.transactions.set(1, tx1); try { block.verify(); fail(); } catch (VerificationException e) { } } |
### Question:
SeedPeers implements PeerDiscovery { public InetSocketAddress[] getPeers(long timeoutValue, TimeUnit timeoutUnit) throws PeerDiscoveryException { try { return allPeers(); } catch (UnknownHostException e) { throw new PeerDiscoveryException(e); } } SeedPeers(NetworkParameters params); InetSocketAddress getPeer(); InetSocketAddress[] getPeers(long timeoutValue, TimeUnit timeoutUnit); void shutdown(); static int[] seedAddrs; }### Answer:
@Test public void getPeers_length() throws Exception{ SeedPeers seedPeers = new SeedPeers(NetworkParameters.prodNet()); InetSocketAddress[] addresses = seedPeers.getPeers(0, TimeUnit.SECONDS); assertThat(addresses.length, equalTo(SeedPeers.seedAddrs.length)); } |
### Question:
Block extends Message { private void readObject(ObjectInputStream ois) throws ClassNotFoundException, IOException { ois.defaultReadObject(); hash = null; } Block(NetworkParameters params); Block(NetworkParameters params, byte[] payloadBytes); Block(NetworkParameters params, byte[] payloadBytes, boolean parseLazy, boolean parseRetain, int length); BigInteger getBlockInflation(int height); int getOptimalEncodingMessageSize(); void ensureParsed(); void ensureParsedHeader(); void ensureParsedTransactions(); byte[] litecoinSerialize(); String getHashAsString(); String getScryptHashAsString(); Sha256Hash getHash(); Sha256Hash getScryptHash(); BigInteger getWork(); Block cloneAsHeader(); @Override String toString(); BigInteger getDifficultyTargetAsInteger(); void verifyHeader(); void verifyTransactions(); void verify(); @Override boolean equals(Object o); @Override int hashCode(); Sha256Hash getMerkleRoot(); void addTransaction(Transaction t); long getVersion(); Sha256Hash getPrevBlockHash(); long getTimeSeconds(); Date getTime(); long getDifficultyTarget(); long getNonce(); List<Transaction> getTransactions(); Block createNextBlock(Address to, TransactionOutPoint prevOut); Block createNextBlock(Address to, BigInteger value); Block createNextBlock(Address to); Block createNextBlockWithCoinbase(byte[] pubKey, BigInteger coinbaseValue); static final int HEADER_SIZE; static final int MAX_BLOCK_SIZE; static final int MAX_BLOCK_SIGOPS; }### Answer:
@Test public void testJavaSerialiazation() throws Exception { Block block = new Block(params, blockBytes); Transaction tx = block.transactions.get(1); ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(bos); oos.writeObject(tx); oos.close(); byte[] javaBits = bos.toByteArray(); ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(javaBits)); Transaction tx2 = (Transaction) ois.readObject(); ois.close(); assertEquals(tx, tx2); } |
### Question:
Peer { public void addEventListener(PeerEventListener listener) { eventListeners.add(listener); } Peer(NetworkParameters params, AbstractBlockChain chain, VersionMessage ver); Peer(NetworkParameters params, AbstractBlockChain chain, VersionMessage ver, MemoryPool mempool); Peer(NetworkParameters params, AbstractBlockChain blockChain, String thisSoftwareName, String thisSoftwareVersion); void addEventListener(PeerEventListener listener); boolean removeEventListener(PeerEventListener listener); @Override String toString(); PeerHandler getHandler(); ListenableFuture<List<Transaction>> downloadDependencies(Transaction tx); ListenableFuture<Block> getBlock(Sha256Hash blockHash); ListenableFuture<Transaction> getPeerMempoolTransaction(Sha256Hash hash); void setDownloadParameters(long secondsSinceEpoch, boolean useFilteredBlocks); void addWallet(Wallet wallet); void removeWallet(Wallet wallet); ChannelFuture sendMessage(Message m); void startBlockChainDownload(); ListenableFuture<Long> ping(); long getLastPingTime(); long getPingTime(); int getPeerBlockHeightDifference(); boolean getDownloadData(); void setDownloadData(boolean downloadData); PeerAddress getAddress(); VersionMessage getPeerVersionMessage(); VersionMessage getVersionMessage(); long getBestHeight(); ChannelFuture setMinProtocolVersion(int minProtocolVersion); void setBloomFilter(BloomFilter filter); BloomFilter getBloomFilter(); }### Answer:
@Test public void testAddEventListener() throws Exception { control.replay(); connect(); PeerEventListener listener = new AbstractPeerEventListener(); peer.addEventListener(listener); assertTrue(peer.removeEventListener(listener)); assertFalse(peer.removeEventListener(listener)); } |
### Question:
Peer { public void setDownloadData(boolean downloadData) { this.vDownloadData = downloadData; } Peer(NetworkParameters params, AbstractBlockChain chain, VersionMessage ver); Peer(NetworkParameters params, AbstractBlockChain chain, VersionMessage ver, MemoryPool mempool); Peer(NetworkParameters params, AbstractBlockChain blockChain, String thisSoftwareName, String thisSoftwareVersion); void addEventListener(PeerEventListener listener); boolean removeEventListener(PeerEventListener listener); @Override String toString(); PeerHandler getHandler(); ListenableFuture<List<Transaction>> downloadDependencies(Transaction tx); ListenableFuture<Block> getBlock(Sha256Hash blockHash); ListenableFuture<Transaction> getPeerMempoolTransaction(Sha256Hash hash); void setDownloadParameters(long secondsSinceEpoch, boolean useFilteredBlocks); void addWallet(Wallet wallet); void removeWallet(Wallet wallet); ChannelFuture sendMessage(Message m); void startBlockChainDownload(); ListenableFuture<Long> ping(); long getLastPingTime(); long getPingTime(); int getPeerBlockHeightDifference(); boolean getDownloadData(); void setDownloadData(boolean downloadData); PeerAddress getAddress(); VersionMessage getPeerVersionMessage(); VersionMessage getVersionMessage(); long getBestHeight(); ChannelFuture setMinProtocolVersion(int minProtocolVersion); void setBloomFilter(BloomFilter filter); BloomFilter getBloomFilter(); }### Answer:
@Test public void invNoDownload() throws Exception { peer.setDownloadData(false); control.replay(); connect(); Block b1 = createFakeBlock(blockStore).block; blockChain.add(b1); Block b2 = makeSolvedTestBlock(b1); InventoryMessage inv = new InventoryMessage(unitTestParams); InventoryItem item = new InventoryItem(InventoryItem.Type.Block, b2.getHash()); inv.addItem(item); inbound(peer, inv); control.verify(); }
@Test public void invDownloadTx() throws Exception { control.replay(); connect(); peer.setDownloadData(true); BigInteger value = Utils.toNanoCoins(1, 0); Transaction tx = createFakeTx(unitTestParams, value, address); InventoryMessage inv = new InventoryMessage(unitTestParams); InventoryItem item = new InventoryItem(InventoryItem.Type.Transaction, tx.getHash()); inv.addItem(item); inbound(peer, inv); GetDataMessage getdata = (GetDataMessage) outbound(); assertEquals(1, getdata.getItems().size()); assertEquals(tx.getHash(), getdata.getItems().get(0).hash); inbound(peer, tx); getdata = (GetDataMessage) outbound(); inbound(peer, new NotFoundMessage(unitTestParams, getdata.getItems())); assertEquals(value, wallet.getBalance(Wallet.BalanceType.ESTIMATED)); } |
### Question:
Peer { public ListenableFuture<Block> getBlock(Sha256Hash blockHash) throws IOException { log.info("Request to fetch block {}", blockHash); GetDataMessage getdata = new GetDataMessage(params); getdata.addBlock(blockHash); return sendSingleGetData(getdata); } Peer(NetworkParameters params, AbstractBlockChain chain, VersionMessage ver); Peer(NetworkParameters params, AbstractBlockChain chain, VersionMessage ver, MemoryPool mempool); Peer(NetworkParameters params, AbstractBlockChain blockChain, String thisSoftwareName, String thisSoftwareVersion); void addEventListener(PeerEventListener listener); boolean removeEventListener(PeerEventListener listener); @Override String toString(); PeerHandler getHandler(); ListenableFuture<List<Transaction>> downloadDependencies(Transaction tx); ListenableFuture<Block> getBlock(Sha256Hash blockHash); ListenableFuture<Transaction> getPeerMempoolTransaction(Sha256Hash hash); void setDownloadParameters(long secondsSinceEpoch, boolean useFilteredBlocks); void addWallet(Wallet wallet); void removeWallet(Wallet wallet); ChannelFuture sendMessage(Message m); void startBlockChainDownload(); ListenableFuture<Long> ping(); long getLastPingTime(); long getPingTime(); int getPeerBlockHeightDifference(); boolean getDownloadData(); void setDownloadData(boolean downloadData); PeerAddress getAddress(); VersionMessage getPeerVersionMessage(); VersionMessage getVersionMessage(); long getBestHeight(); ChannelFuture setMinProtocolVersion(int minProtocolVersion); void setBloomFilter(BloomFilter filter); BloomFilter getBloomFilter(); }### Answer:
@Test public void getBlock() throws Exception { control.replay(); connect(); Block b1 = createFakeBlock(blockStore).block; blockChain.add(b1); Block b2 = makeSolvedTestBlock(b1); Block b3 = makeSolvedTestBlock(b2); Future<Block> resultFuture = peer.getBlock(b3.getHash()); assertFalse(resultFuture.isDone()); GetDataMessage message = (GetDataMessage) event.getValue().getMessage(); assertEquals(message.getItems().get(0).hash, b3.getHash()); assertFalse(resultFuture.isDone()); inbound(peer, b3); Block b = resultFuture.get(); assertEquals(b, b3); } |
### Question:
Peer { public ChannelFuture setMinProtocolVersion(int minProtocolVersion) { this.vMinProtocolVersion = minProtocolVersion; if (getVersionMessage().clientVersion < minProtocolVersion) { log.warn("{}: Disconnecting due to new min protocol version {}", this, minProtocolVersion); return Channels.close(vChannel); } else { return null; } } Peer(NetworkParameters params, AbstractBlockChain chain, VersionMessage ver); Peer(NetworkParameters params, AbstractBlockChain chain, VersionMessage ver, MemoryPool mempool); Peer(NetworkParameters params, AbstractBlockChain blockChain, String thisSoftwareName, String thisSoftwareVersion); void addEventListener(PeerEventListener listener); boolean removeEventListener(PeerEventListener listener); @Override String toString(); PeerHandler getHandler(); ListenableFuture<List<Transaction>> downloadDependencies(Transaction tx); ListenableFuture<Block> getBlock(Sha256Hash blockHash); ListenableFuture<Transaction> getPeerMempoolTransaction(Sha256Hash hash); void setDownloadParameters(long secondsSinceEpoch, boolean useFilteredBlocks); void addWallet(Wallet wallet); void removeWallet(Wallet wallet); ChannelFuture sendMessage(Message m); void startBlockChainDownload(); ListenableFuture<Long> ping(); long getLastPingTime(); long getPingTime(); int getPeerBlockHeightDifference(); boolean getDownloadData(); void setDownloadData(boolean downloadData); PeerAddress getAddress(); VersionMessage getPeerVersionMessage(); VersionMessage getVersionMessage(); long getBestHeight(); ChannelFuture setMinProtocolVersion(int minProtocolVersion); void setBloomFilter(BloomFilter filter); BloomFilter getBloomFilter(); }### Answer:
@Test public void disconnectOldVersions2() throws Exception { expect(channel.close()).andReturn(null); control.replay(); handler.connectRequested(ctx, new UpstreamChannelStateEvent(channel, ChannelState.CONNECTED, socketAddress)); VersionMessage peerVersion = new VersionMessage(unitTestParams, OTHER_PEER_CHAIN_HEIGHT); peerVersion.clientVersion = 70000; DownstreamMessageEvent versionEvent = new DownstreamMessageEvent(channel, Channels.future(channel), peerVersion, null); handler.messageReceived(ctx, versionEvent); peer.setMinProtocolVersion(500); } |
### Question:
PeerGroup extends AbstractIdleService { public void addPeerDiscovery(PeerDiscovery peerDiscovery) { lock.lock(); try { if (getMaxConnections() == 0) setMaxConnections(DEFAULT_CONNECTIONS); peerDiscoverers.add(peerDiscovery); } finally { lock.unlock(); } } PeerGroup(NetworkParameters params); PeerGroup(NetworkParameters params, AbstractBlockChain chain); PeerGroup(NetworkParameters params, AbstractBlockChain chain, ClientBootstrap bootstrap); static ClientBootstrap createClientBootstrap(); void setMaxConnections(int maxConnections); int getMaxConnections(); void setVersionMessage(VersionMessage ver); VersionMessage getVersionMessage(); void setUserAgent(String name, String version, String comments); void setUserAgent(String name, String version); void addEventListener(PeerEventListener listener); boolean removeEventListener(PeerEventListener listener); List<Peer> getConnectedPeers(); List<Peer> getPendingPeers(); void addAddress(PeerAddress peerAddress); void addAddress(InetAddress address); void addPeerDiscovery(PeerDiscovery peerDiscovery); void addWallet(Wallet wallet); void removeWallet(Wallet wallet); void setBloomFilterFalsePositiveRate(double bloomFilterFPRate); int numConnectedPeers(); ChannelFuture connectTo(SocketAddress address); static Peer peerFromChannelFuture(ChannelFuture future); static Peer peerFromChannel(Channel channel); void startBlockChainDownload(PeerEventListener listener); void downloadBlockChain(); MemoryPool getMemoryPool(); void setFastCatchupTimeSecs(long secondsSinceEpoch); long getFastCatchupTimeSecs(); ListenableFuture<PeerGroup> waitForPeers(final int numPeers); int getMinBroadcastConnections(); void setMinBroadcastConnections(int value); ListenableFuture<Transaction> broadcastTransaction(final Transaction tx); ListenableFuture<Transaction> broadcastTransaction(final Transaction tx, final int minConnections); long getPingIntervalMsec(); void setPingIntervalMsec(long pingIntervalMsec); int getMostCommonChainHeight(); Peer getDownloadPeer(); static final long DEFAULT_PING_INTERVAL_MSEC; static final double DEFAULT_BLOOM_FILTER_FP_RATE; }### Answer:
@Test public void peerDiscoveryPolling() throws Exception { final Semaphore sem = new Semaphore(0); final boolean[] result = new boolean[1]; result[0] = false; peerGroup.addPeerDiscovery(new PeerDiscovery() { public InetSocketAddress[] getPeers(long unused, TimeUnit unused2) throws PeerDiscoveryException { if (result[0] == false) { result[0] = true; throw new PeerDiscoveryException("test failure"); } else { sem.release(); return new InetSocketAddress[]{new InetSocketAddress("localhost", 0)}; } } public void shutdown() { } }); peerGroup.startAndWait(); sem.acquire(); assertTrue(result[0]); } |
### Question:
PeerGroup extends AbstractIdleService { public int numConnectedPeers() { return peers.size(); } PeerGroup(NetworkParameters params); PeerGroup(NetworkParameters params, AbstractBlockChain chain); PeerGroup(NetworkParameters params, AbstractBlockChain chain, ClientBootstrap bootstrap); static ClientBootstrap createClientBootstrap(); void setMaxConnections(int maxConnections); int getMaxConnections(); void setVersionMessage(VersionMessage ver); VersionMessage getVersionMessage(); void setUserAgent(String name, String version, String comments); void setUserAgent(String name, String version); void addEventListener(PeerEventListener listener); boolean removeEventListener(PeerEventListener listener); List<Peer> getConnectedPeers(); List<Peer> getPendingPeers(); void addAddress(PeerAddress peerAddress); void addAddress(InetAddress address); void addPeerDiscovery(PeerDiscovery peerDiscovery); void addWallet(Wallet wallet); void removeWallet(Wallet wallet); void setBloomFilterFalsePositiveRate(double bloomFilterFPRate); int numConnectedPeers(); ChannelFuture connectTo(SocketAddress address); static Peer peerFromChannelFuture(ChannelFuture future); static Peer peerFromChannel(Channel channel); void startBlockChainDownload(PeerEventListener listener); void downloadBlockChain(); MemoryPool getMemoryPool(); void setFastCatchupTimeSecs(long secondsSinceEpoch); long getFastCatchupTimeSecs(); ListenableFuture<PeerGroup> waitForPeers(final int numPeers); int getMinBroadcastConnections(); void setMinBroadcastConnections(int value); ListenableFuture<Transaction> broadcastTransaction(final Transaction tx); ListenableFuture<Transaction> broadcastTransaction(final Transaction tx, final int minConnections); long getPingIntervalMsec(); void setPingIntervalMsec(long pingIntervalMsec); int getMostCommonChainHeight(); Peer getDownloadPeer(); static final long DEFAULT_PING_INTERVAL_MSEC; static final double DEFAULT_BLOOM_FILTER_FP_RATE; }### Answer:
@Test public void singleDownloadPeer1() throws Exception { peerGroup.startAndWait(); FakeChannel p1 = connectPeer(1); FakeChannel p2 = connectPeer(2); assertEquals(2, peerGroup.numConnectedPeers()); Block b1 = TestUtils.createFakeBlock(blockStore).block; blockChain.add(b1); Block b2 = TestUtils.makeSolvedTestBlock(b1); Block b3 = TestUtils.makeSolvedTestBlock(b2); InventoryMessage inv = new InventoryMessage(params); inv.addBlock(b3); inbound(p1, inv); assertTrue(outbound(p1) instanceof GetDataMessage); assertNull(outbound(p2)); closePeer(peerOf(p1)); inbound(p2, inv); assertTrue(outbound(p2) instanceof GetDataMessage); peerGroup.stop(); } |
### Question:
IrcDiscovery implements PeerDiscovery { static ArrayList<InetSocketAddress> parseUserList(String[] userNames) throws UnknownHostException { ArrayList<InetSocketAddress> addresses = new ArrayList<InetSocketAddress>(); for (String user : userNames) { if (!user.startsWith("u")) { continue; } byte[] addressBytes; try { addressBytes = Base58.decodeChecked(user.substring(1)); } catch (AddressFormatException e) { log.warn("IRC nick does not parse as base58: " + user); continue; } if (addressBytes.length != 6) { continue; } byte[] ipBytes = new byte[]{addressBytes[0], addressBytes[1], addressBytes[2], addressBytes[3]}; int port = Utils.readUint16BE(addressBytes, 4); InetAddress ip; try { ip = InetAddress.getByAddress(ipBytes); } catch (UnknownHostException e) { continue; } InetSocketAddress address = new InetSocketAddress(ip, port); addresses.add(address); } return addresses; } IrcDiscovery(String channel); IrcDiscovery(String channel, String server, int port); void shutdown(); InetSocketAddress[] getPeers(long timeoutValue, TimeUnit timeoutUnit); }### Answer:
@Test public void testParseUserList() throws UnknownHostException { String[] userList = new String[]{ "x201500200","u4stwEBjT6FYyVV", "u5BKEqDApa8SbA7"}; ArrayList<InetSocketAddress> addresses = IrcDiscovery.parseUserList(userList); assertEquals("Too many addresses.", 2, addresses.size()); String[] ips = new String[]{"69.4.98.82:8333","74.92.222.129:8333"}; InetSocketAddress[] decoded = addresses.toArray(new InetSocketAddress[]{}); for (int i = 0; i < decoded.length; i++) { String formattedIP = decoded[i].getAddress().getHostAddress() + ":" + ((Integer)decoded[i].getPort()) .toString(); assertEquals("IPs decoded improperly", ips[i], formattedIP); } } |
### Question:
PeerGroup extends AbstractIdleService { public void startBlockChainDownload(PeerEventListener listener) { lock.lock(); try { this.downloadListener = listener; synchronized (peers) { if (!peers.isEmpty()) { startBlockChainDownloadFromPeer(peers.iterator().next()); } } } finally { lock.unlock(); } } PeerGroup(NetworkParameters params); PeerGroup(NetworkParameters params, AbstractBlockChain chain); PeerGroup(NetworkParameters params, AbstractBlockChain chain, ClientBootstrap bootstrap); static ClientBootstrap createClientBootstrap(); void setMaxConnections(int maxConnections); int getMaxConnections(); void setVersionMessage(VersionMessage ver); VersionMessage getVersionMessage(); void setUserAgent(String name, String version, String comments); void setUserAgent(String name, String version); void addEventListener(PeerEventListener listener); boolean removeEventListener(PeerEventListener listener); List<Peer> getConnectedPeers(); List<Peer> getPendingPeers(); void addAddress(PeerAddress peerAddress); void addAddress(InetAddress address); void addPeerDiscovery(PeerDiscovery peerDiscovery); void addWallet(Wallet wallet); void removeWallet(Wallet wallet); void setBloomFilterFalsePositiveRate(double bloomFilterFPRate); int numConnectedPeers(); ChannelFuture connectTo(SocketAddress address); static Peer peerFromChannelFuture(ChannelFuture future); static Peer peerFromChannel(Channel channel); void startBlockChainDownload(PeerEventListener listener); void downloadBlockChain(); MemoryPool getMemoryPool(); void setFastCatchupTimeSecs(long secondsSinceEpoch); long getFastCatchupTimeSecs(); ListenableFuture<PeerGroup> waitForPeers(final int numPeers); int getMinBroadcastConnections(); void setMinBroadcastConnections(int value); ListenableFuture<Transaction> broadcastTransaction(final Transaction tx); ListenableFuture<Transaction> broadcastTransaction(final Transaction tx, final int minConnections); long getPingIntervalMsec(); void setPingIntervalMsec(long pingIntervalMsec); int getMostCommonChainHeight(); Peer getDownloadPeer(); static final long DEFAULT_PING_INTERVAL_MSEC; static final double DEFAULT_BLOOM_FILTER_FP_RATE; }### Answer:
@Test public void singleDownloadPeer2() throws Exception { peerGroup.startAndWait(); FakeChannel p1 = connectPeer(1); Block b1 = TestUtils.createFakeBlock(blockStore).block; Block b2 = TestUtils.makeSolvedTestBlock(b1); Block b3 = TestUtils.makeSolvedTestBlock(b2); peerGroup.startBlockChainDownload(new AbstractPeerEventListener() { }); GetBlocksMessage getblocks = (GetBlocksMessage) outbound(p1); assertEquals(Sha256Hash.ZERO_HASH, getblocks.getStopHash()); InventoryMessage inv = new InventoryMessage(params); inv.addBlock(b1); inv.addBlock(b2); inv.addBlock(b3); inbound(p1, inv); assertTrue(outbound(p1) instanceof GetDataMessage); inbound(p1, b1); FakeChannel p2 = connectPeer(2); Message message = (Message)outbound(p2); assertNull(message == null ? "" : message.toString(), message); peerGroup.stop(); } |
### Question:
ECKey implements Serializable { public void verifyMessage(String message, String signatureBase64) throws SignatureException { ECKey key = ECKey.signedMessageToKey(message, signatureBase64); if (!Arrays.equals(key.getPubKey(), pub)) throw new SignatureException("Signature did not match for message"); } ECKey(); ECKey(BigInteger privKey); ECKey(BigInteger privKey, BigInteger pubKey); ECKey(byte[] privKeyBytes, byte[] pubKey); ECKey(EncryptedPrivateKey encryptedPrivateKey, byte[] pubKey, KeyCrypter keyCrypter); ECKey(BigInteger privKey, byte[] pubKey, boolean compressed); private ECKey(BigInteger privKey, byte[] pubKey); static ECKey fromASN1(byte[] asn1privkey); byte[] toASN1(); static byte[] publicKeyFromPrivate(BigInteger privKey, boolean compressed); byte[] getPubKeyHash(); byte[] getPubKey(); boolean isCompressed(); String toString(); String toStringWithPrivate(); Address toAddress(NetworkParameters params); void clearPrivateKey(); ECDSASignature sign(Sha256Hash input); ECDSASignature sign(Sha256Hash input, KeyParameter aesKey); static boolean verify(byte[] data, byte[] signature, byte[] pub); boolean verify(byte[] data, byte[] signature); String signMessage(String message); String signMessage(String message, KeyParameter aesKey); static ECKey signedMessageToKey(String message, String signatureBase64); void verifyMessage(String message, String signatureBase64); static ECKey recoverFromSignature(int recId, ECDSASignature sig, Sha256Hash message, boolean compressed); byte[] getPrivKeyBytes(); DumpedPrivateKey getPrivateKeyEncoded(NetworkParameters params); long getCreationTimeSeconds(); void setCreationTimeSeconds(long newCreationTimeSeconds); @Override boolean equals(Object o); @Override int hashCode(); ECKey encrypt(KeyCrypter keyCrypter, KeyParameter aesKey); ECKey decrypt(KeyCrypter keyCrypter, KeyParameter aesKey); static boolean encryptionIsReversible(ECKey originalKey, ECKey encryptedKey, KeyCrypter keyCrypter, KeyParameter aesKey); boolean isEncrypted(); EncryptedPrivateKey getEncryptedPrivateKey(); KeyCrypter getKeyCrypter(); }### Answer:
@Test public void verifyMessage() throws Exception { String message = "hello"; String sigBase64 = "HxNZdo6ggZ41hd3mM3gfJRqOQPZYcO8z8qdX2BwmpbF11CaOQV+QiZGGQxaYOncKoNW61oRuSMMF8udfK54XqI8="; Address expectedAddress = new Address(NetworkParameters.prodNet(), "LNmLhahYB2gb3Hf3ZJsGaTyhG3HPDEPXfn"); ECKey key = ECKey.signedMessageToKey(message, sigBase64); Address gotAddress = key.toAddress(NetworkParameters.prodNet()); assertEquals(expectedAddress, gotAddress); } |
### Question:
ECKey implements Serializable { public String toString() { StringBuilder b = new StringBuilder(); b.append("pub:").append(Utils.bytesToHexString(pub)); if (creationTimeSeconds != 0) { b.append(" timestamp:").append(creationTimeSeconds); } if (isEncrypted()) { b.append(" encrypted"); } return b.toString(); } ECKey(); ECKey(BigInteger privKey); ECKey(BigInteger privKey, BigInteger pubKey); ECKey(byte[] privKeyBytes, byte[] pubKey); ECKey(EncryptedPrivateKey encryptedPrivateKey, byte[] pubKey, KeyCrypter keyCrypter); ECKey(BigInteger privKey, byte[] pubKey, boolean compressed); private ECKey(BigInteger privKey, byte[] pubKey); static ECKey fromASN1(byte[] asn1privkey); byte[] toASN1(); static byte[] publicKeyFromPrivate(BigInteger privKey, boolean compressed); byte[] getPubKeyHash(); byte[] getPubKey(); boolean isCompressed(); String toString(); String toStringWithPrivate(); Address toAddress(NetworkParameters params); void clearPrivateKey(); ECDSASignature sign(Sha256Hash input); ECDSASignature sign(Sha256Hash input, KeyParameter aesKey); static boolean verify(byte[] data, byte[] signature, byte[] pub); boolean verify(byte[] data, byte[] signature); String signMessage(String message); String signMessage(String message, KeyParameter aesKey); static ECKey signedMessageToKey(String message, String signatureBase64); void verifyMessage(String message, String signatureBase64); static ECKey recoverFromSignature(int recId, ECDSASignature sig, Sha256Hash message, boolean compressed); byte[] getPrivKeyBytes(); DumpedPrivateKey getPrivateKeyEncoded(NetworkParameters params); long getCreationTimeSeconds(); void setCreationTimeSeconds(long newCreationTimeSeconds); @Override boolean equals(Object o); @Override int hashCode(); ECKey encrypt(KeyCrypter keyCrypter, KeyParameter aesKey); ECKey decrypt(KeyCrypter keyCrypter, KeyParameter aesKey); static boolean encryptionIsReversible(ECKey originalKey, ECKey encryptedKey, KeyCrypter keyCrypter, KeyParameter aesKey); boolean isEncrypted(); EncryptedPrivateKey getEncryptedPrivateKey(); KeyCrypter getKeyCrypter(); }### Answer:
@Test public void testToString() throws Exception { ECKey key = new ECKey(BigInteger.TEN); assertEquals("pub:04a0434d9e47f3c86235477c7b1ae6ae5d3442d49b1943c2b752a68e2a47e247c7893aba425419bc27a3b6c7e693a24c696f794c2ed877a1593cbee53b037368d7", key.toString()); assertEquals("pub:04a0434d9e47f3c86235477c7b1ae6ae5d3442d49b1943c2b752a68e2a47e247c7893aba425419bc27a3b6c7e693a24c696f794c2ed877a1593cbee53b037368d7 priv:0a", key.toStringWithPrivate()); } |
### Question:
Utils { public static BigInteger toNanoCoins(int coins, int cents) { checkArgument(cents < 100); BigInteger bi = BigInteger.valueOf(coins).multiply(COIN); bi = bi.add(BigInteger.valueOf(cents).multiply(CENT)); return bi; } static BigInteger toNanoCoins(int coins, int cents); static byte[] bigIntegerToBytes(BigInteger b, int numBytes); static BigInteger toNanoCoins(String coins); static void uint32ToByteArrayBE(long val, byte[] out, int offset); static void uint32ToByteArrayLE(long val, byte[] out, int offset); static void uint32ToByteStreamLE(long val, OutputStream stream); static void int64ToByteStreamLE(long val, OutputStream stream); static void uint64ToByteStreamLE(BigInteger val, OutputStream stream); static byte[] doubleDigest(byte[] input); static byte[] scryptDigest(byte[] input); static byte[] doubleDigest(byte[] input, int offset, int length); static byte[] singleDigest(byte[] input, int offset, int length); static byte[] doubleDigestTwoBuffers(byte[] input1, int offset1, int length1,
byte[] input2, int offset2, int length2); static boolean isLessThanUnsigned(long n1, long n2); static String bytesToHexString(byte[] bytes); static byte[] reverseBytes(byte[] bytes); static byte[] reverseDwordBytes(byte[] bytes, int trimLength); static long readUint32(byte[] bytes, int offset); static long readInt64(byte[] bytes, int offset); static long readUint32BE(byte[] bytes, int offset); static int readUint16BE(byte[] bytes, int offset); static byte[] sha256hash160(byte[] input); static String litecoinValueToFriendlyString(BigInteger value); static String litecoinValueToPlainString(BigInteger value); static BigInteger decodeCompactBits(long compact); static Date rollMockClock(int seconds); static Date now(); static byte[] copyOf(byte[] in, int length); static byte[] parseAsHexOrBase58(String data); static boolean isWindows(); static byte[] formatMessageForSigning(String message); static boolean checkBitLE(byte[] data, int index); static void setBitLE(byte[] data, int index); static final String LITECOIN_SIGNED_MESSAGE_HEADER; static final BigInteger COIN; static final BigInteger CENT; static volatile Date mockTime; }### Answer:
@Test public void testToNanoCoins() { assertEquals(CENT, toNanoCoins("0.01")); assertEquals(CENT, toNanoCoins("1E-2")); assertEquals(COIN.add(Utils.CENT), toNanoCoins("1.01")); try { toNanoCoins("2E-20"); org.junit.Assert.fail("should not have accepted fractional nanocoins"); } catch (ArithmeticException e) { } assertEquals(CENT, toNanoCoins(0, 1)); assertEquals(COIN.subtract(CENT), toNanoCoins(1, -1)); assertEquals(COIN.negate(), toNanoCoins(-1, 0)); assertEquals(COIN.negate(), toNanoCoins("-1")); } |
### Question:
Utils { public static byte[] reverseBytes(byte[] bytes) { byte[] buf = new byte[bytes.length]; for (int i = 0; i < bytes.length; i++) buf[i] = bytes[bytes.length - 1 - i]; return buf; } static BigInteger toNanoCoins(int coins, int cents); static byte[] bigIntegerToBytes(BigInteger b, int numBytes); static BigInteger toNanoCoins(String coins); static void uint32ToByteArrayBE(long val, byte[] out, int offset); static void uint32ToByteArrayLE(long val, byte[] out, int offset); static void uint32ToByteStreamLE(long val, OutputStream stream); static void int64ToByteStreamLE(long val, OutputStream stream); static void uint64ToByteStreamLE(BigInteger val, OutputStream stream); static byte[] doubleDigest(byte[] input); static byte[] scryptDigest(byte[] input); static byte[] doubleDigest(byte[] input, int offset, int length); static byte[] singleDigest(byte[] input, int offset, int length); static byte[] doubleDigestTwoBuffers(byte[] input1, int offset1, int length1,
byte[] input2, int offset2, int length2); static boolean isLessThanUnsigned(long n1, long n2); static String bytesToHexString(byte[] bytes); static byte[] reverseBytes(byte[] bytes); static byte[] reverseDwordBytes(byte[] bytes, int trimLength); static long readUint32(byte[] bytes, int offset); static long readInt64(byte[] bytes, int offset); static long readUint32BE(byte[] bytes, int offset); static int readUint16BE(byte[] bytes, int offset); static byte[] sha256hash160(byte[] input); static String litecoinValueToFriendlyString(BigInteger value); static String litecoinValueToPlainString(BigInteger value); static BigInteger decodeCompactBits(long compact); static Date rollMockClock(int seconds); static Date now(); static byte[] copyOf(byte[] in, int length); static byte[] parseAsHexOrBase58(String data); static boolean isWindows(); static byte[] formatMessageForSigning(String message); static boolean checkBitLE(byte[] data, int index); static void setBitLE(byte[] data, int index); static final String LITECOIN_SIGNED_MESSAGE_HEADER; static final BigInteger COIN; static final BigInteger CENT; static volatile Date mockTime; }### Answer:
@Test public void testReverseBytes() { Assert.assertArrayEquals(new byte[] {1,2,3,4,5}, Utils.reverseBytes(new byte[] {5,4,3,2,1})); } |
### Question:
Utils { public static byte[] reverseDwordBytes(byte[] bytes, int trimLength) { checkArgument(bytes.length % 4 == 0); checkArgument(trimLength < 0 || trimLength % 4 == 0); byte[] rev = new byte[trimLength >= 0 && bytes.length > trimLength ? trimLength : bytes.length]; for (int i = 0; i < rev.length; i += 4) { System.arraycopy(bytes, i, rev, i , 4); for (int j = 0; j < 4; j++) { rev[i + j] = bytes[i + 3 - j]; } } return rev; } static BigInteger toNanoCoins(int coins, int cents); static byte[] bigIntegerToBytes(BigInteger b, int numBytes); static BigInteger toNanoCoins(String coins); static void uint32ToByteArrayBE(long val, byte[] out, int offset); static void uint32ToByteArrayLE(long val, byte[] out, int offset); static void uint32ToByteStreamLE(long val, OutputStream stream); static void int64ToByteStreamLE(long val, OutputStream stream); static void uint64ToByteStreamLE(BigInteger val, OutputStream stream); static byte[] doubleDigest(byte[] input); static byte[] scryptDigest(byte[] input); static byte[] doubleDigest(byte[] input, int offset, int length); static byte[] singleDigest(byte[] input, int offset, int length); static byte[] doubleDigestTwoBuffers(byte[] input1, int offset1, int length1,
byte[] input2, int offset2, int length2); static boolean isLessThanUnsigned(long n1, long n2); static String bytesToHexString(byte[] bytes); static byte[] reverseBytes(byte[] bytes); static byte[] reverseDwordBytes(byte[] bytes, int trimLength); static long readUint32(byte[] bytes, int offset); static long readInt64(byte[] bytes, int offset); static long readUint32BE(byte[] bytes, int offset); static int readUint16BE(byte[] bytes, int offset); static byte[] sha256hash160(byte[] input); static String litecoinValueToFriendlyString(BigInteger value); static String litecoinValueToPlainString(BigInteger value); static BigInteger decodeCompactBits(long compact); static Date rollMockClock(int seconds); static Date now(); static byte[] copyOf(byte[] in, int length); static byte[] parseAsHexOrBase58(String data); static boolean isWindows(); static byte[] formatMessageForSigning(String message); static boolean checkBitLE(byte[] data, int index); static void setBitLE(byte[] data, int index); static final String LITECOIN_SIGNED_MESSAGE_HEADER; static final BigInteger COIN; static final BigInteger CENT; static volatile Date mockTime; }### Answer:
@Test public void testReverseDwordBytes() { Assert.assertArrayEquals(new byte[] {1,2,3,4,5,6,7,8}, Utils.reverseDwordBytes(new byte[] {4,3,2,1,8,7,6,5}, -1)); Assert.assertArrayEquals(new byte[] {1,2,3,4}, Utils.reverseDwordBytes(new byte[] {4,3,2,1,8,7,6,5}, 4)); Assert.assertArrayEquals(new byte[0], Utils.reverseDwordBytes(new byte[] {4,3,2,1,8,7,6,5}, 0)); Assert.assertArrayEquals(new byte[0], Utils.reverseDwordBytes(new byte[0], 0)); } |
### Question:
LitecoinURI { public String getLabel() { return (String) parameterMap.get(FIELD_LABEL); } LitecoinURI(String uri); LitecoinURI(NetworkParameters params, String input); Address getAddress(); BigInteger getAmount(); String getLabel(); String getMessage(); Object getParameterByName(String name); @Override String toString(); static String convertToLitecoinURI(Address address, BigInteger amount, String label, String message); static String convertToLitecoinURI(String address, BigInteger amount, String label, String message); static final String FIELD_MESSAGE; static final String FIELD_LABEL; static final String FIELD_AMOUNT; static final String FIELD_ADDRESS; static final String LITECOIN_SCHEME; }### Answer:
@Test public void testGood_Label() throws LitecoinURIParseException { testObject = new LitecoinURI(NetworkParameters.prodNet(), LitecoinURI.LITECOIN_SCHEME + ":" + PRODNET_GOOD_ADDRESS + "?label=Hello%20World"); assertEquals("Hello World", testObject.getLabel()); } |
### Question:
LitecoinURI { @Override public String toString() { StringBuilder builder = new StringBuilder("LitecoinURI["); boolean first = true; for (Map.Entry<String, Object> entry : parameterMap.entrySet()) { if (first) { first = false; } else { builder.append(","); } builder.append("'").append(entry.getKey()).append("'=").append("'").append(entry.getValue().toString()).append("'"); } builder.append("]"); return builder.toString(); } LitecoinURI(String uri); LitecoinURI(NetworkParameters params, String input); Address getAddress(); BigInteger getAmount(); String getLabel(); String getMessage(); Object getParameterByName(String name); @Override String toString(); static String convertToLitecoinURI(Address address, BigInteger amount, String label, String message); static String convertToLitecoinURI(String address, BigInteger amount, String label, String message); static final String FIELD_MESSAGE; static final String FIELD_LABEL; static final String FIELD_AMOUNT; static final String FIELD_ADDRESS; static final String LITECOIN_SCHEME; }### Answer:
@Test public void testGood_Combinations() throws LitecoinURIParseException { testObject = new LitecoinURI(NetworkParameters.prodNet(), LitecoinURI.LITECOIN_SCHEME + ":" + PRODNET_GOOD_ADDRESS + "?amount=9876543210&label=Hello%20World&message=Be%20well"); assertEquals( "LitecoinURI['address'='LQz2pJYaeqntA9BFB8rDX5AL2TTKGd5AuN','amount'='987654321000000000','label'='Hello World','message'='Be well']", testObject.toString()); } |
### Question:
CloudNoticeDAO { public List<Recipient> getRecipients() { return mapper.scan(Recipient.class, new DynamoDBScanExpression()); } CloudNoticeDAO(boolean local); List<Recipient> getRecipients(); void saveRecipient(Recipient recip); void deleteRecipient(Recipient recip); void shutdown(); static final String TABLE_NAME; }### Answer:
@Test public void getRecipients() { dao.getRecipients(); } |
### Question:
CloudNoticeDAO { public void deleteRecipient(Recipient recip) { mapper.delete(recip); } CloudNoticeDAO(boolean local); List<Recipient> getRecipients(); void saveRecipient(Recipient recip); void deleteRecipient(Recipient recip); void shutdown(); static final String TABLE_NAME; }### Answer:
@Test public void deleteRecipient() { Recipient recip = new Recipient("SMS", "[email protected]"); dao.saveRecipient(recip); Assert.assertEquals(1, dao.getRecipients().size()); dao.deleteRecipient(recip); Assert.assertEquals(0, dao.getRecipients().size()); } |
### Question:
DateCalculator { public DateCalculatorResult calculate(String text) { final DateCalcExpressionParser parser = new DateCalcExpressionParser(); final Queue<Token> tokens = parser.parse(text); try { if (!tokens.isEmpty()) { if (tokens.peek() instanceof DateToken) { return handleDateExpression(tokens); } else if (tokens.peek() instanceof TimeToken) { return handleTimeExpression(tokens); } } } catch (UnsupportedTemporalTypeException utte) { throw new DateCalcException(utte.getLocalizedMessage()); } throw new DateCalcException("An invalid expression was given: " + text); } DateCalculatorResult calculate(String text); }### Answer:
@Test public void testDateMath() { final String expression = "today + 2 weeks 3 days"; DateCalculatorResult result = dc.calculate(expression); Assert.assertNotNull(result.getDate().get(), "'" + expression + "' should have returned a result."); }
@Test public void testDateDiff() { final String expression = "2016/07/04 - 1776/07/04"; DateCalculatorResult result = dc.calculate(expression); Assert.assertEquals(result.getPeriod().get(), Period.of(240,0,0), "'" + expression + "' should..."); }
@Test public void timeMath() { final String expression = "12:37 + 42 m"; DateCalculatorResult result = dc.calculate(expression); Assert.assertEquals(result.getTime().get(), LocalTime.parse("13:19")); }
@Test public void timeDiff() { final String expression = "12:37 - 7:15"; DateCalculatorResult result = dc.calculate(expression); Assert.assertEquals(result.getDuration().get().toHoursPart(), 5); Assert.assertEquals(result.getDuration().get().toMinutesPart(), 22); } |
### Question:
Book { public void addAuthor(Author author) { authors.add(createAuthorRef(author)); } void addAuthor(Author author); }### Answer:
@Test public void booksAndAuthors() { Author author = new Author(); author.name = "Greg L. Turnquist"; author = authorRepo.save(author); Book book = new Book(); book.title = "Spring Boot"; book.addAuthor(author); bookRepo.save(book); bookRepo.deleteAll(); assertThat(authorRepo.count()).isEqualTo(1); } |
### Question:
EnumeratedBerDecoder implements BerDecoder { @Override public Value decode( @NotNull ReaderContext context ) throws IOException, Asn1Exception { assert context.getType().getFamily() == Family.ENUMERATED; return context.getType().optimize( context.getScope(), IntegerBerDecoder.readInteger( context.getReader(), context.getLength() ) ); } @Override Value decode( @NotNull ReaderContext context ); }### Answer:
@Test( expected = AssertionError.class ) public void testDecode_fail_type() throws Exception { Scope scope = CoreModule.getInstance().createScope(); Type type = UniversalType.INTEGER.ref().resolve( scope ); try( AbstractBerReader reader = mock( DefaultBerReader.class ) ) { Tag tag = ( (TagEncoding)type.getEncoding( EncodingInstructions.TAG ) ).toTag( false ); new EnumeratedBerDecoder().decode( new ReaderContext( reader, scope, type, tag, -1, false ) ); fail( "Must fail" ); } } |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.