method2testcases
stringlengths
118
3.08k
### Question: PreparedUpdate implements UpdateContainer { public Credentials getCredentials() { return update.getCredentials(); } PreparedUpdate(final Update update, @Nullable final RpslObject originalObject, @Nullable final RpslObject updatedObject, final Action action); PreparedUpdate(final Update update, @Nullable final RpslObject originalObject, @Nullable final RpslObject updatedObject, final Action action, final OverrideOptions overrideOptions); @Override Update getUpdate(); Paragraph getParagraph(); boolean hasOriginalObject(); @Nullable RpslObject getReferenceObject(); @Nullable RpslObject getUpdatedObject(); RpslObject getSubmittedObject(); Action getAction(); Credentials getCredentials(); boolean isOverride(); OverrideOptions getOverrideOptions(); ObjectType getType(); String getKey(); String getFormattedKey(); Set<CIString> getNewValues(final AttributeType attributeType); Set<CIString> getDifferences(final AttributeType attributeType); @Override String toString(); }### Answer: @Test public void getCredentials() { subject.getCredentials(); verify(update).getCredentials(); }
### Question: PreparedUpdate implements UpdateContainer { public ObjectType getType() { return update.getType(); } PreparedUpdate(final Update update, @Nullable final RpslObject originalObject, @Nullable final RpslObject updatedObject, final Action action); PreparedUpdate(final Update update, @Nullable final RpslObject originalObject, @Nullable final RpslObject updatedObject, final Action action, final OverrideOptions overrideOptions); @Override Update getUpdate(); Paragraph getParagraph(); boolean hasOriginalObject(); @Nullable RpslObject getReferenceObject(); @Nullable RpslObject getUpdatedObject(); RpslObject getSubmittedObject(); Action getAction(); Credentials getCredentials(); boolean isOverride(); OverrideOptions getOverrideOptions(); ObjectType getType(); String getKey(); String getFormattedKey(); Set<CIString> getNewValues(final AttributeType attributeType); Set<CIString> getDifferences(final AttributeType attributeType); @Override String toString(); }### Answer: @Test public void getType() { subject.getType(); verify(update).getType(); }
### Question: PreparedUpdate implements UpdateContainer { public String getKey() { return updatedObject.getKey().toString(); } PreparedUpdate(final Update update, @Nullable final RpslObject originalObject, @Nullable final RpslObject updatedObject, final Action action); PreparedUpdate(final Update update, @Nullable final RpslObject originalObject, @Nullable final RpslObject updatedObject, final Action action, final OverrideOptions overrideOptions); @Override Update getUpdate(); Paragraph getParagraph(); boolean hasOriginalObject(); @Nullable RpslObject getReferenceObject(); @Nullable RpslObject getUpdatedObject(); RpslObject getSubmittedObject(); Action getAction(); Credentials getCredentials(); boolean isOverride(); OverrideOptions getOverrideOptions(); ObjectType getType(); String getKey(); String getFormattedKey(); Set<CIString> getNewValues(final AttributeType attributeType); Set<CIString> getDifferences(final AttributeType attributeType); @Override String toString(); }### Answer: @Test public void getKey() { assertThat(subject.getFormattedKey(), is("[mntner] DEV-TST-MNT")); }
### Question: ObjectKey { @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; final ObjectKey that = (ObjectKey) o; return Objects.equals(objectType, that.objectType) && Objects.equals(pkey, that.pkey); } ObjectKey(final ObjectType objectType, final String pkey); ObjectKey(final ObjectType objectType, final CIString pkey); ObjectType getObjectType(); CIString getPkey(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer: @Test public void equals() { final ObjectKey subject = new ObjectKey(ObjectType.MNTNER, "key"); assertThat(subject.equals(null), is(false)); assertThat(subject.equals(""), is(false)); assertThat(subject.equals(subject), is(true)); assertThat(subject.equals(new ObjectKey(ObjectType.MNTNER, "key")), is(true)); assertThat(subject.equals(new ObjectKey(ObjectType.MNTNER, "KEY")), is(true)); assertThat(subject.equals(new ObjectKey(ObjectType.MNTNER, "key2")), is(false)); assertThat(subject.equals(new ObjectKey(ObjectType.ORGANISATION, "key")), is(false)); }
### Question: ObjectKey { @Override public int hashCode() { return Objects.hash(objectType, pkey); } ObjectKey(final ObjectType objectType, final String pkey); ObjectKey(final ObjectType objectType, final CIString pkey); ObjectType getObjectType(); CIString getPkey(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer: @Test public void hash() { final ObjectKey subject = new ObjectKey(ObjectType.MNTNER, "key"); assertThat(subject.hashCode(), is(new ObjectKey(ObjectType.MNTNER, "key").hashCode())); assertThat(subject.hashCode(), not(is(new ObjectKey(ObjectType.ORGANISATION, "key").hashCode()))); } @Test public void hash_uppercase() { final ObjectKey subject = new ObjectKey(ObjectType.MNTNER, "key"); assertThat(subject.hashCode(), is(new ObjectKey(ObjectType.MNTNER, "KEY").hashCode())); }
### Question: ObjectKey { @Override public String toString() { return String.format("[%s] %s", objectType.getName(), pkey); } ObjectKey(final ObjectType objectType, final String pkey); ObjectKey(final ObjectType objectType, final CIString pkey); ObjectType getObjectType(); CIString getPkey(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer: @Test public void string() { final ObjectKey subject = new ObjectKey(ObjectType.MNTNER, "key"); assertThat(subject.toString(), is("[mntner] key")); } @Test public void string_uppercase() { final ObjectKey subject = new ObjectKey(ObjectType.MNTNER, "KeY"); assertThat(subject.toString(), is("[mntner] KeY")); }
### Question: Notification { public String getEmail() { return email; } Notification(final String email); void add(final Type type, final PreparedUpdate update, UpdateContext updateContext); String getEmail(); Set<Update> getUpdates(final Type type); boolean has(final Type type); }### Answer: @Test public void getEmail() { assertThat(subject.getEmail(), is("[email protected]")); }
### Question: Notification { public Set<Update> getUpdates(final Type type) { return updates.get(type); } Notification(final String email); void add(final Type type, final PreparedUpdate update, UpdateContext updateContext); String getEmail(); Set<Update> getUpdates(final Type type); boolean has(final Type type); }### Answer: @Test public void getUpdates_empty() { for (final Notification.Type type : Notification.Type.values()) { assertThat(subject.getUpdates(type), hasSize(0)); } }
### Question: Notification { public boolean has(final Type type) { return !updates.get(type).isEmpty(); } Notification(final String email); void add(final Type type, final PreparedUpdate update, UpdateContext updateContext); String getEmail(); Set<Update> getUpdates(final Type type); boolean has(final Type type); }### Answer: @Test public void has_empty() { for (final Notification.Type type : Notification.Type.values()) { assertThat(subject.has(type), is(false)); } }
### Question: Credentials { public boolean has(final Class<? extends Credential> clazz) { return !ofType(clazz).isEmpty(); } Credentials(); Credentials(final Set<? extends Credential> credentials); Credentials add(final Collection<Credential> addedCredentials); Set<Credential> all(); T single(final Class<T> clazz); Set<T> ofType(final Class<T> clazz); boolean has(final Class<? extends Credential> clazz); }### Answer: @Test public void pgp_credentials() { final Credential credential1 = Mockito.mock(Credential.class); final Credential credential2 = Mockito.mock(Credential.class); final PgpCredential pgpCredential = Mockito.mock(PgpCredential.class); final Credentials subject = new Credentials(Sets.newHashSet(credential1, credential2, pgpCredential)); assertThat(subject.has(PgpCredential.class), is(true)); }
### Question: Update implements UpdateContainer { public boolean isSigned() { return paragraph.getCredentials().has(PgpCredential.class) || paragraph.getCredentials().has(X509Credential.class); } Update(final Paragraph paragraph, final Operation operation, @Nullable final List<String> deleteReasons, final RpslObject submittedObject); @Override Update getUpdate(); Paragraph getParagraph(); Operation getOperation(); @Nullable List<String> getDeleteReasons(); ObjectType getType(); RpslObject getSubmittedObject(); boolean isSigned(); boolean isOverride(); Credentials getCredentials(); @Override String toString(); void setEffectiveCredential(final String effectiveCredential, final EffectiveCredentialType effectiveCredentialType); String getEffectiveCredential(); EffectiveCredentialType getEffectiveCredentialType(); }### Answer: @Test public void is_signed_with_one_pgp_credential() { final Paragraph paragraph = new Paragraph(content, new Credentials(Sets.newHashSet(PgpCredential.createKnownCredential("PGPKEY-AAAAAAAA")))); Update subject = new Update(paragraph, Operation.UNSPECIFIED, Lists.<String>newArrayList(), rpslObject); assertThat(subject.isSigned(), is(true)); } @Test public void is_signed_with_one_x509_credential() { final Paragraph paragraph = new Paragraph(content, new Credentials(Sets.newHashSet(X509Credential.createKnownCredential("X509-1")))); Update subject = new Update(paragraph, Operation.UNSPECIFIED, Lists.<String>newArrayList(), rpslObject); assertThat(subject.isSigned(), is(true)); } @Test public void is_not_signed_with_one_password_credential() { final Paragraph paragraph = new Paragraph(content, new Credentials(Sets.newHashSet(new PasswordCredential("password")))); Update subject = new Update(paragraph, Operation.UNSPECIFIED, Lists.<String>newArrayList(), rpslObject); assertThat(subject.isSigned(), is(false)); }
### Question: Update implements UpdateContainer { public boolean isOverride() { return paragraph.getCredentials().has(OverrideCredential.class); } Update(final Paragraph paragraph, final Operation operation, @Nullable final List<String> deleteReasons, final RpslObject submittedObject); @Override Update getUpdate(); Paragraph getParagraph(); Operation getOperation(); @Nullable List<String> getDeleteReasons(); ObjectType getType(); RpslObject getSubmittedObject(); boolean isSigned(); boolean isOverride(); Credentials getCredentials(); @Override String toString(); void setEffectiveCredential(final String effectiveCredential, final EffectiveCredentialType effectiveCredentialType); String getEffectiveCredential(); EffectiveCredentialType getEffectiveCredentialType(); }### Answer: @Test public void is_override() { final Paragraph paragraph = new Paragraph(content, new Credentials(Sets.newHashSet(OverrideCredential.parse("username,password")))); Update subject = new Update(paragraph, Operation.UNSPECIFIED, Lists.<String>newArrayList(), rpslObject); assertThat(subject.isOverride(), is(true)); } @Test public void is_not_override() { final Paragraph paragraph = new Paragraph(content, new Credentials(Sets.newHashSet(new PasswordCredential("password")))); Update subject = new Update(paragraph, Operation.UNSPECIFIED, Lists.<String>newArrayList(), rpslObject); assertThat(subject.isOverride(), is(false)); }
### Question: ProxyIterable implements Iterable<R> { @Override public Iterator<R> iterator() { return new Iterator<R>() { private final Iterator<P> sourceIterator = source.iterator(); private List<R> batch = initialBatch; private int idx; @Override public boolean hasNext() { return idx < batch.size() || sourceIterator.hasNext(); } @Override public R next() { if (idx == batch.size()) { idx = 0; batch = load(nextBatch(sourceIterator)); } if (idx >= batch.size()) { throw new NoSuchElementException(); } return batch.get(idx++); } @Override public void remove() { throw new UnsupportedOperationException(); } }; } ProxyIterable(final Iterable<P> source, final ProxyLoader<P, R> loader, final int prefetch); @Override Iterator<R> iterator(); }### Answer: @Test(expected = UnsupportedOperationException.class) public void test_remove() throws Exception { ProxyLoader<Integer, String> proxyLoader = Mockito.mock(ProxyLoader.class); subject = new ProxyIterable<>(Collections.<Integer>emptyList(), proxyLoader, 1); subject.iterator().remove(); } @Test(expected = NoSuchElementException.class) public void test_empty_next() { ProxyLoader<Integer, String> proxyLoader = Mockito.mock(ProxyLoader.class); subject = new ProxyIterable<>(Collections.<Integer>emptyList(), proxyLoader, 1); subject.iterator().next(); } @Test public void test_load_empty() { ProxyLoader<Integer, String> proxyLoader = Mockito.mock(ProxyLoader.class); subject = new ProxyIterable<>(Arrays.asList(1, 2, 3), proxyLoader, 1); final Iterator<String> iterator = subject.iterator(); assertTrue(iterator.hasNext()); assertNull(iterator.next()); }
### Question: NrtmConnectionPerIpLimitHandler extends SimpleChannelUpstreamHandler { private boolean connectionsExceeded(final InetAddress remoteAddresss) { final Integer count = connectionCounter.increment(remoteAddresss); return (count != null && count > maxConnectionsPerIp); } @Autowired NrtmConnectionPerIpLimitHandler( @Value("${whois.limit.connectionsPerIp:3}") final int maxConnectionsPerIp, final NrtmLog nrtmLog); @Override void channelOpen(final ChannelHandlerContext ctx, final ChannelStateEvent e); @Override void channelClosed(final ChannelHandlerContext ctx, final ChannelStateEvent e); }### Answer: @Test public void multiple_connected_same_ip() throws Exception { final InetSocketAddress remoteAddress = new InetSocketAddress("10.0.0.0", 43); when(channel.getRemoteAddress()).thenReturn(remoteAddress); final ChannelEvent openEvent = new UpstreamChannelStateEvent(channel, ChannelState.OPEN, Boolean.TRUE); subject.handleUpstream(ctx, openEvent); subject.handleUpstream(ctx, openEvent); subject.handleUpstream(ctx, openEvent); verify(ctx, times(2)).sendUpstream(openEvent); verify(channel, times(1)).write(argThat(new ArgumentMatcher<Object>() { @Override public boolean matches(Object argument) { return NrtmMessages.connectionsExceeded(MAX_CONNECTIONS_PER_IP).equals(argument); } })); verify(channelFuture, times(1)).addListener(ChannelFutureListener.CLOSE); verify(nrtmLog).log(Inet4Address.getByName("10.0.0.0"), "REJECTED"); verify(ctx, times(2)).sendUpstream(openEvent); }
### Question: SocketChannelFactory { public static Reader createReader(final SocketChannel socketChannel) { return new Reader(socketChannel); } private SocketChannelFactory(); static SocketChannel createSocketChannel(final String host, final int port); static Reader createReader(final SocketChannel socketChannel); static Writer createWriter(final SocketChannel socketChannel); }### Answer: @Test public void read_one_line() throws Exception { mockRead("aaa\n"); SocketChannelFactory.Reader reader = SocketChannelFactory.createReader(socketChannel); assertThat(reader.readLine(), is("aaa")); } @Test public void read_empty_line() throws Exception { mockRead("\n"); SocketChannelFactory.Reader reader = SocketChannelFactory.createReader(socketChannel); assertThat(reader.readLine(), is("")); } @Test public void read_multiple_lines() throws Exception { mockRead("aaa\nbbb\nccc\n"); SocketChannelFactory.Reader reader = SocketChannelFactory.createReader(socketChannel); assertThat(reader.readLine(), is("aaa")); assertThat(reader.readLine(), is("bbb")); assertThat(reader.readLine(), is("ccc")); }
### Question: SocketChannelFactory { public static Writer createWriter(final SocketChannel socketChannel) { return new Writer(socketChannel); } private SocketChannelFactory(); static SocketChannel createSocketChannel(final String host, final int port); static Reader createReader(final SocketChannel socketChannel); static Writer createWriter(final SocketChannel socketChannel); }### Answer: @Test public void write_line() throws Exception { mockWrite("aaa\n"); SocketChannelFactory.Writer writer = SocketChannelFactory.createWriter(socketChannel); writer.writeLine("aaa"); }
### Question: NrtmImporter implements EmbeddedValueResolverAware, ApplicationService { @PostConstruct void checkSources() { for (final CIString source : sources) { if (sourceContext.isVirtual(source)) { throw new IllegalArgumentException(String.format("Cannot use NRTM with virtual source: %s", source)); } JdbcRpslObjectOperations.sanityCheck(sourceContext.getSourceConfiguration(Source.master(source)).getJdbcTemplate()); } } @Autowired NrtmImporter(final NrtmClientFactory nrtmClientFactory, final SourceContext sourceContext, @Value("${nrtm.import.enabled:false}") final boolean enabled, @Value("${nrtm.import.sources:}") final String sources); @Override void setEmbeddedValueResolver(final StringValueResolver resolver); @Override void start(); @Override void stop(final boolean force); }### Answer: @Test(expected = IllegalArgumentException.class) public void invalid_source() { when(sourceContext.isVirtual(CIString.ciString("1-GRS"))).thenReturn(true); subject.checkSources(); }
### Question: NrtmQueryHandler extends SimpleChannelUpstreamHandler { @Override public void channelConnected(final ChannelHandlerContext ctx, final ChannelStateEvent e) throws Exception { PendingWrites.add(ctx.getChannel()); writeMessage(ctx.getChannel(), NrtmMessages.termsAndConditions()); super.channelConnected(ctx, e); } NrtmQueryHandler( @Qualifier("jdbcSlaveSerialDao") final SerialDao serialDao, @Qualifier("dummifierNrtm") final Dummifier dummifier, @Qualifier("clientSynchronisationScheduler") final TaskScheduler clientSynchronisationScheduler, final NrtmLog nrtmLog, final ApplicationVersion applicationVersion, @Value("${whois.source}") final String source, @Value("${whois.nonauth.source}") final String nonAuthSource, @Value("${nrtm.update.interval:60}") final long updateInterval, @Value("${nrtm.keepalive.end.of.stream:false}") final boolean keepaliveEndOfStream); @Override void messageReceived(final ChannelHandlerContext ctx, final MessageEvent e); @Override void channelConnected(final ChannelHandlerContext ctx, final ChannelStateEvent e); @Override void channelDisconnected(final ChannelHandlerContext ctx, final ChannelStateEvent e); }### Answer: @Test public void channelConnected() throws Exception { subject.channelConnected(contextMock, channelStateEventMock); verify(channelMock).write(NrtmMessages.termsAndConditions() + "\n\n"); }
### Question: NrtmExceptionHandler extends SimpleChannelUpstreamHandler { @Override public void exceptionCaught(final ChannelHandlerContext ctx, final ExceptionEvent event) { final Channel channel = event.getChannel(); final Throwable exception = event.getCause(); if (!channel.isOpen()) { return; } if (exception instanceof IllegalArgumentException) { channel.write(exception.getMessage() + "\n\n").addListener(ChannelFutureListener.CLOSE); } else if (exception instanceof IOException) { LOGGER.debug("IO exception", exception); } else { LOGGER.error("Caught exception on channel id = {}, from = {}", channel.getId(), ChannelUtil.getRemoteAddress(channel), exception ); channel.write(MESSAGE).addListener(ChannelFutureListener.CLOSE); } } @Override void exceptionCaught(final ChannelHandlerContext ctx, final ExceptionEvent event); }### Answer: @Test public void handle_illegal_argument_exception() { when(exceptionEventMock.getCause()).thenReturn(new IllegalArgumentException(QUERY)); subject.exceptionCaught(channelHandlerContextMock, exceptionEventMock); verify(channelMock, times(1)).write(QUERY + "\n\n"); verify(channelFutureMock, times(1)).addListener(ChannelFutureListener.CLOSE); } @Test public void handle_exception() { when(exceptionEventMock.getCause()).thenReturn(new Exception()); subject.exceptionCaught(channelHandlerContextMock, exceptionEventMock); verify(channelMock, times(1)).write(NrtmExceptionHandler.MESSAGE); verify(channelFutureMock, times(1)).addListener(ChannelFutureListener.CLOSE); }
### Question: CollectionHelper { public static <T> T uniqueResult(final Collection<T> c) { switch (c.size()) { case 0: return null; case 1: return c.iterator().next(); default: throw new IllegalStateException("Unexpected number of elements in collection: " + c.size()); } } private CollectionHelper(); static T uniqueResult(final Collection<T> c); static Iterable<ResponseObject> iterateProxy( final ProxyLoader<Identifiable, RpslObject> rpslObjectLoader, final Iterable<? extends Identifiable> identifiables); static final byte[] EMPTY_BYTE_ARRAY; }### Answer: @Test public void uniqueResult_no_results() { final Object result = CollectionHelper.uniqueResult(Arrays.asList()); assertNull(result); } @Test public void uniqueResult_single_result() { final Integer result = CollectionHelper.uniqueResult(Arrays.asList(1)); assertThat(result, is(1)); } @Test(expected = IllegalStateException.class) public void uniqueResult_multiple_results() { CollectionHelper.uniqueResult(Arrays.asList(1, 2)); }
### Question: IndexStrategyAdapter implements IndexStrategy { @Override public final AttributeType getAttributeType() { return attributeType; } IndexStrategyAdapter(final AttributeType attributeType); @Override final AttributeType getAttributeType(); @Override final int addToIndex(final JdbcTemplate jdbcTemplate, final RpslObjectInfo objectInfo, final RpslObject object, final CIString value); @Override int addToIndex(final JdbcTemplate jdbcTemplate, final RpslObjectInfo objectInfo, final RpslObject object, final String value); @Override final List<RpslObjectInfo> findInIndex(final JdbcTemplate jdbcTemplate, final CIString value); @Override List<RpslObjectInfo> findInIndex(final JdbcTemplate jdbcTemplate, final String value); @Override final List<RpslObjectInfo> findInIndex(final JdbcTemplate jdbcTemplate, final CIString value, final ObjectType type); @Override List<RpslObjectInfo> findInIndex(final JdbcTemplate jdbcTemplate, final String value, final ObjectType type); @Override List<RpslObjectInfo> findInIndex(final JdbcTemplate jdbcTemplate, final RpslObjectInfo value); @Override List<RpslObjectInfo> findInIndex(final JdbcTemplate jdbcTemplate, final RpslObjectInfo value, final ObjectType type); @Override void removeFromIndex(final JdbcTemplate jdbcTemplate, final RpslObjectInfo objectInfo); @Override String getLookupTableName(); @Override void cleanupMissingObjects(final JdbcTemplate jdbcTemplate); @Override String getLookupColumnName(); }### Answer: @Test public void getAttributeType() { assertThat(subject.getAttributeType(), is(ATTRIBUTE_TYPE)); }
### Question: IndexStrategyAdapter implements IndexStrategy { @Override public final int addToIndex(final JdbcTemplate jdbcTemplate, final RpslObjectInfo objectInfo, final RpslObject object, final CIString value) { return addToIndex(jdbcTemplate, objectInfo, object, value.toString()); } IndexStrategyAdapter(final AttributeType attributeType); @Override final AttributeType getAttributeType(); @Override final int addToIndex(final JdbcTemplate jdbcTemplate, final RpslObjectInfo objectInfo, final RpslObject object, final CIString value); @Override int addToIndex(final JdbcTemplate jdbcTemplate, final RpslObjectInfo objectInfo, final RpslObject object, final String value); @Override final List<RpslObjectInfo> findInIndex(final JdbcTemplate jdbcTemplate, final CIString value); @Override List<RpslObjectInfo> findInIndex(final JdbcTemplate jdbcTemplate, final String value); @Override final List<RpslObjectInfo> findInIndex(final JdbcTemplate jdbcTemplate, final CIString value, final ObjectType type); @Override List<RpslObjectInfo> findInIndex(final JdbcTemplate jdbcTemplate, final String value, final ObjectType type); @Override List<RpslObjectInfo> findInIndex(final JdbcTemplate jdbcTemplate, final RpslObjectInfo value); @Override List<RpslObjectInfo> findInIndex(final JdbcTemplate jdbcTemplate, final RpslObjectInfo value, final ObjectType type); @Override void removeFromIndex(final JdbcTemplate jdbcTemplate, final RpslObjectInfo objectInfo); @Override String getLookupTableName(); @Override void cleanupMissingObjects(final JdbcTemplate jdbcTemplate); @Override String getLookupColumnName(); }### Answer: @Test public void addToIndex() { assertThat(subject.addToIndex(null, null, null, (String) null), is(1)); }
### Question: IndexStrategyAdapter implements IndexStrategy { @Override public final List<RpslObjectInfo> findInIndex(final JdbcTemplate jdbcTemplate, final CIString value) { return findInIndex(jdbcTemplate, value.toString()); } IndexStrategyAdapter(final AttributeType attributeType); @Override final AttributeType getAttributeType(); @Override final int addToIndex(final JdbcTemplate jdbcTemplate, final RpslObjectInfo objectInfo, final RpslObject object, final CIString value); @Override int addToIndex(final JdbcTemplate jdbcTemplate, final RpslObjectInfo objectInfo, final RpslObject object, final String value); @Override final List<RpslObjectInfo> findInIndex(final JdbcTemplate jdbcTemplate, final CIString value); @Override List<RpslObjectInfo> findInIndex(final JdbcTemplate jdbcTemplate, final String value); @Override final List<RpslObjectInfo> findInIndex(final JdbcTemplate jdbcTemplate, final CIString value, final ObjectType type); @Override List<RpslObjectInfo> findInIndex(final JdbcTemplate jdbcTemplate, final String value, final ObjectType type); @Override List<RpslObjectInfo> findInIndex(final JdbcTemplate jdbcTemplate, final RpslObjectInfo value); @Override List<RpslObjectInfo> findInIndex(final JdbcTemplate jdbcTemplate, final RpslObjectInfo value, final ObjectType type); @Override void removeFromIndex(final JdbcTemplate jdbcTemplate, final RpslObjectInfo objectInfo); @Override String getLookupTableName(); @Override void cleanupMissingObjects(final JdbcTemplate jdbcTemplate); @Override String getLookupColumnName(); }### Answer: @Test public void findInIndex() { assertThat(subject.findInIndex(null, (String) null), hasSize(0)); assertThat(subject.findInIndex(null, new RpslObjectInfo(1, ObjectType.AUT_NUM, "AS000")), hasSize(0)); assertThat(subject.findInIndex(null, new RpslObjectInfo(1, ObjectType.AUT_NUM, "AS000"), ObjectType.AUT_NUM), hasSize(0)); }
### Question: IndexStrategyAdapter implements IndexStrategy { @Override public void removeFromIndex(final JdbcTemplate jdbcTemplate, final RpslObjectInfo objectInfo) { } IndexStrategyAdapter(final AttributeType attributeType); @Override final AttributeType getAttributeType(); @Override final int addToIndex(final JdbcTemplate jdbcTemplate, final RpslObjectInfo objectInfo, final RpslObject object, final CIString value); @Override int addToIndex(final JdbcTemplate jdbcTemplate, final RpslObjectInfo objectInfo, final RpslObject object, final String value); @Override final List<RpslObjectInfo> findInIndex(final JdbcTemplate jdbcTemplate, final CIString value); @Override List<RpslObjectInfo> findInIndex(final JdbcTemplate jdbcTemplate, final String value); @Override final List<RpslObjectInfo> findInIndex(final JdbcTemplate jdbcTemplate, final CIString value, final ObjectType type); @Override List<RpslObjectInfo> findInIndex(final JdbcTemplate jdbcTemplate, final String value, final ObjectType type); @Override List<RpslObjectInfo> findInIndex(final JdbcTemplate jdbcTemplate, final RpslObjectInfo value); @Override List<RpslObjectInfo> findInIndex(final JdbcTemplate jdbcTemplate, final RpslObjectInfo value, final ObjectType type); @Override void removeFromIndex(final JdbcTemplate jdbcTemplate, final RpslObjectInfo objectInfo); @Override String getLookupTableName(); @Override void cleanupMissingObjects(final JdbcTemplate jdbcTemplate); @Override String getLookupColumnName(); }### Answer: @Test public void removeFromIndex() { subject.removeFromIndex(null, null); }
### Question: IndexStrategyAdapter implements IndexStrategy { @Override public String getLookupTableName() { return null; } IndexStrategyAdapter(final AttributeType attributeType); @Override final AttributeType getAttributeType(); @Override final int addToIndex(final JdbcTemplate jdbcTemplate, final RpslObjectInfo objectInfo, final RpslObject object, final CIString value); @Override int addToIndex(final JdbcTemplate jdbcTemplate, final RpslObjectInfo objectInfo, final RpslObject object, final String value); @Override final List<RpslObjectInfo> findInIndex(final JdbcTemplate jdbcTemplate, final CIString value); @Override List<RpslObjectInfo> findInIndex(final JdbcTemplate jdbcTemplate, final String value); @Override final List<RpslObjectInfo> findInIndex(final JdbcTemplate jdbcTemplate, final CIString value, final ObjectType type); @Override List<RpslObjectInfo> findInIndex(final JdbcTemplate jdbcTemplate, final String value, final ObjectType type); @Override List<RpslObjectInfo> findInIndex(final JdbcTemplate jdbcTemplate, final RpslObjectInfo value); @Override List<RpslObjectInfo> findInIndex(final JdbcTemplate jdbcTemplate, final RpslObjectInfo value, final ObjectType type); @Override void removeFromIndex(final JdbcTemplate jdbcTemplate, final RpslObjectInfo objectInfo); @Override String getLookupTableName(); @Override void cleanupMissingObjects(final JdbcTemplate jdbcTemplate); @Override String getLookupColumnName(); }### Answer: @Test public void getLookupTableName() { assertNull(subject.getLookupTableName()); }
### Question: IndexStrategyAdapter implements IndexStrategy { @Override public String getLookupColumnName() { return null; } IndexStrategyAdapter(final AttributeType attributeType); @Override final AttributeType getAttributeType(); @Override final int addToIndex(final JdbcTemplate jdbcTemplate, final RpslObjectInfo objectInfo, final RpslObject object, final CIString value); @Override int addToIndex(final JdbcTemplate jdbcTemplate, final RpslObjectInfo objectInfo, final RpslObject object, final String value); @Override final List<RpslObjectInfo> findInIndex(final JdbcTemplate jdbcTemplate, final CIString value); @Override List<RpslObjectInfo> findInIndex(final JdbcTemplate jdbcTemplate, final String value); @Override final List<RpslObjectInfo> findInIndex(final JdbcTemplate jdbcTemplate, final CIString value, final ObjectType type); @Override List<RpslObjectInfo> findInIndex(final JdbcTemplate jdbcTemplate, final String value, final ObjectType type); @Override List<RpslObjectInfo> findInIndex(final JdbcTemplate jdbcTemplate, final RpslObjectInfo value); @Override List<RpslObjectInfo> findInIndex(final JdbcTemplate jdbcTemplate, final RpslObjectInfo value, final ObjectType type); @Override void removeFromIndex(final JdbcTemplate jdbcTemplate, final RpslObjectInfo objectInfo); @Override String getLookupTableName(); @Override void cleanupMissingObjects(final JdbcTemplate jdbcTemplate); @Override String getLookupColumnName(); }### Answer: @Test public void getLookupColumnName() { assertNull(subject.getLookupColumnName()); }
### Question: IndexStrategies { public static IndexStrategy get(final AttributeType attributeType) { return INDEX_BY_ATTRIBUTE.get(attributeType); } private IndexStrategies(); static IndexStrategy get(final AttributeType attributeType); static List<IndexStrategy> getReferencing(final ObjectType objectType); }### Answer: @Test public void check_index_strategied_for_lookup_attributes() { final Set<AttributeType> attibutesWithrequiredIndex = Sets.newHashSet(); for (final ObjectType objectType : ObjectType.values()) { final ObjectTemplate objectTemplate = ObjectTemplate.getTemplate(objectType); attibutesWithrequiredIndex.addAll(objectTemplate.getInverseLookupAttributes()); } for (final AttributeType attributeType : attibutesWithrequiredIndex) { assertThat(attributeType.getName(), IndexStrategies.get(attributeType) instanceof Unindexed, is(false)); } }
### Question: ObjectTypeIds { public static ObjectType getType(final int serialType) throws IllegalArgumentException { final ObjectType objectType = BY_TYPE_ID.get(serialType); if (objectType == null) { throw new IllegalArgumentException("Object type with objectTypeId " + serialType + " not found"); } return objectType; } private ObjectTypeIds(); static Integer getId(final ObjectType objectType); static ObjectType getType(final int serialType); }### Answer: @Test public void getBySerialType() { for (Integer objectTypeId : ImmutableList.of(0, 1, 2, 3, 4, 5, 6, 7, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21)) { assertThat(ObjectTypeIds.getType(objectTypeId), Matchers.instanceOf(ObjectType.class)); } } @Test(expected = IllegalArgumentException.class) public void getBySerialType_unknown() { ObjectTypeIds.getType(-1000); }
### Question: SourceAwareDataSource extends AbstractDataSource { @Override public Connection getConnection() throws SQLException { return getActualDataSource().getConnection(); } @Autowired SourceAwareDataSource(final BasicSourceContext sourceContext); @Override Connection getConnection(); @Override Connection getConnection(final String username, final String password); }### Answer: @Test public void test_getConnection() throws Exception { subject.getConnection(); verify(dataSource, times(1)).getConnection(); } @Test public void test_getConnection_with_user() throws Exception { subject.getConnection("username", "password"); verify(dataSource, times(1)).getConnection("username", "password"); }
### Question: DateUtil { public static LocalDateTime fromDate(final Date date) { return Instant.ofEpochMilli(date.getTime()) .atZone(ZoneOffset.systemDefault()) .toLocalDateTime(); } private DateUtil(); static Date toDate(final LocalDateTime localDateTime); static Date toDate(final LocalDate localDate); static LocalDateTime fromDate(final Date date); }### Answer: @Test public void fromDate() { assertThat(DateUtil.fromDate(new Date(EPOCH_TIMESTAMP)), is(EPOCH_LOCAL_DATE_TIME)); assertThat(DateUtil.fromDate(new Date(RECENT_TIMESTAMP)), is(RECENT_LOCAL_DATE_TIME)); }
### Question: DateUtil { public static Date toDate(final LocalDateTime localDateTime) { return Date.from(localDateTime.atZone(ZoneOffset.systemDefault()) .toInstant()); } private DateUtil(); static Date toDate(final LocalDateTime localDateTime); static Date toDate(final LocalDate localDate); static LocalDateTime fromDate(final Date date); }### Answer: @Test public void toDate() { assertThat(DateUtil.toDate(EPOCH_LOCAL_DATE_TIME), is(new Date(EPOCH_TIMESTAMP))); assertThat(DateUtil.toDate(RECENT_LOCAL_DATE_TIME), is(new Date(RECENT_TIMESTAMP))); }
### Question: BlockEvent { @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; final BlockEvent that = (BlockEvent) o; return Objects.equals(time, that.time) && Objects.equals(type, that.type); } BlockEvent(final LocalDateTime time, final int limit, final Type type); @Override boolean equals(Object o); @Override int hashCode(); LocalDateTime getTime(); int getLimit(); Type getType(); }### Answer: @Test public void equals() { final BlockEvent subject = new BlockEvent(LocalDateTime.of(2012, 2, 16, 12, 0), 1, BlockEvent.Type.BLOCK_TEMPORARY); final BlockEvent clone = new BlockEvent(LocalDateTime.of(2012, 2, 16, 12, 0), 1, BlockEvent.Type.BLOCK_TEMPORARY); final BlockEvent newDate = new BlockEvent(LocalDateTime.of(2011, 2, 16, 12, 0), 1, BlockEvent.Type.BLOCK_TEMPORARY); final BlockEvent newType = new BlockEvent(LocalDateTime.of(2012, 2, 16, 12, 0), 1, BlockEvent.Type.UNBLOCK); assertEquals("same", subject, subject); assertEquals("equal", subject, clone); assertEquals("hashcode", subject.hashCode(), clone.hashCode()); assertFalse("null", subject.equals(null)); assertFalse("different class", subject.equals(1)); assertFalse("different date", subject.equals(newDate)); assertFalse("different type", subject.equals(newType)); }
### Question: BlockEvents { public boolean isPermanentBlockRequired() { return getTemporaryBlockCount() >= NR_TEMP_BLOCKS_BEFORE_PERMANENT; } BlockEvents(final String prefix, final List<BlockEvent> blockEvents); String getPrefix(); int getTemporaryBlockCount(); boolean isPermanentBlockRequired(); static final int NR_TEMP_BLOCKS_BEFORE_PERMANENT; }### Answer: @Test public void test_permanent_block_limit_reached_9() { final BlockEvents blockEvents = createBlockEvents(prefix, 9); assertThat(blockEvents.isPermanentBlockRequired(), is(false)); } @Test public void test_permanent_block_limit_reached_10() { final BlockEvents blockEvents = createBlockEvents(prefix, 10); assertThat(blockEvents.isPermanentBlockRequired(), is(true)); } @Test public void test_permanent_block_limit_reached_50() { final BlockEvents blockEvents = createBlockEvents(prefix, 50); assertThat(blockEvents.isPermanentBlockRequired(), is(true)); }
### Question: ConcurrentState { public void set(final Boolean value) { updates.add(value); } void set(final Boolean value); void waitUntil(final Boolean value); }### Answer: @Test public void set_and_unset_state() { Counter counter = new Counter(); new Thread(counter).start(); subject.set(true); waitForExpectedValue(counter, 1); subject.set(false); subject.set(false); subject.set(false); waitForExpectedValue(counter, 2); subject.set(true); waitForExpectedValue(counter, 3); } @Test public void set_and_unset_state_multiple_updates() { subject.set(true); subject.set(false); subject.set(false); subject.set(false); subject.set(true); Counter counter = new Counter(); new Thread(counter).start(); waitForExpectedValue(counter, 1); }
### Question: IpResourceTree { public V getValue(IpInterval<?> ipInterval) { List<V> list = getTree(ipInterval).findExactOrFirstLessSpecific(ipInterval); return CollectionHelper.uniqueResult(list); } @SuppressWarnings({"unchecked", "rawtypes"}) IpResourceTree(); void add(IpInterval<?> ipInterval, V value); V getValue(IpInterval<?> ipInterval); }### Answer: @Test public void test_getValue_ipv4_exact() { assertThat(subject.getValue(ipv4Resource), is(41)); } @Test public void test_getValue_ipv4_lessSpecific() { assertThat(subject.getValue(ipv4ResourceMoreSpecific), is(41)); } @Test public void test_getValue_ipv4_unknown() { assertThat(subject.getValue(ipv4ResourceUnknown), is(nullValue())); } @Test public void test_getValue_ipv6_exact() { assertThat(subject.getValue(ipv6Resource), is(61)); } @Test public void test_getValue_ipv6_lessSpecific() { assertThat(subject.getValue(ipv6ResourceMoreSpecific), is(61)); } @Test public void test_getValue_ipv6_unknown() { assertThat(subject.getValue(ipv6ResourceUnknown), is(nullValue())); }
### Question: AutomaticPermanentBlocks implements DailyScheduledTask { @Override @Scheduled(cron = "0 0 0 * * *") @SchedulerLock(name = "AutomaticPermanentBlocks") public void run() { final LocalDate now = dateTimeProvider.getCurrentDate(); final LocalDate checkTemporaryBlockTime = now.minusDays(30); final List<BlockEvents> temporaryBlocks = accessControlListDao.getTemporaryBlocks(checkTemporaryBlockTime); for (final BlockEvents blockEvents : temporaryBlocks) { handleBlockEvents(now, blockEvents); } } @Autowired AutomaticPermanentBlocks(final DateTimeProvider dateTimeProvider, final AccessControlListDao accessControlListDao, final IpResourceConfiguration ipResourceConfiguration); @Override @Scheduled(cron = "0 0 0 * * *") @SchedulerLock(name = "AutomaticPermanentBlocks") void run(); }### Answer: @Test public void test_date() throws Exception { subject.run(); verify(accessControlListDao, times(1)).getTemporaryBlocks(now.minusDays(30)); } @Test public void test_run_no_temporary_blocks() throws Exception { when(accessControlListDao.getTemporaryBlocks(now)).thenReturn(Collections.<BlockEvents>emptyList()); subject.run(); verify(accessControlListDao, never()).savePermanentBlock(any(IpInterval.class), any(LocalDate.class), anyInt(), anyString()); } @Test public void test_run_temporary_blocks_already_denied() throws Exception { when(accessControlListDao.getTemporaryBlocks(now.minusDays(30))).thenReturn(Arrays.asList(createBlockEvents(IPV4_PREFIX, 20))); when(ipResourceConfiguration.isDenied(any(InetAddress.class))).thenReturn(true); subject.run(); verify(ipResourceConfiguration).isDenied(any(InetAddress.class)); verify(accessControlListDao, never()).savePermanentBlock(any(IpInterval.class), any(LocalDate.class), anyInt(), anyString()); }
### Question: SynchronizedIntervalMap implements IntervalMap<K, V> { @Override public void put(K key, V value) { synchronized (mutex) { wrapped.put(key, value); } } private SynchronizedIntervalMap(final IntervalMap<K, V> wrapped); private SynchronizedIntervalMap(final IntervalMap<K, V> wrapped, final Object mutex); static IntervalMap<K, V> synchronizedMap(IntervalMap<K, V> toWrap); static IntervalMap<K, V> synchronizedMap(IntervalMap<K, V> toWrap, final Object mutex); @Override void put(K key, V value); @Override void remove(K key); @Override void remove(K key, V value); @Override List<V> findFirstLessSpecific(K key); @Override List<V> findAllLessSpecific(K key); @Override List<V> findExactAndAllLessSpecific(K key); @Override List<V> findExact(K key); @Override List<V> findExactOrFirstLessSpecific(K key); @Override List<V> findFirstMoreSpecific(K key); @Override List<V> findAllMoreSpecific(K key); @Override List<V> findExactAndAllMoreSpecific(K key); @Override void clear(); }### Answer: @Test public void put() { subject.put(key, value); verify(wrapped, times(1)).put(key, value); }
### Question: SynchronizedIntervalMap implements IntervalMap<K, V> { @Override public void remove(K key) { synchronized (mutex) { wrapped.remove(key); } } private SynchronizedIntervalMap(final IntervalMap<K, V> wrapped); private SynchronizedIntervalMap(final IntervalMap<K, V> wrapped, final Object mutex); static IntervalMap<K, V> synchronizedMap(IntervalMap<K, V> toWrap); static IntervalMap<K, V> synchronizedMap(IntervalMap<K, V> toWrap, final Object mutex); @Override void put(K key, V value); @Override void remove(K key); @Override void remove(K key, V value); @Override List<V> findFirstLessSpecific(K key); @Override List<V> findAllLessSpecific(K key); @Override List<V> findExactAndAllLessSpecific(K key); @Override List<V> findExact(K key); @Override List<V> findExactOrFirstLessSpecific(K key); @Override List<V> findFirstMoreSpecific(K key); @Override List<V> findAllMoreSpecific(K key); @Override List<V> findExactAndAllMoreSpecific(K key); @Override void clear(); }### Answer: @Test public void remove() { subject.remove(key); verify(wrapped, times(1)).remove(key); } @Test public void remove_with_value() { subject.remove(key, value); verify(wrapped, times(1)).remove(key, value); }
### Question: SynchronizedIntervalMap implements IntervalMap<K, V> { @Override public List<V> findFirstLessSpecific(K key) { synchronized (mutex) { return wrapped.findFirstLessSpecific(key); } } private SynchronizedIntervalMap(final IntervalMap<K, V> wrapped); private SynchronizedIntervalMap(final IntervalMap<K, V> wrapped, final Object mutex); static IntervalMap<K, V> synchronizedMap(IntervalMap<K, V> toWrap); static IntervalMap<K, V> synchronizedMap(IntervalMap<K, V> toWrap, final Object mutex); @Override void put(K key, V value); @Override void remove(K key); @Override void remove(K key, V value); @Override List<V> findFirstLessSpecific(K key); @Override List<V> findAllLessSpecific(K key); @Override List<V> findExactAndAllLessSpecific(K key); @Override List<V> findExact(K key); @Override List<V> findExactOrFirstLessSpecific(K key); @Override List<V> findFirstMoreSpecific(K key); @Override List<V> findAllMoreSpecific(K key); @Override List<V> findExactAndAllMoreSpecific(K key); @Override void clear(); }### Answer: @Test public void findFirstLessSpecific() { subject.findFirstLessSpecific(key); verify(wrapped, times(1)).findFirstLessSpecific(key); }
### Question: SynchronizedIntervalMap implements IntervalMap<K, V> { @Override public List<V> findAllLessSpecific(K key) { synchronized (mutex) { return wrapped.findAllLessSpecific(key); } } private SynchronizedIntervalMap(final IntervalMap<K, V> wrapped); private SynchronizedIntervalMap(final IntervalMap<K, V> wrapped, final Object mutex); static IntervalMap<K, V> synchronizedMap(IntervalMap<K, V> toWrap); static IntervalMap<K, V> synchronizedMap(IntervalMap<K, V> toWrap, final Object mutex); @Override void put(K key, V value); @Override void remove(K key); @Override void remove(K key, V value); @Override List<V> findFirstLessSpecific(K key); @Override List<V> findAllLessSpecific(K key); @Override List<V> findExactAndAllLessSpecific(K key); @Override List<V> findExact(K key); @Override List<V> findExactOrFirstLessSpecific(K key); @Override List<V> findFirstMoreSpecific(K key); @Override List<V> findAllMoreSpecific(K key); @Override List<V> findExactAndAllMoreSpecific(K key); @Override void clear(); }### Answer: @Test public void findAllLessSpecific() { subject.findAllLessSpecific(key); verify(wrapped, times(1)).findAllLessSpecific(key); }
### Question: SynchronizedIntervalMap implements IntervalMap<K, V> { @Override public List<V> findExactAndAllLessSpecific(K key) { synchronized (mutex) { return wrapped.findExactAndAllLessSpecific(key); } } private SynchronizedIntervalMap(final IntervalMap<K, V> wrapped); private SynchronizedIntervalMap(final IntervalMap<K, V> wrapped, final Object mutex); static IntervalMap<K, V> synchronizedMap(IntervalMap<K, V> toWrap); static IntervalMap<K, V> synchronizedMap(IntervalMap<K, V> toWrap, final Object mutex); @Override void put(K key, V value); @Override void remove(K key); @Override void remove(K key, V value); @Override List<V> findFirstLessSpecific(K key); @Override List<V> findAllLessSpecific(K key); @Override List<V> findExactAndAllLessSpecific(K key); @Override List<V> findExact(K key); @Override List<V> findExactOrFirstLessSpecific(K key); @Override List<V> findFirstMoreSpecific(K key); @Override List<V> findAllMoreSpecific(K key); @Override List<V> findExactAndAllMoreSpecific(K key); @Override void clear(); }### Answer: @Test public void findExactAndAllLessSpecific() { subject.findExactAndAllLessSpecific(key); verify(wrapped, times(1)).findExactAndAllLessSpecific(key); }
### Question: SynchronizedIntervalMap implements IntervalMap<K, V> { @Override public List<V> findExact(K key) { synchronized (mutex) { return wrapped.findExact(key); } } private SynchronizedIntervalMap(final IntervalMap<K, V> wrapped); private SynchronizedIntervalMap(final IntervalMap<K, V> wrapped, final Object mutex); static IntervalMap<K, V> synchronizedMap(IntervalMap<K, V> toWrap); static IntervalMap<K, V> synchronizedMap(IntervalMap<K, V> toWrap, final Object mutex); @Override void put(K key, V value); @Override void remove(K key); @Override void remove(K key, V value); @Override List<V> findFirstLessSpecific(K key); @Override List<V> findAllLessSpecific(K key); @Override List<V> findExactAndAllLessSpecific(K key); @Override List<V> findExact(K key); @Override List<V> findExactOrFirstLessSpecific(K key); @Override List<V> findFirstMoreSpecific(K key); @Override List<V> findAllMoreSpecific(K key); @Override List<V> findExactAndAllMoreSpecific(K key); @Override void clear(); }### Answer: @Test public void findExact() { subject.findExact(key); verify(wrapped, times(1)).findExact(key); }
### Question: SynchronizedIntervalMap implements IntervalMap<K, V> { @Override public List<V> findExactOrFirstLessSpecific(K key) { synchronized (mutex) { return wrapped.findExactOrFirstLessSpecific(key); } } private SynchronizedIntervalMap(final IntervalMap<K, V> wrapped); private SynchronizedIntervalMap(final IntervalMap<K, V> wrapped, final Object mutex); static IntervalMap<K, V> synchronizedMap(IntervalMap<K, V> toWrap); static IntervalMap<K, V> synchronizedMap(IntervalMap<K, V> toWrap, final Object mutex); @Override void put(K key, V value); @Override void remove(K key); @Override void remove(K key, V value); @Override List<V> findFirstLessSpecific(K key); @Override List<V> findAllLessSpecific(K key); @Override List<V> findExactAndAllLessSpecific(K key); @Override List<V> findExact(K key); @Override List<V> findExactOrFirstLessSpecific(K key); @Override List<V> findFirstMoreSpecific(K key); @Override List<V> findAllMoreSpecific(K key); @Override List<V> findExactAndAllMoreSpecific(K key); @Override void clear(); }### Answer: @Test public void findExactOrFirstLessSpecific() { subject.findExactOrFirstLessSpecific(key); verify(wrapped, times(1)).findExactOrFirstLessSpecific(key); }
### Question: SynchronizedIntervalMap implements IntervalMap<K, V> { @Override public List<V> findFirstMoreSpecific(K key) { synchronized (mutex) { return wrapped.findFirstMoreSpecific(key); } } private SynchronizedIntervalMap(final IntervalMap<K, V> wrapped); private SynchronizedIntervalMap(final IntervalMap<K, V> wrapped, final Object mutex); static IntervalMap<K, V> synchronizedMap(IntervalMap<K, V> toWrap); static IntervalMap<K, V> synchronizedMap(IntervalMap<K, V> toWrap, final Object mutex); @Override void put(K key, V value); @Override void remove(K key); @Override void remove(K key, V value); @Override List<V> findFirstLessSpecific(K key); @Override List<V> findAllLessSpecific(K key); @Override List<V> findExactAndAllLessSpecific(K key); @Override List<V> findExact(K key); @Override List<V> findExactOrFirstLessSpecific(K key); @Override List<V> findFirstMoreSpecific(K key); @Override List<V> findAllMoreSpecific(K key); @Override List<V> findExactAndAllMoreSpecific(K key); @Override void clear(); }### Answer: @Test public void findFirstMoreSpecific() { subject.findFirstMoreSpecific(key); verify(wrapped, times(1)).findFirstMoreSpecific(key); }
### Question: SynchronizedIntervalMap implements IntervalMap<K, V> { @Override public List<V> findAllMoreSpecific(K key) { synchronized (mutex) { return wrapped.findAllMoreSpecific(key); } } private SynchronizedIntervalMap(final IntervalMap<K, V> wrapped); private SynchronizedIntervalMap(final IntervalMap<K, V> wrapped, final Object mutex); static IntervalMap<K, V> synchronizedMap(IntervalMap<K, V> toWrap); static IntervalMap<K, V> synchronizedMap(IntervalMap<K, V> toWrap, final Object mutex); @Override void put(K key, V value); @Override void remove(K key); @Override void remove(K key, V value); @Override List<V> findFirstLessSpecific(K key); @Override List<V> findAllLessSpecific(K key); @Override List<V> findExactAndAllLessSpecific(K key); @Override List<V> findExact(K key); @Override List<V> findExactOrFirstLessSpecific(K key); @Override List<V> findFirstMoreSpecific(K key); @Override List<V> findAllMoreSpecific(K key); @Override List<V> findExactAndAllMoreSpecific(K key); @Override void clear(); }### Answer: @Test public void findAllMoreSpecific() { subject.findAllMoreSpecific(key); verify(wrapped, times(1)).findAllMoreSpecific(key); }
### Question: SynchronizedIntervalMap implements IntervalMap<K, V> { @Override public List<V> findExactAndAllMoreSpecific(K key) { synchronized (mutex) { return wrapped.findExactAndAllMoreSpecific(key); } } private SynchronizedIntervalMap(final IntervalMap<K, V> wrapped); private SynchronizedIntervalMap(final IntervalMap<K, V> wrapped, final Object mutex); static IntervalMap<K, V> synchronizedMap(IntervalMap<K, V> toWrap); static IntervalMap<K, V> synchronizedMap(IntervalMap<K, V> toWrap, final Object mutex); @Override void put(K key, V value); @Override void remove(K key); @Override void remove(K key, V value); @Override List<V> findFirstLessSpecific(K key); @Override List<V> findAllLessSpecific(K key); @Override List<V> findExactAndAllLessSpecific(K key); @Override List<V> findExact(K key); @Override List<V> findExactOrFirstLessSpecific(K key); @Override List<V> findFirstMoreSpecific(K key); @Override List<V> findAllMoreSpecific(K key); @Override List<V> findExactAndAllMoreSpecific(K key); @Override void clear(); }### Answer: @Test public void findExactAndAllMoreSpecific() { subject.findExactAndAllMoreSpecific(key); verify(wrapped, times(1)).findExactAndAllMoreSpecific(key); }
### Question: SynchronizedIntervalMap implements IntervalMap<K, V> { @Override public void clear() { synchronized (mutex) { wrapped.clear(); } } private SynchronizedIntervalMap(final IntervalMap<K, V> wrapped); private SynchronizedIntervalMap(final IntervalMap<K, V> wrapped, final Object mutex); static IntervalMap<K, V> synchronizedMap(IntervalMap<K, V> toWrap); static IntervalMap<K, V> synchronizedMap(IntervalMap<K, V> toWrap, final Object mutex); @Override void put(K key, V value); @Override void remove(K key); @Override void remove(K key, V value); @Override List<V> findFirstLessSpecific(K key); @Override List<V> findAllLessSpecific(K key); @Override List<V> findExactAndAllLessSpecific(K key); @Override List<V> findExact(K key); @Override List<V> findExactOrFirstLessSpecific(K key); @Override List<V> findFirstMoreSpecific(K key); @Override List<V> findAllMoreSpecific(K key); @Override List<V> findExactAndAllMoreSpecific(K key); @Override void clear(); }### Answer: @Test public void clear() { subject.clear(); verify(wrapped, times(1)).clear(); }
### Question: InternalNode { void addChild(InternalNode<K, V> nodeToAdd) { if (interval.equals(nodeToAdd.getInterval())) { this.value = nodeToAdd.getValue(); } else if (!interval.contains(nodeToAdd.getInterval())) { throw new IllegalArgumentException(nodeToAdd.getInterval() + " not properly contained in " + interval); } else { if (children == ChildNodeTreeMap.EMPTY) { children = new ChildNodeTreeMap<>(); } children.addChild(nodeToAdd); } } InternalNode(K interval, V value); InternalNode(InternalNode<K, V> source); K getInterval(); V getValue(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); void removeChild(K range); }### Answer: @Test(expected = IllegalArgumentException.class) public void test_intersect_insert_fails() { c.addChild(e); }
### Question: NestedIntervalMap implements IntervalMap<K, V> { @Override public void clear() { children.clear(); } NestedIntervalMap(); NestedIntervalMap(NestedIntervalMap<K, V> source); @Override void put(K key, V value); @Override void remove(K key); @Override void remove(K key, V value); @Override List<V> findFirstLessSpecific(K key); @Override List<V> findAllLessSpecific(K key); @Override List<V> findExactAndAllLessSpecific(K key); @Override List<V> findExact(K key); @Override List<V> findExactOrFirstLessSpecific(K key); @Override List<V> findFirstMoreSpecific(K key); @Override List<V> findAllMoreSpecific(K key); @Override List<V> findExactAndAllMoreSpecific(K key); @Override void clear(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); }### Answer: @Test public void clear() { subject.put(N1_12, N1_1); subject.clear(); assertThat(subject.findExact(N1_12), not(contains(N1_12))); assertThat(subject.findExact(N1_12), not(contains(N1_1))); }
### Question: NestedIntervalMap implements IntervalMap<K, V> { @Override public void put(K key, V value) { Validate.notNull(key); Validate.notNull(value); children.addChild(new InternalNode<>(key, value)); } NestedIntervalMap(); NestedIntervalMap(NestedIntervalMap<K, V> source); @Override void put(K key, V value); @Override void remove(K key); @Override void remove(K key, V value); @Override List<V> findFirstLessSpecific(K key); @Override List<V> findAllLessSpecific(K key); @Override List<V> findExactAndAllLessSpecific(K key); @Override List<V> findExact(K key); @Override List<V> findExactOrFirstLessSpecific(K key); @Override List<V> findFirstMoreSpecific(K key); @Override List<V> findAllMoreSpecific(K key); @Override List<V> findExactAndAllMoreSpecific(K key); @Override void clear(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); }### Answer: @Test public void fail_on_intersecting_siblings() { try { subject.put(new Ipv4Resource(8, 13), N1_1); fail("Exception expected"); } catch (IntersectingIntervalException expected) { assertEquals(new Ipv4Resource(8, 13), expected.getInterval()); assertEquals(asList(N1_12), expected.getIntersections()); } }
### Question: NestedIntervalMap implements IntervalMap<K, V> { @Override public void remove(K key) { Validate.notNull(key); children.removeChild(key); } NestedIntervalMap(); NestedIntervalMap(NestedIntervalMap<K, V> source); @Override void put(K key, V value); @Override void remove(K key); @Override void remove(K key, V value); @Override List<V> findFirstLessSpecific(K key); @Override List<V> findAllLessSpecific(K key); @Override List<V> findExactAndAllLessSpecific(K key); @Override List<V> findExact(K key); @Override List<V> findExactOrFirstLessSpecific(K key); @Override List<V> findFirstMoreSpecific(K key); @Override List<V> findAllMoreSpecific(K key); @Override List<V> findExactAndAllMoreSpecific(K key); @Override void clear(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); }### Answer: @Test public void test_remove_key_value_nonexistant() { NestedIntervalMap<Ipv4Resource, Ipv4Resource> copy = new NestedIntervalMap<>(subject); final Ipv4Resource resource = new Ipv4Resource(0, 100); subject.remove(resource, resource); assertEquals(copy, subject); } @Test public void test_remove_nonexistant() { NestedIntervalMap<Ipv4Resource, Ipv4Resource> copy = new NestedIntervalMap<>(subject); subject.remove(new Ipv4Resource(0, 100)); assertEquals(copy, subject); subject.remove(new Ipv4Resource(1, 7)); assertEquals(copy, subject); subject.remove(new Ipv4Resource(12, 12)); assertEquals(copy, subject); }
### Question: NestedIntervalMap implements IntervalMap<K, V> { @Override public List<V> findAllLessSpecific(K key) { Validate.notNull(key); return mapToValues(internalFindAllLessSpecific(key)); } NestedIntervalMap(); NestedIntervalMap(NestedIntervalMap<K, V> source); @Override void put(K key, V value); @Override void remove(K key); @Override void remove(K key, V value); @Override List<V> findFirstLessSpecific(K key); @Override List<V> findAllLessSpecific(K key); @Override List<V> findExactAndAllLessSpecific(K key); @Override List<V> findExact(K key); @Override List<V> findExactOrFirstLessSpecific(K key); @Override List<V> findFirstMoreSpecific(K key); @Override List<V> findAllMoreSpecific(K key); @Override List<V> findExactAndAllMoreSpecific(K key); @Override void clear(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); }### Answer: @Test public void test_find_all_less_specific() { assertEquals(Collections.emptyList(), subject.findAllLessSpecific(new Ipv4Resource(0, 100))); assertEquals(Collections.emptyList(), subject.findAllLessSpecific(new Ipv4Resource(5, 13))); assertEquals(Collections.emptyList(), subject.findAllLessSpecific(N1_12)); assertEquals(asList(N1_12, N5_10, N5_8), subject.findAllLessSpecific(N6_6)); assertEquals(asList(N1_12, N5_10, N5_8), subject.findAllLessSpecific(N8_8)); assertEquals(asList(N1_12, N1_4), subject.findAllLessSpecific(N2_2)); }
### Question: NestedIntervalMap implements IntervalMap<K, V> { @Override public List<V> findExactAndAllLessSpecific(K key) { Validate.notNull(key); return mapToValues(internalFindExactAndAllLessSpecific(key)); } NestedIntervalMap(); NestedIntervalMap(NestedIntervalMap<K, V> source); @Override void put(K key, V value); @Override void remove(K key); @Override void remove(K key, V value); @Override List<V> findFirstLessSpecific(K key); @Override List<V> findAllLessSpecific(K key); @Override List<V> findExactAndAllLessSpecific(K key); @Override List<V> findExact(K key); @Override List<V> findExactOrFirstLessSpecific(K key); @Override List<V> findFirstMoreSpecific(K key); @Override List<V> findAllMoreSpecific(K key); @Override List<V> findExactAndAllMoreSpecific(K key); @Override void clear(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); }### Answer: @Test public void test_find_exact_and_all_less_specific() { assertEquals(Collections.emptyList(), subject.findExactAndAllLessSpecific(new Ipv4Resource(0, 100))); assertEquals(Collections.emptyList(), subject.findExactAndAllLessSpecific(new Ipv4Resource(5, 13))); assertEquals(asList(N1_12), subject.findExactAndAllLessSpecific(N1_12)); assertEquals(asList(N1_12, N5_10, N5_8, N6_6), subject.findExactAndAllLessSpecific(N6_6)); assertEquals(asList(N1_12, N5_10, N5_8), subject.findExactAndAllLessSpecific(N8_8)); assertEquals(asList(N1_12, N1_4, N2_2), subject.findExactAndAllLessSpecific(N2_2)); }
### Question: NestedIntervalMap implements IntervalMap<K, V> { @Override public List<V> findExactOrFirstLessSpecific(K key) { Validate.notNull(key); return mapToValues(internalFindExactOrFirstLessSpecific(key)); } NestedIntervalMap(); NestedIntervalMap(NestedIntervalMap<K, V> source); @Override void put(K key, V value); @Override void remove(K key); @Override void remove(K key, V value); @Override List<V> findFirstLessSpecific(K key); @Override List<V> findAllLessSpecific(K key); @Override List<V> findExactAndAllLessSpecific(K key); @Override List<V> findExact(K key); @Override List<V> findExactOrFirstLessSpecific(K key); @Override List<V> findFirstMoreSpecific(K key); @Override List<V> findAllMoreSpecific(K key); @Override List<V> findExactAndAllMoreSpecific(K key); @Override void clear(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); }### Answer: @Test public void test_find_exact_or_first_less_specific() { assertThat(subject.findExactOrFirstLessSpecific(new Ipv4Resource(0, 100)), hasSize(0)); assertThat(subject.findExactOrFirstLessSpecific(new Ipv4Resource(5, 13)), hasSize(0)); assertThat(subject.findExactOrFirstLessSpecific(N1_12), contains(N1_12)); assertThat(subject.findExactOrFirstLessSpecific(N6_6), contains(N6_6)); assertThat(subject.findExactOrFirstLessSpecific(N8_8), contains(N5_8)); assertThat(subject.findExactOrFirstLessSpecific(N2_2), contains(N2_2)); }
### Question: NestedIntervalMap implements IntervalMap<K, V> { @Override public List<V> findFirstLessSpecific(K key) { Validate.notNull(key); InternalNode<K, V> node = internalFindFirstLessSpecific(key); return mapToValues(node); } NestedIntervalMap(); NestedIntervalMap(NestedIntervalMap<K, V> source); @Override void put(K key, V value); @Override void remove(K key); @Override void remove(K key, V value); @Override List<V> findFirstLessSpecific(K key); @Override List<V> findAllLessSpecific(K key); @Override List<V> findExactAndAllLessSpecific(K key); @Override List<V> findExact(K key); @Override List<V> findExactOrFirstLessSpecific(K key); @Override List<V> findFirstMoreSpecific(K key); @Override List<V> findAllMoreSpecific(K key); @Override List<V> findExactAndAllMoreSpecific(K key); @Override void clear(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); }### Answer: @Test public void testFindFirstLessSpecific() { assertThat(subject.findFirstLessSpecific(N1_12), hasSize(0)); assertThat(subject.findFirstLessSpecific(N6_6), contains(N5_8)); assertThat(subject.findFirstLessSpecific(N8_8), contains(N5_8)); assertThat(subject.findFirstLessSpecific(N2_2), contains(N1_4)); assertThat(subject.findFirstLessSpecific(new Ipv4Resource(3, 7)), contains(N1_12)); }
### Question: NestedIntervalMap implements IntervalMap<K, V> { @Override public List<V> findFirstMoreSpecific(K key) { Validate.notNull(key); return mapToValues(internalFindFirstMoreSpecific(key)); } NestedIntervalMap(); NestedIntervalMap(NestedIntervalMap<K, V> source); @Override void put(K key, V value); @Override void remove(K key); @Override void remove(K key, V value); @Override List<V> findFirstLessSpecific(K key); @Override List<V> findAllLessSpecific(K key); @Override List<V> findExactAndAllLessSpecific(K key); @Override List<V> findExact(K key); @Override List<V> findExactOrFirstLessSpecific(K key); @Override List<V> findFirstMoreSpecific(K key); @Override List<V> findAllMoreSpecific(K key); @Override List<V> findExactAndAllMoreSpecific(K key); @Override void clear(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); }### Answer: @Test public void testFindFirstMoreSpecific() { assertEquals(asList(N5_8, N9_10), subject.findFirstMoreSpecific(N5_10)); assertEquals(asList(N1_1, N2_2, N3_4), subject.findFirstMoreSpecific(N1_4)); assertEquals(asList(N7_7, N9_9), subject.findFirstMoreSpecific(new Ipv4Resource(7, 9))); assertEquals(asList(N9_9), subject.findFirstMoreSpecific(new Ipv4Resource(8, 9))); }
### Question: NestedIntervalMap implements IntervalMap<K, V> { @Override public List<V> findExact(K key) { Validate.notNull(key); InternalNode<K, V> node = internalFindExact(key); return mapToValues(node); } NestedIntervalMap(); NestedIntervalMap(NestedIntervalMap<K, V> source); @Override void put(K key, V value); @Override void remove(K key); @Override void remove(K key, V value); @Override List<V> findFirstLessSpecific(K key); @Override List<V> findAllLessSpecific(K key); @Override List<V> findExactAndAllLessSpecific(K key); @Override List<V> findExact(K key); @Override List<V> findExactOrFirstLessSpecific(K key); @Override List<V> findFirstMoreSpecific(K key); @Override List<V> findAllMoreSpecific(K key); @Override List<V> findExactAndAllMoreSpecific(K key); @Override void clear(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); }### Answer: @Test public void testFindExact() { for (Ipv4Resource n : all) { assertThat(subject.findExact(n), contains(n)); } }
### Question: NestedIntervalMap implements IntervalMap<K, V> { @Override public List<V> findAllMoreSpecific(K key) { Validate.notNull(key); return mapToValues(internalFindAllMoreSpecific(key)); } NestedIntervalMap(); NestedIntervalMap(NestedIntervalMap<K, V> source); @Override void put(K key, V value); @Override void remove(K key); @Override void remove(K key, V value); @Override List<V> findFirstLessSpecific(K key); @Override List<V> findAllLessSpecific(K key); @Override List<V> findExactAndAllLessSpecific(K key); @Override List<V> findExact(K key); @Override List<V> findExactOrFirstLessSpecific(K key); @Override List<V> findFirstMoreSpecific(K key); @Override List<V> findAllMoreSpecific(K key); @Override List<V> findExactAndAllMoreSpecific(K key); @Override void clear(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); }### Answer: @Test public void testFindAllMoreSpecific() { assertEquals(all.subList(1, all.size()), subject.findAllMoreSpecific(N1_12)); assertEquals(asList(N3_4, N3_3, N4_4, N5_5, N6_6, N7_7), subject.findAllMoreSpecific(new Ipv4Resource(3, 7))); assertEquals(asList(N9_9), subject.findAllMoreSpecific(new Ipv4Resource(8, 9))); }
### Question: NestedIntervalMap implements IntervalMap<K, V> { @Override public List<V> findExactAndAllMoreSpecific(K key) { Validate.notNull(key); return mapToValues(internalFindExactAndAllMoreSpecific(key)); } NestedIntervalMap(); NestedIntervalMap(NestedIntervalMap<K, V> source); @Override void put(K key, V value); @Override void remove(K key); @Override void remove(K key, V value); @Override List<V> findFirstLessSpecific(K key); @Override List<V> findAllLessSpecific(K key); @Override List<V> findExactAndAllLessSpecific(K key); @Override List<V> findExact(K key); @Override List<V> findExactOrFirstLessSpecific(K key); @Override List<V> findFirstMoreSpecific(K key); @Override List<V> findAllMoreSpecific(K key); @Override List<V> findExactAndAllMoreSpecific(K key); @Override void clear(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); }### Answer: @Test public void testFindExactAndAllMoreSpecific() { assertEquals(all, subject.findExactAndAllMoreSpecific(N1_12)); assertEquals(asList(N1_4, N1_1, N2_2, N3_4, N3_3, N4_4), subject.findExactAndAllMoreSpecific(N1_4)); }
### Question: MultiValueIntervalMap implements IntervalMap<K, V> { @Override public List<V> findExact(K key) { return unroll(wrapped.findExact(key)); } MultiValueIntervalMap(); @Override void put(K key, V value); @Override void remove(K key); @Override void remove(K key, V value); @Override void clear(); @Override List<V> findFirstLessSpecific(K key); @Override List<V> findExact(K key); @Override List<V> findExactOrFirstLessSpecific(K key); @Override List<V> findAllLessSpecific(K key); @Override List<V> findExactAndAllLessSpecific(K key); @Override List<V> findFirstMoreSpecific(K key); @Override List<V> findAllMoreSpecific(K key); @Override List<V> findExactAndAllMoreSpecific(K key); }### Answer: @Test public void findExact_k11() { final List<String> result = subject.findExact(k_11); assertThat(result, contains(v_11)); } @Test public void findExact_k13() { final List<String> result = subject.findExact(k_13); assertThat(result, contains(v_131, v_132, v_133)); } @Test public void findExact() { final List<String> result = subject.findExact(k_12); assertThat(result, contains(v_121, v_122)); }
### Question: MultiValueIntervalMap implements IntervalMap<K, V> { @Override public void remove(K key) { wrapped.remove(key); } MultiValueIntervalMap(); @Override void put(K key, V value); @Override void remove(K key); @Override void remove(K key, V value); @Override void clear(); @Override List<V> findFirstLessSpecific(K key); @Override List<V> findExact(K key); @Override List<V> findExactOrFirstLessSpecific(K key); @Override List<V> findAllLessSpecific(K key); @Override List<V> findExactAndAllLessSpecific(K key); @Override List<V> findFirstMoreSpecific(K key); @Override List<V> findAllMoreSpecific(K key); @Override List<V> findExactAndAllMoreSpecific(K key); }### Answer: @Test public void remove() { subject.remove(k_11); final List<String> result = subject.findExact(k_11); assertThat(result, hasSize(0)); }
### Question: MultiValueIntervalMap implements IntervalMap<K, V> { @Override public void clear() { wrapped.clear(); } MultiValueIntervalMap(); @Override void put(K key, V value); @Override void remove(K key); @Override void remove(K key, V value); @Override void clear(); @Override List<V> findFirstLessSpecific(K key); @Override List<V> findExact(K key); @Override List<V> findExactOrFirstLessSpecific(K key); @Override List<V> findAllLessSpecific(K key); @Override List<V> findExactAndAllLessSpecific(K key); @Override List<V> findFirstMoreSpecific(K key); @Override List<V> findAllMoreSpecific(K key); @Override List<V> findExactAndAllMoreSpecific(K key); }### Answer: @Test public void clear() { subject.clear(); final List<String> result = subject.findAllMoreSpecific(Ipv4Resource.MAX_RANGE); assertThat(result, hasSize(0)); }
### Question: MultiValueIntervalMap implements IntervalMap<K, V> { @Override public List<V> findFirstLessSpecific(K key) { return unroll(wrapped.findFirstLessSpecific(key)); } MultiValueIntervalMap(); @Override void put(K key, V value); @Override void remove(K key); @Override void remove(K key, V value); @Override void clear(); @Override List<V> findFirstLessSpecific(K key); @Override List<V> findExact(K key); @Override List<V> findExactOrFirstLessSpecific(K key); @Override List<V> findAllLessSpecific(K key); @Override List<V> findExactAndAllLessSpecific(K key); @Override List<V> findFirstMoreSpecific(K key); @Override List<V> findAllMoreSpecific(K key); @Override List<V> findExactAndAllMoreSpecific(K key); }### Answer: @Test public void findFirstLessSpecific() { final List<String> result = subject.findFirstLessSpecific(k_11); assertThat(result, contains(v_121, v_122)); }
### Question: MultiValueIntervalMap implements IntervalMap<K, V> { @Override public List<V> findExactOrFirstLessSpecific(K key) { return unroll(wrapped.findExactOrFirstLessSpecific(key)); } MultiValueIntervalMap(); @Override void put(K key, V value); @Override void remove(K key); @Override void remove(K key, V value); @Override void clear(); @Override List<V> findFirstLessSpecific(K key); @Override List<V> findExact(K key); @Override List<V> findExactOrFirstLessSpecific(K key); @Override List<V> findAllLessSpecific(K key); @Override List<V> findExactAndAllLessSpecific(K key); @Override List<V> findFirstMoreSpecific(K key); @Override List<V> findAllMoreSpecific(K key); @Override List<V> findExactAndAllMoreSpecific(K key); }### Answer: @Test public void findExactOrFirstLessSpecific() { final List<String> result = subject.findExactOrFirstLessSpecific(k_12); assertThat(result, contains(v_121, v_122)); }
### Question: MultiValueIntervalMap implements IntervalMap<K, V> { @Override public List<V> findAllLessSpecific(K key) { return unroll(wrapped.findAllLessSpecific(key)); } MultiValueIntervalMap(); @Override void put(K key, V value); @Override void remove(K key); @Override void remove(K key, V value); @Override void clear(); @Override List<V> findFirstLessSpecific(K key); @Override List<V> findExact(K key); @Override List<V> findExactOrFirstLessSpecific(K key); @Override List<V> findAllLessSpecific(K key); @Override List<V> findExactAndAllLessSpecific(K key); @Override List<V> findFirstMoreSpecific(K key); @Override List<V> findAllMoreSpecific(K key); @Override List<V> findExactAndAllMoreSpecific(K key); }### Answer: @Test public void findAllLessSpecific() { final List<String> result = subject.findAllLessSpecific(k_11); assertThat(result, contains(v_131, v_132, v_133, v_121, v_122)); }
### Question: MultiValueIntervalMap implements IntervalMap<K, V> { @Override public List<V> findExactAndAllLessSpecific(K key) { return unroll(wrapped.findExactAndAllLessSpecific(key)); } MultiValueIntervalMap(); @Override void put(K key, V value); @Override void remove(K key); @Override void remove(K key, V value); @Override void clear(); @Override List<V> findFirstLessSpecific(K key); @Override List<V> findExact(K key); @Override List<V> findExactOrFirstLessSpecific(K key); @Override List<V> findAllLessSpecific(K key); @Override List<V> findExactAndAllLessSpecific(K key); @Override List<V> findFirstMoreSpecific(K key); @Override List<V> findAllMoreSpecific(K key); @Override List<V> findExactAndAllMoreSpecific(K key); }### Answer: @Test public void findExactAndAllLessSpecific() { final List<String> result = subject.findExactAndAllLessSpecific(k_12); assertThat(result, contains(v_131, v_132, v_133, v_121, v_122)); }
### Question: MultiValueIntervalMap implements IntervalMap<K, V> { @Override public List<V> findFirstMoreSpecific(K key) { return unroll(wrapped.findFirstMoreSpecific(key)); } MultiValueIntervalMap(); @Override void put(K key, V value); @Override void remove(K key); @Override void remove(K key, V value); @Override void clear(); @Override List<V> findFirstLessSpecific(K key); @Override List<V> findExact(K key); @Override List<V> findExactOrFirstLessSpecific(K key); @Override List<V> findAllLessSpecific(K key); @Override List<V> findExactAndAllLessSpecific(K key); @Override List<V> findFirstMoreSpecific(K key); @Override List<V> findAllMoreSpecific(K key); @Override List<V> findExactAndAllMoreSpecific(K key); }### Answer: @Test public void findFirstMoreSpecific() { final List<String> result = subject.findFirstMoreSpecific(k_12); assertThat(result, contains(v_11)); }
### Question: MultiValueIntervalMap implements IntervalMap<K, V> { @Override public List<V> findAllMoreSpecific(K key) { return unroll(wrapped.findAllMoreSpecific(key)); } MultiValueIntervalMap(); @Override void put(K key, V value); @Override void remove(K key); @Override void remove(K key, V value); @Override void clear(); @Override List<V> findFirstLessSpecific(K key); @Override List<V> findExact(K key); @Override List<V> findExactOrFirstLessSpecific(K key); @Override List<V> findAllLessSpecific(K key); @Override List<V> findExactAndAllLessSpecific(K key); @Override List<V> findFirstMoreSpecific(K key); @Override List<V> findAllMoreSpecific(K key); @Override List<V> findExactAndAllMoreSpecific(K key); }### Answer: @Test public void findAllMoreSpecific() { final List<String> result = subject.findAllMoreSpecific(Ipv4Resource.MAX_RANGE); assertThat(result, contains(v_131, v_132, v_133, v_121, v_122, v_11)); }
### Question: MultiValueIntervalMap implements IntervalMap<K, V> { @Override public List<V> findExactAndAllMoreSpecific(K key) { return unroll(wrapped.findExactAndAllMoreSpecific(key)); } MultiValueIntervalMap(); @Override void put(K key, V value); @Override void remove(K key); @Override void remove(K key, V value); @Override void clear(); @Override List<V> findFirstLessSpecific(K key); @Override List<V> findExact(K key); @Override List<V> findExactOrFirstLessSpecific(K key); @Override List<V> findAllLessSpecific(K key); @Override List<V> findExactAndAllLessSpecific(K key); @Override List<V> findFirstMoreSpecific(K key); @Override List<V> findAllMoreSpecific(K key); @Override List<V> findExactAndAllMoreSpecific(K key); }### Answer: @Test public void findExactAndAllMoreSpecific() { final List<String> result = subject.findExactAndAllMoreSpecific(k_12); assertThat(result, contains(v_121, v_122, v_11)); }
### Question: AuthoritativeResourceDataValidator { void checkOverlaps(final Writer writer) throws IOException { for (int i1 = 0; i1 < sources.size(); i1++) { for (int i2 = i1 + 1; i2 < sources.size(); i2++) { final CIString source1 = sources.get(i1); final CIString source2 = sources.get(i2); checkOverlaps(writer, source1, authoritativeResourceData.getAuthoritativeResource(source1), source2, authoritativeResourceData.getAuthoritativeResource(source2)); } } } @Autowired AuthoritativeResourceDataValidator( @Value("${grs.sources}") final String[] grsSourceNames, final AuthoritativeResourceData authoritativeResourceData); }### Answer: @Test public void checkOverlaps() throws IOException { final StringWriter writer = new StringWriter(); subject.checkOverlaps(writer); final String output = writer.getBuffer().toString(); LOGGER.debug("overlaps:\n{}", output); final List<String> overlaps = Splitter.on("\n").splitToList(output); assertThat(overlaps, hasSize(11)); assertThat(overlaps, containsInAnyOrder( "GRS1 GRS2 aut-num AS1-AS2", "GRS1 GRS2 inetnum 10.0.0.0-10.0.0.0", "GRS1 GRS2 inetnum 192.0.0.1-192.0.0.2", "GRS1 GRS2 inet6num ::/0", "GRS1 GRS3 aut-num AS1-AS1", "GRS1 GRS3 inetnum 193.0.0.10-193.0.0.11", "GRS1 GRS3 inet6num ::/0", "GRS2 GRS3 aut-num AS10-AS10", "GRS2 GRS3 aut-num AS1-AS1", "GRS2 GRS3 inet6num ::/0", "")); }
### Question: AuthoritativeResourceData { public AuthoritativeResource getAuthoritativeResource(final CIString source) { final String sourceName = StringUtils.removeEnd(source.toLowerCase(), "-grs"); final AuthoritativeResource authoritativeResource = authoritativeResourceCache.get(sourceName); if (authoritativeResource == null) { throw new IllegalSourceException(source); } return authoritativeResource; } @Autowired AuthoritativeResourceData(@Value("${grs.sources}") final String grsSourceNames, @Value("${whois.source}") final String source, final ResourceDataDao resourceDataDao); synchronized void refreshGrsSources(); synchronized void refreshActiveSource(); AuthoritativeResource getAuthoritativeResource(final CIString source); AuthoritativeResource getAuthoritativeResource(); }### Answer: @Test(expected = IllegalSourceException.class) public void nonexistant_source_throws_exception() { authoritativeResourceData.getAuthoritativeResource(ciString("BLAH")); }
### Question: AuthoritativeResource { public static AuthoritativeResource loadFromFile(final Logger logger, final String name, final Path path) { try (final Scanner scanner = new Scanner(path)) { return loadFromScanner(logger, name, scanner); } catch (IOException e) { throw new IllegalArgumentException(e); } } AuthoritativeResource(final SortedRangeSet<Asn, AsnRange> autNums, final SortedRangeSet<Ipv4, Ipv4Range> inetRanges, final SortedRangeSet<Ipv6, Ipv6Range> inet6Ranges); static AuthoritativeResource loadFromFile(final Logger logger, final String name, final Path path); static AuthoritativeResource unknown(); static AuthoritativeResource loadFromScanner(final Logger logger, final String name, final Scanner scanner); int getNrAutNums(); int getNrInetnums(); int getNrInet6nums(); boolean isMaintainedInRirSpace(final RpslObject rpslObject); boolean isMaintainedInRirSpace(final ObjectType objectType, final CIString pkey); boolean isRouteMaintainedInRirSpace(final RpslObject rpslObject); boolean isRouteMaintainedInRirSpace(final ObjectType objectType, CIString key); Set<ObjectType> getResourceTypes(); Iterable<String> findAutnumOverlaps(AuthoritativeResource other); Iterable<String> findInetnumOverlaps(AuthoritativeResource other); Iterable<String> findInet6numOverlaps(AuthoritativeResource other); @Override boolean equals(Object o); @Override int hashCode(); List<String> getResources(); }### Answer: @Test(expected = IllegalArgumentException.class) public void unknown_file() throws IOException { AuthoritativeResource.loadFromFile(logger, "unknown", folder.getRoot().toPath().resolve("unknown")); }
### Question: AuthoritativeResourceDataJmx extends JmxBase { @ManagedOperation(description = "Refresh authoritative resource cache") @ManagedOperationParameters({ @ManagedOperationParameter(name = "comment", description = "Optional comment for invoking the operation") }) public String refreshCache(final String comment) { return invokeOperation("Refresh authoritative resource cache", comment, () -> { authoritativeResourceRefreshTask.refreshGrsAuthoritativeResourceCaches(); return "Refreshed caches"; }); } @Autowired AuthoritativeResourceDataJmx(final AuthoritativeResourceRefreshTask authoritativeResourceRefreshTask, final AuthoritativeResourceDataValidator authoritativeResourceDataValidator); @ManagedOperation(description = "Refresh authoritative resource cache") @ManagedOperationParameters({ @ManagedOperationParameter(name = "comment", description = "Optional comment for invoking the operation") }) String refreshCache(final String comment); @ManagedOperation(description = "Check overlaps in authoritative resource definitions and output to file") @ManagedOperationParameters({ @ManagedOperationParameter(name = "outputFile", description = "The file to write overlaps to"), @ManagedOperationParameter(name = "comment", description = "Optional comment for invoking the operation") }) String checkOverlaps(final String outputFile, final String comment); }### Answer: @Test public void refreshCache() { final String msg = subject.refreshCache("comment"); assertThat(msg, is("Refreshed caches")); verify(authoritativeResourceRefreshTask).refreshGrsAuthoritativeResourceCaches(); }
### Question: RpslObjectFilter { public static boolean isFiltered(final RpslObject rpslObject) { final List<RpslAttribute> attributes = rpslObject.findAttributes(AttributeType.SOURCE); return !attributes.isEmpty() && attributes.get(0).getValue().contains(FILTERED); } private RpslObjectFilter(); static String getCertificateFromKeyCert(final RpslObject object); static String diff(final RpslObject original, final RpslObject revised); static RpslObjectBuilder keepKeyAttributesOnly(final RpslObjectBuilder builder); static RpslObjectBuilder setFiltered(final RpslObjectBuilder builder); static void addFilteredSourceReplacement(final RpslObject object, final Map<RpslAttribute, RpslAttribute> replacementsMap); static boolean isFiltered(final RpslObject rpslObject); static RpslObject buildGenericObject(final RpslObject object, final String ... attributes); static RpslObject buildGenericObject(final String object, final String ... attributes); static RpslObject buildGenericObject(final RpslObjectBuilder builder, final String ... attributes); static boolean ignoreGeneratedAttributesEqual(final RpslObject object1, final RpslObject object2); }### Answer: @Test public void isFiltered() { final boolean filtered = RpslObjectFilter.isFiltered(mntner); assertThat(filtered, is(false)); }
### Question: Changed { public static Changed parse(final CIString value) { return parse(value.toString()); } Changed(final CIString email, final LocalDate date); Changed(final String email, final LocalDate date); String getEmail(); @CheckForNull LocalDate getDate(); @CheckForNull String getDateString(); @Override String toString(); static Changed parse(final CIString value); static Changed parse(final String value); }### Answer: @Test(expected = AttributeParseException.class) public void empty() { Changed.parse(""); } @Test(expected = AttributeParseException.class) public void no_email() { Changed.parse("20010101"); } @Test(expected = AttributeParseException.class) public void invalid_date() { Changed.parse("[email protected] 13131313"); } @Test(expected = AttributeParseException.class) public void too_long() { Changed.parse("abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz 20010101"); } @Test(expected = AttributeParseException.class) public void mixedUpDateAndEmail() { Changed subject = Changed.parse("20130112 [email protected]"); }
### Question: AddressPrefixRange { public static AddressPrefixRange parse(final CIString value) { return parse(value.toString()); } private AddressPrefixRange(final String value, final IpInterval ipInterval, final RangeOperation rangeOperation); IpInterval getIpInterval(); RangeOperation getRangeOperation(); @Override String toString(); @SuppressWarnings("unchecked") BoundaryCheckResult checkWithinBounds(final IpInterval bounds); @SuppressWarnings("unchecked") BoundaryCheckResult checkRange(final IpInterval contained); static AddressPrefixRange parse(final CIString value); static AddressPrefixRange parse(final String value); }### Answer: @Test(expected = AttributeParseException.class) public void empty() { AddressPrefixRange.parse(""); } @Test(expected = AttributeParseException.class) public void invalid_address() { AddressPrefixRange.parse("300.104.182.0/12"); } @Test(expected = AttributeParseException.class) public void range_too_long() { AddressPrefixRange.parse("194.104.182.0/33"); } @Test(expected = AttributeParseException.class) public void range_too_long_ipv6() { AddressPrefixRange.parse("2a00:c00::/129"); } @Test(expected = AttributeParseException.class) public void operation_range_ipv4_too_long() { AddressPrefixRange.parse("193.151.47.0/24^24-33"); } @Test(expected = AttributeParseException.class) public void operation_range_ipv4_invalid_order() { AddressPrefixRange.parse("193.151.47.0/24^24-12"); } @Test(expected = AttributeParseException.class) public void operation_length_too_long() { AddressPrefixRange.parse("77.74.152.0/23^33"); } @Test(expected = AttributeParseException.class) public void n_lower_than_prefix_range() { AddressPrefixRange.parse("77.74.152.0/23^22"); }
### Question: NServer { public static NServer parse(final CIString value) { return parse(value.toString()); } private NServer(final CIString hostname, final IpInterval ipInterval); CIString getHostname(); @CheckForNull IpInterval getIpInterval(); @Override String toString(); static NServer parse(final CIString value); static NServer parse(final String value); }### Answer: @Test(expected = AttributeParseException.class) public void empty() { NServer.parse(""); } @Test(expected = AttributeParseException.class) public void hostname_invalid() { NServer.parse("$"); } @Test(expected = AttributeParseException.class) public void hostname_and_ipv4_range_24() { NServer.parse("dns.comcor.ru 194.0.0.0/24"); } @Test(expected = AttributeParseException.class) public void hostname_and_ipv4_list() { NServer.parse("dns.comcor.ru 194.0.0.0 194.0.0.0"); } @Test(expected = AttributeParseException.class) public void hostname_and_invalid_ip() { NServer.parse("dns.comcor.ru dns.comcor.ru"); }
### Question: Domain { public static Domain parse(final CIString value) { return parse(value.toString()); } private Domain(final CIString value, final IpInterval<?> reverseIp, final Type type, final boolean dashNotation); CIString getValue(); Type getType(); @CheckForNull IpInterval<?> getReverseIp(); boolean endsWithDomain(final CIString hostname); static Domain parse(final CIString value); static Domain parse(final String domain); }### Answer: @Test(expected = AttributeParseException.class) public void empty() { Domain.parse(""); } @Test(expected = AttributeParseException.class) public void hostname() { Domain.parse("hostname"); } @Test(expected = AttributeParseException.class) public void ipv4_dash_invalid_position() { Domain.parse("0-127.10.10.in-addr.arpa"); } @Test(expected = AttributeParseException.class) public void ipv4_dash_range_0_255() { Domain.parse("0-255.10.10.in-addr.arpa"); } @Test(expected = AttributeParseException.class) public void ipv4_dash_range_start_is_range_end() { Domain.parse("1-1.10.10.in-addr.arpa"); } @Test(expected = AttributeParseException.class) public void suffix() { Domain.parse("200.193.193.193.some-suffix."); } @Test(expected = AttributeParseException.class) public void suffix_almost_correct() { Domain.parse("200.193.193.in-addraarpa"); }
### Question: ObjectMessages { public Messages getMessages() { return messages; } Messages getMessages(); Map<RpslAttribute, Messages> getAttributeMessages(); boolean contains(final Message message); void addMessage(final Message message); void addMessage(final RpslAttribute attribute, final Message message); Messages getMessages(final RpslAttribute attribute); boolean hasErrors(); boolean hasMessages(); int getErrorCount(); void addAll(final ObjectMessages objectMessages); @Override String toString(); }### Answer: @Test public void empty() { assertThat(subject.getMessages().getAllMessages(), hasSize(0)); }
### Question: ObjectMessages { public void addAll(final ObjectMessages objectMessages) { messages.addAll(objectMessages.messages); for (final Map.Entry<RpslAttribute, Messages> entry : objectMessages.attributeMessages.entrySet()) { getMessages(entry.getKey()).addAll(entry.getValue()); } } Messages getMessages(); Map<RpslAttribute, Messages> getAttributeMessages(); boolean contains(final Message message); void addMessage(final Message message); void addMessage(final RpslAttribute attribute, final Message message); Messages getMessages(final RpslAttribute attribute); boolean hasErrors(); boolean hasMessages(); int getErrorCount(); void addAll(final ObjectMessages objectMessages); @Override String toString(); }### Answer: @Test public void addAll() { final RpslAttribute attribute = object.getAttributes().get(0); final ObjectMessages other = new ObjectMessages(); other.addMessage(error); other.addMessage(attribute, warning); subject.addAll(other); assertThat(subject.contains(error), is(true)); assertThat(subject.getMessages(attribute).getWarnings(), contains(warning)); }
### Question: ObjectTemplate implements Comparable<ObjectTemplate> { public static ObjectTemplate getTemplate(final ObjectType type) { final ObjectTemplate objectTemplate = TEMPLATE_MAP.get(type); if (objectTemplate == null) { throw new IllegalStateException("No template for " + type); } return objectTemplate; } private ObjectTemplate(final ObjectType objectType, final int orderPosition, final AttributeTemplate... attributeTemplates); static ObjectTemplate getTemplate(final ObjectType type); static Collection<ObjectTemplate> getTemplates(); ObjectType getObjectType(); List<AttributeTemplate> getAttributeTemplates(); Set<AttributeType> getAllAttributes(); Set<AttributeType> getKeyAttributes(); Set<AttributeType> getLookupAttributes(); AttributeType getKeyLookupAttribute(); Set<AttributeType> getMandatoryAttributes(); Set<AttributeType> getInverseLookupAttributes(); Set<AttributeType> getGeneratedAttributes(); Set<AttributeType> getMultipleAttributes(); Comparator<RpslAttribute> getAttributeTypeComparator(); boolean isSet(); String getNameToFirstUpper( ); String getNameToFirstLower( ); @Override boolean equals(final Object o); @Override int hashCode(); @Override int compareTo(@Nonnull final ObjectTemplate o); void validateStructure(final RpslObject rpslObject, final ObjectMessages objectMessages); void validateSyntax(final RpslObject rpslObject, final ObjectMessages objectMessages, final boolean skipGenerated); ObjectMessages validate(final RpslObject rpslObject); @Override String toString(); String toVerboseString(); boolean hasAttribute(final AttributeType attributeType); }### Answer: @Test(expected = IllegalStateException.class) public void getObjectSpec_null() { ObjectTemplate.getTemplate(null); } @Test public void allObjectTypesSupported() { for (final ObjectType objectType : ObjectType.values()) { ObjectTemplate.getTemplate(objectType); } }
### Question: ObjectTemplate implements Comparable<ObjectTemplate> { public ObjectType getObjectType() { return objectType; } private ObjectTemplate(final ObjectType objectType, final int orderPosition, final AttributeTemplate... attributeTemplates); static ObjectTemplate getTemplate(final ObjectType type); static Collection<ObjectTemplate> getTemplates(); ObjectType getObjectType(); List<AttributeTemplate> getAttributeTemplates(); Set<AttributeType> getAllAttributes(); Set<AttributeType> getKeyAttributes(); Set<AttributeType> getLookupAttributes(); AttributeType getKeyLookupAttribute(); Set<AttributeType> getMandatoryAttributes(); Set<AttributeType> getInverseLookupAttributes(); Set<AttributeType> getGeneratedAttributes(); Set<AttributeType> getMultipleAttributes(); Comparator<RpslAttribute> getAttributeTypeComparator(); boolean isSet(); String getNameToFirstUpper( ); String getNameToFirstLower( ); @Override boolean equals(final Object o); @Override int hashCode(); @Override int compareTo(@Nonnull final ObjectTemplate o); void validateStructure(final RpslObject rpslObject, final ObjectMessages objectMessages); void validateSyntax(final RpslObject rpslObject, final ObjectMessages objectMessages, final boolean skipGenerated); ObjectMessages validate(final RpslObject rpslObject); @Override String toString(); String toVerboseString(); boolean hasAttribute(final AttributeType attributeType); }### Answer: @Test public void getObjectType() { assertThat(subject.getObjectType(), is(ObjectType.MNTNER)); }
### Question: ObjectTemplate implements Comparable<ObjectTemplate> { public Set<AttributeType> getMultipleAttributes() { return multipleAttributes; } private ObjectTemplate(final ObjectType objectType, final int orderPosition, final AttributeTemplate... attributeTemplates); static ObjectTemplate getTemplate(final ObjectType type); static Collection<ObjectTemplate> getTemplates(); ObjectType getObjectType(); List<AttributeTemplate> getAttributeTemplates(); Set<AttributeType> getAllAttributes(); Set<AttributeType> getKeyAttributes(); Set<AttributeType> getLookupAttributes(); AttributeType getKeyLookupAttribute(); Set<AttributeType> getMandatoryAttributes(); Set<AttributeType> getInverseLookupAttributes(); Set<AttributeType> getGeneratedAttributes(); Set<AttributeType> getMultipleAttributes(); Comparator<RpslAttribute> getAttributeTypeComparator(); boolean isSet(); String getNameToFirstUpper( ); String getNameToFirstLower( ); @Override boolean equals(final Object o); @Override int hashCode(); @Override int compareTo(@Nonnull final ObjectTemplate o); void validateStructure(final RpslObject rpslObject, final ObjectMessages objectMessages); void validateSyntax(final RpslObject rpslObject, final ObjectMessages objectMessages, final boolean skipGenerated); ObjectMessages validate(final RpslObject rpslObject); @Override String toString(); String toVerboseString(); boolean hasAttribute(final AttributeType attributeType); }### Answer: @Test public void getMultipleAttributes(){ final ObjectTemplate template = ObjectTemplate.getTemplate(ObjectType.AS_BLOCK); Set<AttributeType> multipleAttributes = template.getMultipleAttributes(); assertThat(multipleAttributes.size(), is(6)); }
### Question: ObjectTemplate implements Comparable<ObjectTemplate> { public boolean isSet() { return ObjectType.getSets().contains(objectType); } private ObjectTemplate(final ObjectType objectType, final int orderPosition, final AttributeTemplate... attributeTemplates); static ObjectTemplate getTemplate(final ObjectType type); static Collection<ObjectTemplate> getTemplates(); ObjectType getObjectType(); List<AttributeTemplate> getAttributeTemplates(); Set<AttributeType> getAllAttributes(); Set<AttributeType> getKeyAttributes(); Set<AttributeType> getLookupAttributes(); AttributeType getKeyLookupAttribute(); Set<AttributeType> getMandatoryAttributes(); Set<AttributeType> getInverseLookupAttributes(); Set<AttributeType> getGeneratedAttributes(); Set<AttributeType> getMultipleAttributes(); Comparator<RpslAttribute> getAttributeTypeComparator(); boolean isSet(); String getNameToFirstUpper( ); String getNameToFirstLower( ); @Override boolean equals(final Object o); @Override int hashCode(); @Override int compareTo(@Nonnull final ObjectTemplate o); void validateStructure(final RpslObject rpslObject, final ObjectMessages objectMessages); void validateSyntax(final RpslObject rpslObject, final ObjectMessages objectMessages, final boolean skipGenerated); ObjectMessages validate(final RpslObject rpslObject); @Override String toString(); String toVerboseString(); boolean hasAttribute(final AttributeType attributeType); }### Answer: @Test public void isSet() { for (ObjectType objectType : ObjectType.values()) { assertThat(objectType.getName().toLowerCase().contains("set"), is(ObjectTemplate.getTemplate(objectType).isSet())); } }
### Question: RpslObject implements Identifiable, ResponseObject { public final CIString getKey() { return key; } RpslObject(final RpslObject oldObject, final List<RpslAttribute> attributes); RpslObject(final Integer objectId, final List<RpslAttribute> attributes); RpslObject(final Integer objectId, final RpslObject rpslObject); RpslObject(final List<RpslAttribute> attributes); static RpslObject parse(final String input); static RpslObject parse(final byte[] input); static RpslObject parse(final Integer objectId, final String input); static RpslObject parse(final Integer objectId, final byte[] input); @Override int getObjectId(); ObjectType getType(); List<RpslAttribute> getAttributes(); int size(); final CIString getKey(); String getFormattedKey(); @Override boolean equals(final Object obj); @Override int hashCode(); RpslAttribute getTypeAttribute(); RpslAttribute findAttribute(final AttributeType attributeType); List<RpslAttribute> findAttributes(final AttributeType attributeType); List<RpslAttribute> findAttributes(final Iterable<AttributeType> attributeTypes); List<RpslAttribute> findAttributes(final AttributeType... attributeTypes); boolean containsAttributes(final Collection<AttributeType> attributeTypes); boolean containsAttribute(final AttributeType attributeType); @Override void writeTo(final OutputStream out); void writeTo(final Writer writer); @Override byte[] toByteArray(); @Override String toString(); CIString getValueForAttribute(final AttributeType attributeType); @Nullable CIString getValueOrNullForAttribute(final AttributeType attributeType); Set<CIString> getValuesForAttribute(final AttributeType... attributeType); }### Answer: @Test(expected = IllegalArgumentException.class) public void test_get_key_person_empty() { parseAndAssign("person: foo # Comment \n"); subject.getKey(); }
### Question: RpslObject implements Identifiable, ResponseObject { public boolean containsAttribute(final AttributeType attributeType) { return getOrCreateCache().containsKey(attributeType); } RpslObject(final RpslObject oldObject, final List<RpslAttribute> attributes); RpslObject(final Integer objectId, final List<RpslAttribute> attributes); RpslObject(final Integer objectId, final RpslObject rpslObject); RpslObject(final List<RpslAttribute> attributes); static RpslObject parse(final String input); static RpslObject parse(final byte[] input); static RpslObject parse(final Integer objectId, final String input); static RpslObject parse(final Integer objectId, final byte[] input); @Override int getObjectId(); ObjectType getType(); List<RpslAttribute> getAttributes(); int size(); final CIString getKey(); String getFormattedKey(); @Override boolean equals(final Object obj); @Override int hashCode(); RpslAttribute getTypeAttribute(); RpslAttribute findAttribute(final AttributeType attributeType); List<RpslAttribute> findAttributes(final AttributeType attributeType); List<RpslAttribute> findAttributes(final Iterable<AttributeType> attributeTypes); List<RpslAttribute> findAttributes(final AttributeType... attributeTypes); boolean containsAttributes(final Collection<AttributeType> attributeTypes); boolean containsAttribute(final AttributeType attributeType); @Override void writeTo(final OutputStream out); void writeTo(final Writer writer); @Override byte[] toByteArray(); @Override String toString(); CIString getValueForAttribute(final AttributeType attributeType); @Nullable CIString getValueOrNullForAttribute(final AttributeType attributeType); Set<CIString> getValuesForAttribute(final AttributeType... attributeType); }### Answer: @Test public void containsAttribute_works() { parseAndAssign(maintainer); assertThat(subject.containsAttribute(AttributeType.SOURCE), is(true)); } @Test public void containsAttribute_unknown() { parseAndAssign(maintainer); assertThat(subject.containsAttribute(AttributeType.PERSON), is(false)); }
### Question: RpslObject implements Identifiable, ResponseObject { public CIString getValueForAttribute(final AttributeType attributeType) { return findAttribute(attributeType).getCleanValue(); } RpslObject(final RpslObject oldObject, final List<RpslAttribute> attributes); RpslObject(final Integer objectId, final List<RpslAttribute> attributes); RpslObject(final Integer objectId, final RpslObject rpslObject); RpslObject(final List<RpslAttribute> attributes); static RpslObject parse(final String input); static RpslObject parse(final byte[] input); static RpslObject parse(final Integer objectId, final String input); static RpslObject parse(final Integer objectId, final byte[] input); @Override int getObjectId(); ObjectType getType(); List<RpslAttribute> getAttributes(); int size(); final CIString getKey(); String getFormattedKey(); @Override boolean equals(final Object obj); @Override int hashCode(); RpslAttribute getTypeAttribute(); RpslAttribute findAttribute(final AttributeType attributeType); List<RpslAttribute> findAttributes(final AttributeType attributeType); List<RpslAttribute> findAttributes(final Iterable<AttributeType> attributeTypes); List<RpslAttribute> findAttributes(final AttributeType... attributeTypes); boolean containsAttributes(final Collection<AttributeType> attributeTypes); boolean containsAttribute(final AttributeType attributeType); @Override void writeTo(final OutputStream out); void writeTo(final Writer writer); @Override byte[] toByteArray(); @Override String toString(); CIString getValueForAttribute(final AttributeType attributeType); @Nullable CIString getValueOrNullForAttribute(final AttributeType attributeType); Set<CIString> getValuesForAttribute(final AttributeType... attributeType); }### Answer: @Test public void getValueForAttribute() { assertThat(RpslObject.parse("mntner: DEV-MNT\n").getValueForAttribute(AttributeType.MNTNER).toString(), is("DEV-MNT")); }
### Question: RpslAttribute { public void validateSyntax(final ObjectType objectType, final ObjectMessages objectMessages) { for (final CIString cleanValue : getCleanValues()) { if (!type.getSyntax().matches(objectType, cleanValue.toString())) { objectMessages.addMessage(this, ValidationMessages.syntaxError(cleanValue.toString())); } } } RpslAttribute(final AttributeType attributeType, final CIString value); RpslAttribute(final AttributeType attributeType, final String value); RpslAttribute(final String key, final CIString value); RpslAttribute(final String key, final String value); String getKey(); String getValue(); String getCleanComment(); CIString getCleanValue(); Set<CIString> getCleanValues(); Set<CIString> getReferenceValues(); CIString getReferenceValue(); void validateSyntax(final ObjectType objectType, final ObjectMessages objectMessages); void writeTo(final Writer writer); String getFormattedValue(); void writeAttributeValueTo(final Writer writer); @Override boolean equals(Object o); @Override int hashCode(); @CheckForNull AttributeType getType(); @Override String toString(); }### Answer: @Test public void validateSyntax_syntax_error_and_invalid_email() { final ObjectMessages objectMessages = new ObjectMessages(); final RpslAttribute rpslAttribute = new RpslAttribute("inetnum", "[email protected]"); rpslAttribute.validateSyntax(ObjectType.INETNUM, objectMessages); assertThat(objectMessages.getMessages(rpslAttribute).getAllMessages(), contains(ValidationMessages.syntaxError("[email protected]"))); }
### Question: RpslAttribute { @Override public String toString() { try { final StringWriter writer = new StringWriter(); writeTo(writer); return writer.toString(); } catch (IOException e) { throw new IllegalStateException("Should never occur", e); } } RpslAttribute(final AttributeType attributeType, final CIString value); RpslAttribute(final AttributeType attributeType, final String value); RpslAttribute(final String key, final CIString value); RpslAttribute(final String key, final String value); String getKey(); String getValue(); String getCleanComment(); CIString getCleanValue(); Set<CIString> getCleanValues(); Set<CIString> getReferenceValues(); CIString getReferenceValue(); void validateSyntax(final ObjectType objectType, final ObjectMessages objectMessages); void writeTo(final Writer writer); String getFormattedValue(); void writeAttributeValueTo(final Writer writer); @Override boolean equals(Object o); @Override int hashCode(); @CheckForNull AttributeType getType(); @Override String toString(); }### Answer: @Test public void format_single_line_no_spaces() { final RpslAttribute subject = new RpslAttribute("person", "Brian Riddle"); assertThat(subject.toString(), is("person: Brian Riddle\n")); } @Test public void format_single_line_some_spaces() { final RpslAttribute subject = new RpslAttribute("person", " Brian Riddle"); assertThat(subject.toString(), is("person: Brian Riddle\n")); } @Test public void format_single_line_too_many_spaces() { final RpslAttribute subject = new RpslAttribute("person", " Brian Riddle"); assertThat(subject.toString(), is("person: Brian Riddle\n")); }
### Question: RpslAttribute { public String getCleanComment() { if (cleanValues == null) { extractCleanValueAndComment(value); } return cleanComment; } RpslAttribute(final AttributeType attributeType, final CIString value); RpslAttribute(final AttributeType attributeType, final String value); RpslAttribute(final String key, final CIString value); RpslAttribute(final String key, final String value); String getKey(); String getValue(); String getCleanComment(); CIString getCleanValue(); Set<CIString> getCleanValues(); Set<CIString> getReferenceValues(); CIString getReferenceValue(); void validateSyntax(final ObjectType objectType, final ObjectMessages objectMessages); void writeTo(final Writer writer); String getFormattedValue(); void writeAttributeValueTo(final Writer writer); @Override boolean equals(Object o); @Override int hashCode(); @CheckForNull AttributeType getType(); @Override String toString(); }### Answer: @Test public void get_comment_in_second_line() { subject = new RpslAttribute("remarks", "remark1\n remark2 # comment"); assertThat(subject.getCleanComment(), is("comment")); subject = new RpslAttribute("remarks", "foo\t # comment1 \n bar # \t comment2\n+ bla"); assertThat(subject.getCleanComment(), is("comment1 comment2")); }
### Question: ParserHelper { public static void validateMoreSpecificsOperator(final String yytext) { int val = Integer.valueOf(yytext.substring(1)); if (val > MAX_BIT_LENGTH_IPV4) { syntaxError("more specifics operator " + yytext.substring(1) + " not 0 to 32 bits"); } } private ParserHelper(); static void check16bit(final String number); static void check32bit(final String number); static void checkMaskLength(final String maskLength); static void checkMaskLengthv6(final String maskLength); static void checkStringLength(final String ip, final int maxAllowedLength); static void validateMoreSpecificsOperator(final String yytext); static void validateRangeMoreSpecificsOperators(final String yytext); static void validateAsNumber(final String yytext); static void validateIpv4PrefixRange(final String yytext); static void validateIpv6PrefixRange(final String yytext); static void validateIpv4Prefix(final String yytext); static void validateIpv6Prefix(final String yytext); static void validateIpv4(final String yytext); static void validateIpv6(final String yytext); static void validateCommunity(final String yytext); static void validateDomainName(final String yytext); static void validateDomainNameLabel(final String yytext); static void validateSmallInt(final String yytext); static void validateAsRange(final String yytext); static void log(final String message); static void log(final Exception exception); static void syntaxError(final String message); static void parserError(final String message); }### Answer: @Test public void validateMoreSpecificsOperator() { ParserHelper.validateMoreSpecificsOperator("^0"); ParserHelper.validateMoreSpecificsOperator("^32"); } @Test(expected = IllegalArgumentException.class) public void validateMoreSpecificsOperatorFailsTooLarge() { ParserHelper.validateMoreSpecificsOperator("^33"); }
### Question: ParserHelper { public static void validateAsNumber(final String yytext) { final long value = Long.valueOf(yytext.substring(2)); if (value > MAX_32BIT_NUMBER) { syntaxError("AS Number " + yytext + " length is invalid"); } } private ParserHelper(); static void check16bit(final String number); static void check32bit(final String number); static void checkMaskLength(final String maskLength); static void checkMaskLengthv6(final String maskLength); static void checkStringLength(final String ip, final int maxAllowedLength); static void validateMoreSpecificsOperator(final String yytext); static void validateRangeMoreSpecificsOperators(final String yytext); static void validateAsNumber(final String yytext); static void validateIpv4PrefixRange(final String yytext); static void validateIpv6PrefixRange(final String yytext); static void validateIpv4Prefix(final String yytext); static void validateIpv6Prefix(final String yytext); static void validateIpv4(final String yytext); static void validateIpv6(final String yytext); static void validateCommunity(final String yytext); static void validateDomainName(final String yytext); static void validateDomainNameLabel(final String yytext); static void validateSmallInt(final String yytext); static void validateAsRange(final String yytext); static void log(final String message); static void log(final Exception exception); static void syntaxError(final String message); static void parserError(final String message); }### Answer: @Test public void validateAsNumber() { ParserHelper.validateAsNumber("AS0"); ParserHelper.validateAsNumber("AS" + ParserHelper.MAX_32BIT_NUMBER); } @Test(expected = IllegalArgumentException.class) public void validateAsNumberOutOfRange() { ParserHelper.validateAsNumber("AS" + (ParserHelper.MAX_32BIT_NUMBER + 1L)); }
### Question: ParserHelper { public static void validateIpv4(final String yytext) { try { Ipv4Resource.parse(yytext); } catch (IllegalArgumentException e) { syntaxError("IP address " + yytext + " contains an invalid octet"); } } private ParserHelper(); static void check16bit(final String number); static void check32bit(final String number); static void checkMaskLength(final String maskLength); static void checkMaskLengthv6(final String maskLength); static void checkStringLength(final String ip, final int maxAllowedLength); static void validateMoreSpecificsOperator(final String yytext); static void validateRangeMoreSpecificsOperators(final String yytext); static void validateAsNumber(final String yytext); static void validateIpv4PrefixRange(final String yytext); static void validateIpv6PrefixRange(final String yytext); static void validateIpv4Prefix(final String yytext); static void validateIpv6Prefix(final String yytext); static void validateIpv4(final String yytext); static void validateIpv6(final String yytext); static void validateCommunity(final String yytext); static void validateDomainName(final String yytext); static void validateDomainNameLabel(final String yytext); static void validateSmallInt(final String yytext); static void validateAsRange(final String yytext); static void log(final String message); static void log(final Exception exception); static void syntaxError(final String message); static void parserError(final String message); }### Answer: @Test public void validateIpv4() { ParserHelper.validateIpv4("1.2.3.4/32"); } @Test(expected = IllegalArgumentException.class) public void validateIpv4InvalidPrefixLength() { ParserHelper.validateIpv4("1.2.3.4/33"); }
### Question: ByteArrayOutput extends OutputStream { public void write(final int b) { final int newcount = count + 1; if (newcount > buf.length) { buf = Arrays.copyOf(buf, Math.max(buf.length << 1, newcount)); } buf[count] = (byte) b; count = newcount; } ByteArrayOutput(); ByteArrayOutput(final int initialCapacity); void write(final int b); void write(final byte b[]); void write(final byte b[], final int off, final int len); void reset(); byte[] toByteArray(); int size(); }### Answer: @Test(expected = IndexOutOfBoundsException.class) public void write_bytes_offset_out_of_bounds() { subject.write(buffer, 2, buffer.length); }
### Question: ByteArrayOutput extends OutputStream { public void reset() { count = 0; } ByteArrayOutput(); ByteArrayOutput(final int initialCapacity); void write(final int b); void write(final byte b[]); void write(final byte b[], final int off, final int len); void reset(); byte[] toByteArray(); int size(); }### Answer: @Test public void reset() { subject.write(buffer); subject.reset(); assertThat(subject.toByteArray(), is(new byte[]{})); subject.write(buffer); assertThat(subject.toByteArray(), is(buffer)); }
### Question: ByteArrayOutput extends OutputStream { public int size() { return count; } ByteArrayOutput(); ByteArrayOutput(final int initialCapacity); void write(final int b); void write(final byte b[]); void write(final byte b[], final int off, final int len); void reset(); byte[] toByteArray(); int size(); }### Answer: @Test public void size() { subject.write(buffer); assertThat(subject.size(), is(buffer.length)); }
### Question: Ipv4Resource extends IpInterval<Ipv4Resource> implements Comparable<Ipv4Resource> { @Override public Ipv4Resource singletonIntervalAtLowerBound() { return new Ipv4Resource(this.begin(), this.begin()); } private Ipv4Resource(final int begin, final int end); Ipv4Resource(final long begin, final long end); Ipv4Resource(final InetAddress inetAddress); static Ipv4Resource parse(final CIString resource); static Ipv4Resource parse(final String resource); static Ipv4Resource parseIPv4Resource(final String resource); static Ipv4Resource parsePrefixWithLength(final long prefix, final int prefixLength); static Ipv4Resource parseReverseDomain(final String address); @Override AttributeType getAttributeType(); long begin(); long end(); @Override boolean contains(final Ipv4Resource that); @Override boolean intersects(final Ipv4Resource that); @Override int hashCode(); @Override boolean equals(final Object obj); @Override String toString(); String toRangeString(); @Override int compareTo(final Ipv4Resource that); @Override Ipv4Resource singletonIntervalAtLowerBound(); @Override int compareUpperBound(final Ipv4Resource that); @Override InetAddress beginAsInetAddress(); @Override InetAddress endAsInetAddress(); @Override int getPrefixLength(); static final String IPV4_REVERSE_DOMAIN; static final Ipv4Resource MAX_RANGE; }### Answer: @Test public void singletonIntervalAtLowerBound() { assertEquals(Ipv4Resource.parse("127.0.0.0/32"), Ipv4Resource.parse("127.0.0.0/8").singletonIntervalAtLowerBound()); }
### Question: ResourceTagger { void tagObjects(final GrsSource grsSource) { final Stopwatch stopwatch = Stopwatch.createStarted(); try { sourceContext.setCurrent(Source.master(grsSource.getName())); if (sourceContext.isTagRoutes()) { tagRouteObjectsInContext(grsSource); } tagsDao.deleteOrphanedTags(); } finally { sourceContext.removeCurrentSource(); grsSource.getLogger().info("Tagging objects complete in {}", stopwatch.stop()); } } @Autowired ResourceTagger(final SourceContext sourceContext, final TagsDao tagsDao); }### Answer: @Test public void tagObjects() { subject.tagObjects(grsSource); verify(sourceContext).setCurrent(any(Source.class)); verify(sourceContext).removeCurrentSource(); verify(tagsDao).updateTags(any(Iterable.class), any(List.class), any(List.class)); verify(tagsDao).deleteOrphanedTags(); }
### Question: GrsSource implements InitializingBean { @Override public String toString() { return name.toString(); } GrsSource(final String name, final SourceContext sourceContext, final DateTimeProvider dateTimeProvider, final AuthoritativeResourceData authoritativeResourceData, final Downloader downloader); @Override void afterPropertiesSet(); Logger getLogger(); @Override String toString(); }### Answer: @Test public void string() { assertThat(subject.toString(), is("SOME-GRS")); }
### Question: IpInterval implements Interval<K> { public static IpInterval<?> parseReverseDomain(final String reverse) { final String result = removeTrailingDot(reverse).toLowerCase(); if (result.endsWith(Ipv4Resource.IPV4_REVERSE_DOMAIN)) { return Ipv4Resource.parseReverseDomain(result); } return Ipv6Resource.parseReverseDomain(result); } static String removeTrailingDot(final String address); abstract AttributeType getAttributeType(); static IpInterval<?> parse(final CIString prefix); static IpInterval<?> parse(final String prefix); static IpInterval<?> parseReverseDomain(final String reverse); static IpInterval<?> asIpInterval(final InetAddress address); abstract InetAddress beginAsInetAddress(); abstract InetAddress endAsInetAddress(); abstract int getPrefixLength(); }### Answer: @Test public void parseReverseDomain() { assertThat(IpInterval.parseReverseDomain("0.0.193.in-ADDR.arpA").toString(), is("193.0.0.0/24")); assertThat(IpInterval.parseReverseDomain("a.b.0.0.1.iP6.arpA").toString(), is("100b:a000::/20")); assertThat(IpInterval.parseReverseDomain("0.0.193.in-ADDR.arpA.").toString(), is("193.0.0.0/24")); assertThat(IpInterval.parseReverseDomain("a.b.0.0.1.iP6.arpA.").toString(), is("100b:a000::/20")); }