src_fm_fc_ms_ff
stringlengths
43
86.8k
target
stringlengths
20
276k
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); }
@Test public void getUpdates_empty() { for (final Notification.Type type : Notification.Type.values()) { assertThat(subject.getUpdates(type), hasSize(0)); } }
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); }
@Test public void has_empty() { for (final Notification.Type type : Notification.Type.values()) { assertThat(subject.has(type), is(false)); } }
UpdateResult { @Override public String toString() { final Writer writer = new StringWriter(); try { toString(writer); return writer.toString(); } catch (IOException e) { throw new IllegalStateException("Should not occur", e); } } UpdateResult(@Nullable final RpslObject originalObject, final RpslObject updatedObject, final Action action, final UpdateStatus status, final ObjectMessages objectMessages, final int retryCount, final boolean dryRun); RpslObject getUpdatedObject(); String getKey(); UpdateStatus getStatus(); Action getAction(); String getActionString(); Collection<Message> getErrors(); Collection<Message> getWarnings(); Collection<Message> getInfos(); boolean isNoop(); boolean isDryRun(); int getRetryCount(); @Override String toString(); void toString(final Writer writer); }
@Test public void string_representation() { final RpslObject updatedObject = RpslObject.parse("mntner: DEV-ROOT-MNT\nsource: RIPE #Filtered\ninvalid: invalid\nmnt-by: MNT2"); when(update.getType()).thenReturn(ObjectType.MNTNER); when(update.getSubmittedObject()).thenReturn(updatedObject); final ObjectMessages objectMessages = new ObjectMessages(); objectMessages.addMessage(UpdateMessages.filteredNotAllowed()); objectMessages.addMessage(updatedObject.getAttributes().get(0), UpdateMessages.objectInUse(updatedObject)); objectMessages.addMessage(updatedObject.getAttributes().get(2), ValidationMessages.unknownAttribute("invalid")); objectMessages.addMessage(updatedObject.getAttributes().get(3), UpdateMessages.referencedObjectMissingAttribute(ObjectType.MNTNER, "MNT2", AttributeType.DESCR)); final UpdateResult subject = new UpdateResult(null, updatedObject, Action.MODIFY, UpdateStatus.FAILED, objectMessages, 0, false); final String string = subject.toString(); assertThat(string, is("" + "mntner: DEV-ROOT-MNT\n" + "***Error: Object [mntner] DEV-ROOT-MNT is referenced from other objects\n" + "source: RIPE #Filtered\n" + "invalid: invalid\n" + "***Error: \"invalid\" is not a known RPSL attribute\n" + "mnt-by: MNT2\n" + "***Warning: Referenced mntner object MNT2 is missing mandatory attribute\n" + " \"descr:\"\n" + "\n" + "***Error: Cannot submit filtered whois output for updates\n" + "\n")); }
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); }
@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)); }
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(); }
@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)); }
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(); }
@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)); }
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(); }
@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()); }
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); }
@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); }
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); }
@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")); }
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); }
@Test public void write_line() throws Exception { mockWrite("aaa\n"); SocketChannelFactory.Writer writer = SocketChannelFactory.createWriter(socketChannel); writer.writeLine("aaa"); }
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); }
@Test(expected = IllegalArgumentException.class) public void invalid_source() { when(sourceContext.isVirtual(CIString.ciString("1-GRS"))).thenReturn(true); subject.checkSources(); }
NrtmImporter implements EmbeddedValueResolverAware, ApplicationService { @Override public void start() { if (!enabled) { return; } final List<NrtmSource> nrtmSources = readNrtmSources(); if (nrtmSources.size() > 0) { LOGGER.info("Initializing thread pool with {} thread(s)", nrtmSources.size()); executorService = Executors.newFixedThreadPool(nrtmSources.size(), new ThreadFactory() { final ThreadGroup threadGroup = new ThreadGroup(Thread.currentThread().getThreadGroup(), "NrtmClients"); final AtomicInteger threadNum = new AtomicInteger(); @Override public Thread newThread(final Runnable r) { return new Thread(threadGroup, r, String.format("NrtmClient-%s", threadNum.incrementAndGet())); } }); for (NrtmSource nrtmSource : nrtmSources) { final NrtmClientFactory.NrtmClient nrtmClient = nrtmClientFactory.createNrtmClient(nrtmSource); clients.add(nrtmClient); executorService.submit(nrtmClient); } } } @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); }
@Test public void start() { when(valueResolver.resolveStringValue("${nrtm.import.1-GRS.source}")).thenReturn("RIPE"); when(valueResolver.resolveStringValue("${nrtm.import.1-GRS.host}")).thenReturn("localhost"); when(valueResolver.resolveStringValue("${nrtm.import.1-GRS.port}")).thenReturn("1044"); when(nrtmClientFactory.createNrtmClient(any(NrtmSource.class))).thenReturn(mock(NrtmClientFactory.NrtmClient.class)); subject.start(); verify(nrtmClientFactory).createNrtmClient(any(NrtmSource.class)); }
NrtmQueryHandler extends SimpleChannelUpstreamHandler { @Override public void messageReceived(final ChannelHandlerContext ctx, final MessageEvent e) { if (isKeepAlive()) { return; } final String queryString = e.getMessage().toString().trim(); nrtmLog.log(ChannelUtil.getRemoteAddress(ctx.getChannel()), queryString); LOGGER.debug("Received query: {}", queryString); final Query query = parseQueryString(queryString); final Channel channel = ctx.getChannel(); if (query.isMirrorQuery()) { final SerialRange range = serialDao.getSerials(); if (query.getSerialEnd() == -1 || query.isKeepalive()) { query.setSerialEnd(range.getEnd()); } if (!isRequestedSerialInRange(query, range)) { throw new IllegalArgumentException("%ERROR:401: invalid range: Not within " + range.getBegin() + "-" + range.getEnd()); } final Integer serialAge = serialDao.getAgeOfExactOrNextExistingSerial(query.getSerialBegin()); if (serialAge == null || serialAge > HISTORY_AGE_LIMIT) { throw new IllegalArgumentException(String.format("%%ERROR:401: (Requesting serials older than %d days will be rejected)", HISTORY_AGE_LIMIT / SECONDS_PER_DAY)); } final int version = query.getVersion(); writeMessage(channel, String.format("%%START Version: %d %s %d-%d", version, query.getSource(), query.getSerialBegin(), query.getSerialEnd() )); if (version < NrtmServer.NRTM_VERSION) { writeMessage(channel, NrtmMessages.deprecatedVersion(version)); } if (query.isKeepalive()) { handleMirrorQueryWithKeepalive(query, channel); return; } else { handleMirrorQuery(query, channel); } } else if (query.isInfoQuery()) { switch (query.getQueryOption()) { case SOURCES: handleSourcesQuery(channel); break; case VERSION: handleVersionQuery(channel); break; } } channel.write(ChannelBuffers.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE); } 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); }
@Test public void gFlagWithVersion2Works() { when(dummifierMock.isAllowed(2, person)).thenReturn(true); when(dummifierMock.isAllowed(2, inetnum)).thenReturn(true); when(dummifierMock.dummify(2, inetnum)).thenReturn(inetnum); when(dummifierMock.dummify(2, person)).thenReturn(DummifierNrtm.getPlaceholderPersonObject()); when(messageEventMock.getMessage()).thenReturn("-g RIPE:2:1-2"); subject.messageReceived(contextMock, messageEventMock); InOrder orderedChannelMock = inOrder(channelMock); verify(channelMock, times(7)).write(argThat(instanceofString())); orderedChannelMock.verify(channelMock).write("%START Version: 2 RIPE 1-2\n\n"); orderedChannelMock.verify(channelMock).write("%WARNING: NRTM version 2 is deprecated, please consider migrating to version 3!\n\n"); orderedChannelMock.verify(channelMock).write("ADD\n\n"); orderedChannelMock.verify(channelMock).write(inetnum + "\n"); orderedChannelMock.verify(channelMock).write("ADD\n\n"); orderedChannelMock.verify(channelMock).write(DummifierNrtm.getPlaceholderPersonObject() + "\n"); orderedChannelMock.verify(channelMock).write("%END RIPE\n\n"); } @Test public void qFlagVersionArgument() { when(messageEventMock.getMessage()).thenReturn("-q version"); subject.messageReceived(contextMock, messageEventMock); verify(channelMock).write(argThat(instanceofString())); verify(channelMock).write("% nrtm-server-" + VERSION + "\n\n"); } @Test public void qFlagSourcesArgument() { when(messageEventMock.getMessage()).thenReturn("-q sources"); subject.messageReceived(contextMock, messageEventMock); verify(channelMock).write(argThat(instanceofString())); verify(channelMock).write(SOURCE + ":3:X:1-2\n\n"); } @Test public void gFlagValidRange() { when(messageEventMock.getMessage()).thenReturn("-g RIPE:3:1-2"); subject.messageReceived(contextMock, messageEventMock); verify(channelMock, times(4)).write(argThat(instanceofString())); verify(channelMock).write("%START Version: 3 RIPE 1-2\n\n"); verify(channelMock).write("ADD 1\n\n"); verify(channelMock).write(inetnum.toString() + "\n"); verify(channelMock, never()).write("ADD 2\n\n"); verify(channelMock, never()).write(person.toString() + "\n"); verify(channelMock).write("%END RIPE\n\n"); } @Test public void keepalive() { when(messageEventMock.getMessage()).thenReturn("-g RIPE:3:1-LAST -k"); subject.messageReceived(contextMock, messageEventMock); verify(channelMock, times(3)).write(argThat(instanceofString())); verify(channelMock).write("%START Version: 3 RIPE 1-2\n\n"); verify(mySchedulerMock).scheduleAtFixedRate(any(Runnable.class), anyLong()); verify(channelMock).write("ADD 1\n\n"); verify(channelMock).write(inetnum.toString() + "\n"); } @Test public void keepaliveEndOfStreamIndicator() { subject = new NrtmQueryHandler(serialDaoMock, dummifierMock, mySchedulerMock, nrtmLogMock, applicationVersion, SOURCE, NONAUTH_SOURCE, UPDATE_INTERVAL, true); when(messageEventMock.getMessage()).thenReturn("-g RIPE:3:1-LAST -k"); subject.messageReceived(contextMock, messageEventMock); verify(channelMock, times(4)).write(argThat(instanceofString())); verify(channelMock).write("%START Version: 3 RIPE 1-2\n\n"); verify(mySchedulerMock).scheduleAtFixedRate(any(Runnable.class), anyLong()); verify(channelMock).write("ADD 1\n\n"); verify(channelMock).write(inetnum.toString() + "\n"); verify(channelMock).write("%END 1 - 2\n\n"); } @Test public void gFlagValidRangeToLast() { when(messageEventMock.getMessage()).thenReturn("-g RIPE:3:1-LAST"); subject.messageReceived(contextMock, messageEventMock); verify(channelMock, times(4)).write(argThat(instanceofString())); verify(channelMock).write("%START Version: 3 RIPE 1-2\n\n"); verify(channelMock).write("ADD 1\n\n"); verify(channelMock).write(inetnum.toString() + "\n"); verify(channelMock).write("%END RIPE\n\n"); } @Test public void gFlag_InvalidRange() { when(messageEventMock.getMessage()).thenReturn("-g RIPE:3:4-5"); try { subject.messageReceived(contextMock, messageEventMock); fail("Didn't catch IllegalArgumentException"); } catch (IllegalArgumentException e) { assertThat(e.getMessage(), containsString("%ERROR:401: invalid range: Not within 1-2")); } } @Test public void closedChannel() { when(channelMock.isOpen()).thenReturn(false); when(messageEventMock.getMessage()).thenReturn("-g RIPE:3:1-2"); try { subject.messageReceived(contextMock, messageEventMock); fail("expected ChannelException"); } catch (ChannelException expected) { verify(channelMock, atLeast(1)).isOpen(); } } @Test public void gFlagRequestOutOfDateSerial() { when(serialDaoMock.getAgeOfExactOrNextExistingSerial(1)).thenReturn(NrtmQueryHandler.HISTORY_AGE_LIMIT + 1); when(messageEventMock.getMessage()).thenReturn("-g RIPE:3:1-2"); try { subject.messageReceived(contextMock, messageEventMock); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException e) { assertThat(e.getMessage(), containsString("%ERROR:401: (Requesting serials older than " + (NrtmQueryHandler.HISTORY_AGE_LIMIT / NrtmQueryHandler.SECONDS_PER_DAY) + " days will be rejected)")); } } @Test public void gFlagDeprecatedVersion() { when(messageEventMock.getMessage()).thenReturn("-g RIPE:2:1-1"); subject.messageReceived(contextMock, messageEventMock); verify(channelMock, times(3)).write(argThat(instanceofString())); verify(channelMock).write("%START Version: 2 RIPE 1-1\n\n"); verify(channelMock).write("%WARNING: NRTM version 2 is deprecated, please consider migrating to version 3!\n\n"); verify(channelMock).write("%END RIPE\n\n"); } @Test public void throttleChannelKeepaliveQuery() { setPending(channelMock); when(messageEventMock.getMessage()).thenReturn("-g RIPE:3:1-LAST -k"); messageReceived(); unsetPending(channelMock); verify(channelMock).write("%START Version: 3 RIPE 1-2\n\n"); verify(channelMock, atMost(1)).write(any(String.class)); verify(mySchedulerMock).scheduleAtFixedRate(any(Runnable.class), anyLong()); } @Test public void retryForAnnotation() { when(serialDaoMock.getByIdForNrtm(any(Integer.class))).thenThrow(CannotGetJdbcConnectionException.class); when(messageEventMock.getMessage()).thenReturn("-g RIPE:3:1-LAST"); try { subject.messageReceived(contextMock, messageEventMock); fail(); } catch (CannotGetJdbcConnectionException e) { verify(serialDaoMock, times(10)).getByIdForNrtm(1); } }
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); }
@Test public void channelConnected() throws Exception { subject.channelConnected(contextMock, channelStateEventMock); verify(channelMock).write(NrtmMessages.termsAndConditions() + "\n\n"); }
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); }
@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); }
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; }
@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)); }
GrsImporter implements DailyScheduledTask { public List<Future> grsImport(String sources, final boolean rebuild) { final Set<CIString> sourcesToImport = splitSources(sources); LOGGER.info("GRS import sources: {}", sourcesToImport); final List<Future> futures = Lists.newArrayListWithCapacity(sourcesToImport.size()); for (final CIString enabledSource : sourcesToImport) { final GrsSource grsSource = grsSources.get(enabledSource); if (grsSource == null) { LOGGER.warn("Unknown source: {}", enabledSource); continue; } futures.add(executorService.submit(new Runnable() { @Override public void run() { if (!currentlyImporting.add(enabledSource)) { grsSource.getLogger().warn("Skipped, already running"); return; } try { LOGGER.info("Importing: {}", enabledSource); grsSourceImporter.grsImport(grsSource, rebuild); } catch (RuntimeException e) { grsSource.getLogger().error("Unexpected", e); } finally { currentlyImporting.remove(enabledSource); } } })); } return futures; } @Autowired GrsImporter(final GrsSourceImporter grsSourceImporter, final GrsSource[] grsSources); @Value("${grs.import.enabled}") void setGrsImportEnabled(final boolean grsImportEnabled); @Value("${grs.import.sources}") void setDefaultSources(final String defaultSources); @Override @Scheduled(cron = "0 0 0 * * *") @SchedulerLock(name = "GrsImporter") void run(); List<Future> grsImport(String sources, final boolean rebuild); }
@Test public void grsImport_RIPE_GRS_no_rebuild() throws Exception { await(subject.grsImport("RIPE-GRS", false)); verify(grsSourceImporter).grsImport(grsSourceRipe, false); verify(grsSourceImporter, never()).grsImport(grsSourceOther, false); } @Test public void grsImport_RIPE_GRS_rebuild() throws Exception { await(subject.grsImport("RIPE-GRS", true)); verify(grsSourceImporter).grsImport(grsSourceRipe, true); verify(grsSourceImporter, never()).grsImport(grsSourceOther, true); } @Test public void grsImport_unknown_source() throws Exception { await(subject.grsImport("UNKNOWN-GRS", true)); verify(grsSourceRipe, never()).acquireDump(any(Path.class)); verify(grsSourceRipe, never()).handleObjects(any(File.class), any(ObjectHandler.class)); verify(grsDao, never()).cleanDatabase(); } @Test public void grsImport_RIPE_GRS_acquire_fails() throws Exception { doThrow(RuntimeException.class).when(grsSourceRipe).acquireDump(any(Path.class)); await(subject.grsImport("RIPE-GRS", false)); verify(grsSourceRipe, never()).handleObjects(any(File.class), any(ObjectHandler.class)); }
CollectionHelper { public static Iterable<ResponseObject> iterateProxy( final ProxyLoader<Identifiable, RpslObject> rpslObjectLoader, final Iterable<? extends Identifiable> identifiables) { final ProxyIterable<Identifiable, ? extends ResponseObject> rpslObjects = new ProxyIterable<>((Iterable<Identifiable>) identifiables, rpslObjectLoader, 100); return Iterables.filter((Iterable<ResponseObject>)rpslObjects, (Objects::nonNull)); } 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; }
@Test public void iterateProxy_empty() { ProxyLoader<Identifiable, RpslObject> proxyLoader = Mockito.mock(ProxyLoader.class); final Iterable<ResponseObject> responseObjects = CollectionHelper.iterateProxy(proxyLoader, Collections.<Identifiable>emptyList()); verify(proxyLoader, never()).load(anyListOf(Identifiable.class), (List<RpslObject>) anyObject()); final Iterator<ResponseObject> iterator = responseObjects.iterator(); assertThat(iterator.hasNext(), is(false)); verify(proxyLoader, never()).load(anyListOf(Identifiable.class), (List<RpslObject>) anyObject()); } @Test public void iterateProxy() { final RpslObjectInfo info1 = new RpslObjectInfo(1, ObjectType.INETNUM, "1"); final RpslObject object1 = RpslObject.parse("inetnum: 10.0.0.0"); final RpslObjectInfo info2 = new RpslObjectInfo(2, ObjectType.INETNUM, "2"); final RpslObject object2 = RpslObject.parse("inetnum: 10.0.0.1"); ProxyLoader<Identifiable, RpslObject> proxyLoader = Mockito.mock(ProxyLoader.class); doAnswer(new Answer() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { Object[] args = invocation.getArguments(); List<RpslObject> response = (List<RpslObject>) args[1]; response.add(object1); response.add(object2); return null; } }).when(proxyLoader).load(any(List.class), any(List.class)); final Iterable<ResponseObject> responseObjects = CollectionHelper.iterateProxy(proxyLoader, Arrays.asList(info1, info2)); verify(proxyLoader).load(anyListOf(Identifiable.class), anyListOf(RpslObject.class)); final Iterator<ResponseObject> iterator = responseObjects.iterator(); assertThat(iterator.hasNext(), is(true)); assertThat((RpslObject) iterator.next(), is(object1)); assertThat(iterator.hasNext(), is(true)); assertThat((RpslObject) iterator.next(), is(object2)); assertThat(iterator.hasNext(), is(false)); verify(proxyLoader).load(anyListOf(Identifiable.class), anyListOf(RpslObject.class)); }
DatabaseMaintenanceJmx extends JmxBase { @ManagedOperation(description = "Recovers a deleted object (you will need to issue an IP tree rebuild if needed)") @ManagedOperationParameters({ @ManagedOperationParameter(name = "objectId", description = "Id of the object to recover"), @ManagedOperationParameter(name = "comment", description = "Optional comment for invoking the operation") }) public String undeleteObject(final int objectId, final String comment) { return invokeOperation("Undelete Object", comment, new Callable<String>() { @Override public String call() { try { final RpslObjectUpdateInfo updateInfo = updateDao.undeleteObject(objectId); return String.format("Recovered object: %s\n *** Remember to update IP trees if needed", updateInfo); } catch (RuntimeException e) { LOGGER.error("Unable to recover object with id: {}", objectId, e); return String.format("Unable to recover: %s", e.getMessage()); } } }); } @Autowired DatabaseMaintenanceJmx(final RpslObjectUpdateDao updateDao, final IndexDao indexDao); @ManagedOperation(description = "Recovers a deleted object (you will need to issue an IP tree rebuild if needed)") @ManagedOperationParameters({ @ManagedOperationParameter(name = "objectId", description = "Id of the object to recover"), @ManagedOperationParameter(name = "comment", description = "Optional comment for invoking the operation") }) String undeleteObject(final int objectId, final String comment); @ManagedOperation(description = "Rebuild all indexes based on objects in last") @ManagedOperationParameters({ @ManagedOperationParameter(name = "comment", description = "Optional comment for invoking the operation") }) void rebuildIndexes(final String comment); @ManagedOperation(description = "Rebuild indexes for specified object") @ManagedOperationParameters({ @ManagedOperationParameter(name = "objectId", description = "Id of the object to rebuild"), @ManagedOperationParameter(name = "comment", description = "Optional comment for invoking the operation") }) String rebuildIndexesForObject(final int objectId, final String comment); @ManagedOperation(description = "Pause rebuild indexes") void pause(); @ManagedOperation(description = "Resume rebuild indexes") void resume(); }
@Test public void undeleteObject_success() { when(updateDao.undeleteObject(1)).thenReturn(new RpslObjectUpdateInfo(1, 1, ObjectType.MNTNER, "DEV-MNT")); final String response = subject.undeleteObject(1, "comment"); assertThat(response, is( "Recovered object: RpslObjectUpdateInfo{objectId=1, objectType=MNTNER, key=DEV-MNT, sequenceId=1}\n" + " *** Remember to update IP trees if needed")); } @Test public void undeleteObject_error() { when(updateDao.undeleteObject(1)).thenThrow(EmptyResultDataAccessException.class); final String response = subject.undeleteObject(1, "comment"); assertThat(response, is("Unable to recover: null")); }
JdbcRpslObjectOperations { public static void sanityCheck(final JdbcTemplate jdbcTemplate) { try { final String dbName = jdbcTemplate.queryForObject("SELECT database()", String.class); if (!dbName.matches("(?i).*_mirror_.+_grs.*") && !dbName.matches("(?i).*test.*")) { throw new IllegalStateException(String.format("%s has no 'test' or 'grs' in the name, exiting", dbName)); } if (jdbcTemplate.queryForList("SHOW TABLES", String.class).contains("serials")) { if (jdbcTemplate.queryForObject("SELECT count(*) FROM serials", Integer.class) > 50_000_000) { throw new IllegalStateException(String.format("%s has more than 50M serials, exiting", dbName)); } } } catch (DataAccessException e) { throw new IllegalStateException(e); } } static void insertIntoTables(final JdbcTemplate jdbcTemplate, final RpslObjectInfo rpslObjectInfo, final RpslObject rpslObject); static Set<CIString> insertIntoTablesIgnoreMissing(final JdbcTemplate jdbcTemplate, final RpslObjectInfo rpslObjectInfo, final RpslObject rpslObject); static RpslObjectUpdateInfo lookupRpslObjectUpdateInfo(final JdbcTemplate jdbcTemplate, final ObjectType type, final String pkey); static RpslObjectUpdateInfo lookupRpslObjectUpdateInfo(final JdbcTemplate jdbcTemplate, final int objectId, final String pkey); static void deleteFromTables(final JdbcTemplate jdbcTemplate, final RpslObjectInfo rpslObjectInfo); static void copyToHistoryAndUpdateSerials(final JdbcTemplate jdbcTemplate, final RpslObjectUpdateInfo rpslObjectInfo); static void deleteFromLastAndUpdateSerials(final DateTimeProvider dateTimeProvider, final JdbcTemplate jdbcTemplate, final RpslObjectUpdateInfo rpslObjectInfo); static void deleteFromLastAndSetSerials(final DateTimeProvider dateTimeProvider, final JdbcTemplate jdbcTemplate, final RpslObjectUpdateInfo rpslObjectInfo, final int serialId); static int updateLastAndUpdateSerials(final DateTimeProvider dateTimeProvider, final JdbcTemplate jdbcTemplate, final RpslObjectUpdateInfo rpslObjectInfo, final RpslObject object); static int updateLastAndSetSerials(final DateTimeProvider dateTimeProvider, final JdbcTemplate jdbcTemplate, final RpslObjectUpdateInfo rpslObjectInfo, final RpslObject object, final int serialId); static RpslObjectUpdateInfo insertIntoLastAndUpdateSerials(final DateTimeProvider dateTimeProvider, final JdbcTemplate jdbcTemplate, final RpslObject object); static RpslObjectUpdateInfo insertIntoLastAndSetSerials(final DateTimeProvider dateTimeProvider, final JdbcTemplate jdbcTemplate, final RpslObject object, final int serialId); static int now(final DateTimeProvider dateTimeProvider); static void truncateTables(final JdbcTemplate... jdbcTemplates); static void loadScripts(final JdbcTemplate jdbcTemplate, final String... initSql); static void sanityCheck(final JdbcTemplate jdbcTemplate); static SerialRange getSerials(final JdbcTemplate jdbcTemplate); static RpslObject getObjectById(final JdbcTemplate jdbcTemplate, final Identifiable identifiable); static RpslObject getObjectById(final JdbcTemplate jdbcTemplate, final int objectId); @CheckForNull static SerialEntry getSerialEntry(final JdbcTemplate jdbcTemplate, final int serialId); @CheckForNull static SerialEntry getSerialEntryForNrtm(final JdbcTemplate jdbcTemplate, final int serialId); @CheckForNull static Integer getAgeOfExactOrNextExistingSerial(final DateTimeProvider dateTimeProvider, final JdbcTemplate jdbcTemplate, final int serialId); }
@Test public void sanityCheckKickingIn() { for (String dbName : ImmutableList.of("WHOIS_UPDATE_RIPE", "MAILUPDATES")) { try { when(whoisTemplate.queryForObject("SELECT database()", String.class)).thenReturn(dbName); JdbcRpslObjectOperations.sanityCheck(whoisTemplate); fail("Database name '" + dbName + "' did not trigger exception"); } catch (Exception e) { assertThat(e.getMessage(), endsWith("has no 'test' or 'grs' in the name, exiting")); } } } @Test public void sanityCheckLettingThrough() { when(whoisTemplate.queryForObject(startsWith("SELECT count(*) FROM "), eq(Integer.class))).thenReturn(10); for (String dbName : ImmutableList.of("WHOIS_TEST_TEST", "GRSteST", "WHOIS_MIRROR_APNIC_GRS")) { when(whoisTemplate.queryForObject(eq("SELECT database()"), eq(String.class))).thenReturn(dbName); JdbcRpslObjectOperations.sanityCheck(whoisTemplate); } }
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(); }
@Test public void getAttributeType() { assertThat(subject.getAttributeType(), is(ATTRIBUTE_TYPE)); }
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(); }
@Test public void addToIndex() { assertThat(subject.addToIndex(null, null, null, (String) null), is(1)); }
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(); }
@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)); }
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(); }
@Test public void removeFromIndex() { subject.removeFromIndex(null, null); }
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(); }
@Test public void getLookupTableName() { assertNull(subject.getLookupTableName()); }
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(); }
@Test public void getLookupColumnName() { assertNull(subject.getLookupColumnName()); }
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); }
@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)); } }
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); }
@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); }
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); }
@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"); }
DatabaseVersionCheck { public static int compareVersions(final String v1, final String v2) { Iterator<String> i1 = VERSION_SPLITTER.split(v1).iterator(); Iterator<String> i2 = VERSION_SPLITTER.split(v2).iterator(); while (i1.hasNext() && i2.hasNext()) { int res = Integer.parseInt(i1.next()) - Integer.parseInt(i2.next()); if (res != 0) { return res; } } if (i1.hasNext() && !i2.hasNext()) { return 1; } if (!i1.hasNext() && i2.hasNext()) { return -1; } return 0; } @Autowired DatabaseVersionCheck(ApplicationContext applicationContext); static int compareVersions(final String v1, final String v2); Iterable<String> getSqlPatchResources(); @PostConstruct void checkDatabaseVersions(); void checkDatabase(Iterable<String> resources, String dataSourceName, String dbVersion); }
@Test public void testVersionNumberCheck() { assertThat(DatabaseVersionCheck.compareVersions("1.0", "2.0"), lessThan(0)); assertThat(DatabaseVersionCheck.compareVersions("1.1", "2.0"), lessThan(0)); assertThat(DatabaseVersionCheck.compareVersions("1.01", "2.0"), lessThan(0)); assertThat(DatabaseVersionCheck.compareVersions("1.2.3.4", "2.0.1"), lessThan(0)); assertThat(DatabaseVersionCheck.compareVersions("10.0", "2.0"), greaterThan(0)); assertThat(DatabaseVersionCheck.compareVersions("12.12.12.12.12.12", "11.99.2"), greaterThan(0)); assertThat(DatabaseVersionCheck.compareVersions("2.0", "2.0.0"), lessThan(0)); assertThat(DatabaseVersionCheck.compareVersions("2.0", "2.0.0.1"), lessThan(0)); assertThat(DatabaseVersionCheck.compareVersions("2.0.0", "2.0.0.1"), lessThan(0)); assertThat(DatabaseVersionCheck.compareVersions("2.0.0.0", "2.0.0.1"), lessThan(0)); assertThat(DatabaseVersionCheck.compareVersions("2.0.0.0.0.0.0.0", "2.0.0.1"), lessThan(0)); assertThat(DatabaseVersionCheck.compareVersions("1.0-1", "1.0-2"), lessThan(0)); assertThat(DatabaseVersionCheck.compareVersions("1.1-99", "2.0"), lessThan(0)); assertThat(DatabaseVersionCheck.compareVersions("1.01-0.11", "2.0"), lessThan(0)); assertThat(DatabaseVersionCheck.compareVersions("1.01-0.11", "1.1-1"), lessThan(0)); assertThat(DatabaseVersionCheck.compareVersions("1.01-0.11", "1.1-00.12"), lessThan(0)); }
DatabaseVersionCheck { public void checkDatabase(Iterable<String> resources, String dataSourceName, String dbVersion) { final Matcher dbVersionMatcher = RESOURCE_MATCHER.matcher(dbVersion); if (!dbVersionMatcher.matches()) { throw new IllegalStateException("Invalid version: " + dbVersion); } for (String resource : resources) { final Matcher resourceMatcher = RESOURCE_MATCHER.matcher(resource); if (!resourceMatcher.matches()) continue; if (!dbVersionMatcher.group(1).equals(resourceMatcher.group(1))) continue; final String dbVersionNumber = dbVersionMatcher.group(2); final String resourceVersionNumber = resourceMatcher.group(2); if (compareVersions(dbVersionNumber, resourceVersionNumber) < 0) { throw new IllegalStateException("Patch " + resource + ".sql was not applied"); } } LOGGER.info("Datasource {} validated OK (DB version: {})", dataSourceName, dbVersion); } @Autowired DatabaseVersionCheck(ApplicationContext applicationContext); static int compareVersions(final String v1, final String v2); Iterable<String> getSqlPatchResources(); @PostConstruct void checkDatabaseVersions(); void checkDatabase(Iterable<String> resources, String dataSourceName, String dbVersion); }
@Test public void testCheckDatabaseOK() { DatabaseVersionCheck subject = new DatabaseVersionCheck(null); subject.checkDatabase(ImmutableList.of("whois-1.51", "whois-1.4", "whois-2.15.4"), "TEST", "whois-2.16"); } @Test(expected = IllegalStateException.class) public void testCheckDatabaseFail() { DatabaseVersionCheck subject = new DatabaseVersionCheck(null); subject.checkDatabase(ImmutableList.of("whois-1.51", "whois-1.4", "whois-2.15.4"), "TEST", "whois-1.16"); } @Test public void testCheckDatabaseSucceedForAnotherDB() { DatabaseVersionCheck subject = new DatabaseVersionCheck(null); subject.checkDatabase(ImmutableList.of("scheduler-1.51", "whois-1.4", "acl-2.15.4"), "TEST", "whois-1.16"); }
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); }
@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)); }
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); }
@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))); }
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(); }
@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)); }
BlockEvents { public int getTemporaryBlockCount() { int numberOfBlocks = 0; for (final BlockEvent blockEvent : blockEvents) { switch (blockEvent.getType()) { case BLOCK_TEMPORARY: numberOfBlocks++; break; case UNBLOCK: case BLOCK_PERMANENTLY: return numberOfBlocks; default: throw new IllegalStateException("Unexpected block event type: " + blockEvent.getType()); } } return numberOfBlocks; } BlockEvents(final String prefix, final List<BlockEvent> blockEvents); String getPrefix(); int getTemporaryBlockCount(); boolean isPermanentBlockRequired(); static final int NR_TEMP_BLOCKS_BEFORE_PERMANENT; }
@Test(expected = NullPointerException.class) public void test_events_null() { final BlockEvents blockEvents = new BlockEvents(prefix, null); blockEvents.getTemporaryBlockCount(); } @Test public void test_number_of_blocks() { final BlockEvents blockEvents = createBlockEvents("10.0.0.0", 3); assertThat(blockEvents.getTemporaryBlockCount(), is(3)); } @Test public void test_number_of_blocks_after_unblock() { final List<BlockEvent> events = Arrays.asList( createBlockEvent(1, BlockEvent.Type.BLOCK_TEMPORARY), createBlockEvent(2, BlockEvent.Type.BLOCK_TEMPORARY), createBlockEvent(3, BlockEvent.Type.BLOCK_TEMPORARY), createBlockEvent(4, BlockEvent.Type.UNBLOCK), createBlockEvent(5, BlockEvent.Type.BLOCK_TEMPORARY) ); final BlockEvents blockEvents = new BlockEvents(prefix, events); assertThat(blockEvents.getTemporaryBlockCount(), is(1)); } @Test public void test_number_of_blocks_after_unblock_unspecified_order() { final List<BlockEvent> events = Arrays.asList( createBlockEvent(4, BlockEvent.Type.UNBLOCK), createBlockEvent(5, BlockEvent.Type.BLOCK_TEMPORARY), createBlockEvent(3, BlockEvent.Type.BLOCK_TEMPORARY), createBlockEvent(2, BlockEvent.Type.BLOCK_TEMPORARY), createBlockEvent(1, BlockEvent.Type.BLOCK_TEMPORARY) ); final BlockEvents blockEvents = new BlockEvents(prefix, events); assertThat(blockEvents.getTemporaryBlockCount(), is(1)); }
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; }
@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)); }
ConcurrentState { public void set(final Boolean value) { updates.add(value); } void set(final Boolean value); void waitUntil(final Boolean value); }
@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); }
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); }
@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())); }
ApnicGrsSource extends GrsSource { @Override public void handleObjects(final File file, final ObjectHandler handler) throws IOException { FileInputStream is = null; try { is = new FileInputStream(file); final BufferedReader reader = new BufferedReader(new InputStreamReader(new GZIPInputStream(is), StandardCharsets.UTF_8)); handleLines(reader, new LineHandler() { @Override public void handleLines(final List<String> lines) { handler.handle(lines); } }); } finally { IOUtils.closeQuietly(is); } } @Autowired ApnicGrsSource( @Value("${grs.import.apnic.source:}") final String source, final SourceContext sourceContext, final DateTimeProvider dateTimeProvider, final AuthoritativeResourceData authoritativeResourceData, final Downloader downloader, @Value("${grs.import.apnic.download:}") final String download); @Override void acquireDump(final Path path); @Override void handleObjects(final File file, final ObjectHandler handler); }
@Test public void handleObjects() throws Exception { final File file = new File(getClass().getResource("/grs/apnic.test.gz").toURI()); subject.handleObjects(file, objectHandler); assertThat(objectHandler.getObjects(), hasSize(0)); assertThat(objectHandler.getLines(), hasSize(2)); assertThat(objectHandler.getLines(), contains((List<String>) Lists.newArrayList( "as-block: AS7467 - AS7722\n", "descr: APNIC ASN block\n", "remarks: These AS numbers are further assigned by APNIC\n", "remarks: to APNIC members and end-users in the APNIC region\n", "admin-c: HM20-AP\n", "tech-c: HM20-AP\n", "mnt-by: APNIC-HM\n", "mnt-lower: APNIC-HM\n", "changed: [email protected] 20020926\n", "source: APNIC\n"), Lists.newArrayList( "as-block: AS18410 - AS18429\n", "descr: TWNIC-TW-AS-BLOCK8\n", "remarks: These AS numbers are further assigned by TWNIC\n", "remarks: to TWNIC members\n", "admin-c: TWA2-AP\n", "tech-c: TWA2-AP\n", "mnt-by: MAINT-TW-TWNIC\n", "mnt-lower: MAINT-TW-TWNIC\n", "changed: [email protected] 20021220\n", "changed: [email protected] 20050624\n", "source: APNIC\n") )); }
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(); }
@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()); }
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(); }
@Test public void put() { subject.put(key, value); verify(wrapped, times(1)).put(key, value); }
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(); }
@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); }
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(); }
@Test public void findFirstLessSpecific() { subject.findFirstLessSpecific(key); verify(wrapped, times(1)).findFirstLessSpecific(key); }
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(); }
@Test public void findAllLessSpecific() { subject.findAllLessSpecific(key); verify(wrapped, times(1)).findAllLessSpecific(key); }
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(); }
@Test public void findExactAndAllLessSpecific() { subject.findExactAndAllLessSpecific(key); verify(wrapped, times(1)).findExactAndAllLessSpecific(key); }
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(); }
@Test public void findExact() { subject.findExact(key); verify(wrapped, times(1)).findExact(key); }
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(); }
@Test public void findExactOrFirstLessSpecific() { subject.findExactOrFirstLessSpecific(key); verify(wrapped, times(1)).findExactOrFirstLessSpecific(key); }
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(); }
@Test public void findFirstMoreSpecific() { subject.findFirstMoreSpecific(key); verify(wrapped, times(1)).findFirstMoreSpecific(key); }
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(); }
@Test public void findAllMoreSpecific() { subject.findAllMoreSpecific(key); verify(wrapped, times(1)).findAllMoreSpecific(key); }
LacnicGrsSource extends GrsSource { @Override public void handleObjects(final File file, final ObjectHandler handler) throws IOException { FileInputStream is = null; try { is = new FileInputStream(file); final BufferedReader reader = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8)); handleLines(reader, lines -> { final String rpslObjectString = Joiner.on("").join(lines); final RpslObject rpslObjectBase = RpslObject.parse(rpslObjectString); final List<RpslAttribute> newAttributes = Lists.newArrayList(); for (RpslAttribute attribute : rpslObjectBase.getAttributes()) { final Function<RpslAttribute, RpslAttribute> transformFunction = TRANSFORM_FUNCTIONS.get(ciString(attribute.getKey())); if (transformFunction != null) { attribute = transformFunction.apply(attribute); } if (attribute.getType() != null) { newAttributes.add(attribute); } } handler.handle(FILTER_CHANGED_FUNCTION.apply(new RpslObject(newAttributes))); }); } finally { IOUtils.closeQuietly(is); } } @Autowired LacnicGrsSource( @Value("${grs.import.lacnic.source:}") final String source, final SourceContext sourceContext, final DateTimeProvider dateTimeProvider, final AuthoritativeResourceData authoritativeResourceData, final Downloader downloader, @Value("${grs.import.lacnic.userId:}") final String userId, @Value("${grs.import.lacnic.password:}") final String password); @Override void acquireDump(final Path path); @Override void handleObjects(final File file, final ObjectHandler handler); }
@Test public void handleObjects() throws Exception { final File file = new File(getClass().getResource("/grs/lacnic.test").toURI()); subject.handleObjects(file, objectHandler); assertThat(objectHandler.getLines(), hasSize(0)); assertThat(objectHandler.getObjects(), hasSize(3)); assertThat(objectHandler.getObjects(), contains( RpslObject.parse("" + "aut-num: AS278\n" + "descr: Description\n" + "country: MX\n" + "created: 19890331 # created\n" + "source: LACNIC\n"), RpslObject.parse("" + "inetnum: 24.232.16/24\n" + "status: reallocated\n" + "descr: Description\n" + "country: AR\n" + "tech-c:\n" + "created: 19990312 # created\n" + "source: LACNIC\n"), RpslObject.parse("" + "inet6num: 2001:1200:2000::/48\n" + "status: reallocated\n" + "descr: Description\n" + "country: MX\n" + "tech-c: IIM\n" + "abuse-c: IIM\n" + "created: 20061106 # created\n" + "source: LACNIC\n") )); }
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(); }
@Test public void findExactAndAllMoreSpecific() { subject.findExactAndAllMoreSpecific(key); verify(wrapped, times(1)).findExactAndAllMoreSpecific(key); }
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(); }
@Test public void clear() { subject.clear(); verify(wrapped, times(1)).clear(); }
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); }
@Test(expected = IllegalArgumentException.class) public void test_intersect_insert_fails() { c.addChild(e); }
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(); }
@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))); }
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(); }
@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()); } }
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(); }
@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); }
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(); }
@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)); }
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(); }
@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)); }
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(); }
@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)); }
GrsSourceImporter { void grsImport(final GrsSource grsSource, final boolean rebuild) { final AuthoritativeResource authoritativeResource = grsSource.getAuthoritativeResource(); if (sourceContext.isVirtual(grsSource.getName())) { grsSource.getLogger().info("Not updating GRS data"); } else { acquireAndUpdateGrsData(grsSource, rebuild, authoritativeResource); } resourceTagger.tagObjects(grsSource); } @Autowired GrsSourceImporter( @Value("${dir.grs.import.download}") final String downloadDir, final AttributeSanitizer sanitizer, final ResourceTagger resourceTagger, final SourceContext sourceContext); }
@Test public void run_rebuild() { when(grsSource.getName()).thenReturn(ciString("APNIC-GRS")); subject.grsImport(grsSource, true); verify(grsDao).cleanDatabase(); verify(grsDao, never()).getCurrentObjectIds(); } @Test public void run_rebuild_ripe() { when(grsSource.getName()).thenReturn(ciString("RIPE-GRS")); when(sourceContext.isVirtual(ciString("RIPE-GRS"))).thenReturn(true); subject.grsImport(grsSource, true); verify(grsDao, never()).cleanDatabase(); verify(grsDao, never()).getCurrentObjectIds(); } @Test public void run_without_rebuild() { when(grsSource.getName()).thenReturn(ciString("APNIC-GRS")); subject.grsImport(grsSource, false); verify(grsDao, never()).cleanDatabase(); verify(grsDao).getCurrentObjectIds(); } @Test public void run_without_rebuild_ripe() { when(grsSource.getName()).thenReturn(ciString("RIPE-GRS")); when(sourceContext.isVirtual(ciString("RIPE-GRS"))).thenReturn(true); subject.grsImport(grsSource, false); verify(grsDao, never()).cleanDatabase(); verify(grsDao, never()).getCurrentObjectIds(); } @Test public void acquire_and_process() throws IOException { when(grsSource.getName()).thenReturn(ciString("APNIC-GRS")); subject.grsImport(grsSource, false); final Path dumpFile = folder.getRoot().toPath().resolve("APNIC-GRS-DMP"); verify(grsSource).acquireDump(dumpFile); verify(grsSource).handleObjects(eq(dumpFile.toFile()), any(ObjectHandler.class)); } @Test public void acquire_and_process_ripe() throws IOException { when(grsSource.getName()).thenReturn(ciString("RIPE-GRS")); when(sourceContext.isVirtual(ciString("RIPE-GRS"))).thenReturn(true); subject.grsImport(grsSource, false); verify(grsSource, never()).acquireDump(any(Path.class)); verify(grsSource, never()).handleObjects(any(File.class), any(ObjectHandler.class)); } @Test public void process_nothing_does_not_delete() { when(grsSource.getName()).thenReturn(ciString("APNIC-GRS")); when(grsDao.getCurrentObjectIds()).thenReturn(Lists.newArrayList(1)); subject.grsImport(grsSource, false); verify(grsDao, never()).deleteObject(anyInt()); } @Test public void process_throws_exception() throws IOException { when(grsSource.getName()).thenReturn(ciString("APNIC-GRS")); doThrow(RuntimeException.class).when(grsSource).handleObjects(any(File.class), any(ObjectHandler.class)); try { subject.grsImport(grsSource, false); fail("Expected RuntimeException"); } catch (RuntimeException e) { verify(grsSource).handleObjects(any(File.class), any(ObjectHandler.class)); } } @Test public void handle_object_create() throws IOException { when(grsSource.getName()).thenReturn(ciString("APNIC-GRS")); when(authoritativeResource.isMaintainedInRirSpace(any(RpslObject.class))).thenReturn(true); doAnswer(new Answer() { @Override public Object answer(InvocationOnMock invocationOnMock) throws Throwable { final ObjectHandler objectHandler = (ObjectHandler) invocationOnMock.getArguments()[1]; objectHandler.handle(RpslObject.parse("" + "aut-num: AS1263\n" + "as-name: NSN-TEST-AS\n" + "descr: NSN-TEST-AS\n" + "admin-c: Not available\n" + "tech-c: See MAINT-AS1263\n" + "mnt-by: MAINT-AS1263\n" + "changed: [email protected] 19950201\n" + "source: RIPE" )); return null; } }).when(grsSource).handleObjects(any(File.class), any(ObjectHandler.class)); subject.grsImport(grsSource, false); verify(grsDao).createObject(RpslObject.parse("" + "aut-num: AS1263\n" + "as-name: NSN-TEST-AS\n" + "descr: NSN-TEST-AS\n" + "admin-c: Not available\n" + "tech-c: See MAINT-AS1263\n" + "mnt-by: MAINT-AS1263\n" + "source: APNIC-GRS")); verify(sanitizer).sanitize(any(RpslObject.class), any(ObjectMessages.class)); } @Test public void handle_object_create_syntax_errors() throws IOException { when(grsSource.getName()).thenReturn(ciString("APNIC-GRS")); doAnswer(new Answer() { @Override public Object answer(InvocationOnMock invocationOnMock) throws Throwable { final ObjectHandler objectHandler = (ObjectHandler) invocationOnMock.getArguments()[1]; objectHandler.handle(RpslObject.parse("" + "mntner: SOME\n" + "changed: [email protected] 19950201\n" + "unknown: unknown" + "source: RIPE" )); return null; } }).when(grsSource).handleObjects(any(File.class), any(ObjectHandler.class)); subject.grsImport(grsSource, false); verify(grsDao, never()).createObject(any(RpslObject.class)); verify(sanitizer).sanitize(any(RpslObject.class), any(ObjectMessages.class)); } @Test public void handle_lines_create_with_unknown_attribute() throws IOException { when(grsSource.getName()).thenReturn(ciString("APNIC-GRS")); when(authoritativeResource.isMaintainedInRirSpace(any(RpslObject.class))).thenReturn(true); doAnswer(new Answer() { @Override public Object answer(InvocationOnMock invocationOnMock) throws Throwable { final ObjectHandler objectHandler = (ObjectHandler) invocationOnMock.getArguments()[1]; objectHandler.handle(Lists.newArrayList( "aut-num: AS1263\n", "as-name: NSN-TEST-AS\n", "descr: NSN-TEST-AS\n", " NSN-TEST-AS\n", "admin-c: Not available\n", "unknown: oops\n", "tech-c: See MAINT-AS1263\n", "mnt-by: MAINT-AS1263\n", "changed: [email protected] 19950201\n", "source: RIPE\n" )); return null; } }).when(grsSource).handleObjects(any(File.class), any(ObjectHandler.class)); subject.grsImport(grsSource, false); verify(grsDao).createObject(RpslObject.parse("" + "aut-num: AS1263\n" + "as-name: NSN-TEST-AS\n" + "descr: NSN-TEST-AS\n" + " NSN-TEST-AS\n" + "admin-c: Not available\n" + "tech-c: See MAINT-AS1263\n" + "mnt-by: MAINT-AS1263\n" + "source: APNIC-GRS")); verify(sanitizer).sanitize(any(RpslObject.class), any(ObjectMessages.class)); } @Test public void handle_lines_no_source_managed_by_rir() throws IOException { when(grsSource.getName()).thenReturn(ciString("APNIC-GRS")); when(authoritativeResource.isMaintainedInRirSpace(any(RpslObject.class))).thenReturn(true); doAnswer(new Answer() { @Override public Object answer(InvocationOnMock invocationOnMock) throws Throwable { final ObjectHandler objectHandler = (ObjectHandler) invocationOnMock.getArguments()[1]; objectHandler.handle(Lists.newArrayList( "aut-num: AS1263\n", "changed: [email protected] 19950201\n" )); return null; } }).when(grsSource).handleObjects(any(File.class), any(ObjectHandler.class)); subject.grsImport(grsSource, false); verify(grsDao).createObject(RpslObject.parse("" + "aut-num: AS1263\n" + "source: APNIC-GRS")); verify(sanitizer).sanitize(any(RpslObject.class), any(ObjectMessages.class)); } @Test public void try_inserting_role_and_person_with_same_nichdl() throws Exception { when(grsSource.getName()).thenReturn(ciString("APNIC-GRS")); when(authoritativeResource.isMaintainedInRirSpace(any(RpslObject.class))).thenReturn(true); doAnswer(new Answer() { @Override public Object answer(final InvocationOnMock invocation) throws Throwable { final ObjectHandler objectHandler = (ObjectHandler) invocation.getArguments()[1]; objectHandler.handle(RpslObject.parse("" + "person: Ninja Person\n" + "nic-hdl: NI124-RIPE\n")); return null; } }).when(grsSource).handleObjects(any(File.class), any(ObjectHandler.class)); final GrsObjectInfo grsObjectInfo1 = new GrsObjectInfo(1, 1, RpslObject.parse("role: Ninja Role\nnic-hdl: NI124-RIPE\n")); when(grsDao.find("NI124-RIPE", ObjectType.PERSON)).thenReturn(null); when(grsDao.find("NI124-RIPE", ObjectType.ROLE)).thenReturn(grsObjectInfo1); subject.grsImport(grsSource, false); verify(grsDao, times(0)).createObject(any(RpslObject.class)); verify(grsDao, times(0)).updateObject(any(GrsObjectInfo.class), any(RpslObject.class)); } @Test public void run_create_update_delete() throws IOException { when(grsSource.getName()).thenReturn(ciString("APNIC-GRS")); when(grsDao.getCurrentObjectIds()).thenReturn(Lists.newArrayList(1, 2, 3)); when(authoritativeResource.isMaintainedInRirSpace(any(RpslObject.class))).thenReturn(true); doAnswer(new Answer() { @Override public Object answer(final InvocationOnMock invocation) throws Throwable { final ObjectHandler objectHandler = (ObjectHandler) invocation.getArguments()[1]; objectHandler.handle(RpslObject.parse("" + "mntner: MODIFY-MNT\n" + "mnt-by: CREATE-MNT\n")); objectHandler.handle(RpslObject.parse("" + "mntner: CREATE-MNT\n" + "mnt-by: CREATE-MNT\n")); objectHandler.handle(RpslObject.parse("" + "mntner: NOOP-MNT\n")); return null; } }).when(grsSource).handleObjects(any(File.class), any(ObjectHandler.class)); when(updateResultUpdate.hasMissingReferences()).thenReturn(true); final GrsObjectInfo grsObjectInfo1 = new GrsObjectInfo(1, 1, RpslObject.parse("mntner: MODIFY-MNT")); when(grsDao.find("MODIFY-MNT", ObjectType.MNTNER)).thenReturn(grsObjectInfo1); final GrsObjectInfo grsObjectInfo2 = new GrsObjectInfo(2, 2, RpslObject.parse("mntner: NOOP-MNT\nsource: APNIC-GRS")); when(grsDao.find("NOOP-MNT", ObjectType.MNTNER)).thenReturn(grsObjectInfo2); subject.grsImport(grsSource, false); verify(grsDao).createObject(RpslObject.parse("" + "mntner: CREATE-MNT\n" + "mnt-by: CREATE-MNT\n" + "source: APNIC-GRS")); verify(grsDao).updateObject(grsObjectInfo1, RpslObject.parse("" + "mntner: MODIFY-MNT\n" + "mnt-by: CREATE-MNT\n" + "source: APNIC-GRS")); verify(grsDao).updateIndexes(0); verify(grsDao, times(1)).updateObject(any(GrsObjectInfo.class), any(RpslObject.class)); verify(grsDao).deleteObject(3); }
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(); }
@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)); }
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(); }
@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))); }
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(); }
@Test public void testFindExact() { for (Ipv4Resource n : all) { assertThat(subject.findExact(n), contains(n)); } }
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(); }
@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))); }
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(); }
@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)); }
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); }
@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)); }
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); }
@Test public void remove() { subject.remove(k_11); final List<String> result = subject.findExact(k_11); assertThat(result, hasSize(0)); }
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); }
@Test public void clear() { subject.clear(); final List<String> result = subject.findAllMoreSpecific(Ipv4Resource.MAX_RANGE); assertThat(result, hasSize(0)); }
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); }
@Test public void findFirstLessSpecific() { final List<String> result = subject.findFirstLessSpecific(k_11); assertThat(result, contains(v_121, v_122)); }
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); }
@Test public void findExactOrFirstLessSpecific() { final List<String> result = subject.findExactOrFirstLessSpecific(k_12); assertThat(result, contains(v_121, v_122)); }
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); }
@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)); }
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); }
@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)); }
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); }
@Test public void findFirstMoreSpecific() { final List<String> result = subject.findFirstMoreSpecific(k_12); assertThat(result, contains(v_11)); }
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); }
@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)); }
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); }
@Test public void findExactAndAllMoreSpecific() { final List<String> result = subject.findExactAndAllMoreSpecific(k_12); assertThat(result, contains(v_121, v_122, v_11)); }
AuthoritativeResourceJsonLoader extends AbstractAuthoritativeResourceLoader { public AuthoritativeResource load(final JsonNode root) { handleAllocations(root.get("asnResources"), "asn"); handleFreeResources(root.get("asnResources"), "asn"); handleReservedResources(root.get("asnResources"), "asn"); handleAssignments(root.get("ipv4Resources"), "ipv4"); handleAllocations(root.get("ipv4Resources"), "ipv4"); handleFreeResources(root.get("ipv4Resources"), "ipv4"); handleReservedResources(root.get("ipv4Resources"), "ipv4"); handleAssignments(root.get("ipv6Resources"), "ipv6"); handleAllocations(root.get("ipv6Resources"), "ipv6"); handleFreeResources(root.get("ipv6Resources"), "ipv6"); handleReservedResources(root.get("ipv6Resources"), "ipv6"); return new AuthoritativeResource(autNums, ipv4Space, ipv6Space); } AuthoritativeResourceJsonLoader(final Logger logger); AuthoritativeResource load(final JsonNode root); }
@Test public void load() throws IOException { final AuthoritativeResource authoritativeResource = new AuthoritativeResourceJsonLoader(logger).load( new ObjectMapper().readValue(IOUtils.toString(getClass().getResourceAsStream("/grs/rirstats.json")), JsonNode.class) ); assertTrue(authoritativeResource.isMaintainedInRirSpace(ObjectType.AUT_NUM, ciString("AS7"))); assertTrue(authoritativeResource.isMaintainedInRirSpace(ObjectType.AUT_NUM, ciString("AS1877"))); assertTrue(authoritativeResource.isMaintainedInRirSpace(ObjectType.AUT_NUM, ciString("AS2849"))); assertTrue(authoritativeResource.isMaintainedInRirSpace(ObjectType.INETNUM, ciString("2.0.0.0-2.15.255.255"))); assertTrue(authoritativeResource.isMaintainedInRirSpace(ObjectType.INETNUM, ciString("2.56.168.0-2.56.171.255"))); assertTrue(authoritativeResource.isMaintainedInRirSpace(ObjectType.INETNUM, ciString("5.44.248.0-5.44.255.255"))); assertTrue(authoritativeResource.isMaintainedInRirSpace(ObjectType.INETNUM, ciString("13.116.0.0-13.123.255.255"))); assertTrue(authoritativeResource.isMaintainedInRirSpace(ObjectType.INET6NUM, ciString("2001:600::/32"))); assertTrue(authoritativeResource.isMaintainedInRirSpace(ObjectType.INET6NUM, ciString("2001:678::/48"))); assertTrue(authoritativeResource.isMaintainedInRirSpace(ObjectType.INET6NUM, ciString("2001:678:1::/48"))); assertTrue(authoritativeResource.isMaintainedInRirSpace(ObjectType.INET6NUM, ciString("2001:601::/32"))); }
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); }
@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", "")); }
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(); }
@Test(expected = IllegalSourceException.class) public void nonexistant_source_throws_exception() { authoritativeResourceData.getAuthoritativeResource(ciString("BLAH")); }
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(); }
@Test(expected = IllegalArgumentException.class) public void unknown_file() throws IOException { AuthoritativeResource.loadFromFile(logger, "unknown", folder.getRoot().toPath().resolve("unknown")); }
AuthoritativeResource { public static AuthoritativeResource loadFromScanner(final Logger logger, final String name, final Scanner scanner) { return new AuthoritativeResourceLoader(logger, name, scanner).load(); } 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(); }
@Test public void test_frankenranges_using_maintained_in_rir_space_in_order() { final AuthoritativeResource resourceData = AuthoritativeResource.loadFromScanner(logger, "RIPE-GRS", new Scanner( first + second + third)); testFranken(resourceData); } @Test public void test_frankenranges_using_maintained_in_rir_space_reverse_order() { final AuthoritativeResource resourceData = AuthoritativeResource.loadFromScanner(logger, "RIPE-GRS", new Scanner( third + second + first)); testFranken(resourceData); } @Test public void test_frankenranges_using_maintained_in_rir_space_random_order() { final AuthoritativeResource resourceData = AuthoritativeResource.loadFromScanner(logger, "RIPE-GRS", new Scanner( first + third + second)); testFranken(resourceData); } @Test public void test_frankenranges_using_maintained_in_rir_space_duplicates() { final AuthoritativeResource resourceData = AuthoritativeResource.loadFromScanner(logger, "RIPE-GRS", new Scanner( first + third + second + third + second + first)); testFranken(resourceData); }
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); }
@Test public void refreshCache() { final String msg = subject.refreshCache("comment"); assertThat(msg, is("Refreshed caches")); verify(authoritativeResourceRefreshTask).refreshGrsAuthoritativeResourceCaches(); }
AuthoritativeResourceDataJmx extends JmxBase { @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") }) public String checkOverlaps(final String outputFile, final String comment) { return invokeOperation(String.format("Writing overlaps to %s", outputFile), comment, () -> { final File output = new File(outputFile); final String absolutePath = output.getAbsolutePath(); BufferedWriter writer = null; try { if (!output.createNewFile()) { return String.format("Abort, file already exists: %s", absolutePath); } writer = new BufferedWriter(new FileWriter(output)); authoritativeResourceDataValidator.checkOverlaps(writer); } catch (IOException e) { LOGGER.error("Checking overlaps", e); return String.format("Failed writing to: %s, %s", absolutePath, e.getMessage()); } finally { IOUtils.closeQuietly(writer); } return String.format("Overlaps written to: %s", absolutePath); }); } @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); }
@Test public void checkOverlaps_existing_file() throws IOException { final File file = File.createTempFile("overlaps", "test"); final String msg = subject.checkOverlaps(file.getAbsolutePath(), ""); assertThat(msg, startsWith("Abort, file already exists")); verifyZeroInteractions(authoritativeResourceDataValidator); } @Test public void checkOverlaps_unwriteable_file() throws IOException { final File file = new File("/some/unexisting/dir/overlaps"); final String msg = subject.checkOverlaps(file.getAbsolutePath(), ""); assertThat(msg, startsWith("Failed writing to: /some/unexisting/dir/overlaps")); verifyZeroInteractions(authoritativeResourceDataValidator); } @Test public void checkOverlaps() throws IOException { folder.getRoot().mkdirs(); final File file = new File(folder.getRoot(), "overlaps.txt"); final String msg = subject.checkOverlaps(file.getAbsolutePath(), ""); assertThat(msg, startsWith("Overlaps written to")); verify(authoritativeResourceDataValidator).checkOverlaps(any(Writer.class)); }
AuthoritativeResourceImportTask extends AbstractAutoritativeResourceImportTask implements DailyScheduledTask, EmbeddedValueResolverAware { @Override @Scheduled(cron = "0 15 0 * * *") @SchedulerLock(name = TASK_NAME) public void run() { doImport(sourceNames); } @Autowired AuthoritativeResourceImportTask(@Value("${grs.sources}") final String grsSourceNames, final ResourceDataDao resourceDataDao, final Downloader downloader, @Value("${dir.grs.import.download:}") final String downloadDir, @Value("${grs.import.enabled}") final boolean enabled, @Value("${rsng.base.url:}") final String rsngBaseUrl); @Override void setEmbeddedValueResolver(final StringValueResolver valueResolver); @Override @Scheduled(cron = "0 15 0 * * *") @SchedulerLock(name = TASK_NAME) void run(); }
@Test public void init_url_not_defined() throws IOException { subject.run(); verify(resourceDataDao).store(eq("test"), resourceCaptor.capture()); assertThat(resourceCaptor.getValue().getNrAutNums(), is(0)); assertThat(resourceCaptor.getValue().getNrInet6nums(), is(0)); assertThat(resourceCaptor.getValue().getNrInetnums(), is(0)); } @Test public void download_not_resource_data() throws IOException { when(valueResolver.resolveStringValue(anyString())).thenReturn("http: subject.run(); verify(resourceDataDao, never()).store(anyString(), Mockito.<AuthoritativeResource>anyObject()); } @Test public void downloaded_fails() throws IOException { when(valueResolver.resolveStringValue(anyString())).thenReturn("http: doThrow(IOException.class).when(downloader).downloadToWithMd5Check(any(Logger.class), any(URL.class), any(Path.class)); subject.run(); } @Test public void download() throws IOException { when(valueResolver.resolveStringValue(anyString())).thenReturn("http: doAnswer(invocation -> { final Path path = (Path) invocation.getArguments()[2]; Files.createFile(path); return null; }).when(downloader).downloadToWithMd5Check(any(Logger.class), any(URL.class), any(Path.class)); subject.run(); verify(resourceDataDao).store(eq("test"), resourceCaptor.capture()); assertThat(resourceCaptor.getValue().getNrAutNums(), is(0)); assertThat(resourceCaptor.getValue().getNrInet6nums(), is(0)); assertThat(resourceCaptor.getValue().getNrInetnums(), is(0)); }
RpslObjectFilter { public static String getCertificateFromKeyCert(final RpslObject object) { if (!ObjectType.KEY_CERT.equals(object.getType())) { throw new AuthenticationException("No key cert for object: " + object.getKey()); } final StringBuilder builder = new StringBuilder(); for (RpslAttribute next : object.findAttributes(AttributeType.CERTIF)) { for (String s : LINE_CONTINUATION_SPLITTER.split(next.getValue())) { builder.append(s).append('\n'); } } return builder.toString(); } 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); }
@Test(expected = AuthenticationException.class) public void getCertificateFromKeyCert() { RpslObjectFilter.getCertificateFromKeyCert(mntner); } @Test public void getCertificateOnlyOneCertifAttribute() { RpslObject keycert = RpslObject.parse( "key-cert: X509-1\n" + "certif: -----BEGIN CERTIFICATE-----\n" + " MIIHaTCCBlGgAwIBAgICGSowDQYJKoZIhvcNAQEFBQAwgYwxCzAJBgNVBAYTAklM\n" + " -----END CERTIFICATE-----"); final String certificate = RpslObjectFilter.getCertificateFromKeyCert(keycert); assertThat(certificate, is( "-----BEGIN CERTIFICATE-----\n" + "MIIHaTCCBlGgAwIBAgICGSowDQYJKoZIhvcNAQEFBQAwgYwxCzAJBgNVBAYTAklM\n" + "-----END CERTIFICATE-----\n")); } @Test public void getCertificateMultipleCertifAttributes() { RpslObject keycert = RpslObject.parse( "key-cert: X509-1\n" + "certif: -----BEGIN CERTIFICATE-----\n" + "certif: MIIHaTCCBlGgAwIBAgICGSowDQYJKoZIhvcNAQEFBQAwgYwxCzAJBgNVBAYTAklM\n" + "certif: -----END CERTIFICATE-----"); final String certificate = RpslObjectFilter.getCertificateFromKeyCert(keycert); assertThat(certificate, is( "-----BEGIN CERTIFICATE-----\n" + "MIIHaTCCBlGgAwIBAgICGSowDQYJKoZIhvcNAQEFBQAwgYwxCzAJBgNVBAYTAklM\n" + "-----END CERTIFICATE-----\n")); } @Test public void certificateContinuationLines() { RpslObject keycert = RpslObject.parse( "key-cert: X509-1\n" + "certif: -----BEGIN CERTIFICATE-----\n" + " MIIHaTCCBlGgAwIBAgICGSowDQYJKoZIhvcNAQEFBQAwgYwxCzAJBgNVBAYTAklM\n" + "\t MRYwFAYDVQQKEw1TdGFydENvbSBMdGQuMSswKQYDVQQLEyJTZWN1cmUgRGlnaXRh\n" + "+ -----END CERTIFICATE-----"); final String certificate = RpslObjectFilter.getCertificateFromKeyCert(keycert); assertThat(certificate, is( "-----BEGIN CERTIFICATE-----\n" + "MIIHaTCCBlGgAwIBAgICGSowDQYJKoZIhvcNAQEFBQAwgYwxCzAJBgNVBAYTAklM\n" + "MRYwFAYDVQQKEw1TdGFydENvbSBMdGQuMSswKQYDVQQLEyJTZWN1cmUgRGlnaXRh\n" + "-----END CERTIFICATE-----\n")); }
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); }
@Test public void isFiltered() { final boolean filtered = RpslObjectFilter.isFiltered(mntner); assertThat(filtered, is(false)); }
RpslObjectFilter { public static String diff(final RpslObject original, final RpslObject revised) { final StringBuilder builder = new StringBuilder(); final List<String> originalLines = Lists.newArrayList(LINE_SPLITTER.split(original.toString())); final List<String> revisedLines = Lists.newArrayList(LINE_SPLITTER.split(revised.toString())); final List<String> diff = DiffUtils.generateUnifiedDiff(null, null, originalLines, DiffUtils.diff(originalLines, revisedLines), 1); for (int index = 2; index < diff.size(); index++) { builder.append(diff.get(index)); builder.append('\n'); } return builder.toString(); } 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); }
@Test public void diff_idential() { final RpslObject original = RpslObject.parse( "mntner: UPD-MNT\n" + "description: descr\n" + "mnt-by: UPD-MNT\n" + "source: TEST\n"); assertThat(RpslObjectFilter.diff(original, original), is("")); } @Test public void diff_delete_lines() throws Exception { final RpslObject original = RpslObject.parse( "mntner: UPD-MNT\n" + "description: descr\n" + "mnt-by: UPD-MNT\n" + "source: TEST\n"); final RpslObject updated = RpslObject.parse( "mntner: UPD-MNT\n" + "source: TEST\n"); assertThat(RpslObjectFilter.diff(original, updated), is("@@ -1,4 +1,2 @@\n" + " mntner: UPD-MNT\n" + "-description: descr\n" + "-mnt-by: UPD-MNT\n" + " source: TEST\n")); } @Test public void diff_add_lines() { final RpslObject original = RpslObject.parse( "mntner: UPD-MNT\n" + "source: TEST\n"); final RpslObject updated = RpslObject.parse( "mntner: UPD-MNT\n" + "description: descr\n" + "mnt-by: UPD-MNT\n" + "source: TEST\n"); assertThat(RpslObjectFilter.diff(original, updated), is("@@ -1,2 +1,4 @@\n" + " mntner: UPD-MNT\n" + "+description: descr\n" + "+mnt-by: UPD-MNT\n" + " source: TEST\n")); } @Test public void diff_change_line() { final RpslObject original = RpslObject.parse( "mntner: UPD-MNT\n" + "description: descr\n" + "mnt-by: UPD-MNT\n" + "source: TEST\n"); final RpslObject updated = RpslObject.parse( "mntner: UPD-MNT\n" + "description: updated\n" + "mnt-by: UPD-MNT\n" + "source: TEST\n"); assertThat(RpslObjectFilter.diff(original, updated), is("@@ -1,3 +1,3 @@\n" + " mntner: UPD-MNT\n" + "-description: descr\n" + "+description: updated\n" + " mnt-by: UPD-MNT\n")); } @Test public void diff_add_and_change_lines() { final RpslObject original = RpslObject.parse( "mntner: UPD-MNT\n" + "mnt-by: UPD-MNT\n" + "source: TEST\n"); final RpslObject updated = RpslObject.parse( "mntner: UPD-MNT\n" + "description: updated\n" + "mnt-by: UPD-MNT2\n" + "source: TEST\n"); assertThat(RpslObjectFilter.diff(original, updated), is("@@ -1,3 +1,4 @@\n" + " mntner: UPD-MNT\n" + "-mnt-by: UPD-MNT\n" + "+description: updated\n" + "+mnt-by: UPD-MNT2\n" + " source: TEST\n")); } @Test public void diff_separate_changes() { final RpslObject original = RpslObject.parse( "mntner: UPD-MNT\n" + "description: original\n" + "admin-c: OR1-TEST\n" + "tech-c: OR2-TEST\n" + "remarks: remark\n" + "mnt-by: UPD-MNT\n" + "remarks: original\n" + "source: TEST\n"); final RpslObject updated = RpslObject.parse( "mntner: UPD-MNT\n" + "description: updated\n" + "admin-c: OR1-TEST\n" + "tech-c: OR2-TEST\n" + "remarks: remark\n" + "mnt-by: UPD-MNT\n" + "remarks: updated\n" + "source: TEST\n"); assertThat(RpslObjectFilter.diff(original, updated), is("@@ -1,3 +1,3 @@\n" + " mntner: UPD-MNT\n" + "-description: original\n" + "+description: updated\n" + " admin-c: OR1-TEST\n" + "@@ -6,3 +6,3 @@\n" + " mnt-by: UPD-MNT\n" + "-remarks: original\n" + "+remarks: updated\n" + " source: TEST\n")); }
AsBlockRange { public static AsBlockRange parse(final String range) { final Matcher match = AS_BLOCK_PATTERN.matcher(range); if (match.find()) { long begin = Long.valueOf(match.group(1)); long end = Long.valueOf(match.group(2)); if (end < begin) { throw new AttributeParseException(end + " < " + begin, range); } return new AsBlockRange(begin, end); } throw new AttributeParseException("invalid asblock", range); } private AsBlockRange(final long begin, final long end); static AsBlockRange parse(final String range); @Override boolean equals(final Object o); @Override int hashCode(); boolean contains(final AsBlockRange asBlockRange); long getBegin(); long getEnd(); String getEndWithPrefix(); String getBeginWithPrefix(); @Override String toString(); }
@Test public void validAsBlockRanges() { checkAsBlockRange(AsBlockRange.parse("AS1-AS2"), 1, 2); checkAsBlockRange(AsBlockRange.parse("as1-as2"), 1, 2); checkAsBlockRange(AsBlockRange.parse("AS1 -AS2"), 1, 2); checkAsBlockRange(AsBlockRange.parse("AS1 - AS2"), 1, 2); checkAsBlockRange(AsBlockRange.parse("AS1 - AS4294967295"), 1, 4294967295L); checkAsBlockRange(AsBlockRange.parse("AS1 - AS1"), 1, 1); } @Test(expected = AttributeParseException.class) public void invalidRange() { AsBlockRange.parse("AS2 - AS1"); } @Test(expected = AttributeParseException.class) public void nonNumericAsBlockSingleArgument() { AsBlockRange.parse("ASx"); } @Test(expected = AttributeParseException.class) public void singleAsBlockWithSeparator() { AsBlockRange.parse("AS1-"); } @Test(expected = AttributeParseException.class) public void nonNumericAsBlockRangeFirstArgument() { AsBlockRange.parse("ASx-AS1"); } @Test(expected = AttributeParseException.class) public void nonNumericAsBlockRangeSecondArgument() { AsBlockRange.parse("AS1-ASx"); } @Test(expected = AttributeParseException.class) public void asBlockRangeThirdArgument() { AsBlockRange.parse("AS1-AS2-AS3"); } @Test(expected = AttributeParseException.class) public void asBlockArgumentWithoutPrefix() { AsBlockRange.parse("1-2"); } @Test(expected = AttributeParseException.class) public void emptyAsBlockRangeString() { AsBlockRange.parse(""); }
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); }
@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]"); }
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); }
@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"); }
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); }
@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"); }
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); }
@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"); }
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(); }
@Test public void empty() { assertThat(subject.getMessages().getAllMessages(), hasSize(0)); }
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(); }
@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)); }
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); }
@Test(expected = IllegalStateException.class) public void getObjectSpec_null() { ObjectTemplate.getTemplate(null); } @Test public void allObjectTypesSupported() { for (final ObjectType objectType : ObjectType.values()) { ObjectTemplate.getTemplate(objectType); } }
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); }
@Test public void getObjectType() { assertThat(subject.getObjectType(), is(ObjectType.MNTNER)); }
ObjectTemplate implements Comparable<ObjectTemplate> { public ObjectMessages validate(final RpslObject rpslObject) { final ObjectMessages objectMessages = new ObjectMessages(); validateStructure(rpslObject, objectMessages); validateSyntax(rpslObject, objectMessages, false); return objectMessages; } 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); }
@Test public void validate_no_errors() { final ObjectMessages objectMessages = subject.validate(RpslObject.parse(MAINTAINER_OBJECT_STRING)); assertThat(objectMessages.hasErrors(), is(false)); } @Test public void validate_mandatory_missing() { final RpslObject rpslObject = RpslObject.parse(MAINTAINER_OBJECT_STRING.substring(0, MAINTAINER_OBJECT_STRING.lastIndexOf('\n') + 1)); final ObjectMessages objectMessages = subject.validate(rpslObject); assertThat(objectMessages.hasErrors(), is(true)); assertThat(objectMessages.getMessages().getErrors(), contains(ValidationMessages.missingMandatoryAttribute(AttributeType.SOURCE))); assertZeroAttributeErrors(rpslObject, objectMessages); } @Test public void validate_single_occurs_multiple_times() { final RpslObject rpslObject = RpslObject.parse(MAINTAINER_OBJECT_STRING + "\nsource: RIPE\n"); final ObjectMessages objectMessages = subject.validate(rpslObject); assertThat(objectMessages.hasErrors(), is(true)); assertThat(objectMessages.getMessages().getErrors(), contains(ValidationMessages.tooManyAttributesOfType(AttributeType.SOURCE))); assertZeroAttributeErrors(rpslObject, objectMessages); }
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); }
@Test public void getMultipleAttributes(){ final ObjectTemplate template = ObjectTemplate.getTemplate(ObjectType.AS_BLOCK); Set<AttributeType> multipleAttributes = template.getMultipleAttributes(); assertThat(multipleAttributes.size(), is(6)); }
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); }
@Test public void isSet() { for (ObjectType objectType : ObjectType.values()) { assertThat(objectType.getName().toLowerCase().contains("set"), is(ObjectTemplate.getTemplate(objectType).isSet())); } }
RpslObject implements Identifiable, ResponseObject { public static RpslObject parse(final String input) { return new RpslObject(RpslObjectBuilder.getAttributes(input)); } 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); }
@Test(expected = IllegalArgumentException.class) public void parseNullFails() { RpslObject.parse((byte[]) null); } @Test(expected = IllegalArgumentException.class) public void parseEmptyFails() { RpslObject.parse(new byte[]{}); } @Test public void tab_continuation_equivalent_to_space_continuation() { assertThat(RpslObject.parse("mntner: mnt\n a"), is(RpslObject.parse("mntner: mnt\n\ta"))); } @Test public void compareRpslObjects_single() { assertThat(RpslObject.parse("mntner: mnt"), is(RpslObject.parse("mntner: mnt"))); assertThat(RpslObject.parse("mntner: mnt"), is(RpslObject.parse("mntner: mnt\n"))); assertThat(RpslObject.parse("mntner: mnt"), is(not(RpslObject.parse("mntner: mnt\n\ta")))); assertThat(RpslObject.parse("mntner: mnt\n a"), is(RpslObject.parse("mntner: mnt\n\ta"))); assertThat(RpslObject.parse("mntner: mnt\n \t\t a"), is(RpslObject.parse("mntner: mnt\n\ta"))); assertThat(RpslObject.parse("mntner: \t mnt \t \n \t a"), is(RpslObject.parse("mntner: mnt\n\ta"))); assertThat(RpslObject.parse("mntner: \t one \t two \t \n \t a"), is(RpslObject.parse("mntner: one two\n\ta"))); assertThat(RpslObject.parse("mntner:one \t two \t \n \t a"), is(RpslObject.parse("mntner: one two\n\ta"))); assertThat(RpslObject.parse("mntner: mnt # comment"), is(RpslObject.parse("mntner: mnt"))); assertThat(RpslObject.parse("mntner: mnt # comment"), is(RpslObject.parse("mntner: mnt # comment"))); assertThat(RpslObject.parse("mntner: mnt# comment"), is(RpslObject.parse("mntner: mnt # comment"))); assertThat(RpslObject.parse("mntner: mnt # com ment"), is(RpslObject.parse("mntner: mnt # com ment"))); assertThat(RpslObject.parse("mntner: mnt # com ment"), is(RpslObject.parse("mntner: mnt #com ment"))); assertThat(RpslObject.parse("mntner: mnt two three four"), is(RpslObject.parse("mntner: mnt # one\n two\n+ three\n\tfour"))); } @Test public void compareRpslObjects_multiple() { assertThat(RpslObject.parse("mntner: mnt\nsource: RIPE"), is(RpslObject.parse("mntner: mnt\nsource: RIPE\n"))); assertThat(RpslObject.parse("mntner: mnt\nsource: RIPE"), is(RpslObject.parse("mntner: mnt\nsource:\tRIPE\n"))); assertThat(RpslObject.parse("mntner: mnt\n+one\nsource: RIPE"), is(RpslObject.parse("mntner: mnt\n\tone\nsource:\tRIPE\n"))); assertThat(RpslObject.parse("mntner: mnt\n+#one\nsource: RIPE"), is(RpslObject.parse("mntner: mnt\n\t #two\nsource:\tRIPE\n"))); } @Test public void cleanvalue_comparator_different_order() { final RpslObject object1 = RpslObject.parse("mntner: DEV-MNT\nmnt-by:DEV-MNT1,DEV-MNT2,DEV-MNT3"); final RpslObject object2 = RpslObject.parse("mntner: DEV-MNT\nmnt-by:DEV-MNT3,DEV-MNT1,DEV-MNT2"); assertThat(object1, not(is(object2))); } @Test public void cleanvalue_comparator_different_values() { final RpslObject object1 = RpslObject.parse("mntner: DEV-MNT\nmnt-by:DEV-MNT1,DEV-MNT2,DEV-MNT3"); final RpslObject object2 = RpslObject.parse("mntner: DEV-MNT\nmnt-by:DEV-MNT1,DEV-MNT2,DEV-MNT4"); assertThat(object1, not(is(object2))); } @Test public void cleanvalue_comparator_same_order() { final RpslObject object1 = RpslObject.parse("mntner: DEV-MNT\nmnt-by:DEV-MNT1,DEV-MNT2,DEV-MNT3"); final RpslObject object2 = RpslObject.parse("mntner: DEV-MNT\nmnt-by:DEV-MNT1,DEV-MNT2,DEV-MNT3"); assertThat(object1, is(object2)); } @Test public void cleanvalue_comparator_same_order_different_casing() { final RpslObject object1 = RpslObject.parse("mntner: DEV-MNT\nmnt-by:DEV-MNT1,DEV-MNT2,DEV-MNT3"); final RpslObject object2 = RpslObject.parse("MNTNER: dev-mnt\nmnt-by:DEV-MNT1,DEV-MNT2,DEV-MNT3"); assertThat(object1, is(object2)); } @Test public void cleanvalue_comparator_same_order_different_key() { final RpslObject object1 = RpslObject.parse("mntner: DEV-MNT\nmnt-by:DEV-MNT1,DEV-MNT2,DEV-MNT3"); final RpslObject object2 = RpslObject.parse("poem: dev-mnt\nmnt-by:DEV-MNT1,DEV-MNT2,DEV-MNT3"); assertThat(object1, not(is(object2))); } @Test public void cleanvalue_comparator_different_order_same_attributes() { final RpslObject object1 = RpslObject.parse("mntner: DEV-MNT\nmnt-by:DEV-MNT1\nnic-hdl:NIC-RIPE\nmnt-by:DEV-MNT2,DEV-MNT3"); final RpslObject object2 = RpslObject.parse("mntner: DEV-MNT\nnic-hdl:NIC-RIPE\nmnt-by:DEV-MNT1,DEV-MNT2,DEV-MNT3"); assertThat(object1, not(is(object2))); } @Test public void cleanvalue_comparator_subset() { final RpslObject object1 = RpslObject.parse("mntner: DEV-MNT\nmnt-by:DEV-MNT1,DEV-MNT2,DEV-MNT3"); final RpslObject object2 = RpslObject.parse("mntner: DEV-MNT\nmnt-by:DEV-MNT1,DEV-MNT3"); assertThat(object1, not(is(object2))); } @Test public void multiple_newlines_is_reserved_as_object_separator() { try { RpslObject.parse("mntner: AA1-MNT\n\n"); fail(); } catch (IllegalArgumentException e) { assertThat(e.getMessage(), is("Read illegal character in key: '\n'")); } }
RpslObject implements Identifiable, ResponseObject { @Override public String toString() { try { final StringWriter writer = new StringWriter(); for (final RpslAttribute attribute : getAttributes()) { attribute.writeTo(writer); } return writer.toString(); } catch (IOException e) { throw new IllegalStateException("Should never occur", e); } } 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); }
@Test public void checkThatSpecialCharactersGetThrough() { parseAndAssign("person: New Test Person\n" + "address: Flughafenstraße 120\n" + "address: D - 40474 Düsseldorf\n" + "nic-hdl: ABC-RIPE\n"); assertThat(subject.toString(), containsString("Flughafenstraße")); assertThat(subject.toString(), containsString("Düsseldorf")); }