src_fm_fc_ms_ff
stringlengths
43
86.8k
target
stringlengths
20
276k
NamingUtils { public static String getPartitionAddress(String address, int partition) { Objects.requireNonNull(address); return String.format("%s-%d", address, partition); } static String getPartitionAddress(String address, int partition); static String getQueueName(String address, String group); static String getAnonymousGroupName(); }
@Test public void shouldGetPartitionAddress() { assertThat(NamingUtils.getPartitionAddress("testAddress", 0)).isEqualTo("testAddress-0"); } @Test(expected = NullPointerException.class) public void shouldNotAcceptNullAddressToGetPartitionAddress() { NamingUtils.getPartitionAddress(null, 0); }
ArtemisProducerDestination implements ProducerDestination { @Override public String getNameForPartition(int i) { return getPartitionAddress(name, i); } ArtemisProducerDestination(String name); @Override String getName(); @Override String getNameForPartition(int i); @Override String toString(); }
@Test public void shouldGetNameForPartition() { String name = "test-name"; ArtemisProducerDestination destination = new ArtemisProducerDestination(name); assertThat(destination.getNameForPartition(0)).isEqualTo(getPartitionAddress(name, 0)); }
ArtemisConsumerDestination implements ConsumerDestination { @Override public String getName() { return name; } ArtemisConsumerDestination(String name); @Override String getName(); @Override String toString(); }
@Test public void shouldGetName() { String name = "test-name"; ArtemisConsumerDestination destination = new ArtemisConsumerDestination(name); assertThat(destination.getName()).isEqualTo(name); }
ArtemisBrokerManager { public void createAddress(String name, ArtemisCommonProperties properties) { logger.debug("Creating address '{}'", name); SimpleString nameString = SimpleString.toSimpleString(name); try (ClientSessionFactory sessionFactory = serverLocator.createSessionFactory(); ClientSession session = getClientSession(sessionFactory)) { session.start(); if (!session.addressQuery(nameString).isExists()) { session.createAddress(nameString, RoutingType.MULTICAST, true); if (properties.isModifyAddressSettings()) { configureAddress(session, name, properties); } } else { logger.debug("Address '{}' already exists, ignoring", name); } session.stop(); } catch (Exception e) { throw new ProvisioningException(String.format("Failed to create address '%s'", name), e); } } ArtemisBrokerManager(ServerLocator serverLocator, String username, String password); void createAddress(String name, ArtemisCommonProperties properties); void createQueue(String address, String name); }
@Test public void shouldCreateAddress() throws Exception { ArtemisBrokerManager manager = new ArtemisBrokerManager(mockServerLocator, null, null); manager.createAddress(address.toString(), artemisCommonProperties); verify(mockServerLocator).createSessionFactory(); verify(mockClientSessionFactory).createSession(); verify(mockClientSession).start(); verify(mockClientSession).createAddress(address, MULTICAST, true); verify(mockClientSession).stop(); verify(mockClientSession, times(0)).queueQuery(any(SimpleString.class)); verify(mockClientSession, times(0)).createMessage(anyBoolean()); } @Test public void shouldCreateAddressWithCredentials() throws Exception { given(mockServerLocator.isPreAcknowledge()).willReturn(true); given(mockServerLocator.getAckBatchSize()).willReturn(1); ArtemisBrokerManager manager = new ArtemisBrokerManager(mockServerLocator, "user", "pass"); manager.createAddress(address.toString(), artemisCommonProperties); verify(mockServerLocator).createSessionFactory(); verify(mockClientSessionFactory).createSession("user", "pass", true, false, false, true, 1); verify(mockClientSession).start(); verify(mockClientSession).createAddress(address, MULTICAST, true); verify(mockClientSession).stop(); verify(mockClientSession, times(0)).queueQuery(any(SimpleString.class)); verify(mockClientSession, times(0)).createMessage(anyBoolean()); } @Test public void shouldNotCreateAddressIfOneExists() throws Exception { given(mockAddressQuery.isExists()).willReturn(true); ArtemisBrokerManager manager = new ArtemisBrokerManager(mockServerLocator, null, null); manager.createAddress(address.toString(), artemisCommonProperties); verify(mockServerLocator).createSessionFactory(); verify(mockClientSessionFactory).createSession(); verify(mockClientSession).start(); verify(mockClientSession).stop(); verify(mockClientSession, times(0)).createAddress(any(), any(RoutingType.class), anyBoolean()); verify(mockClientSession, times(0)).queueQuery(any(SimpleString.class)); verify(mockClientSession, times(0)).createMessage(anyBoolean()); } @Test public void shouldFailToCreateAddress() throws Exception { given(mockServerLocator.createSessionFactory()).willThrow(new RuntimeException("test")); ArtemisBrokerManager manager = new ArtemisBrokerManager(mockServerLocator, null, null); try { manager.createAddress(address.toString(), artemisCommonProperties); fail("Provisioning exception was expected"); } catch (ProvisioningException e) { String message = String.format("Failed to create address '%s'", address); assertThat(e.getMessage()).contains(message); } }
ArtemisBrokerManager { public void createQueue(String address, String name) { try (ClientSessionFactory sessionFactory = serverLocator.createSessionFactory(); ClientSession session = getClientSession(sessionFactory)) { createQueueInternal(session, address, name); } catch (ProvisioningException e) { throw e; } catch (Exception e) { throw new ProvisioningException( String.format("Failed to create queue '%s' with address '%s'", name, address), e); } } ArtemisBrokerManager(ServerLocator serverLocator, String username, String password); void createAddress(String name, ArtemisCommonProperties properties); void createQueue(String address, String name); }
@Test public void shouldCreateQueue() throws Exception { ArtemisBrokerManager manager = new ArtemisBrokerManager(mockServerLocator, null, null); manager.createQueue(address.toString(), queue.toString()); verify(mockServerLocator).createSessionFactory(); verify(mockClientSessionFactory).createSession(); verify(mockClientSession).createSharedQueue(address, MULTICAST, queue, true); } @Test public void shouldCreateQueueWithCredentials() throws Exception { given(mockServerLocator.isPreAcknowledge()).willReturn(true); given(mockServerLocator.getAckBatchSize()).willReturn(1); ArtemisBrokerManager manager = new ArtemisBrokerManager(mockServerLocator, "user", "pass"); manager.createQueue(address.toString(), queue.toString()); verify(mockServerLocator).createSessionFactory(); verify(mockClientSessionFactory).createSession("user", "pass", true, false, false, true, 1); verify(mockClientSession).createSharedQueue(address, MULTICAST, queue, true); } @Test public void shouldNotCreateQueueIfOneAlreadyExists() throws Exception { given(mockQueueQuery.getAddress()).willReturn(address); given(mockQueueQuery.isExists()).willReturn(true); ArtemisBrokerManager manager = new ArtemisBrokerManager(mockServerLocator, null, null); manager.createQueue(address.toString(), queue.toString()); verify(mockServerLocator).createSessionFactory(); verify(mockClientSessionFactory).createSession(); verify(mockClientSession, times(0)).createSharedQueue(any(), any(RoutingType.class), any(), anyBoolean()); } @Test public void shouldFailToCreateQueue() throws Exception { given(mockServerLocator.createSessionFactory()).willThrow(new RuntimeException("test")); ArtemisBrokerManager manager = new ArtemisBrokerManager(mockServerLocator, null, null); try { manager.createQueue(address.toString(), queue.toString()); fail("Provisioning exception was expected"); } catch (ProvisioningException e) { String message = String.format("Failed to create queue '%s' with address '%s'", queue, address); assertThat(e.getMessage()).contains(message); } } @Test public void shouldFailToCreateQueueIfOneAlreadyExistsUnderAnotherAddress() { SimpleString anotherAddress = toSimpleString("another-address-name"); given(mockQueueQuery.getAddress()).willReturn(anotherAddress); given(mockQueueQuery.isExists()).willReturn(true); ArtemisBrokerManager manager = new ArtemisBrokerManager(mockServerLocator, null, null); try { manager.createQueue(address.toString(), queue.toString()); fail("Provisioning exception was expected"); } catch (ProvisioningException e) { String message = String.format( "Failed to create queue '%s' with address '%s'. Queue already exists under another address '%s'", queue, address, anotherAddress); assertThat(e.getMessage()).contains(message); } }
ArtemisProvisioningProvider implements ProvisioningProvider< ExtendedConsumerProperties<ArtemisConsumerProperties>, ExtendedProducerProperties<ArtemisProducerProperties>> { @Override public ProducerDestination provisionProducerDestination(String address, ExtendedProducerProperties<ArtemisProducerProperties> properties) throws ProvisioningException { if (properties.isPartitioned()) { return provisionPartitionedProducerDestination(address, properties); } return provisionUnpartitionedProducerDestination(address, properties); } ArtemisProvisioningProvider(ArtemisBrokerManager artemisBrokerManager); @Override ProducerDestination provisionProducerDestination(String address, ExtendedProducerProperties<ArtemisProducerProperties> properties); @Override ConsumerDestination provisionConsumerDestination(String address, String group, ExtendedConsumerProperties<ArtemisConsumerProperties> properties); }
@Test public void shouldProvisionUnpartitionedProducer() { ProducerDestination destination = provider.provisionProducerDestination(address, mockProducerProperties); assertThat(destination).isInstanceOf(ArtemisProducerDestination.class); assertThat(destination.getName()).isEqualTo(address); verify(mockArtemisBrokerManager).createAddress(address, mockArtemisProducerProperties); verify(mockArtemisBrokerManager, times(0)).createQueue(anyString(), anyString()); } @Test public void shouldProvisionUnpartitionedProducerWithRequiredGroups() { given(mockProducerProperties.getRequiredGroups()).willReturn(groups); ProducerDestination destination = provider.provisionProducerDestination(address, mockProducerProperties); assertThat(destination).isInstanceOf(ArtemisProducerDestination.class); assertThat(destination.getName()).isEqualTo(address); verify(mockArtemisBrokerManager).createAddress(address, mockArtemisProducerProperties); verify(mockArtemisBrokerManager).createQueue(address, getQueueName(address, groups[0])); verify(mockArtemisBrokerManager).createQueue(address, getQueueName(address, groups[1])); } @Test public void shouldProvisionPartitionedProducer() { String partitionedAddress0 = String.format("%s-0", address); String partitionedAddress1 = String.format("%s-1", address); given(mockProducerProperties.isPartitioned()).willReturn(true); given(mockProducerProperties.getPartitionCount()).willReturn(2); ProducerDestination destination = provider.provisionProducerDestination(address, mockProducerProperties); assertThat(destination).isInstanceOf(ArtemisProducerDestination.class); assertThat(destination.getNameForPartition(0)).isEqualTo(partitionedAddress0); assertThat(destination.getNameForPartition(1)).isEqualTo(partitionedAddress1); verify(mockArtemisBrokerManager).createAddress(partitionedAddress0, mockArtemisProducerProperties); verify(mockArtemisBrokerManager).createAddress(partitionedAddress1, mockArtemisProducerProperties); verify(mockArtemisBrokerManager, times(0)).createQueue(anyString(), anyString()); } @Test public void shouldProvisionPartitionedProducerWithRequiredGroups() { String partitionedAddress0 = String.format("%s-0", address); String partitionedAddress1 = String.format("%s-1", address); given(mockProducerProperties.getRequiredGroups()).willReturn(groups); given(mockProducerProperties.isPartitioned()).willReturn(true); given(mockProducerProperties.getPartitionCount()).willReturn(2); ProducerDestination destination = provider.provisionProducerDestination(address, mockProducerProperties); assertThat(destination).isInstanceOf(ArtemisProducerDestination.class); assertThat(destination.getNameForPartition(0)).isEqualTo(partitionedAddress0); assertThat(destination.getNameForPartition(1)).isEqualTo(partitionedAddress1); verify(mockArtemisBrokerManager).createAddress(partitionedAddress0, mockArtemisProducerProperties); verify(mockArtemisBrokerManager).createAddress(partitionedAddress1, mockArtemisProducerProperties); verify(mockArtemisBrokerManager).createQueue(partitionedAddress0, getQueueName(partitionedAddress0, groups[0])); verify(mockArtemisBrokerManager).createQueue(partitionedAddress0, getQueueName(partitionedAddress0, groups[1])); verify(mockArtemisBrokerManager).createQueue(partitionedAddress1, getQueueName(partitionedAddress1, groups[0])); verify(mockArtemisBrokerManager).createQueue(partitionedAddress1, getQueueName(partitionedAddress1, groups[1])); }
ArtemisProvisioningProvider implements ProvisioningProvider< ExtendedConsumerProperties<ArtemisConsumerProperties>, ExtendedProducerProperties<ArtemisProducerProperties>> { @Override public ConsumerDestination provisionConsumerDestination(String address, String group, ExtendedConsumerProperties<ArtemisConsumerProperties> properties) throws ProvisioningException { ArtemisConsumerDestination destination; if (properties.isPartitioned()) { logger.debug("Provisioning partitioned consumer destination with address '{}' and instance index '{}'", address, properties.getInstanceIndex()); destination = new ArtemisConsumerDestination(getPartitionAddress(address, properties.getInstanceIndex())); } else { logger.debug("Provisioning unpartitioned consumer destination with address '{}'", address); destination = new ArtemisConsumerDestination(address); } artemisBrokerManager.createAddress(destination.getName(), properties.getExtension()); return destination; } ArtemisProvisioningProvider(ArtemisBrokerManager artemisBrokerManager); @Override ProducerDestination provisionProducerDestination(String address, ExtendedProducerProperties<ArtemisProducerProperties> properties); @Override ConsumerDestination provisionConsumerDestination(String address, String group, ExtendedConsumerProperties<ArtemisConsumerProperties> properties); }
@Test public void shouldProvisionUnpartitionedConsumer() { ConsumerDestination destination = provider.provisionConsumerDestination(address, null, mockConsumerProperties); assertThat(destination).isInstanceOf(ArtemisConsumerDestination.class); assertThat(destination.getName()).isEqualTo(address); verify(mockArtemisBrokerManager).createAddress(address, mockArtemisConsumerProperties); } @Test public void shouldProvisionPartitionedConsumer() { given(mockConsumerProperties.isPartitioned()).willReturn(true); given(mockConsumerProperties.getInstanceIndex()).willReturn(0); ConsumerDestination destination = provider.provisionConsumerDestination(address, null, mockConsumerProperties); String partitionedAddress = String.format("%s-0", address); assertThat(destination).isInstanceOf(ArtemisConsumerDestination.class); assertThat(destination.getName()).isEqualTo(partitionedAddress); verify(mockArtemisBrokerManager).createAddress(partitionedAddress, mockArtemisConsumerProperties); }
ListenerContainerFactory { public AbstractMessageListenerContainer getListenerContainer(String topic, String subscriptionName) { DefaultMessageListenerContainer listenerContainer = new DefaultMessageListenerContainer(); listenerContainer.setConnectionFactory(connectionFactory); listenerContainer.setPubSubDomain(true); listenerContainer.setDestinationName(topic); listenerContainer.setSubscriptionName(subscriptionName); listenerContainer.setSessionTransacted(true); listenerContainer.setSubscriptionDurable(true); listenerContainer.setSubscriptionShared(true); return listenerContainer; } ListenerContainerFactory(ConnectionFactory connectionFactory); AbstractMessageListenerContainer getListenerContainer(String topic, String subscriptionName); }
@Test public void shouldGetListenerContainer() { ListenerContainerFactory factory = new ListenerContainerFactory(mockConnectionFactory); AbstractMessageListenerContainer container = factory.getListenerContainer("testTopic", "testSubscription"); assertThat(container.getConnectionFactory()).isEqualTo(mockConnectionFactory); assertThat(container.getDestinationName()).isEqualTo("testTopic"); assertThat(container.isPubSubDomain()).isTrue(); assertThat(container.getSubscriptionName()).isEqualTo("testSubscription"); assertThat(container.isSessionTransacted()).isTrue(); assertThat(container.isSubscriptionDurable()).isTrue(); assertThat(container.isSubscriptionShared()).isTrue(); }
NamingUtils { public static String getQueueName(String address, String group) { Objects.requireNonNull(address); Objects.requireNonNull(group); return String.format("%s-%s", address, group); } static String getPartitionAddress(String address, int partition); static String getQueueName(String address, String group); static String getAnonymousGroupName(); }
@Test public void shouldGetQueueName() { assertThat(NamingUtils.getQueueName("testAddress", "testGroup")).isEqualTo("testAddress-testGroup"); } @Test(expected = NullPointerException.class) public void shouldNotAcceptNullAddressToGetQueueName() { NamingUtils.getQueueName(null, "testGroup"); } @Test(expected = NullPointerException.class) public void shouldNotAcceptNullGroupToGetQueueName() { NamingUtils.getQueueName("testAddress", null); }
NamingUtils { public static String getAnonymousGroupName() { UUID uuid = UUID.randomUUID(); ByteBuffer buffer = ByteBuffer.wrap(new byte[16]); buffer.putLong(uuid.getMostSignificantBits()) .putLong(uuid.getLeastSignificantBits()); return "anonymous-" + Base64Utils.encodeToUrlSafeString(buffer.array()) .replaceAll("=", ""); } static String getPartitionAddress(String address, int partition); static String getQueueName(String address, String group); static String getAnonymousGroupName(); }
@Test public void shouldGetAnonymousQueueName() { assertThat(NamingUtils.getAnonymousGroupName()).hasSize(32) .startsWith("anonymous-"); }
ArtemisMessageChannelBinder extends AbstractMessageChannelBinder<ExtendedConsumerProperties<ArtemisConsumerProperties>, ExtendedProducerProperties<ArtemisProducerProperties>, ArtemisProvisioningProvider> implements ExtendedPropertiesBinder<MessageChannel, ArtemisConsumerProperties, ArtemisProducerProperties> { @Override protected MessageHandler createProducerMessageHandler(ProducerDestination destination, ExtendedProducerProperties<ArtemisProducerProperties> properties, MessageChannel errorChannel) { logger.debug("Creating producer message handler for '" + destination + "'"); JmsSendingMessageHandler handler = Jms.outboundAdapter(connectionFactory) .destination(message -> getMessageDestination(message, destination)) .configureJmsTemplate(templateSpec -> templateSpec.pubSubDomain(true)) .get(); handler.setApplicationContext(getApplicationContext()); handler.setBeanFactory(getBeanFactory()); return handler; } ArtemisMessageChannelBinder(ArtemisProvisioningProvider provisioningProvider, ConnectionFactory connectionFactory, ArtemisExtendedBindingProperties bindingProperties); @Override ArtemisConsumerProperties getExtendedConsumerProperties(String channelName); @Override ArtemisProducerProperties getExtendedProducerProperties(String channelName); @Override String getDefaultsPrefix(); @Override Class<? extends BinderSpecificPropertiesProvider> getExtendedPropertiesEntryClass(); }
@Test public void shouldCreateProducerMessageHandler() { MessageHandler handler = binder.createProducerMessageHandler(null, null, null); assertThat(handler).isInstanceOf(JmsSendingMessageHandler.class); }
ArtemisMessageChannelBinder extends AbstractMessageChannelBinder<ExtendedConsumerProperties<ArtemisConsumerProperties>, ExtendedProducerProperties<ArtemisProducerProperties>, ArtemisProvisioningProvider> implements ExtendedPropertiesBinder<MessageChannel, ArtemisConsumerProperties, ArtemisProducerProperties> { @Override protected MessageProducer createConsumerEndpoint(ConsumerDestination destination, String group, ExtendedConsumerProperties<ArtemisConsumerProperties> properties) { logger.debug("Creating consumer endpoint for '{" + destination + "}' with a group '{" + group + "}'"); if (!StringUtils.hasText(group)) { group = getAnonymousGroupName(); } String subscriptionName = getQueueName(destination.getName(), group); ListenerContainerFactory listenerContainerFactory = new ListenerContainerFactory(connectionFactory); AbstractMessageListenerContainer listenerContainer = listenerContainerFactory .getListenerContainer(destination.getName(), subscriptionName); if (properties.getMaxAttempts() == 1) { return Jms.messageDrivenChannelAdapter(listenerContainer).get(); } RetryTemplate retryTemplate = buildRetryTemplate(properties); ErrorInfrastructure errorInfrastructure = registerErrorInfrastructure(destination, group, properties); RetryableChannelPublishingJmsMessageListener listener = new RetryableChannelPublishingJmsMessageListener(retryTemplate, errorInfrastructure.getRecoverer()); listener.setExpectReply(false); return new JmsMessageDrivenEndpoint(listenerContainer, listener); } ArtemisMessageChannelBinder(ArtemisProvisioningProvider provisioningProvider, ConnectionFactory connectionFactory, ArtemisExtendedBindingProperties bindingProperties); @Override ArtemisConsumerProperties getExtendedConsumerProperties(String channelName); @Override ArtemisProducerProperties getExtendedProducerProperties(String channelName); @Override String getDefaultsPrefix(); @Override Class<? extends BinderSpecificPropertiesProvider> getExtendedPropertiesEntryClass(); }
@Test public void shouldCreateRegularConsumerEndpoint() { given(mockConsumerProperties.getMaxAttempts()).willReturn(1); ArtemisConsumerDestination destination = new ArtemisConsumerDestination("test-destination"); MessageProducer producer = binder.createConsumerEndpoint(destination, "test-group", mockConsumerProperties); assertThat(producer).isInstanceOf(JmsMessageDrivenEndpoint.class); JmsMessageDrivenEndpoint endpoint = (JmsMessageDrivenEndpoint) producer; assertThat(endpoint.getListener()).isNotInstanceOf(RetryableChannelPublishingJmsMessageListener.class); } @Test public void shouldCreateRetryableConsumerEndpoint() { given(mockConsumerProperties.getMaxAttempts()).willReturn(2); ArtemisConsumerDestination destination = new ArtemisConsumerDestination("test-destination"); MessageProducer producer = binder.createConsumerEndpoint(destination, "test-group", mockConsumerProperties); assertThat(producer).isInstanceOf(JmsMessageDrivenEndpoint.class); ChannelPublishingJmsMessageListener listener = ((JmsMessageDrivenEndpoint) producer).getListener(); assertThat(listener).isInstanceOf(RetryableChannelPublishingJmsMessageListener.class); assertThat(listener.getComponentType()).isEqualTo("jms:message-driven-channel-adapter"); }
ArtemisProducerDestination implements ProducerDestination { @Override public String getName() { return name; } ArtemisProducerDestination(String name); @Override String getName(); @Override String getNameForPartition(int i); @Override String toString(); }
@Test public void shouldGetName() { String name = "test-name"; ArtemisProducerDestination destination = new ArtemisProducerDestination(name); assertThat(destination.getName()).isEqualTo(name); }
Scorer { public static Map<String, Integer> readLabelsFromFile(File file) throws IOException { FileInputStream inputStream = new FileInputStream(file); List<String> lines = IOUtils.readLines(inputStream, UTF8); IOUtils.closeQuietly(inputStream); Map<String, Integer> result = new TreeMap<>(); for (int i = 0; i < lines.size(); i++) { String line = lines.get(i); if (!line.trim().isEmpty() && !line.trim().startsWith("#")) { String[] split = line.split("\\s+"); if (split.length != 2) { throw new IllegalArgumentException("Error on line " + (i + 1) + ", expected two whitespace-delimited entries but got '" + line + "' (file " + file.getAbsolutePath() + ")"); } String id = split[0].trim(); int value; try { value = Integer.valueOf(split[1]); } catch (NumberFormatException e) { throw new IllegalArgumentException("Error on line " + (i + 1) + ", expected an integer but got '" + split[1] + "' (file " + file.getAbsolutePath() + ")"); } if (!(value == 0 || value == 1)) { throw new IllegalArgumentException("Error on line " + (i + 1) + ", expected 0 or 1 but got '" + split[1] + "' (file " + file.getAbsolutePath() + ")"); } result.put(id, value); } } return result; } static Map<String, Integer> readLabelsFromFile(File file); static double computeAccuracy(Map<String, Integer> gold, Map<String, Integer> predictions); static void main(String[] args); }
@Test public void readLabelsFromFile1() throws Exception { Scorer.readLabelsFromFile(getFileFromResources("test-gold1.txt")); } @Test public void readLabelsFromFile2() throws Exception { Scorer.readLabelsFromFile(getFileFromResources("test-gold2.txt")); } @Test(expected = IllegalArgumentException.class) public void readLabelsFromFileWrong1() throws Exception { Scorer.readLabelsFromFile(getFileFromResources("test-wrong1.txt")); } @Test(expected = IllegalArgumentException.class) public void readLabelsFromFileWrong2() throws Exception { Scorer.readLabelsFromFile(getFileFromResources("test-wrong2.txt")); } @Test(expected = IllegalArgumentException.class) public void readLabelsFromFileWrong3() throws Exception { Scorer.readLabelsFromFile(getFileFromResources("test-wrong3.txt")); }
Scorer { public static double computeAccuracy(Map<String, Integer> gold, Map<String, Integer> predictions) throws IllegalArgumentException { if (gold == null) { throw new IllegalArgumentException("Parameter 'gold' is null"); } if (predictions == null) { throw new IllegalArgumentException("Parameter 'predictions' is null"); } if (gold.isEmpty()) { throw new IllegalArgumentException("Parameter 'gold' is an empty map"); } if (predictions.isEmpty()) { throw new IllegalArgumentException("Parameter 'predictions' is an empty map"); } if (!(gold.keySet().containsAll(predictions.keySet()) && predictions.keySet() .containsAll(gold.keySet()))) { throw new IllegalArgumentException( "Gold set and predictions contain different instance IDs"); } Set<String> correctPredictions = new TreeSet<>(); Set<String> wrongPredictions = new TreeSet<>(); for (String id : gold.keySet()) { int goldLabel = gold.get(id); int predictedLabel = predictions.get(id); if (goldLabel == predictedLabel) { correctPredictions.add(id); } else { wrongPredictions.add(id); } } return ((double) correctPredictions.size()) / ((double) correctPredictions.size() + wrongPredictions.size()); } static Map<String, Integer> readLabelsFromFile(File file); static double computeAccuracy(Map<String, Integer> gold, Map<String, Integer> predictions); static void main(String[] args); }
@Test public void computeAccuracy() throws Exception { Map<String, Integer> gold = Scorer .readLabelsFromFile(getFileFromResources("test-gold1.txt")); Map<String, Integer> predictions1 = Scorer .readLabelsFromFile(getFileFromResources("test-predictions1.txt")); assertEquals(0.6, Scorer.computeAccuracy(gold, predictions1), 0.01); Map<String, Integer> predictions2 = Scorer .readLabelsFromFile(getFileFromResources("test-predictions2.txt")); assertEquals(1.0, Scorer.computeAccuracy(gold, predictions2), 0.01); Map<String, Integer> predictions3 = Scorer .readLabelsFromFile(getFileFromResources("test-predictions3.txt")); assertEquals(0.0, Scorer.computeAccuracy(gold, predictions3), 0.01); }
LookupEngine { public String fetchDOI(String input) { Matcher doiMatcher = DOIPattern.matcher(input); while (doiMatcher.find()) { if (doiMatcher.groupCount() == 1) { return doiMatcher.group(1); } } return null; } LookupEngine(); LookupEngine(StorageEnvFactory storageFactory); String retrieveByArticleMetadata(String title, String firstAuthor, Boolean postValidate); void retrieveByArticleMetadataAsync(String title, String firstAuthor, Boolean postValidate, Consumer<MatchingDocument> callback); String retrieveByJournalMetadata(String title, String volume, String firstPage); void retrieveByJournalMetadataAsync(String jtitle, String volume, String firstPage, String atitle, String firstAuthor, Boolean postValidate, Consumer<MatchingDocument> callback); void retrieveByJournalMetadataAsync(String jtitle, String volume, String firstPage, Consumer<MatchingDocument> callback); String retrieveByJournalMetadata(String title, String volume, String firstPage, String firstAuthor); void retrieveByJournalMetadataAsync(String title, String volume, String firstPage, String firstAuthor, Consumer<MatchingDocument> callback); String retrieveByDoi(String doi, Boolean postValidate, String firstAuthor, String atitle); String retrieveByPmid(String pmid, Boolean postValidate, String firstAuthor, String atitle); String retrieveByPmc(String pmc, Boolean postValidate, String firstAuthor, String atitle); String retrieveByIstexid(String istexid, Boolean postValidate, String firstAuthor, String atitle); String retrieveByPii(String pii, Boolean postValidate, String firstAuthor, String atitle); PmidData retrievePMidsByDoi(String doi); PmidData retrievePMidsByPmid(String pmid); PmidData retrievePMidsByPmc(String pmc); IstexData retrieveIstexIdsByDoi(String doi); IstexData retrieveIstexIdsByIstexId(String istexId); String retrieveOAUrlByDoi(String doi); Pair<String,String> retrieveOaIstexUrlByDoi(String doi); String retrieveOAUrlByPmid(String pmid); Pair<String,String> retrieveOaIstexUrlByPmid(String pmid); String retrieveOAUrlByPmc(String pmc); Pair<String,String> retrieveOaIstexUrlByPmc(String pmc); String retrieveOAUrlByPii(String pii); Pair<String,String> retrieveOaIstexUrlByPii(String pii); String retrieveByBiblio(String biblio); void retrieveByBiblioAsync(String biblio, Boolean postValidate, String firstAuthor, String title, Boolean parseReference, Consumer<MatchingDocument> callback); void retrieveByBiblioAsync(String biblio, Consumer<MatchingDocument> callback); String fetchDOI(String input); void setMetadataMatching(MetadataMatching metadataMatching); void setOaDoiLookup(OALookup oaDoiLookup); void setIstexLookup(IstexIdsLookup istexLookup); void setMetadataLookup(MetadataLookup metadataLookup); void setPmidLookup(PMIdsLookup pmidLookup); void setGrobidClient(GrobidClient grobidClient); static Pattern DOIPattern; }
@Test public void getDOI_inInput_shouldWork() { String input = "{\"reference-count\":176,\"publisher\":\"IOP Publishing\",\"issue\":\"4\",\"content-domain\":{\"domain\":[],\"crossmark-restriction\":false},\"short-container-title\":[\"Russ. Chem. Rev.\"],\"published-print\":{\"date-parts\":[[1998,4,30]]},\"DOI\":\"10.1070/rc1998v067n04abeh000372\",\"type\":\"journal-article\",\"created\":{\"date-parts\":[[2002,8,24]],\"date-time\":\"2002-08-24T21:29:52Z\",\"timestamp\":{\"$numberLong\":\"1030224592000\"}},\"page\":\"279-293\",\"source\":\"Crossref\",\"is-referenced-by-count\":24,\"title\":[\"Haloalkenes activated by geminal groups in reactions with N-nucleophiles\"],\"prefix\":\"10.1070\",\"volume\":\"67\",\"author\":[{\"given\":\"Alexander Yu\",\"family\":\"Rulev\",\"sequence\":\"first\",\"affiliation\":[]}],\"member\":\"266\",\"published-online\":{\"date-parts\":[[2007,10,17]]},\"container-title\":[\"Russian Chemical Reviews\"],\"deposited\":{\"date-parts\":[[2017,11,23]],\"date-time\":\"2017-11-23T03:38:45Z\",\"timestamp\":{\"$numberLong\":\"1511408325000\"}},\"score\":1,\"issued\":{\"date-parts\":[[1998,4,30]]},\"references-count\":176,\"journal-issue\":{\"published-print\":{\"date-parts\":[[1998,4,30]]},\"issue\":\"4\"},\"URL\":\"http: String doi = "10.1070/rc1998v067n04abeh000372"; String output = target.fetchDOI(input); assertThat(output, is(doi)); } @Test public void getDOI_notInInput_shouldReturnNull() { String input = "{\"reference-count\":176,\"publisher\":\"IOP Publishing\",\"issue\":\"4\",\"content-domain\":{\"domain\":[],\"crossmark-restriction\":false},\"short-container-title\":[\"Russ. Chem. Rev.\"],\"published-print\":{\"date-parts\":[[1998,4,30]]},\"type\":\"journal-article\",\"created\":{\"date-parts\":[[2002,8,24]],\"date-time\":\"2002-08-24T21:29:52Z\",\"timestamp\":{\"$numberLong\":\"1030224592000\"}},\"page\":\"279-293\",\"source\":\"Crossref\",\"is-referenced-by-count\":24,\"title\":[\"Haloalkenes activated by geminal groups in reactions with N-nucleophiles\"],\"prefix\":\"10.1070\",\"volume\":\"67\",\"author\":[{\"given\":\"Alexander Yu\",\"family\":\"Rulev\",\"sequence\":\"first\",\"affiliation\":[]}],\"member\":\"266\",\"published-online\":{\"date-parts\":[[2007,10,17]]},\"container-title\":[\"Russian Chemical Reviews\"],\"deposited\":{\"date-parts\":[[2017,11,23]],\"date-time\":\"2017-11-23T03:38:45Z\",\"timestamp\":{\"$numberLong\":\"1511408325000\"}},\"score\":1,\"issued\":{\"date-parts\":[[1998,4,30]]},\"references-count\":176,\"journal-issue\":{\"published-print\":{\"date-parts\":[[1998,4,30]]},\"issue\":\"4\"},\"URL\":\"http: String output = target.fetchDOI(input); assertThat(output, is(nullValue())); }
LookupController { protected void getByQuery( String doi, String pmid, String pmc, String pii, String istexid, String firstAuthor, String atitle, final Boolean postValidate, String jtitle, String volume, String firstPage, String biblio, final Boolean parseReference, AsyncResponse asyncResponse ) { boolean areParametersEnoughToLookup = false; StringBuilder messagesSb = new StringBuilder(); if (isNotBlank(doi)) { areParametersEnoughToLookup = true; try { final String response = lookupEngine.retrieveByDoi(doi, postValidate, firstAuthor, atitle); if (isNotBlank(response)) { asyncResponse.resume(response); return; } } catch (NotFoundException e) { messagesSb.append(e.getMessage()); LOGGER.warn("DOI did not matched, move to additional metadata"); } } if (isNotBlank(pmid)) { areParametersEnoughToLookup = true; try { final String response = lookupEngine.retrieveByPmid(pmid, postValidate, firstAuthor, atitle); if (isNotBlank(response)) { asyncResponse.resume(response); return; } } catch (NotFoundException e) { LOGGER.warn("PMID did not matched, move to additional metadata"); } } if (isNotBlank(pmc)) { areParametersEnoughToLookup = true; try { final String response = lookupEngine.retrieveByPmc(pmc, postValidate, firstAuthor, atitle); if (isNotBlank(response)) { asyncResponse.resume(response); return; } } catch (NotFoundException e) { LOGGER.warn("PMC ID did not matched, move to additional metadata"); } } if (isNotBlank(pii)) { areParametersEnoughToLookup = true; try { final String response = lookupEngine.retrieveByPii(pii, postValidate, firstAuthor, atitle); if (isNotBlank(response)) { asyncResponse.resume(response); return; } } catch (NotFoundException e) { LOGGER.warn("PII ID did not matched, move to additional metadata"); } } if (isNotBlank(istexid)) { areParametersEnoughToLookup = true; try { final String response = lookupEngine.retrieveByIstexid(istexid, postValidate, firstAuthor, atitle); if (isNotBlank(response)) { asyncResponse.resume(response); return; } } catch (NotFoundException e) { LOGGER.warn("ISTEX ID did not matched, move to additional metadata"); } } if (isNotBlank(atitle) && isNotBlank(firstAuthor)) { LOGGER.debug("Match with metadata"); lookupEngine.retrieveByArticleMetadataAsync(atitle, firstAuthor, postValidate, matchingDocument -> { if (matchingDocument.isException()) { LOGGER.debug("Error with title/first author, trying to match with journal infos (no first author)"); if (isNotBlank(jtitle) && isNotBlank(volume) && isNotBlank(firstPage)) { lookupEngine.retrieveByJournalMetadataAsync(jtitle, volume, firstPage, atitle, firstAuthor, postValidate, matchingDocumentJournal -> { if (matchingDocumentJournal.isException()) { LOGGER.debug("Error with journal title, trying to match with biblio string"); if (isNotBlank(biblio)) { lookupEngine.retrieveByBiblioAsync(biblio, postValidate, firstAuthor, atitle, parseReference, MatchingDocumentBiblio -> { if (MatchingDocumentBiblio.isException()) { asyncResponse.resume(MatchingDocumentBiblio.getException()); } else { asyncResponse.resume(MatchingDocumentBiblio.getFinalJsonObject()); } }); return; } else { asyncResponse.resume(matchingDocument.getException()); } } else { asyncResponse.resume(matchingDocumentJournal.getFinalJsonObject()); } }); return; } LOGGER.debug("Error with title/first author, trying to match with journal infos (with first author)"); if (isNotBlank(jtitle) && isNotBlank(volume) && isNotBlank(firstPage)) { lookupEngine.retrieveByJournalMetadataAsync(jtitle, volume, firstPage, atitle, firstAuthor, postValidate, matchingDocumentJournal -> { if (matchingDocumentJournal.isException()) { LOGGER.debug("Error with journal info, trying to match with biblio string"); if (isNotBlank(biblio)) { lookupEngine.retrieveByBiblioAsync(biblio, postValidate, firstAuthor, atitle, parseReference, matchingDocumentBiblio -> { if (matchingDocumentBiblio.isException()) { asyncResponse.resume(matchingDocumentBiblio.getException()); } else { asyncResponse.resume(matchingDocumentBiblio.getFinalJsonObject()); } }); return; } else { asyncResponse.resume(matchingDocument.getException()); } } else { asyncResponse.resume(matchingDocumentJournal.getFinalJsonObject()); } }); return; } LOGGER.debug("Error with title/first author, trying to match with biblio string"); if (isNotBlank(biblio)) { lookupEngine.retrieveByBiblioAsync(biblio, postValidate, firstAuthor, atitle, parseReference, matchingDocumentBiblio -> { if (matchingDocumentBiblio.isException()) { asyncResponse.resume(matchingDocumentBiblio.getException()); } else { asyncResponse.resume(matchingDocumentBiblio.getFinalJsonObject()); } }); return; } else { asyncResponse.resume(matchingDocument.getException()); } } else { asyncResponse.resume(matchingDocument.getFinalJsonObject()); } }); return; } if (isNotBlank(jtitle) && isNotBlank(firstAuthor) && isNotBlank(volume) && isNotBlank(firstPage)) { LOGGER.debug("Match with journal title and first page"); lookupEngine.retrieveByJournalMetadataAsync(jtitle, volume, firstPage, atitle, firstAuthor, postValidate, matchingDocument -> { if (matchingDocument.isException()) { if (isNotBlank(biblio)) { lookupEngine.retrieveByBiblioAsync(biblio, postValidate, firstAuthor, atitle, parseReference, matchingDocumentBiblio -> { if (matchingDocumentBiblio.isException()) { asyncResponse.resume(matchingDocumentBiblio.getException()); } else { asyncResponse.resume(matchingDocumentBiblio.getFinalJsonObject()); } }); return; } else { asyncResponse.resume(matchingDocument.getException()); } } else { asyncResponse.resume(matchingDocument.getFinalJsonObject()); } }); return; } if (isNotBlank(jtitle) && isNotBlank(volume) && isNotBlank(firstPage)) { LOGGER.debug("Match with journal title without first author"); lookupEngine.retrieveByJournalMetadataAsync(jtitle, volume, firstPage, atitle, firstAuthor, postValidate, matchingDocument -> { if (matchingDocument.isException()) { if (isNotBlank(biblio)) { lookupEngine.retrieveByBiblioAsync(biblio, postValidate, firstAuthor, atitle, parseReference, matchingDocumentBiblio -> { if (matchingDocumentBiblio.isException()) { asyncResponse.resume(matchingDocumentBiblio.getException()); } else { asyncResponse.resume(matchingDocumentBiblio.getFinalJsonObject()); } }); return; } else { asyncResponse.resume(matchingDocument.getException()); } } else { asyncResponse.resume(matchingDocument.getFinalJsonObject()); } }); return; } if (isNotBlank(biblio)) { LOGGER.debug("Match with biblio string"); lookupEngine.retrieveByBiblioAsync(biblio, postValidate, firstAuthor, atitle, parseReference, matchingDocumentBiblio -> { if (matchingDocumentBiblio.isException()) { asyncResponse.resume(matchingDocumentBiblio.getException()); } else { asyncResponse.resume(matchingDocumentBiblio.getFinalJsonObject()); } }); return; } if (areParametersEnoughToLookup) { throw new ServiceException(404, messagesSb.toString()); } else { throw new ServiceException(400, "The supplied parameters were not sufficient to select the query"); } } protected LookupController(); @Inject LookupController(LookupConfiguration configuration, StorageEnvFactory storageEnvFactory); @GET @Produces(MediaType.APPLICATION_JSON) @Path("/") void getByQueryAsync( @QueryParam("doi") String doi, @QueryParam("pmid") String pmid, @QueryParam("pmc") String pmc, @QueryParam("pii") String pii, @QueryParam("istexid") String istexid, @QueryParam("firstAuthor") String firstAuthor, @QueryParam("atitle") String atitle, @QueryParam("postValidate") Boolean postValidate, @QueryParam("jtitle") String jtitle, @QueryParam("volume") String volume, @QueryParam("firstPage") String firstPage, @QueryParam("biblio") String biblio, @QueryParam("parseReference") Boolean parseReference, @Suspended final AsyncResponse asyncResponse); @GET @Produces(MediaType.APPLICATION_JSON) @Path("/doi/{doi}") String getByDoi(@PathParam("doi") String doi); @GET @Produces(MediaType.APPLICATION_JSON) @Path("/pmid/{pmid}") String getByPmid(@PathParam("pmid") String pmid); @GET @Produces(MediaType.APPLICATION_JSON) @Path("/pii/{pii}") String getByPii(@PathParam("pii") String pii); @GET @Produces(MediaType.APPLICATION_JSON) @Path("/pmc/{pmc}") String getByPmc(@PathParam("pmc") String pmc); @GET @Produces(MediaType.APPLICATION_JSON) @Path("/istexid/{istexid}") String getByIstexid(@PathParam("istexid") String istexid); @POST @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.TEXT_PLAIN) @Path("/") void getByBiblioStringWithPost(String biblio, @Suspended final AsyncResponse asyncResponse); }
@Test public void getByQuery_DOIexists_WithPostvalidation_shouldReturnJSONFromTitleFirstAuthor() { final String myDOI = "myDOI"; final boolean postValidate = true; final String atitle = "atitle"; final String firstAuthor = "firstAuthor"; final String jsonOutput = "{\"DOI\":\"" + myDOI + "\",\"title\":[\"" + atitle + "12312312313\"],\"author\":[{\"given\":\"Alexander Yu\",\"family\":\"" + firstAuthor + "\",\"sequence\":\"first\",\"affiliation\":[]}]}"; final MatchingDocument response = new MatchingDocument(myDOI, jsonOutput); expect(mockMetadataLookup.retrieveByMetadata(myDOI)).andReturn(new MatchingDocument()); mockMetadataMatching.retrieveByMetadataAsync(eq(atitle), eq(firstAuthor), anyObject()); replay(mockMetadataLookup, mockedAsyncResponse, mockPmidsLookup, mockOALookup, mockIstexLookup, mockMetadataMatching); target.getByQuery(myDOI, null, null, null, null, firstAuthor, atitle, postValidate, null, null, null, null, null, mockedAsyncResponse); verify(mockMetadataLookup, mockedAsyncResponse, mockPmidsLookup, mockOALookup, mockIstexLookup, mockMetadataMatching); } @Test public void getByQuery_DOIexists_passingPostValidation_shouldReturnJSONBody() { final String myDOI = "myDOI"; final boolean postValidate = true; final String atitle = "atitle"; final String firstAuthor = "firstAuthor"; final String jsonOutput = "{\"DOI\":\"" + myDOI + "\",\"title\":[\"" + atitle + "\"],\"author\":[{\"given\":\"Alexander Yu\",\"family\":\"" + firstAuthor + "\",\"sequence\":\"first\",\"affiliation\":[]}]}"; final MatchingDocument response = new MatchingDocument(myDOI, jsonOutput); expect(mockMetadataLookup.retrieveByMetadata(myDOI)).andReturn(response); expect(mockIstexLookup.retrieveByDoi(myDOI)).andReturn(null); expect(mockPmidsLookup.retrieveIdsByDoi(myDOI)).andReturn(null); expect(mockOALookup.retrieveOaLinkByDoi(myDOI)).andReturn(null); expect(mockedAsyncResponse.resume(response.getJsonObject())).andReturn(true); replay(mockMetadataLookup, mockedAsyncResponse, mockPmidsLookup, mockOALookup, mockIstexLookup, mockMetadataMatching); target.getByQuery(myDOI, null, null, null, null, firstAuthor, atitle, postValidate, null, null, null, null, null, mockedAsyncResponse); verify(mockMetadataLookup, mockedAsyncResponse, mockPmidsLookup, mockOALookup, mockIstexLookup, mockMetadataMatching); } @Test public void getByQuery_DOIexists_NotPassingPostValidation_shouldReturnJSONFromTitleFirstAuthor() { final String myDOI = "myDOI"; final boolean postValidate = true; final String atitle = "atitle"; final String firstAuthor = "firstAuthor"; final String jsonOutput = "{\"DOI\":\"" + myDOI + "\",\"title\":[\"" + atitle + "12312312313\"],\"author\":[{\"given\":\"Alexander Yu\",\"family\":\"" + firstAuthor + "\",\"sequence\":\"first\",\"affiliation\":[]}]}"; final MatchingDocument response = new MatchingDocument(myDOI, jsonOutput); expect(mockMetadataLookup.retrieveByMetadata(myDOI)).andReturn(response); mockMetadataMatching.retrieveByMetadataAsync(eq(atitle), eq(firstAuthor), anyObject()); replay(mockMetadataLookup, mockedAsyncResponse, mockPmidsLookup, mockOALookup, mockIstexLookup, mockMetadataMatching); target.getByQuery(myDOI, null, null, null, null, firstAuthor, atitle, postValidate, null, null, null, null, null, mockedAsyncResponse); verify(mockMetadataLookup, mockedAsyncResponse, mockPmidsLookup, mockOALookup, mockIstexLookup, mockMetadataMatching); }
GrobidResponseStaxHandler implements StaxParserContentHandler { public GrobidResponse getResponse() { return response; } @Override void onStartDocument(XMLStreamReader2 reader); @Override void onEndDocument(XMLStreamReader2 reader); @Override void onStartElement(XMLStreamReader2 reader); @Override void onEndElement(XMLStreamReader2 reader); @Override void onCharacter(XMLStreamReader2 reader); GrobidResponse getResponse(); }
@Test public void testParsingPublication_shouldWork() throws Exception { InputStream inputStream = this.getClass().getResourceAsStream("/sample.grobid.xml"); XMLStreamReader2 reader = (XMLStreamReader2) inputFactory.createXMLStreamReader(inputStream); StaxUtils.traverse(reader, target); GrobidResponseStaxHandler.GrobidResponse structures = target.getResponse(); assertThat(structures.getAtitle(), is("This si the end of the world")); assertThat(structures.getFirstAuthor(), is("Foppiano")); } @Test public void testParsingPublication2_shouldWork() throws Exception { InputStream inputStream = this.getClass().getResourceAsStream("/sample.grobid-2.xml"); XMLStreamReader2 reader = (XMLStreamReader2) inputFactory.createXMLStreamReader(inputStream); StaxUtils.traverse(reader, target); GrobidResponseStaxHandler.GrobidResponse structures = target.getResponse(); assertThat(structures.getFirstAuthorMonograph(), is("Gupta")); } @Test public void testParsingPublication3_shouldWork() throws Exception { InputStream inputStream = this.getClass().getResourceAsStream("/sample.grobid-3.xml"); XMLStreamReader2 reader = (XMLStreamReader2) inputFactory.createXMLStreamReader(inputStream); StaxUtils.traverse(reader, target); GrobidResponseStaxHandler.GrobidResponse structures = target.getResponse(); assertThat(structures.getAtitle(), is("This si the end of the world")); assertThat(structures.getFirstAuthor(), is("Foppiano")); }
IstexIdsReader { public IstexData fromJson(String inputLine) { try { ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true); mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true); return mapper.readValue(inputLine, IstexData.class); } catch (JsonGenerationException | JsonMappingException e) { LOGGER.error("The input line cannot be processed\n " + inputLine + "\n ", e); } catch (IOException e) { LOGGER.error("Some serious error when deserialize the JSON object: \n" + inputLine, e); } return null; } void load(String input, Consumer<IstexData> closure); void load(InputStream input, Consumer<IstexData> closure); IstexData fromJson(String inputLine); }
@Test public void test() throws Exception { IstexData metadata = target.fromJson("{\"corpusName\":\"bmj\",\"istexId\":\"052DFBD14E0015CA914E28A0A561675D36FFA2CC\",\"ark\":[\"ark:/67375/NVC-W015BZV5-Q\"],\"doi\":[\"10.1136/sti.53.1.56\"],\"pmid\":[\"557360\"],\"pii\":[\"123\"]}"); assertThat(metadata, is(not(nullValue()))); assertThat(metadata.getCorpusName(), is("bmj")); assertThat(metadata.getIstexId(), is("052DFBD14E0015CA914E28A0A561675D36FFA2CC")); assertThat(metadata.getDoi(), hasSize(1)); assertThat(metadata.getDoi().get(0), is("10.1136/sti.53.1.56")); assertThat(metadata.getArk(), hasSize(1)); assertThat(metadata.getArk().get(0), is("ark:/67375/NVC-W015BZV5-Q")); assertThat(metadata.getPmid(), hasSize(1)); assertThat(metadata.getPmid().get(0), is("557360")); assertThat(metadata.getPii(), hasSize(1)); assertThat(metadata.getPii().get(0), is("123")); }
IstexIdsReader { public void load(String input, Consumer<IstexData> closure) { try (Stream<String> stream = Files.lines(Paths.get(input))) { stream.forEach(line -> closure.accept(fromJson(line))); } catch (IOException e) { LOGGER.error("Some serious error when processing the input Istex ID file.", e); } } void load(String input, Consumer<IstexData> closure); void load(InputStream input, Consumer<IstexData> closure); IstexData fromJson(String inputLine); }
@Test public void test3() throws Exception { target.load( new GZIPInputStream(this.getClass().getResourceAsStream("/sample-istex-ids.json.gz")), unpaidWallMetadata -> System.out.println(unpaidWallMetadata.getDoi() )); }
PmidReader { public PmidData fromCSV(String inputLine) { final String[] split = StringUtils.splitPreserveAllTokens(inputLine, ","); if (split.length > 0 && split.length <= 3) { return new PmidData(split[0], split[1], replaceAll(split[2], "\"", "")); } return null; } void load(String input, Consumer<PmidData> closure); void load(InputStream input, Consumer<PmidData> closure); PmidData fromCSV(String inputLine); }
@Test public void test() throws Exception { PmidData metadata = target.fromCSV("9999996,,\"https: assertThat(metadata, is(not(nullValue()))); assertThat(metadata.getDoi(), is ("10.1103/physrevb.44.3678")); assertThat(metadata.getPmid(), is ("9999996")); assertThat(metadata.getPmcid(), is ("")); }
SupplyLocationBulkUploadController { public List<SupplyLocation> uploadFitleredLocations(List<SupplyLocation> locations) { return this.service.saveSupplyLocationsZipContains504(locations); } @Autowired SupplyLocationBulkUploadController(SupplyLocationRepository repository); @Autowired SupplyLocationBulkUploadController(SupplyLocationRepository repository, SupplyLocationService service); @RequestMapping(value = "/bulk/supplyLocations", method = RequestMethod.POST) @ResponseStatus(HttpStatus.CREATED) void upload(@RequestBody List<SupplyLocation> locations); @RequestMapping(value = "/purge", method = RequestMethod.POST) void purge(); List<SupplyLocation> uploadFitleredLocations(List<SupplyLocation> locations); }
@Test public void whenListFiltered_returnSavedList() { List<SupplyLocation> locations = new ArrayList<>(); locations.add(generateSupplyLocations(4, 4, "504")); when(service.saveSupplyLocationsZipContains504(inputLocations)).thenReturn(locations); assertThat(controller.uploadFitleredLocations(inputLocations)).size().isEqualTo(1); assertThat(controller.uploadFitleredLocations(inputLocations).get(0).getZip()).isEqualTo("504"); }
HashtableGenerator extends MapGenerator<Hashtable> { @Override protected boolean okToAdd(Object key, Object value) { return key != null && value != null; } HashtableGenerator(); @Override void addComponentGenerators(List<Generator<?>> newComponents); }
@Test public void disallowsNullKeyAndNullValue() { assertFalse(generator.okToAdd(null, null)); } @Test public void disallowsNullKey() { assertFalse(generator.okToAdd(null, new Object())); } @Test public void disallowsNullValue() { assertFalse(generator.okToAdd(new Object(), null)); } @Test public void allowsKeyAndValueWhenNeitherIsNull() { assertTrue(generator.okToAdd(new Object(), new Object())); }
Items { @SuppressWarnings("unchecked") public static <T> T choose(Collection<T> items, SourceOfRandomness random) { int size = items.size(); if (size == 0) { throw new IllegalArgumentException( "Collection is empty, can't pick an element from it"); } if (items instanceof RandomAccess && items instanceof List<?>) { List<T> list = (List<T>) items; return size == 1 ? list.get(0) : list.get(random.nextInt(size)); } if (size == 1) { return items.iterator().next(); } Object[] array = items.toArray(new Object[0]); return (T) array[random.nextInt(array.length)]; } private Items(); @SuppressWarnings("unchecked") static T choose(Collection<T> items, SourceOfRandomness random); static T chooseWeighted( Collection<Weighted<T>> items, SourceOfRandomness random); }
@Test public void choosingFromEmptyCollection() { thrown.expect(IllegalArgumentException.class); Items.choose(emptyList(), random); } @Test public void choosingFromSet() { Set<String> names = new LinkedHashSet<>(asList("alpha", "bravo", "charlie", "delta")); when(random.nextInt(names.size())).thenReturn(2); assertEquals("charlie", Items.choose(names, random)); }
Items { public static <T> T chooseWeighted( Collection<Weighted<T>> items, SourceOfRandomness random) { if (items.size() == 1) return items.iterator().next().item; int range = items.stream().mapToInt(i -> i.weight).sum(); int sample = random.nextInt(range); int threshold = 0; for (Weighted<T> each : items) { threshold += each.weight; if (sample < threshold) return each.item; } throw new AssertionError( String.format("sample = %d, range = %d", sample, range)); } private Items(); @SuppressWarnings("unchecked") static T choose(Collection<T> items, SourceOfRandomness random); static T chooseWeighted( Collection<Weighted<T>> items, SourceOfRandomness random); }
@Test public void choosingWeightedFromEmptyCollection() { thrown.expect(AssertionError.class); thrown.expectMessage("sample = 0, range = 0"); Items.chooseWeighted(emptyList(), random); } @Test public void singleWeightedItem() { when(random.nextInt(2)).thenReturn(1); assertEquals("a", Items.chooseWeighted(singletonList(first), random)); } @Test public void choosingFirstOfManyWeightedItems() { when(random.nextInt(9)).thenReturn(0).thenReturn(1); assertEquals("a", Items.chooseWeighted(asList(first, second, third), random)); assertEquals("a", Items.chooseWeighted(asList(first, second, third), random)); } @Test public void choosingMiddleOfManyWeightedItems() { when(random.nextInt(9)).thenReturn(2).thenReturn(3).thenReturn(4); assertEquals("b", Items.chooseWeighted(asList(first, second, third), random)); assertEquals("b", Items.chooseWeighted(asList(first, second, third), random)); assertEquals("b", Items.chooseWeighted(asList(first, second, third), random)); } @Test public void choosingLastOfManyWeightedItems() { when(random.nextInt(9)).thenReturn(5).thenReturn(6).thenReturn(7).thenReturn(8); assertEquals("c", Items.chooseWeighted(asList(first, second, third), random)); assertEquals("c", Items.chooseWeighted(asList(first, second, third), random)); assertEquals("c", Items.chooseWeighted(asList(first, second, third), random)); assertEquals("c", Items.chooseWeighted(asList(first, second, third), random)); }
Lists { public static <T> List<List<T>> removeFrom(List<T> target, int howMany) { if (howMany < 0) throw new IllegalArgumentException("Can't remove " + howMany + " elements from a list"); if (howMany == 0) return singletonList(target); if (howMany > target.size()) return emptyList(); List<T> left = target.subList(0, howMany); List<T> right = target.subList(howMany, target.size()); if (right.isEmpty()) return singletonList(emptyList()); List<List<T>> removals = new ArrayList<>(); removals.add(right); removals.addAll(removeFrom(right, howMany) .stream() .map(r -> { List<T> items = new ArrayList<>(left); items.addAll(r); return items; }) .collect(toList())); return removals; } private Lists(); static List<List<T>> removeFrom(List<T> target, int howMany); static List<List<T>> shrinksOfOneItem( SourceOfRandomness random, List<T> target, Shrink<T> shrink); static boolean isDistinct(List<T> target); }
@Test public void rejectsNegativeRemovalCount() { thrown.expect(IllegalArgumentException.class); Lists.removeFrom(newArrayList("abc"), -1); } @Test public void removalsOfZeroElementsFromAList() { List<Integer> target = newArrayList(1, 2, 3); assertEquals(singletonList(target), Lists.removeFrom(target, 0)); } @Test public void removalsFromAnEmptyList() { assertEquals(emptyList(), Lists.removeFrom(emptyList(), 1)); } @Test public void singleRemovalsFromASingletonList() { assertEquals(singletonList(emptyList()), Lists.removeFrom(singletonList('a'), 1)); } @Test public void singleRemovalsFromADoubletonList() { assertEquals( newHashSet(singletonList('a'), singletonList('b')), newHashSet(Lists.removeFrom(newArrayList('a', 'b'), 1))); } @Test public void doubleRemovalsFromADoubletonList() { assertEquals(singletonList(emptyList()), Lists.removeFrom(newArrayList('a', 'b'), 2)); } @Test public void tooManyRemovalsFromADoubletonList() { assertEquals(emptyList(), Lists.removeFrom(newArrayList('a', 'b'), 3)); }
Lists { public static <T> List<List<T>> shrinksOfOneItem( SourceOfRandomness random, List<T> target, Shrink<T> shrink) { if (target.isEmpty()) return new ArrayList<>(); T head = target.get(0); List<T> tail = target.subList(1, target.size()); List<List<T>> shrinks = new ArrayList<>(); shrinks.addAll( shrink.shrink(random, head) .stream() .map(i -> { List<T> items = new ArrayList<>(); items.add(i); items.addAll(tail); return items; }) .collect(toList())); shrinks.addAll( shrinksOfOneItem(random, tail, shrink) .stream() .map(s -> { List<T> items = new ArrayList<>(); items.add(head); items.addAll(s); return items; }) .collect(toList())); return shrinks; } private Lists(); static List<List<T>> removeFrom(List<T> target, int howMany); static List<List<T>> shrinksOfOneItem( SourceOfRandomness random, List<T> target, Shrink<T> shrink); static boolean isDistinct(List<T> target); }
@Test public void shrinksOfEmptyList() { assertEquals(emptyList(), Lists.shrinksOfOneItem(random, emptyList(), null)); } @Test public void shrinksOfNonEmptyList() { List<List<Integer>> shrinks = Lists.shrinksOfOneItem( random, newArrayList(1, 2, 3), (r, i) -> { assumeThat(r, sameInstance(random)); return newArrayList(4, 5); }); assertEquals( newArrayList( newArrayList(4, 2, 3), newArrayList(5, 2, 3), newArrayList(1, 4, 3), newArrayList(1, 5, 3), newArrayList(1, 2, 4), newArrayList(1, 2, 5) ), shrinks); }
Lambdas { public static <T, U> T makeLambda( Class<T> lambdaType, Generator<U> returnValueGenerator, GenerationStatus status) { if (singleAbstractMethodOf(lambdaType) == null) { throw new IllegalArgumentException( lambdaType + " is not a functional interface type"); } return lambdaType.cast( newProxyInstance( lambdaType.getClassLoader(), new Class<?>[] { lambdaType }, new LambdaInvocationHandler<>( lambdaType, returnValueGenerator, status.attempts()))); } private Lambdas(); static T makeLambda( Class<T> lambdaType, Generator<U> returnValueGenerator, GenerationStatus status); }
@Test public void rejectsNonFunctionalInterface() { thrown.expect(IllegalArgumentException.class); thrown.expectMessage(Cloneable.class + " is not a functional interface"); makeLambda(Cloneable.class, new AnInt(), status); } @Test public void invokingDefaultMethodOnFunctionalInterface() { System.out.println(System.getProperty("java.version")); @SuppressWarnings("unchecked") Predicate<Integer> another = makeLambda(Predicate.class, returnValueGenerator, status); boolean firstResult = predicate.test(4); boolean secondResult = another.test(4); assertEquals(firstResult || secondResult, predicate.or(another).test(4)); } @Test public void equalsBasedOnIdentity() { Predicate<?> duplicate = makeLambda(Predicate.class, returnValueGenerator, status); assertEquals(predicate, predicate); assertEquals(duplicate, duplicate); assertNotEquals(predicate, duplicate); assertNotEquals(duplicate, predicate); }
Pair { @Override public String toString() { return String.format("[%s = %s]", first, second); } Pair(F first, S second); @Override int hashCode(); @Override boolean equals(Object o); @Override String toString(); final F first; final S second; }
@Test public void stringifying() { assertEquals("[1 = 2]", new Pair<>(1, 2).toString()); }
Sequences { public static Iterable<BigInteger> halvingIntegral( BigInteger max, BigInteger start) { return () -> new BigIntegerHalvingIterator(start, max); } private Sequences(); static Iterable<BigInteger> halvingIntegral( BigInteger max, BigInteger start); static Iterable<BigDecimal> halvingDecimal( BigDecimal max, BigDecimal start); static Iterable<Integer> halving(int start); }
@Test public void halvingBigIntegers() { assertEquals( newArrayList( BigInteger.valueOf(5), BigInteger.valueOf(7), BigInteger.valueOf(8), BigInteger.valueOf(9)), newArrayList(Sequences.halvingIntegral(BigInteger.TEN, BigInteger.ZERO))); } @Test public void halvingNegativeBigIntegers() { assertEquals( newArrayList( BigInteger.valueOf(-5), BigInteger.valueOf(-7), BigInteger.valueOf(-8), BigInteger.valueOf(-9)), newArrayList(Sequences.halvingIntegral(BigInteger.TEN.negate(), BigInteger.ZERO))); } @Test public void callingNextOutOfSequenceOnHalvingBigIntegers() { Iterator<BigInteger> i = Sequences.halvingIntegral(BigInteger.ZERO, BigInteger.ZERO).iterator(); i.next(); thrown.expect(NoSuchElementException.class); i.next(); }
Sequences { public static Iterable<BigDecimal> halvingDecimal( BigDecimal max, BigDecimal start) { return () -> new BigDecimalHalvingIterator(start, max); } private Sequences(); static Iterable<BigInteger> halvingIntegral( BigInteger max, BigInteger start); static Iterable<BigDecimal> halvingDecimal( BigDecimal max, BigDecimal start); static Iterable<Integer> halving(int start); }
@Test public void halvingBigDecimals() { assertEquals( newArrayList( BigDecimal.valueOf(5), BigDecimal.valueOf(8), BigDecimal.valueOf(9), BigDecimal.TEN), newArrayList(Sequences.halvingDecimal(BigDecimal.TEN, BigDecimal.ZERO))); } @Test public void halvingNegativeBigDecimals() { assertEquals( newArrayList( BigDecimal.valueOf(-5), BigDecimal.valueOf(-8), BigDecimal.valueOf(-9), BigDecimal.TEN.negate()), newArrayList(Sequences.halvingDecimal(BigDecimal.TEN.negate(), BigDecimal.ZERO))); } @Test public void callingNextOutOfSequenceOnHalvingBigDecimals() { Iterator<BigDecimal> i = Sequences.halvingDecimal(BigDecimal.ZERO, BigDecimal.ZERO).iterator(); i.next(); thrown.expect(NoSuchElementException.class); i.next(); }
Sequences { public static Iterable<Integer> halving(int start) { return () -> new IntegerHalvingIterator(start); } private Sequences(); static Iterable<BigInteger> halvingIntegral( BigInteger max, BigInteger start); static Iterable<BigDecimal> halvingDecimal( BigDecimal max, BigDecimal start); static Iterable<Integer> halving(int start); }
@Test public void halvingInts() { assertEquals( newArrayList(27, 13, 6, 3, 1), newArrayList(Sequences.halving(27))); } @Test public void callingNextOutOfSequenceOnHalvingInts() { Iterator<Integer> i = Sequences.halving(0).iterator(); i.next(); thrown.expect(NoSuchElementException.class); i.next(); }
EnumGenerator extends Generator<Enum> { @Override public boolean canShrink(Object larger) { return enumType.isInstance(larger); } EnumGenerator(Class<?> enumType); @Override Enum<?> generate( SourceOfRandomness random, GenerationStatus status); @Override boolean canShrink(Object larger); }
@Test public void capabilityOfShrinkingNonEnum() { assertFalse(generator.canShrink(new Object())); } @Test public void capabilityOfShrinkingEnumOfDesiredType() { assertTrue(generator.canShrink(ElementType.METHOD)); } @Test public void capabilityOfShrinkingEnumOfOtherType() { assertFalse(generator.canShrink(RetentionPolicy.SOURCE)); }
CompositeGenerator extends Generator<Object> { @Override public boolean canShrink(Object larger) { return composed.stream() .map(w -> w.item) .anyMatch(g -> g.canShrink(larger)); } CompositeGenerator(List<Weighted<Generator<?>>> composed); @Override Object generate(SourceOfRandomness random, GenerationStatus status); @Override boolean canShrink(Object larger); @Override List<Object> doShrink(SourceOfRandomness random, Object larger); Generator<?> composed(int index); int numberOfComposedGenerators(); @Override void provide(Generators provided); @Override BigDecimal magnitude(Object value); @Override void configure(AnnotatedType annotatedType); @Override void configure(AnnotatedElement element); @Override void addComponentGenerators(List<Generator<?>> newComponents); }
@Test public void capabilityOfShrinkingDependsOnComponents() { when(first.canShrink(9)).thenReturn(true); when(second.canShrink(9)).thenReturn(false); when(third.canShrink(9)).thenReturn(true); assertTrue(composite.canShrink(9)); } @Test public void capabilityOfShrinkingFalseIfNoComponentsCanShrinkAValue() { when(first.canShrink(8)).thenReturn(false); when(second.canShrink(8)).thenReturn(false); when(third.canShrink(8)).thenReturn(false); assertFalse(composite.canShrink(8)); }
ArrayGenerator extends Generator<Object> { @Override public boolean canShrink(Object larger) { return larger.getClass().getComponentType() == componentType; } ArrayGenerator(Class<?> componentType, Generator<?> component); void configure(Size size); void configure(Distinct distinct); @Override Object generate( SourceOfRandomness random, GenerationStatus status); @Override boolean canShrink(Object larger); @Override List<Object> doShrink(SourceOfRandomness random, Object larger); @Override void provide(Generators provided); @Override BigDecimal magnitude(Object value); @Override void configure(AnnotatedType annotatedType); }
@Test public void capabilityOfShrinkingNonArray() { assertFalse(intArrayGenerator.canShrink(3)); } @Test public void capabilityOfShrinkingArrayOfIdenticalComponentType() { assertTrue(intArrayGenerator.canShrink(new int[0])); } @Test public void capabilityOfShrinkingArrayOfEquivalentWrapperComponentType() { assertFalse(intArrayGenerator.canShrink(new Integer[0])); }
Comparables { public static <T extends Comparable<? super T>> T leastMagnitude( T min, T max, T zero) { if (min == null && max == null) return zero; if (min == null) return max.compareTo(zero) <= 0 ? max : zero; if (max == null) return min.compareTo(zero) >= 0 ? min : zero; if (min.compareTo(zero) > 0) return min; if (max.compareTo(zero) < 0) return max; return zero; } private Comparables(); static Predicate<T> inRange( T min, T max); static T leastMagnitude( T min, T max, T zero); }
@Test public void leastMagnitudeUnbounded() { assertEquals(Integer.valueOf(0), Comparables.leastMagnitude(null, null, 0)); } @Test public void leastMagnitudeNegativeMinOnly() { assertEquals(Integer.valueOf(0), Comparables.leastMagnitude(-3, null, 0)); } @Test public void leastMagnitudePositiveMinOnly() { assertEquals(Integer.valueOf(4), Comparables.leastMagnitude(4, null, 0)); } @Test public void leastMagnitudeNegativeMaxOnly() { assertEquals(Integer.valueOf(-2), Comparables.leastMagnitude(null, -2, 0)); } @Test public void leastMagnitudePositiveMaxOnly() { assertEquals(Integer.valueOf(0), Comparables.leastMagnitude(null, 5, 0)); } @Test public void leastMagnitudeBothLessThanZero() { assertEquals(Integer.valueOf(-1), Comparables.leastMagnitude(-4, -1, 0)); } @Test public void leastMagnitudeBothGreaterThanZero() { assertEquals(Integer.valueOf(5), Comparables.leastMagnitude(5, 7, 0)); } @Test public void leastMagnitudeStraddlingZero() { assertEquals(Integer.valueOf(0), Comparables.leastMagnitude(-2, 4, 0)); }
GeometricDistribution { int sample(double p, SourceOfRandomness random) { ensureProbability(p); if (p == 1) return 0; double uniform = random.nextDouble(); return (int) ceil(log(1 - uniform) / log(1 - p)); } int sampleWithMean(double mean, SourceOfRandomness random); }
@Test public void negativeProbability() { thrown.expect(IllegalArgumentException.class); distro.sample(-ulp(0), random); } @Test public void zeroProbability() { thrown.expect(IllegalArgumentException.class); distro.sample(0, random); } @Test public void greaterThanOneProbability() { thrown.expect(IllegalArgumentException.class); distro.sample(1 + ulp(1), random); } @Test public void sampleWithCertainProbability() { assertEquals(0, distro.sample(1, random)); } @Test public void sampleWithNonCertainProbability() { when(random.nextDouble()).thenReturn(0.88); assertEquals(10, distro.sample(0.2, random)); }
GeometricDistribution { double probabilityOfMean(double mean) { if (mean <= 0) throw new IllegalArgumentException("Need a positive mean, got " + mean); return 1 / mean; } int sampleWithMean(double mean, SourceOfRandomness random); }
@Test public void negativeMeanProbability() { thrown.expect(IllegalArgumentException.class); distro.probabilityOfMean(-ulp(0)); } @Test public void zeroMeanProbability() { thrown.expect(IllegalArgumentException.class); distro.probabilityOfMean(0); } @Test public void nonZeroMeanProbability() { assertEquals(1 / 6D, distro.probabilityOfMean(6), 0); }
GeometricDistribution { public int sampleWithMean(double mean, SourceOfRandomness random) { return sample(probabilityOfMean(mean), random); } int sampleWithMean(double mean, SourceOfRandomness random); }
@Test public void sampleWithMean() { when(random.nextDouble()).thenReturn(0.76); assertEquals(8, distro.sampleWithMean(6, random)); }
Reflection { public static <T> Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes) { try { return type.getConstructor(parameterTypes); } catch (Exception ex) { throw reflectionException(ex); } } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor( Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType( AnnotatedElement e, Class<T> type); static Method findMethod( Class<?> target, String methodName, Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField( Field field, Object target, Object value, boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes( AnnotatedType annotatedType); }
@Test public void findingConstructorQuietly() { Constructor<Integer> ctor = findConstructor(Integer.class, int.class); assertEquals(int.class, ctor.getParameterTypes()[0]); } @Test public void findingConstructorQuietlyWhenNoSuchConstructor() { thrown.expect(ReflectionException.class); thrown.expectMessage(NoSuchMethodException.class.getName()); assertNull(findConstructor(Integer.class, Object.class)); }
Reflection { public static <T> Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes) { try { Constructor<T> ctor = type.getDeclaredConstructor(parameterTypes); ctor.setAccessible(true); return ctor; } catch (Exception ex) { throw reflectionException(ex); } } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor( Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType( AnnotatedElement e, Class<T> type); static Method findMethod( Class<?> target, String methodName, Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField( Field field, Object target, Object value, boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes( AnnotatedType annotatedType); }
@Test public void findingDeclaredConstructorQuietly() { Constructor<Integer> ctor = findDeclaredConstructor(Integer.class, int.class); assertEquals(int.class, ctor.getParameterTypes()[0]); } @Test public void findingDeclaredConstructorQuietlyWhenNoSuchConstructor() { thrown.expect(ReflectionException.class); thrown.expectMessage(NoSuchMethodException.class.getName()); assertNull(findDeclaredConstructor(Integer.class, Object.class)); }
CodePoints { public static CodePoints forCharset(Charset c) { if (ENCODABLES.containsKey(c)) return ENCODABLES.get(c); CodePoints points = load(c); ENCODABLES.put(c, points); return points; } CodePoints(); int at(int index); int size(); boolean contains(int codePoint); static CodePoints forCharset(Charset c); }
@Test public void versusCharsetThatDoesNotSupportEncoding() { Charset noEncoding; try { noEncoding = Charset.forName("ISO-2022-CN"); } catch (UnsupportedCharsetException testNotValid) { return; } thrown.expect(IllegalArgumentException.class); CodePoints.forCharset(noEncoding); }
Reflection { @SuppressWarnings("unchecked") public static <T> Constructor<T> singleAccessibleConstructor( Class<T> type) { Constructor<?>[] constructors = type.getConstructors(); if (constructors.length != 1) { throw new ReflectionException( type + " needs a single accessible constructor"); } return (Constructor<T>) constructors[0]; } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor( Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType( AnnotatedElement e, Class<T> type); static Method findMethod( Class<?> target, String methodName, Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField( Field field, Object target, Object value, boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes( AnnotatedType annotatedType); }
@Test public void findingSingleAccessibleConstructorSuccessfully() { Constructor<Object> ctor = singleAccessibleConstructor(Object.class); assertEquals(0, ctor.getParameterTypes().length); } @Test public void rejectsFindingSingleAccessibleConstructorOnNonConformingClass() { thrown.expect(ReflectionException.class); thrown.expectMessage(Integer.class + " needs a single accessible constructor"); singleAccessibleConstructor(Integer.class); }
Reflection { public static <T> T instantiate(Class<T> clazz) { try { return clazz.newInstance(); } catch (Exception ex) { throw reflectionException(ex); } } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor( Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType( AnnotatedElement e, Class<T> type); static Method findMethod( Class<?> target, String methodName, Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField( Field field, Object target, Object value, boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes( AnnotatedType annotatedType); }
@Test public void invokingZeroArgConstructorQuietlyWrapsInstantiationException() { thrown.expect(ReflectionException.class); thrown.expectMessage(InstantiationException.class.getName()); instantiate(ZeroArgInstantiationProblematic.class); } @Test public void invokingZeroArgConstructorQuietlyWrapsIllegalAccessException() { thrown.expect(ReflectionException.class); thrown.expectMessage(IllegalAccessException.class.getName()); instantiate(ZeroArgIllegalAccessProblematic.class); } @Test public void invokingZeroArgConstructorPropagatesExceptionsRaisedByConstructor() { thrown.expect(IllegalStateException.class); instantiate(InvocationTargetProblematic.class); } @Test public void invokingNonZeroArgConstructorQuietlyWrapsInstantiationException() throws Exception { thrown.expect(ReflectionException.class); thrown.expectMessage(InstantiationException.class.getName()); instantiate(MultiArgInstantiationProblematic.class.getConstructor(int.class), 2); } @Test public void invokingNonZeroArgConstructorQuietlyWrapsIllegalAccessException() throws Exception { thrown.expect(ReflectionException.class); thrown.expectMessage(IllegalAccessException.class.getName()); instantiate(MultiArgIllegalAccessProblematic.class.getDeclaredConstructor(int.class), 2); } @Test public void invokingNonZeroArgConstructorQuietlyPropagatesIllegalArgumentException() throws Exception { thrown.expect(IllegalArgumentException.class); instantiate(Integer.class.getDeclaredConstructor(int.class), "2"); } @Test public void invokingNonZeroArgConstructorWrapsExceptionsRaisedByConstructor() throws Exception { thrown.expect(ReflectionException.class); thrown.expectMessage(IndexOutOfBoundsException.class.getName()); instantiate(InvocationTargetProblematic.class.getConstructor(int.class), 2); }
Reflection { public static Method findMethod( Class<?> target, String methodName, Class<?>... argTypes) { try { return target.getMethod(methodName, argTypes); } catch (Exception ex) { throw reflectionException(ex); } } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor( Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType( AnnotatedElement e, Class<T> type); static Method findMethod( Class<?> target, String methodName, Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField( Field field, Object target, Object value, boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes( AnnotatedType annotatedType); }
@Test public void findingNonExistentMethodQuietlyWrapsNoSuchMethodException() { thrown.expect(ReflectionException.class); thrown.expectMessage(NoSuchMethodException.class.getName()); findMethod(getClass(), "foo"); }
CodePoints { public int at(int index) { if (index < 0) throw new IndexOutOfBoundsException("illegal negative index: " + index); int min = 0; int max = ranges.size() - 1; while (min <= max) { int midpoint = min + ((max - min) / 2); CodePointRange current = ranges.get(midpoint); if (index >= current.previousCount && index < current.previousCount + current.size()) return current.low + index - current.previousCount; else if (index < current.previousCount) max = midpoint - 1; else min = midpoint + 1; } throw new IndexOutOfBoundsException(String.valueOf(index)); } CodePoints(); int at(int index); int size(); boolean contains(int codePoint); static CodePoints forCharset(Charset c); }
@Test public void lowIndex() { thrown.expect(IndexOutOfBoundsException.class); new CodePoints().at(-1); } @Test public void highIndex() { thrown.expect(IndexOutOfBoundsException.class); new CodePoints().at(0); }
Reflection { public static Object invoke(Method method, Object target, Object... args) { try { return method.invoke(target, args); } catch (Exception ex) { throw reflectionException(ex); } } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor( Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType( AnnotatedElement e, Class<T> type); static Method findMethod( Class<?> target, String methodName, Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField( Field field, Object target, Object value, boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes( AnnotatedType annotatedType); }
@Test public void invokingMethodQuietlyWrapsIllegalAccessException() throws Exception { Method method = ZeroArgIllegalAccessProblematic.class.getDeclaredMethod("foo"); thrown.expect(ReflectionException.class); thrown.expectMessage(IllegalAccessException.class.getName()); invoke(method, new ZeroArgIllegalAccessProblematic(0)); }
Reflection { public static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute) { try { return annotationType.getMethod(attribute).getDefaultValue(); } catch (Exception ex) { throw reflectionException(ex); } } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor( Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType( AnnotatedElement e, Class<T> type); static Method findMethod( Class<?> target, String methodName, Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField( Field field, Object target, Object value, boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes( AnnotatedType annotatedType); }
@Test public void findingDefaultValueOfAnnotationAttribute() throws Exception { assertEquals("baz", defaultValueOf(Foo.class, "bar")); } @Test public void missingAnnotationAttribute() throws Exception { thrown.expect(ReflectionException.class); thrown.expectMessage(NoSuchMethodException.class.getName()); defaultValueOf(Foo.class, "noneSuch"); }
Reflection { public static Method singleAbstractMethodOf(Class<?> rawClass) { if (!rawClass.isInterface()) return null; int abstractCount = 0; Method singleAbstractMethod = null; for (Method each : rawClass.getMethods()) { if (isAbstract(each.getModifiers()) && !overridesJavaLangObjectMethod(each)) { singleAbstractMethod = each; ++abstractCount; } } return abstractCount == 1 ? singleAbstractMethod : null; } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor( Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType( AnnotatedElement e, Class<T> type); static Method findMethod( Class<?> target, String methodName, Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField( Field field, Object target, Object value, boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes( AnnotatedType annotatedType); }
@Test public void aClassIsNotASingleAbstractMethodType() { assertNull(singleAbstractMethodOf(String.class)); } @Test public void anInterfaceWithNoMethodsIsNotASingleAbstractMethodType() { assertNull(singleAbstractMethodOf(Serializable.class)); } @Test public void anInterfaceWithASingleAbstractMethodIsASingleAbstractMethodType() throws Exception { assertEquals( Comparator.class.getMethod("compare", Object.class, Object.class), singleAbstractMethodOf(Comparator.class)); } @Test public void anInterfaceThatOverridesEqualsIsNotASingleAbstractMethodType() throws Exception { assertNull(singleAbstractMethodOf(OverridingEquals.class)); } @Test public void anInterfaceThatOverloadsEqualsCanBeASingleAbstractMethodType() throws Exception { assertEquals( OverloadingEquals.class.getMethod("equals", String.class), singleAbstractMethodOf(OverloadingEquals.class)); } @Test public void anInterfaceThatOverloadsEqualsWithMoreThanOneParameterCanBeASingleAbstractMethodType() throws Exception { assertEquals( OverloadingEqualsWithMoreParameters.class.getMethod("equals", Object.class, Object.class), singleAbstractMethodOf(OverloadingEqualsWithMoreParameters.class)); } @Test public void anInterfaceThatOverloadsEqualsWithMixedParameterTypesIsNotASingleAbstractMethodType() throws Exception { assertEquals( OverloadingEqualsWithMixedParameterTypes.class.getMethod("equals", Object.class, String.class, int.class), singleAbstractMethodOf(OverloadingEqualsWithMixedParameterTypes.class)); } @Test public void anInterfaceThatOverridesHashCodeIsNotASingleAbstractMethodType() throws Exception { assertNull(singleAbstractMethodOf(OverridingHashCode.class)); } @Test public void anInterfaceThatOverloadsHashCodeCanBeASingleAbstractMethodType() throws Exception { assertEquals( OverloadingHashCode.class.getMethod("hashCode", Object.class), singleAbstractMethodOf(OverloadingHashCode.class)); } @Test public void anInterfaceThatOverridesToStringIsNotASingleAbstractMethodType() throws Exception { assertNull(singleAbstractMethodOf(OverridingToString.class)); } @Test public void anInterfaceThatOverloadsToStringCanBeASingleAbstractMethodType() throws Exception { assertEquals( OverloadingToString.class.getMethod("toString", Object.class), singleAbstractMethodOf(OverloadingToString.class)); }
Reflection { public static boolean isMarkerInterface(Class<?> clazz) { if (!clazz.isInterface()) return false; return Arrays.stream(clazz.getMethods()) .filter(m -> !m.isDefault()) .noneMatch(m -> !overridesJavaLangObjectMethod(m)); } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor( Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType( AnnotatedElement e, Class<T> type); static Method findMethod( Class<?> target, String methodName, Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField( Field field, Object target, Object value, boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes( AnnotatedType annotatedType); }
@Test public void aClassIsNotAMarkerInterface() { assertFalse(isMarkerInterface(Object.class)); } @Test public void anInterfaceWithAMethodIsNotAMarkerInterface() { assertFalse(isMarkerInterface(NotAMarker.class)); } @Test public void anInterfaceWithNoMethodsButSuperMethodsIsNotAMarkerInterface() { assertFalse(isMarkerInterface(SubNotAMarker.class)); } @Test public void anInterfaceThatOverridesEqualsIsAMarkerInterface() { assertTrue(isMarkerInterface(OverridingEquals.class)); } @Test public void anInterfaceThatOverloadsEqualsIsNotAMarkerInterface() { assertFalse(isMarkerInterface(OverloadingEquals.class)); } @Test public void anInterfaceThatOverloadsEqualsWithMoreThanOneParameterIsNotAMarkerInterface() { assertFalse( isMarkerInterface(OverloadingEqualsWithMoreParameters.class)); } @Test public void anInterfaceThatOverloadsEqualsWithMixedParameterTypesIsNotAMarkerInterface() { assertFalse( isMarkerInterface(OverloadingEqualsWithMixedParameterTypes.class)); } @Test public void anInterfaceThatOverridesHashCodeIsAMarkerInterface() { assertTrue(isMarkerInterface(OverridingHashCode.class)); } @Test public void anInterfaceThatOverloadsHashCodeIsNotAMarkerInterface() { assertFalse(isMarkerInterface(OverloadingHashCode.class)); } @Test public void anInterfaceThatOverridesToStringIsAMarkerInterface() { assertTrue(isMarkerInterface(OverridingToString.class)); } @Test public void anInterfaceThatOverloadsToStringIsNotAMarkerInterface() { assertFalse(isMarkerInterface(OverloadingToString.class)); } @Test public void anInterfaceWithOnlyDefaultMethodsIsAMarkerInterface() { assertTrue(isMarkerInterface(OnlyDefaultMethods.class)); }
CodePoints { public int size() { if (ranges.isEmpty()) return 0; CodePointRange last = ranges.get(ranges.size() - 1); return last.previousCount + last.size(); } CodePoints(); int at(int index); int size(); boolean contains(int codePoint); static CodePoints forCharset(Charset c); }
@Test public void sizeOfEmpty() { assertEquals(0, new CodePoints().size()); }
Reflection { public static void setField( Field field, Object target, Object value, boolean suppressProtection) { doPrivileged((PrivilegedAction<Void>) () -> { field.setAccessible(suppressProtection); return null; }); try { field.set(target, value); } catch (Exception ex) { throw reflectionException(ex); } } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor( Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType( AnnotatedElement e, Class<T> type); static Method findMethod( Class<?> target, String methodName, Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField( Field field, Object target, Object value, boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes( AnnotatedType annotatedType); }
@Test public void settingFieldWithoutBypassingProtection() throws Exception { WithAccessibleField target = new WithAccessibleField(); setField(target.getClass().getField("i"), target, 2, false); assertEquals(2, target.i); } @Test public void settingInaccessibleFieldBypassingProtection() throws Exception { WithInaccessibleField target = new WithInaccessibleField(); setField(target.getClass().getDeclaredField("i"), target, 3, true); assertEquals(3, target.i); } @Test public void settingInaccessibleFieldWithoutBypassingProtection() throws Exception { WithInaccessibleField target = new WithInaccessibleField(); thrown.expect(ReflectionException.class); thrown.expectMessage(IllegalAccessException.class.getName()); setField(target.getClass().getDeclaredField("i"), target, 4, false); }
Reflection { public static List<Field> allDeclaredFieldsOf(Class<?> type) { List<Field> allFields = new ArrayList<>(); for (Class<?> c = type; c != null; c = c.getSuperclass()) Collections.addAll(allFields, c.getDeclaredFields()); List<Field> results = allFields.stream() .filter(f -> !f.isSynthetic()) .collect(toList()); results.forEach(f -> f.setAccessible(true)); return results; } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor( Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType( AnnotatedElement e, Class<T> type); static Method findMethod( Class<?> target, String methodName, Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField( Field field, Object target, Object value, boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes( AnnotatedType annotatedType); }
@Test public void findingAllDeclaredFieldsOnAClass() throws Exception { List<Field> fields = allDeclaredFieldsOf(Child.class); assertEquals(2, fields.size()); assertThat(fields, hasItem(Child.class.getDeclaredField("s"))); assertThat(fields, hasItem(Parent.class.getDeclaredField("i"))); } @Test public void findingAllDeclaredFieldsOnAClassExcludesSynthetics() throws Exception { List<Field> fields = allDeclaredFieldsOf(Outer.Inner.class); assertEquals(1, fields.size()); assertThat(fields, hasItem(Outer.Inner.class.getDeclaredField("s"))); }
VoidGenerator extends Generator<Void> { @Override public Void generate(SourceOfRandomness random, GenerationStatus status) { return null; } @SuppressWarnings("unchecked") VoidGenerator(); @Override Void generate(SourceOfRandomness random, GenerationStatus status); @Override boolean canRegisterAsType(Class<?> type); }
@Test public void canOnlyGenerateNull() { VoidGenerator generator = new VoidGenerator(); Void value = generator.generate(null, null); assertNull(value); }
Reflection { public static Field findField(Class<?> type, String fieldName) { try { return type.getDeclaredField(fieldName); } catch (NoSuchFieldException ex) { throw reflectionException(ex); } } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor( Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType( AnnotatedElement e, Class<T> type); static Method findMethod( Class<?> target, String methodName, Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField( Field field, Object target, Object value, boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes( AnnotatedType annotatedType); }
@Test public void findingField() { Field i = findField(Parent.class, "i"); assertEquals(int.class, i.getType()); } @Test public void findingNonExistentField() { thrown.expect(ReflectionException.class); thrown.expectMessage(NoSuchFieldException.class.getName()); findField(Parent.class, "missing"); }
Ranges { static long findNextPowerOfTwoLong(long positiveLong) { return isPowerOfTwoLong(positiveLong) ? positiveLong : ((long) 1) << (64 - Long.numberOfLeadingZeros(positiveLong)); } private Ranges(); static int checkRange( Type type, T min, T max); static BigInteger choose( SourceOfRandomness random, BigInteger min, BigInteger max); static long choose(SourceOfRandomness random, long min, long max); }
@Test public void checkFindNextPowerOfTwoLong() { assertEquals(1, findNextPowerOfTwoLong(1)); assertEquals(2, findNextPowerOfTwoLong(2)); assertEquals(4, findNextPowerOfTwoLong(3)); assertEquals(4, findNextPowerOfTwoLong(4)); assertEquals(8, findNextPowerOfTwoLong(5)); assertEquals((long) 1 << 61, findNextPowerOfTwoLong((long) 1 << 61)); assertEquals((long) 1 << 62, findNextPowerOfTwoLong(1 + (long) 1 << 61)); }
Ranges { public static BigInteger choose( SourceOfRandomness random, BigInteger min, BigInteger max) { BigInteger range = max.subtract(min).add(BigInteger.ONE); BigInteger generated; do { generated = random.nextBigInteger(range.bitLength()); } while (generated.compareTo(range) >= 0); return generated.add(min); } private Ranges(); static int checkRange( Type type, T min, T max); static BigInteger choose( SourceOfRandomness random, BigInteger min, BigInteger max); static long choose(SourceOfRandomness random, long min, long max); }
@Test public void weakSanityCheckForDistributionOfChooseLongs() { boolean[] hits = new boolean[5]; SourceOfRandomness random = new SourceOfRandomness(new Random(0)); for (int i = 0; i < 100; i++) { hits[(int) Ranges.choose(random, 0, (long) hits.length - 1)] = true; } for (boolean hit : hits) { assertTrue(hit); } }
MappingsResolver { public static List<String> getRequestMappings(Method method, Class<?> controller) { return getJoinedMappings(method, controller, PathExtractor.of(RequestMapping.class, RequestMapping::path)); } static List<String> getRequestMappings(Method method, Class<?> controller); static List<String> getMessageMappings(Method method, Class<?> controller); static List<String> getSubscribeMappings(Method method, Class<?> controller); }
@Test public void getRequestMappings_noClassAnnotation() throws NoSuchMethodException { Class<?> ctrl = StandardController.class; Method none = ctrl.getDeclaredMethod("none"); Method slash = ctrl.getDeclaredMethod("slash"); Method slashPath = ctrl.getDeclaredMethod("slashPath"); Method longPath = ctrl.getDeclaredMethod("slashLongPath"); Method pathAttribute = ctrl.getDeclaredMethod("pathAttribute"); assertEquals(singletonList("/"), MappingsResolver.getRequestMappings(none, ctrl)); assertEquals(singletonList("/"), MappingsResolver.getRequestMappings(slash, ctrl)); assertEquals(singletonList("/path"), MappingsResolver.getRequestMappings(slashPath, ctrl)); assertEquals(singletonList("/long/path"), MappingsResolver.getRequestMappings(longPath, ctrl)); assertEquals(singletonList("/path/attr"), MappingsResolver.getRequestMappings(pathAttribute, ctrl)); } @Test public void getRequestMappings_emptyClassAnnotation() throws NoSuchMethodException { Class<?> ctrl = EmptyAnnotatedController.class; Method none = ctrl.getDeclaredMethod("none"); Method test = ctrl.getDeclaredMethod("test"); assertEquals(singletonList("/"), MappingsResolver.getRequestMappings(none, ctrl)); assertEquals(singletonList("/test"), MappingsResolver.getRequestMappings(test, ctrl)); } @Test public void getRequestMappings_classAnnotationWithPrefix() throws NoSuchMethodException { Class<?> ctrl = PrefixAnnotatedController.class; Method none = ctrl.getDeclaredMethod("none"); Method test = ctrl.getDeclaredMethod("test"); assertEquals(singletonList("/prefix"), MappingsResolver.getRequestMappings(none, ctrl)); assertEquals(singletonList("/prefix/test"), MappingsResolver.getRequestMappings(test, ctrl)); } @Test public void getRequestMappings_childController_prefixOverride() throws NoSuchMethodException { Class<?> ctrl = PrefixOverrideChildController.class; Method none = ctrl.getMethod("none"); Method test = ctrl.getMethod("test"); assertEquals(singletonList("/child"), MappingsResolver.getRequestMappings(none, ctrl)); assertEquals(singletonList("/child/test"), MappingsResolver.getRequestMappings(test, ctrl)); } @Test public void getRequestMappings_multiplePaths() throws NoSuchMethodException { Class<?> ctrl = MultiPathController.class; Method test = ctrl.getMethod("test"); List<String> expectedPaths = Arrays.asList("/path1/path3", "/path1/path4", "/path2/path3", "/path2/path4"); assertEquals(expectedPaths, MappingsResolver.getRequestMappings(test, ctrl)); }
FieldPropertyScanner implements PropertyScanner { @Override public List<Property> getProperties(Type type) { Class<?> clazz = extractClass(type); return getAllFields(clazz).stream() .filter(FieldPropertyScanner::isRelevantWhenSerialized) .map(FieldPropertyScanner::toProperty) .collect(toList()); } @Override List<Property> getProperties(Type type); }
@Test public void getFieldTypes_primitive() { List<Property> props = scanner.getProperties(int.class); assertTrue(props.isEmpty()); } @Test public void getFieldTypes_excludesTransient() throws NoSuchFieldException { Set<Property> props = new HashSet<>(); props.add(createFieldProperty("stringField", String.class, CustomObject.class)); props.add(createFieldProperty("intField", int.class, CustomObject.class)); props.add(createFieldProperty("objField", Object.class, CustomObject.class)); props.add(new Property("genericField", List.class, new TypeToken<List<Integer>>() {}.getType(), CustomObject.class.getDeclaredField("genericField"))); assertEquals(props, new HashSet<>(scanner.getProperties(CustomObject.class))); } @Test public void getFieldTypes_inheritedFields() throws NoSuchFieldException { Set<Property> props = new HashSet<>(); props.add(createFieldProperty("parentField", Float.class, Parent.class)); props.add(createFieldProperty("childField", Double.class, Child.class)); assertEquals(props, new HashSet<>(scanner.getProperties(Child.class))); } @Test public void getFieldTypes_enum() throws NoSuchFieldException { Set<Property> props = new HashSet<>(); props.add(createFieldProperty("name", String.class, Enum.class)); props.add(createFieldProperty("ordinal", int.class, Enum.class)); props.add(createFieldProperty("intField", int.class, MyEnum.class)); props.add(createFieldProperty("doubleField", Double.class, MyEnum.class)); assertEquals(props, new HashSet<>(scanner.getProperties(MyEnum.class))); }
RecursivePropertyTypeScanner implements TypeScanner { @Override public Set<Class<?>> findTypesToDocument(Collection<? extends Type> rootTypes) { Set<Class<?>> allTypes = new HashSet<>(); rootTypes.forEach(type -> exploreType(type, allTypes)); return allTypes; } RecursivePropertyTypeScanner(PropertyScanner scanner); Predicate<? super Class<?>> getTypeFilter(); void setTypeFilter(Predicate<? super Class<?>> typeFilter); Predicate<? super Class<?>> getTypeInspectionFilter(); void setTypeInspectionFilter(Predicate<? super Class<?>> typeInspectionFilter); Function<Class<?>, Set<Class<?>>> getTypeMapper(); void setTypeMapper(Function<Class<?>, Set<Class<?>>> mapper); @Override Set<Class<?>> findTypesToDocument(Collection<? extends Type> rootTypes); }
@Test public void findTypes_simpleString() { Set<Type> rootTypes = Collections.singleton(String.class); assertSetEquals(explorer.findTypesToDocument(rootTypes), String.class); } @Test public void findTypes_simpleCharacter() { Set<Type> rootTypes = Collections.singleton(Character.class); assertSetEquals(explorer.findTypesToDocument(rootTypes), Character.class); } @Test public void findTypes_customType() { Set<Type> rootTypes = Collections.singleton(Custom.class); assertSetEquals(explorer.findTypesToDocument(rootTypes), Custom.class, Long.class); } @Test public void findTypes_inheritedFields() { Set<Type> rootTypes = Collections.singleton(Child.class); assertSetEquals(explorer.findTypesToDocument(rootTypes), Child.class, Double.class, Long.class); } @Test public void findTypes_complexHierarchy() { Set<Type> rootTypes = Collections.singleton(TestRoot.class); assertSetEquals(explorer.findTypesToDocument(rootTypes), TestRoot.class, WithCustomObject.class, WithPrimitives.class, Custom.class, Long.class, String.class, int.class); }
ConcreteSubtypesMapper implements Function<Class<?>, Set<Class<?>>> { @Override public Set<Class<?>> apply(Class<?> type) { if (isAbstract(type)) { return getImplementationsOf(type); } return Collections.singleton(type); } ConcreteSubtypesMapper(Reflections reflections); @Override Set<Class<?>> apply(Class<?> type); }
@Test public void apply_concreteClass() { assertEquals(mapper.apply(SimpleAImpl.class), SimpleAImpl.class); assertEquals(mapper.apply(ConcreteAImpl.class), ConcreteAImpl.class); assertEquals(mapper.apply(BImpl.class), BImpl.class); } @Test public void apply_abstractClass() { assertEquals(mapper.apply(AbstractA.class), ConcreteAImpl.class); } @Test public void apply_interface() { assertEquals(mapper.apply(B.class), BImpl.class); assertEquals(mapper.apply(A.class), SimpleAImpl.class, ConcreteAImpl.class, BImpl.class); }
Defaults { public static Object defaultValueFor(@Nullable Class<?> type) { if (type == null) { return null; } return primitiveDefaults.get(type); } static Object defaultValueFor(@Nullable Class<?> type); }
@Test public void defaultValueFor_primitives() { assertEquals(0, Defaults.defaultValueFor(byte.class)); assertEquals(0, Defaults.defaultValueFor(short.class)); assertEquals(0, Defaults.defaultValueFor(int.class)); assertEquals(0L, Defaults.defaultValueFor(long.class)); assertEquals(0f, Defaults.defaultValueFor(float.class)); assertEquals(0.0, Defaults.defaultValueFor(double.class)); assertEquals(false, Defaults.defaultValueFor(boolean.class)); assertEquals('\0', Defaults.defaultValueFor(char.class)); } @Test public void defaultValueFor_objects() { assertNull(Defaults.defaultValueFor(Integer.class)); assertNull(Defaults.defaultValueFor(Double.class)); assertNull(Defaults.defaultValueFor(Boolean.class)); assertNull(Defaults.defaultValueFor(String.class)); }
JavadocTypeDocReader implements TypeDocReader { @NotNull @Override public Optional<TypeDoc> buildTypeDocBase(@NotNull Class<?> clazz, @NotNull TypeReferenceProvider typeReferenceProvider, @NotNull TemplateProvider templateProvider) { TypeDoc doc = new TypeDoc(clazz); doc.setName(clazz.getSimpleName()); doc.setDescription(JavadocHelper.getJavadocDescription(clazz).orElse(null)); return Optional.of(doc); } @NotNull @Override Optional<TypeDoc> buildTypeDocBase(@NotNull Class<?> clazz, @NotNull TypeReferenceProvider typeReferenceProvider, @NotNull TemplateProvider templateProvider); @NotNull @Override Optional<PropertyDoc> buildPropertyDoc(Property property, TypeDoc parentDoc, TypeReferenceProvider typeReferenceProvider); }
@Test public void buildTypeDocBase() { Optional<TypeDoc> doc = reader.buildTypeDocBase(Person.class, typeReferenceProvider, c -> null); assertTrue(doc.isPresent()); TypeDoc typeDoc = doc.get(); assertEquals("Person", typeDoc.getName()); assertEquals("Represents a person.", typeDoc.getDescription()); }
JavadocTypeDocReader implements TypeDocReader { @NotNull @Override public Optional<PropertyDoc> buildPropertyDoc(Property property, TypeDoc parentDoc, TypeReferenceProvider typeReferenceProvider) { PropertyDoc doc = new PropertyDoc(); doc.setName(property.getName()); doc.setDescription(getPropertyDescription(property)); return Optional.of(doc); } @NotNull @Override Optional<TypeDoc> buildTypeDocBase(@NotNull Class<?> clazz, @NotNull TypeReferenceProvider typeReferenceProvider, @NotNull TemplateProvider templateProvider); @NotNull @Override Optional<PropertyDoc> buildPropertyDoc(Property property, TypeDoc parentDoc, TypeReferenceProvider typeReferenceProvider); }
@Test public void buildPropertyDoc() throws NoSuchMethodException, NoSuchFieldException { Field nameField = Person.class.getDeclaredField("name"); Field ageField = Person.class.getDeclaredField("age"); Field phoneField = Person.class.getDeclaredField("phone"); Method getName = Person.class.getDeclaredMethod("getName"); Method getAge = Person.class.getDeclaredMethod("getAge"); Method getPhone = Person.class.getDeclaredMethod("getPhone"); Property nameProp = new Property("name", String.class, getName); nameProp.setField(nameField); nameProp.setGetter(getName); Property ageProp = new Property("age", Integer.class, getAge); ageProp.setField(ageField); ageProp.setGetter(getAge); Property phoneProp = new Property("phone", String.class, getPhone); phoneProp.setField(phoneField); phoneProp.setGetter(getPhone); Optional<TypeDoc> doc = reader.buildTypeDocBase(Person.class, typeReferenceProvider, c -> null); assertTrue(doc.isPresent()); TypeDoc typeDoc = doc.get(); Optional<PropertyDoc> maybeNameDoc = reader.buildPropertyDoc(nameProp, typeDoc, typeReferenceProvider); Optional<PropertyDoc> maybeAgeDoc = reader.buildPropertyDoc(ageProp, typeDoc, typeReferenceProvider); Optional<PropertyDoc> maybePhoneDoc = reader.buildPropertyDoc(phoneProp, typeDoc, typeReferenceProvider); assertTrue(maybeNameDoc.isPresent()); assertTrue(maybeAgeDoc.isPresent()); assertTrue(maybePhoneDoc.isPresent()); PropertyDoc nameDoc = maybeNameDoc.get(); PropertyDoc ageDoc = maybeAgeDoc.get(); PropertyDoc phoneDoc = maybePhoneDoc.get(); assertEquals("name", nameDoc.getName()); assertEquals("age", ageDoc.getName()); assertEquals("phone", phoneDoc.getName()); assertEquals("The name of this <code>Person</code>.", nameDoc.getDescription()); assertEquals("this person's age", ageDoc.getDescription()); assertEquals("Gets this person's <code>phone number</code>.", phoneDoc.getDescription()); }
JacksonPropertyScanner implements PropertyScanner { @Override public List<Property> getProperties(Type type) { return getJacksonProperties(type).stream() .filter(JacksonPropertyScanner::isReadable) .map(this::convertProp) .collect(toList()); } JacksonPropertyScanner(ObjectMapper mapper); @Override List<Property> getProperties(Type type); }
@Test public void getProperties_primitive() { assertTrue(scanner.getProperties(int.class).isEmpty()); }
RestUserDetailsService implements UserDetailsManager { @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { return restTemplate.getForObject("/{0}", User.class, username); } RestUserDetailsService(RestTemplateBuilder builder, @Value("${app.service.url.users}") String rootUri); @Override UserDetails loadUserByUsername(String username); @Override void createUser(UserDetails userDetails); @Override void updateUser(UserDetails userDetails); @Override void deleteUser(String username); @Override void changePassword(String username, String password); @Override boolean userExists(String username); }
@Test public void testLoadUserByUsername() { server.expect(requestTo("/" + USERNAME)).andExpect(method(GET)) .andRespond(withHalJsonResponse("/user_jbloggs_GET.txt")); UserDetails userDetails = service.loadUserByUsername(USERNAME); assertNotNull(userDetails); }
SpannersService { public void create(Spanner spanner) { restTemplate.postForObject("/", spanner, Spanner.class); } SpannersService(RestTemplateBuilder builder, @Value("${app.service.url.spanners}") String rootUri); Collection<Spanner> findAll(); Spanner findOne(Long id); @PreAuthorize("hasPermission(#spanner, 'owner')") void delete(Spanner spanner); void create(Spanner spanner); @PreAuthorize("hasPermission(#spanner, 'owner')") void update(Spanner spanner); }
@Test public void testCreate() throws Exception { server.expect(requestTo("/")).andExpect(method(POST)) .andRespond(withStatus(HttpStatus.CREATED)); Spanner newSpanner = aSpanner().withId(null).build(); service.create(newSpanner); server.verify(); }
SpannersService { @PreAuthorize("hasPermission(#spanner, 'owner')") public void update(Spanner spanner) { restTemplate.put("/{0}", spanner, spanner.getId()); } SpannersService(RestTemplateBuilder builder, @Value("${app.service.url.spanners}") String rootUri); Collection<Spanner> findAll(); Spanner findOne(Long id); @PreAuthorize("hasPermission(#spanner, 'owner')") void delete(Spanner spanner); void create(Spanner spanner); @PreAuthorize("hasPermission(#spanner, 'owner')") void update(Spanner spanner); }
@Test public void testUpdate() throws Exception { server.expect(requestTo("/1")).andExpect(method(PUT)) .andRespond(withStatus(HttpStatus.OK)); Spanner update = aSpanner().withId(1L).build(); service.update(update); server.verify(); }
AddSpannerController { @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.GET) public ModelAndView displayPage() { SpannerForm newSpanner = new SpannerForm(); return new ModelAndView(VIEW_ADD_SPANNER, MODEL_SPANNER, newSpanner); } @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.GET) ModelAndView displayPage(); @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.POST) ModelAndView addSpanner(@Valid @ModelAttribute(MODEL_SPANNER) SpannerForm formData, BindingResult validationResult, Principal principal); static final String CONTROLLER_URL; static final String VIEW_ADD_SPANNER; static final String VIEW_SUCCESS; static final String VIEW_VALIDATION_FAIL; static final String MODEL_SPANNER; }
@Test public void testPageDisplay() { ModelAndView response = controller.displayPage(); assertNotNull("no response", response); assertEquals("view", VIEW_ADD_SPANNER, response.getViewName()); }
AddSpannerController { @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.POST) public ModelAndView addSpanner(@Valid @ModelAttribute(MODEL_SPANNER) SpannerForm formData, BindingResult validationResult, Principal principal) { if (validationResult.hasErrors()) { return new ModelAndView(VIEW_VALIDATION_FAIL); } Spanner spanner = new Spanner(); spanner.setOwner(principal.getName()); spanner.setName(formData.getName()); spanner.setSize(formData.getSize()); spannersService.create(spanner); return new ModelAndView(VIEW_SUCCESS); } @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.GET) ModelAndView displayPage(); @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.POST) ModelAndView addSpanner(@Valid @ModelAttribute(MODEL_SPANNER) SpannerForm formData, BindingResult validationResult, Principal principal); static final String CONTROLLER_URL; static final String VIEW_ADD_SPANNER; static final String VIEW_SUCCESS; static final String VIEW_VALIDATION_FAIL; static final String MODEL_SPANNER; }
@Test public void testAddSpanner() { SpannerForm formData = new SpannerForm(); formData.setName("Keeley"); formData.setSize(12); Principal currentUser = new TestingAuthenticationToken("user", "pass"); BindingResult noErrors = new BeanPropertyBindingResult(formData, MODEL_SPANNER); ModelAndView response = controller.addSpanner(formData, noErrors, currentUser); assertNotNull("no response", response); ArgumentCaptor<Spanner> spannerArgumentCaptor = ArgumentCaptor.forClass(Spanner.class); verify(spannersService).create(spannerArgumentCaptor.capture()); Spanner createdSpanner = spannerArgumentCaptor.getValue(); assertEquals("name", formData.getName(), createdSpanner.getName()); assertEquals("size", formData.getSize(), createdSpanner.getSize()); assertEquals("owner", currentUser.getName(), createdSpanner.getOwner()); assertEquals("view", VIEW_SUCCESS, response.getViewName()); } @Test public void testValidationFail() { SpannerForm formData = new SpannerForm(); formData.setName("Keeley"); formData.setSize(12); BindingResult validationFail = new BeanPropertyBindingResult(formData, MODEL_SPANNER); validationFail.addError(new ObjectError("size", "TOO_BIG")); Principal currentUser = new TestingAuthenticationToken("user", "pass"); ModelAndView response = controller.addSpanner(formData, validationFail, currentUser); assertNotNull("no response", response); verify(spannersService, never()).update(any(Spanner.class)); assertEquals("view", VIEW_VALIDATION_FAIL, response.getViewName()); }
DetailSpannerController { @RequestMapping(value = "/detailSpanner", method = RequestMethod.GET) public ModelAndView displayDetail(@RequestParam Long id) throws SpannerNotFoundException { Spanner spanner = spannersService.findOne(id); if (spanner == null) { throw new SpannerNotFoundException(id); } return new ModelAndView(VIEW_DETAIL_SPANNER, MODEL_SPANNER, spanner); } @RequestMapping(value = "/detailSpanner", method = RequestMethod.GET) ModelAndView displayDetail(@RequestParam Long id); static final String VIEW_DETAIL_SPANNER; static final String MODEL_SPANNER; }
@Test public void testDisplayPage() throws Exception { when(spannersService.findOne(SPANNER_ID)).thenReturn(SPANNER); ModelAndView response = controller.displayDetail(SPANNER_ID); assertNotNull("no response", response); assertEquals(VIEW_DETAIL_SPANNER, response.getViewName()); Spanner spannerInModel = (Spanner)response.getModelMap().get(MODEL_SPANNER); assertSpannerEquals(SPANNER, spannerInModel); } @Test public void testSpannerNotFound() throws Exception { when(spannersService.findOne(SPANNER_ID)).thenReturn(null); try { controller.displayDetail(SPANNER_ID); fail("Expected: SpannerNotFoundException"); } catch(SpannerNotFoundException notFoundEx) { assertEquals("Exception spanner id", SPANNER_ID, notFoundEx.getSpannerId()); } }
HomeController { @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.GET) public String index() { return VIEW_NOT_SIGNED_IN; } @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.GET) String index(); static final String CONTROLLER_URL; static final String VIEW_NOT_SIGNED_IN; }
@Test public void testHomePage() { String response = controller.index(); assertEquals("view name", VIEW_NOT_SIGNED_IN, response); }
SignupController { @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.POST) public String signup(@Valid @ModelAttribute SignupForm signupForm, Errors errors) { if (errors.hasErrors()) { log.warn("Oh no! Signup failed as there are validation errors."); return null; } String hashedPassword = passwordEncoder.encode(signupForm.getPassword()); UserDetails userDetails = new User(signupForm.getName(), hashedPassword, ENABLED); userDetailsManager.createUser(userDetails); log.info("Success! Created new user " + userDetails.getUsername()); return VIEW_SUCCESS; } @RequestMapping(value = CONTROLLER_URL) SignupForm displayPage(); @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.POST) String signup(@Valid @ModelAttribute SignupForm signupForm, Errors errors); static final String CONTROLLER_URL; static final String VIEW_SUCCESS; }
@Test public void testSuccessForward() { SignupForm form = populateForm(NAME, PASSWORD); Errors noErrors = new DirectFieldBindingResult(form, "form"); String response = controller.signup(form, noErrors); assertEquals(SignupController.VIEW_SUCCESS, response); } @Test public void testAccountCreation() { SignupForm form = populateForm(NAME, PASSWORD); Errors noErrors = new DirectFieldBindingResult(form, "form"); controller.signup(form, noErrors); verify(userDetailsManager).createUser(argThat(hasProperty("username", equalTo(NAME)))); } @Test public void testPasswordHash() { given(passwordEncoder.encode(PASSWORD)).willReturn(HASHED_PASSWORD); SignupForm form = populateForm(NAME, PASSWORD); Errors noErrors = new DirectFieldBindingResult(form, "form"); controller.signup(form, noErrors); verify(userDetailsManager).createUser(argThat(hasProperty("password", equalTo(HASHED_PASSWORD)))); } @Test public void testValidationFailIsLogged() { SignupForm invalidForm = populateForm(null, null); Errors errors = new DirectFieldBindingResult(invalidForm, "form"); errors.rejectValue("name", "Invalid name"); errors.rejectValue("password", "Invalid password"); controller.signup(invalidForm, errors); assertThat(sysOut.asString(), containsString("Oh no!")); } @Test public void testSuccessIsLogged() { SignupForm form = populateForm(NAME, PASSWORD); Errors noErrors = new DirectFieldBindingResult(form, "form"); controller.signup(form, noErrors); assertThat(sysOut.asString(), containsString("Success!")); }
RestUserDetailsService implements UserDetailsManager { @Override public void createUser(UserDetails userDetails) { restTemplate.postForLocation("/", userDetails); } RestUserDetailsService(RestTemplateBuilder builder, @Value("${app.service.url.users}") String rootUri); @Override UserDetails loadUserByUsername(String username); @Override void createUser(UserDetails userDetails); @Override void updateUser(UserDetails userDetails); @Override void deleteUser(String username); @Override void changePassword(String username, String password); @Override boolean userExists(String username); }
@Test public void testCreateUser() throws Exception { server.expect(requestTo("/")).andExpect(method(POST)) .andRespond(withStatus(HttpStatus.CREATED)); UserDetails user = new User(USERNAME, PASSWORD, ENABLED); service.createUser(user); server.verify(); }
DisplaySpannersController { @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.GET) public String displaySpanners(ModelMap model) { Collection<Spanner> spanners = spannersService.findAll(); String greeting = timeOfDayGreeting(); model.addAttribute(MODEL_ATTRIBUTE_SPANNERS, spanners); model.addAttribute(MODEL_ATTRIBUTE_GREETING, greeting); return VIEW_DISPLAY_SPANNERS; } @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.GET) String displaySpanners(ModelMap model); @RequestMapping(value = "/deleteSpanner", method = RequestMethod.GET) String deleteSpanner(@RequestParam Long id, ModelMap model); }
@Test public void testDisplaySpanners() { when(spannersService.findAll()).thenReturn(SPANNERS); ModelMap model = new ModelMap(); String view = controller.displaySpanners(model); assertEquals("view name", VIEW_DISPLAY_SPANNERS, view); @SuppressWarnings("unchecked") List<Spanner> spannersInModel = (List<Spanner>)model.get(MODEL_ATTRIBUTE_SPANNERS); assertNotNull(MODEL_ATTRIBUTE_SPANNERS + " is null", spannersInModel); assertEquals(SPANNERS, spannersInModel); } @Test public void testTimeOfDayGreetingMorning() { when(currentTime.get()).thenReturn(LocalTime.of(9,0)); ModelMap model = new ModelMap(); controller.displaySpanners(model); String greeting = (String)model.get(MODEL_ATTRIBUTE_GREETING); assertEquals(GREETING_MORNING, greeting); } @Test public void testTimeOfDayGreetingAfternoon() { when(currentTime.get()).thenReturn(LocalTime.of(14,0)); ModelMap model = new ModelMap(); controller.displaySpanners(model); String greeting = (String)model.get(MODEL_ATTRIBUTE_GREETING); assertEquals(GREETING_AFTERNOON, greeting); } @Test public void testTimeOfDayGreetingEvening() { when(currentTime.get()).thenReturn(LocalTime.of(20,0)); ModelMap model = new ModelMap(); controller.displaySpanners(model); String greeting = (String)model.get(MODEL_ATTRIBUTE_GREETING); assertEquals(GREETING_EVENING, greeting); }
DisplaySpannersController { @RequestMapping(value = "/deleteSpanner", method = RequestMethod.GET) public String deleteSpanner(@RequestParam Long id, ModelMap model) throws SpannerNotFoundException { Spanner spanner = spannersService.findOne(id); if (spanner == null) { throw new SpannerNotFoundException(id); } spannersService.delete(spanner); return displaySpanners(model); } @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.GET) String displaySpanners(ModelMap model); @RequestMapping(value = "/deleteSpanner", method = RequestMethod.GET) String deleteSpanner(@RequestParam Long id, ModelMap model); }
@Test public void testDeleteSpanner() throws Exception { when(spannersService.findOne(SPANNER_ID)).thenReturn(SPANNER); ModelMap model = new ModelMap(); String view = controller.deleteSpanner(SPANNER_ID, model); verify(spannersService).delete(SPANNER); assertEquals("view name", VIEW_DISPLAY_SPANNERS, view); } @Test public void testDeleteSpannerNotFound() { when(spannersService.findOne(SPANNER_ID)).thenReturn(null); try { controller.deleteSpanner(SPANNER_ID, new ModelMap()); fail("Expected: SpannerNotFoundException"); } catch(SpannerNotFoundException notFoundEx) { assertEquals("Exception spanner id", SPANNER_ID, notFoundEx.getSpannerId()); } }
EditSpannerController implements ApplicationEventPublisherAware { @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.GET) public ModelAndView displayPage(@RequestParam Long id) throws SpannerNotFoundException { Spanner spanner = spannersService.findOne(id); if (spanner == null) { throw new SpannerNotFoundException(id); } SpannerForm initializedForm = new SpannerForm(spanner); return new ModelAndView(VIEW_EDIT_SPANNER, MODEL_SPANNER, initializedForm); } @Override void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher); @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.GET) ModelAndView displayPage(@RequestParam Long id); @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.POST) ModelAndView updateSpanner(@Valid @ModelAttribute(MODEL_SPANNER) SpannerForm formData, BindingResult validationResult); static final String VIEW_EDIT_SPANNER; static final String VIEW_UPDATE_SUCCESS; static final String VIEW_VALIDATION_ERRORS; static final String MODEL_SPANNER; static final String CONTROLLER_URL; }
@Test public void testDisplayPage() throws Exception { when(spannersService.findOne(SPANNER_ID)).thenReturn(SPANNER); ModelAndView response = controller.displayPage(SPANNER_ID); assertNotNull("no response", response); assertEquals("view", VIEW_EDIT_SPANNER, response.getViewName()); SpannerForm spannerFormData = (SpannerForm)response.getModelMap().get(MODEL_SPANNER); assertSpannerEquals(SPANNER, spannerFormData); } @Test public void testSpannerNotFound() { when(spannersService.findOne(SPANNER_ID)).thenReturn(null); try { controller.displayPage(SPANNER_ID); fail("Expected: SpannerNotFoundException"); } catch(SpannerNotFoundException notFoundEx) { assertEquals("Exception spanner id", SPANNER_ID, notFoundEx.getSpannerId()); } }
RestUserDetailsService implements UserDetailsManager { @Override public void updateUser(UserDetails userDetails) { restTemplate.put("/{0}", userDetails, userDetails.getUsername()); } RestUserDetailsService(RestTemplateBuilder builder, @Value("${app.service.url.users}") String rootUri); @Override UserDetails loadUserByUsername(String username); @Override void createUser(UserDetails userDetails); @Override void updateUser(UserDetails userDetails); @Override void deleteUser(String username); @Override void changePassword(String username, String password); @Override boolean userExists(String username); }
@Test public void testUpdateUser() throws Exception { server.expect(requestTo("/" + USERNAME)).andExpect(method(PUT)) .andRespond(withStatus(HttpStatus.OK)); UserDetails user = new User(USERNAME, PASSWORD, ENABLED); service.updateUser(user); server.verify(); }
RestUserDetailsService implements UserDetailsManager { @Override public void deleteUser(String username) { restTemplate.delete("/{0}", username); } RestUserDetailsService(RestTemplateBuilder builder, @Value("${app.service.url.users}") String rootUri); @Override UserDetails loadUserByUsername(String username); @Override void createUser(UserDetails userDetails); @Override void updateUser(UserDetails userDetails); @Override void deleteUser(String username); @Override void changePassword(String username, String password); @Override boolean userExists(String username); }
@Test public void testDeleteUser() throws Exception { server.expect(requestTo("/" + USERNAME)).andExpect(method(DELETE)) .andRespond(withStatus(HttpStatus.OK)); service.deleteUser(USERNAME); server.verify(); }
RestUserDetailsService implements UserDetailsManager { @Override public boolean userExists(String username) { try { ResponseEntity<User> responseEntity = restTemplate.getForEntity("/{0}", User.class, username); return HttpStatus.OK.equals(responseEntity.getStatusCode()); } catch (HttpClientErrorException e) { return false; } } RestUserDetailsService(RestTemplateBuilder builder, @Value("${app.service.url.users}") String rootUri); @Override UserDetails loadUserByUsername(String username); @Override void createUser(UserDetails userDetails); @Override void updateUser(UserDetails userDetails); @Override void deleteUser(String username); @Override void changePassword(String username, String password); @Override boolean userExists(String username); }
@Test public void testUserExists() throws Exception { server.expect(requestTo("/" + USERNAME)).andExpect(method(GET)) .andRespond(withHalJsonResponse("/user_jbloggs_GET.txt")); boolean userExists = service.userExists(USERNAME); assertTrue(userExists); } @Test public void testUserNotExists() throws Exception { server.expect(requestTo("/" + USERNAME)).andExpect(method(GET)) .andRespond(withStatus(HttpStatus.NOT_FOUND)); boolean userExists = service.userExists(USERNAME); assertFalse(userExists); }
RestUserDetailsService implements UserDetailsManager { @Override public void changePassword(String username, String password) { User user = new User(); user.setUsername(username); user.setPassword(password); HttpEntity<User> requestEntity = new HttpEntity<>(user); restTemplate.exchange("/{0}", HttpMethod.PATCH, requestEntity, Void.class, username); } RestUserDetailsService(RestTemplateBuilder builder, @Value("${app.service.url.users}") String rootUri); @Override UserDetails loadUserByUsername(String username); @Override void createUser(UserDetails userDetails); @Override void updateUser(UserDetails userDetails); @Override void deleteUser(String username); @Override void changePassword(String username, String password); @Override boolean userExists(String username); }
@Test public void changePassword() throws Exception { server.expect(requestTo("/" + USERNAME)).andExpect(method(PATCH)) .andRespond(withStatus(HttpStatus.OK)); service.changePassword(USERNAME, PASSWORD); server.verify(); }
SpannersService { public Collection<Spanner> findAll() { ResponseEntity<PagedResources<Spanner>> response = restTemplate.exchange("/", HttpMethod.GET, null, new ParameterizedTypeReference<PagedResources<Spanner>>(){}); PagedResources<Spanner> pages = response.getBody(); return pages.getContent(); } SpannersService(RestTemplateBuilder builder, @Value("${app.service.url.spanners}") String rootUri); Collection<Spanner> findAll(); Spanner findOne(Long id); @PreAuthorize("hasPermission(#spanner, 'owner')") void delete(Spanner spanner); void create(Spanner spanner); @PreAuthorize("hasPermission(#spanner, 'owner')") void update(Spanner spanner); }
@Test public void testFindAll() throws Exception { server.expect(requestTo("/")).andExpect(method(GET)) .andRespond(withHalJsonResponse("/spannersGET.txt")); Collection<Spanner> spanners = service.findAll(); assertThat(spanners, hasSize(2)); }
SpannersService { public Spanner findOne(Long id) { return restTemplate.getForObject("/{0}", Spanner.class, id); } SpannersService(RestTemplateBuilder builder, @Value("${app.service.url.spanners}") String rootUri); Collection<Spanner> findAll(); Spanner findOne(Long id); @PreAuthorize("hasPermission(#spanner, 'owner')") void delete(Spanner spanner); void create(Spanner spanner); @PreAuthorize("hasPermission(#spanner, 'owner')") void update(Spanner spanner); }
@Test public void testFindOne() throws Exception { server.expect(requestTo("/1")).andExpect(method(GET)) .andRespond(withHalJsonResponse("/spanner1GET.txt")); Spanner spanner = service.findOne(1L); assertSpanner("Belinda", 10, "jones", spanner); }
SpannersService { @PreAuthorize("hasPermission(#spanner, 'owner')") public void delete(Spanner spanner) { restTemplate.delete("/{0}", spanner.getId()); } SpannersService(RestTemplateBuilder builder, @Value("${app.service.url.spanners}") String rootUri); Collection<Spanner> findAll(); Spanner findOne(Long id); @PreAuthorize("hasPermission(#spanner, 'owner')") void delete(Spanner spanner); void create(Spanner spanner); @PreAuthorize("hasPermission(#spanner, 'owner')") void update(Spanner spanner); }
@Test public void testDelete() throws Exception { server.expect(requestTo("/1")).andExpect(method(DELETE)) .andRespond(withStatus(HttpStatus.NO_CONTENT)); Spanner susan = aSpanner().withId(1L).named("Susan").build(); service.delete(susan); server.verify(); }
MongoDbController { @GetMapping("/mongo/findAll") public List<Book> findAll() { return mongoDbService.findAll(); } @PostMapping("/mongo/save") String saveObj(@RequestBody Book book); @GetMapping("/mongo/findAll") List<Book> findAll(); @GetMapping("/mongo/findOne") Book findOne(@RequestParam String id); @GetMapping("/mongo/findOneByName") Book findOneByName(@RequestParam String name); @PostMapping("/mongo/update") String update(@RequestBody Book book); @PostMapping("/mongo/delOne") String delOne(@RequestBody Book book); @GetMapping("/mongo/delById") String delById(@RequestParam String id); @GetMapping("/mongo/findLikes") List<Book> findByLikes(@RequestParam String search); }
@Test public void findAllTest() throws Exception{ MockUtils.mockGetTest("/mongo/findAll",mockMvc); }
MongoDbController { @PostMapping("/mongo/update") public String update(@RequestBody Book book) { return mongoDbService.updateBook(book); } @PostMapping("/mongo/save") String saveObj(@RequestBody Book book); @GetMapping("/mongo/findAll") List<Book> findAll(); @GetMapping("/mongo/findOne") Book findOne(@RequestParam String id); @GetMapping("/mongo/findOneByName") Book findOneByName(@RequestParam String name); @PostMapping("/mongo/update") String update(@RequestBody Book book); @PostMapping("/mongo/delOne") String delOne(@RequestBody Book book); @GetMapping("/mongo/delById") String delById(@RequestParam String id); @GetMapping("/mongo/findLikes") List<Book> findByLikes(@RequestParam String search); }
@Test public void updateTest() throws Exception{ Book book = new Book(); book.setId("4"); book.setPrice(130); book.setName("VUE从入门到放弃"); book.setInfo("前端框架--更新"); Gson gson = new Gson(); String params = gson.toJson(book); MvcResult mvcResult = MockUtils.mockPostTest("/mongo/delOne",params,mockMvc); String result = mvcResult.getResponse().getContentAsString(); System.out.println("更新对象-->" + result); }
MongoDbController { @GetMapping("/mongo/findLikes") public List<Book> findByLikes(@RequestParam String search) { return mongoDbService.findByLikes(search); } @PostMapping("/mongo/save") String saveObj(@RequestBody Book book); @GetMapping("/mongo/findAll") List<Book> findAll(); @GetMapping("/mongo/findOne") Book findOne(@RequestParam String id); @GetMapping("/mongo/findOneByName") Book findOneByName(@RequestParam String name); @PostMapping("/mongo/update") String update(@RequestBody Book book); @PostMapping("/mongo/delOne") String delOne(@RequestBody Book book); @GetMapping("/mongo/delById") String delById(@RequestParam String id); @GetMapping("/mongo/findLikes") List<Book> findByLikes(@RequestParam String search); }
@Test public void findByLikesTest() throws Exception{ MockUtils.mockGetTest("/mongo/findLikes?search=从",mockMvc); }
OptimizedBubbleSort { public <T> int sort(T[] array, Comparator<T> comparator, boolean optimized) { if (array == null) { return 0; } int counter = 0; boolean swapped = true; int lastSwap = array.length-1; while (swapped) { swapped = false; int limit = array.length - 1; if(optimized){ limit = lastSwap; } for (int i = 0; i < limit; i++) { int j = i + 1; counter++; if (comparator.compare(array[i], array[j]) > 0) { T tmp = array[i]; array[i] = array[j]; array[j] = tmp; swapped = true; lastSwap = i; } } } return counter; } int sort(T[] array, Comparator<T> comparator, boolean optimized); }
@Test public void testNull(){ int comparisons = sorter.sort(null, new StringComparator(), false); assertEquals(0, comparisons); } @Test public void testAlreadySorted(){ String[] array = {"a", "b", "c", "d"}; int comparisons = sorter.sort(array, new StringComparator(), false); assertEquals(3, comparisons); assertEquals("a", array[0]); assertEquals("b", array[1]); assertEquals("c", array[2]); assertEquals("d", array[3]); } @Test public void testInverted(){ String[] array = {"d", "c", "b", "a"}; int comparisons = sorter.sort(array, new StringComparator(), false); assertEquals(12, comparisons); assertEquals("a", array[0]); assertEquals("b", array[1]); assertEquals("c", array[2]); assertEquals("d", array[3]); } @Test public void testBase(){ String[] array = {"d", "a", "c", "b"}; sorter.sort(array, new StringComparator(), false); assertEquals("a", array[0]); assertEquals("b", array[1]); assertEquals("c", array[2]); assertEquals("d", array[3]); } @Test public void testNearly(){ String[] array = {"c", "b", "a", "d", "e", "f"}; int optimized = sorter.sort(array, new StringComparator(), true); array = new String[]{"c", "b", "a", "d", "e", "f"}; int base = sorter.sort(array, new StringComparator(), false); assertTrue(optimized < base); assertTrue(optimized < base/2); assertEquals("a", array[0]); assertEquals("b", array[1]); assertEquals("c", array[2]); assertEquals("d", array[3]); assertEquals("e", array[4]); assertEquals("f", array[5]); } @Test public void testGameUsers(){ GameUser a = new GameUser("a", 10); GameUser b = new GameUser("b", 5); GameUser c = new GameUser("c", 2); GameUser d = new GameUser("d", 5); GameUser[] array = {a,b,c,d}; sorter.sort(array, new GameUserComparator(), true); assertEquals("c", array[0].getUserId()); assertEquals("b", array[1].getUserId()); assertEquals("d", array[2].getUserId()); assertEquals("a", array[3].getUserId()); }
TriangleClassification { public static Classification classify(int a, int b, int c) { if(a <= 0 || b <= 0 || c <= 0){ return NOT_A_TRIANGLE; } if(a==b && b==c){ return EQUILATERAL; } int max = Math.max(a, Math.max(b, c)); if ((max == a && max - b - c >= 0) || (max == b && max - a - c >= 0) || (max == c && max - a - b >= 0)) { return NOT_A_TRIANGLE; } if(a==b || a==c || b==c){ return ISOSCELES; } else { return SCALENE; } } static Classification classify(int a, int b, int c); }
@Test public void testNegativeA(){ Classification res = TriangleClassification.classify(-1, 1, 1); assertEquals(NOT_A_TRIANGLE, res); } @Test public void testNegativeB(){ Classification res = TriangleClassification.classify(1, -1, 1); assertEquals(NOT_A_TRIANGLE, res); } @Test public void testNegativeC(){ Classification res = TriangleClassification.classify(1, 1, -1); assertEquals(NOT_A_TRIANGLE, res); } @Test public void testZeroA(){ Classification res = TriangleClassification.classify(0, 1, 1); assertEquals(NOT_A_TRIANGLE, res); } @Test public void testZeroB(){ Classification res = TriangleClassification.classify(1, 0, 1); assertEquals(NOT_A_TRIANGLE, res); } @Test public void testZeroC(){ Classification res = TriangleClassification.classify(1, 1, 0); assertEquals(NOT_A_TRIANGLE, res); } @Test public void testAllNegatives(){ Classification res = TriangleClassification.classify(-1, -1, -1); assertEquals(NOT_A_TRIANGLE, res); } @Test public void testAllZeros(){ Classification res = TriangleClassification.classify(0, 0, 0); assertEquals(NOT_A_TRIANGLE, res); } @Test public void testEquilateral(){ Classification res = TriangleClassification.classify(1, 1, 1); assertEquals(EQUILATERAL, res); } @Test public void testLargeEquilateral(){ int edge = Integer.MAX_VALUE; Classification res = TriangleClassification.classify(edge, edge, edge); assertEquals(EQUILATERAL, res); } @Test public void testIsoscelesAB(){ Classification res = TriangleClassification.classify(2, 2, 1); assertEquals(ISOSCELES, res); } @Test public void testIsoscelesAC(){ Classification res = TriangleClassification.classify(2, 1, 2); assertEquals(ISOSCELES, res); } @Test public void testIsoscelesBC(){ Classification res = TriangleClassification.classify(1, 2, 2); assertEquals(ISOSCELES, res); } @Test public void testTooLargeA(){ Classification res = TriangleClassification.classify(5, 2, 2); assertEquals(NOT_A_TRIANGLE, res); } @Test public void testTooLargeB(){ Classification res = TriangleClassification.classify(2, 5, 2); assertEquals(NOT_A_TRIANGLE, res); } @Test public void testTooLargeC(){ Classification res = TriangleClassification.classify(2, 2, 5); assertEquals(NOT_A_TRIANGLE, res); } @Test public void testLargeButShorterA(){ int max = Integer.MAX_VALUE; Classification res = TriangleClassification.classify(max-1, max, max); assertEquals(ISOSCELES, res); } @Test public void testLargeButShorterB(){ int max = Integer.MAX_VALUE; Classification res = TriangleClassification.classify(max, max-1, max); assertEquals(ISOSCELES, res); } @Test public void testLargeButShorterC(){ int max = Integer.MAX_VALUE; Classification res = TriangleClassification.classify(max, max, max-1); assertEquals(ISOSCELES, res); } @Test public void testScalene(){ Classification res = TriangleClassification.classify(2, 3, 4); assertEquals(SCALENE, res); } @Test public void testLargeScalene(){ int max = Integer.MAX_VALUE; Classification res = TriangleClassification.classify(max, max-1, max-2); assertEquals(SCALENE, res); }
MyRingArrayQueue implements MyQueue<T> { @Override public T peek() { if(isEmpty()){ throw new RuntimeException(); } return (T) data[head]; } MyRingArrayQueue(); MyRingArrayQueue(int capacity); @Override void enqueue(T value); @Override T dequeue(); @Override T peek(); @Override int size(); }
@Test public void testFailToPeekOnEmpty(){ assertThrows(RuntimeException.class, () -> queue.peek()); }
CopyExample { public static String[] copyWrong(String[] input){ if(input == null){ return null; } String[] output = input; return output; } static String[] copyWrong(String[] input); static String[] copy(String[] input); static String[][] copyWrong(String[][] input); static String[][] copy(String[][] input); }
@Test public void testCopyArrayWrong(){ String[] foo = {"hello", "there", "!"}; String[] copy = CopyExample.copyWrong(foo); checkSameData(foo, copy); String WRONG = "WRONG"; copy[0] = WRONG; assertEquals(WRONG, foo[0]); } @Test public void testCopyMatrixWrong(){ String[][] foo = new String[2][]; foo[0] = new String[]{"Hi", "first row"}; foo[1] = new String[]{"Hello", "second row", "rows do not have to have same length"}; String[][] copy = CopyExample.copyWrong(foo); checkSameData(foo, copy); String WRONG = "WRONG"; copy[0] = new String[]{WRONG}; assertEquals(2, foo[0].length); assertNotEquals(WRONG, foo[0][0]); assertEquals("Hi", foo[0][0]); copy[1][0] = WRONG; assertEquals(WRONG, foo[1][0]); }
CopyExample { public static String[] copy(String[] input){ if(input == null){ return null; } String[] output = new String[input.length]; for(int i=0; i<output.length; i++){ output[i] = input[i]; } return output; } static String[] copyWrong(String[] input); static String[] copy(String[] input); static String[][] copyWrong(String[][] input); static String[][] copy(String[][] input); }
@Test public void testCopyArray(){ String[] foo = {"hello", "there", "!"}; String[] copy = CopyExample.copy(foo); checkSameData(foo, copy); String ORIGINAL = foo[0]; String WRONG = "WRONG"; copy[0] = WRONG; assertNotEquals(WRONG, foo[0]); assertEquals(ORIGINAL, foo[0]); } @Test public void testCopyMatrix(){ String[][] foo = new String[2][]; foo[0] = new String[]{"Hi", "first row"}; foo[1] = new String[]{"Hello", "second row", "raws do not have to have same length"}; String[][] copy = CopyExample.copy(foo); checkSameData(foo, copy); String WRONG = "WRONG"; copy[0] = new String[]{WRONG}; assertEquals(2, foo[0].length); assertNotEquals(WRONG, foo[0][0]); assertEquals("Hi", foo[0][0]); copy[1][0] = WRONG; assertNotEquals(WRONG, foo[1][0]); assertEquals("Hello", foo[1][0]); }
User { public void setName(String name) { this.name = name; } User(String name, String surname, int id); @Override boolean equals(Object o); @Override int hashCode(); String getName(); void setName(String name); String getSurname(); void setSurname(String surname); int getId(); void setId(int id); }
@Test public void testMutabilityProblem(){ User foo = new User("foo", "bar", 0); MySet<User> users = new MySetHashMap<>(); users.add(foo); assertEquals(1, users.size()); assertTrue(users.isPresent(foo)); foo.setName("changed"); assertEquals(1, users.size()); assertFalse(users.isPresent(foo)); User copy = new User("foo", "bar", 0); assertFalse(users.isPresent(copy)); User changedCopy = new User("changed", "bar", 0); assertEquals(foo, changedCopy); assertFalse(users.isPresent(changedCopy)); foo.setName("foo"); assertTrue(users.isPresent(copy)); }
MySetHashMap implements MySet<E> { @Override public int size() { return map.size(); } @Override void add(E element); @Override void remove(E element); @Override boolean isPresent(E element); @Override int size(); }
@Test public void testEmpty() { assertEquals(0, set.size()); assertTrue(set.isEmpty()); }
MySetHashMap implements MySet<E> { @Override public void remove(E element) { map.delete(element); } @Override void add(E element); @Override void remove(E element); @Override boolean isPresent(E element); @Override int size(); }
@Test public void testRemove() { int n = set.size(); String element = "foo"; set.add(element); assertTrue(set.isPresent(element)); assertEquals(n + 1, set.size()); set.remove(element); assertFalse(set.isPresent(element)); assertEquals(n, set.size()); }
HashFunctions { public static int hashLongToInt(long x) { return (int) x; } static int nonUniformHash(int x); static int identityHash(int x); static int shiftedHash(int x); static int hashLongToInt(long x); static int hashLongToIntRevised(long x); static int hashStringSum(String x); static int hashStringSumRevised(String x); }
@Test public void testHashLongToInt(){ assertEquals(0, HashFunctions.hashLongToInt(0)); assertEquals(42, HashFunctions.hashLongToInt(42)); assertEquals(0, HashFunctions.hashLongToInt(0x1_00_00_00_00L)); assertEquals(5, HashFunctions.hashLongToInt(0x7_00_00_00_05L)); assertEquals(0, HashFunctions.hashLongToInt(0xFF_FF_00_00_00_00L)); } @Test public void testHashLongToIntNegative(){ long one32times = 0xFF_FF_FF_FFL; assertTrue(one32times > 2_000_000_000); assertEquals(-1, HashFunctions.hashLongToInt(one32times)); long singleOne = 0x80_00_00_00L; assertTrue(singleOne > 2_000_000_000); int hashed = HashFunctions.hashLongToInt(singleOne); assertTrue(hashed < -2_000_000_000); assertEquals(Integer.MIN_VALUE, hashed); }
HashFunctions { public static int hashLongToIntRevised(long x) { return (int) (x ^ (x >>> 32)); } static int nonUniformHash(int x); static int identityHash(int x); static int shiftedHash(int x); static int hashLongToInt(long x); static int hashLongToIntRevised(long x); static int hashStringSum(String x); static int hashStringSumRevised(String x); }
@Test public void testHashLongToIntRevised(){ long x = 0b0001_0000_0000_0000_0000_0000_0000_0000_____0000_0000_0000_0000_0000_0000_0000_0000L; long w = 0b0001_0000_0000_0000_0000_0000_0000_0000_____0000_0000_0000_0000_0000_0000_0001_0000L; long z = 0b0001_0001_0000_0000_0000_0000_0000_0000_____0000_0000_0000_0000_0000_0000_0000_0000L; assertNotEquals(HashFunctions.hashLongToInt(x), HashFunctions.hashLongToInt(w)); assertEquals(HashFunctions.hashLongToInt(x), HashFunctions.hashLongToInt(z)); assertNotEquals(HashFunctions.hashLongToIntRevised(x), HashFunctions.hashLongToIntRevised(w)); assertNotEquals(HashFunctions.hashLongToIntRevised(x), HashFunctions.hashLongToIntRevised(z)); }
UndirectedGraph implements Graph<V> { @Override public List<V> findPathBFS(V start, V end) { if(! graph.containsKey(start) || ! graph.containsKey(end)){ return null; } if(start.equals(end)){ throw new IllegalArgumentException(); } Queue<V> queue = new ArrayDeque<>(); Map<V,V> bestParent = new HashMap<>(); queue.add(start); mainLoop: while(! queue.isEmpty()){ V parent = queue.poll(); for(V child : graph.get(parent)){ if( child.equals(start) || bestParent.get(child) != null){ continue; } bestParent.put(child, parent); if(child.equals(end)){ break mainLoop; } queue.add(child); } } if(! bestParent.containsKey(end)){ return null; } List<V> path = new ArrayList<>(); V current = end; while (current != null){ path.add(0, current); current = bestParent.get(current); } return path; } @Override void addVertex(V vertex); @Override void addEdge(V from, V to); @Override int getNumberOfVertices(); @Override int getNumberOfEdges(); @Override void removeEdge(V from, V to); @Override void removeVertex(V vertex); @Override Collection<V> getAdjacents(V vertex); @Override List<V> findPathDFS(V start, V end); @Override List<V> findPathBFS(V start, V end); @Override Set<V> findConnected(V vertex); @Override Set<V> findConnected(Iterable<V> vertices); }
@Test public void testShortestPath_simple() { Graph<Integer> graph = createGraph(); List<Integer> path = graph.findPathBFS(1, 2); assertNotNull(path); assertEquals(2, path.size()); assertEquals(1, (int) path.get(0)); assertEquals(2, (int) path.get(1)); } @Test public void testShortestPath_complex() { Graph<Integer> graph = createGraph(); List<Integer> path = graph.findPathBFS(2, 8); assertNotNull(path); assertEquals(4, path.size()); assertEquals(2, (int) path.get(0)); assertEquals(3, (int) path.get(1)); assertEquals(6, (int) path.get(2)); assertEquals(8, (int) path.get(3)); } @Test public void testNoPathBFS(){ Graph<Integer> graph = createGraph(); List<Integer> path = graph.findPathBFS(3, 9); assertNull(path); }
UndirectedGraph implements Graph<V> { @Override public List<V> findPathDFS(V start, V end) { if(! graph.containsKey(start) || ! graph.containsKey(end)){ return null; } if(start.equals(end)){ throw new IllegalArgumentException(); } Set<V> alreadyVisited = new HashSet<>(); Deque<V> stack = new ArrayDeque<>(); dfs(alreadyVisited, stack, start, end); if(isPathTo(stack, end)){ List<V> path = new ArrayList<>(stack); Collections.reverse(path); return path; } return null; } @Override void addVertex(V vertex); @Override void addEdge(V from, V to); @Override int getNumberOfVertices(); @Override int getNumberOfEdges(); @Override void removeEdge(V from, V to); @Override void removeVertex(V vertex); @Override Collection<V> getAdjacents(V vertex); @Override List<V> findPathDFS(V start, V end); @Override List<V> findPathBFS(V start, V end); @Override Set<V> findConnected(V vertex); @Override Set<V> findConnected(Iterable<V> vertices); }
@Test public void testNoPathDFS(){ Graph<Integer> graph = createGraph(); List<Integer> path = graph.findPathDFS(10, 4); assertNull(path); }
UndirectedGraph implements Graph<V> { @Override public Set<V> findConnected(V vertex) { if(! graph.containsKey(vertex)){ return null; } Set<V> connected = new HashSet<>(); findConnected(connected, vertex); return connected; } @Override void addVertex(V vertex); @Override void addEdge(V from, V to); @Override int getNumberOfVertices(); @Override int getNumberOfEdges(); @Override void removeEdge(V from, V to); @Override void removeVertex(V vertex); @Override Collection<V> getAdjacents(V vertex); @Override List<V> findPathDFS(V start, V end); @Override List<V> findPathBFS(V start, V end); @Override Set<V> findConnected(V vertex); @Override Set<V> findConnected(Iterable<V> vertices); }
@Test public void testConnected(){ Graph<Integer> graph = createGraph(); Set<Integer> left = graph.findConnected(3); Set<Integer> right = graph.findConnected(10); assertEquals(8, left.size()); assertEquals(2, right.size()); }
README.md exists but content is empty.
Downloads last month
39