method2testcases
stringlengths
118
6.63k
### Question: FormatHelper { public static String dateToString(final TemporalAccessor temporalAccessor) { if (temporalAccessor == null) { return null; } return DATE_FORMAT.format(temporalAccessor); } private FormatHelper(); static String dateToString(final TemporalAccessor temporalAccessor); static String dateTimeToString(final TemporalAccessor temporalAccessor); static String dateTimeToUtcString(final TemporalAccessor temporalAccessor); static String prettyPrint(final String prefix, final String value, final int indentation, final int maxLineLength); static String prettyPrint(final String prefix, final String value, final int indentation, final int maxLineLength, boolean repeatPrefix); }### Answer: @Test public void testDateToString_null() { assertNull(FormatHelper.dateToString(null)); } @Test public void testDateToString_date() { assertThat(FormatHelper.dateToString(LocalDate.of(2001, 10, 1)), is("2001-10-01")); } @Test public void testDateToString_dateTime() throws Exception { assertThat(FormatHelper.dateToString(LocalDateTime.of(2001, 10, 1, 12, 0, 0)), is("2001-10-01")); }
### Question: NicHandleFactory extends AbstractAutoKeyFactory<NicHandle> { @Override public NicHandle generate(final String keyPlaceHolder, final RpslObject object) { return generateForName(keyPlaceHolder, object.getTypeAttribute().getCleanValue().toString()); } @Autowired NicHandleFactory(final NicHandleRepository nicHandleRepository, final CountryCodeRepository countryCodeRepository); @Override AttributeType getAttributeType(); @Override NicHandle generate(final String keyPlaceHolder, final RpslObject object); @Override NicHandle claim(final String key); boolean isAvailable(final String key); }### Answer: @Test(expected = IllegalArgumentException.class) public void generate_invalid_placeHolder() { subject.generate("AUTO", RpslObject.parse("person: name")); } @Test public void generate_specified_space() { when(nicHandleRepository.claimNextAvailableIndex("DW", SOURCE)).thenReturn(new NicHandle("DW", 10, SOURCE)); final NicHandle nicHandle = subject.generate("AUTO-1234567DW", RpslObject.parse("person: name\nnic-hdl: AUTO-1234567DW")); assertThat(nicHandle.toString(), is("DW10-RIPE")); } @Test public void generate_unspecified_space() { when(nicHandleRepository.claimNextAvailableIndex("JAS", SOURCE)).thenReturn(new NicHandle("JAS", 10, SOURCE)); final NicHandle nicHandle = subject.generate("AUTO-111", RpslObject.parse("person: John Archibald Smith\nnic-hdl: AUTO-111")); assertThat(nicHandle.toString(), is("JAS10-RIPE")); } @Test public void generate_unspecified_lower() { when(nicHandleRepository.claimNextAvailableIndex("SN", SOURCE)).thenReturn(new NicHandle("SN", 10, SOURCE)); final NicHandle nicHandle = subject.generate("AUTO-111", RpslObject.parse("person: some name\nnic-hdl: AUTO-111")); assertThat(nicHandle.toString(), is("SN10-RIPE")); } @Test public void generate_unspecified_long() { when(nicHandleRepository.claimNextAvailableIndex("SATG", SOURCE)).thenReturn(new NicHandle("SATG", 10, SOURCE)); final NicHandle nicHandle = subject.generate("AUTO-1234567", RpslObject.parse("person: Satellite advisory Technologies Group Ltd\nnic-hdl: AUTO-1234567")); assertThat(nicHandle.toString(), is("SATG10-RIPE")); }
### Question: NicHandleFactory extends AbstractAutoKeyFactory<NicHandle> { @Override public AttributeType getAttributeType() { return AttributeType.NIC_HDL; } @Autowired NicHandleFactory(final NicHandleRepository nicHandleRepository, final CountryCodeRepository countryCodeRepository); @Override AttributeType getAttributeType(); @Override NicHandle generate(final String keyPlaceHolder, final RpslObject object); @Override NicHandle claim(final String key); boolean isAvailable(final String key); }### Answer: @Test public void getAttributeType() { assertThat(subject.getAttributeType(), is(AttributeType.NIC_HDL)); }
### Question: NicHandleFactory extends AbstractAutoKeyFactory<NicHandle> { @Override public NicHandle claim(final String key) throws ClaimException { final NicHandle nicHandle = parseNicHandle(key); if (!nicHandleRepository.claimSpecified(nicHandle)) { throw new ClaimException(UpdateMessages.nicHandleNotAvailable(nicHandle.toString())); } return nicHandle; } @Autowired NicHandleFactory(final NicHandleRepository nicHandleRepository, final CountryCodeRepository countryCodeRepository); @Override AttributeType getAttributeType(); @Override NicHandle generate(final String keyPlaceHolder, final RpslObject object); @Override NicHandle claim(final String key); boolean isAvailable(final String key); }### Answer: @Test public void claim() throws Exception { final NicHandle nicHandle = new NicHandle("DW", 10, "RIPE"); when(nicHandleRepository.claimSpecified(nicHandle)).thenReturn(true); assertThat(subject.claim("DW10-RIPE"), is(nicHandle)); } @Test public void claim_not_available() { when(nicHandleRepository.claimSpecified(new NicHandle("DW", 10, "RIPE"))).thenReturn(false); try { subject.claim("DW10-RIPE"); fail("Claim succeeded?"); } catch (ClaimException e) { assertThat(e.getErrorMessage(), is(UpdateMessages.nicHandleNotAvailable("DW10-RIPE"))); } } @Test public void claim_invalid_handle() { try { subject.claim("INVALID_HANDLE"); fail("Claim succeeded?"); } catch (ClaimException e) { assertThat(e.getErrorMessage(), is(ValidationMessages.syntaxError("INVALID_HANDLE"))); } }
### Question: OrganisationIdFactory extends AbstractAutoKeyFactory<OrganisationId> { @Override public OrganisationId generate(final String keyPlaceHolder, final RpslObject object) { return generateForName(keyPlaceHolder, object.getValueForAttribute(AttributeType.ORG_NAME).toString()); } @Autowired OrganisationIdFactory(final OrganisationIdRepository organisationIdRepository); @Override AttributeType getAttributeType(); @Override OrganisationId generate(final String keyPlaceHolder, final RpslObject object); @Override OrganisationId claim(final String key); }### Answer: @Test(expected = IllegalArgumentException.class) public void generate_invalid_placeHolder() { subject.generate("AUTO", RpslObject.parse("organisation: AUTO\norg-name: name")); } @Test public void generate_specified_space() { when(organisationIdRepository.claimNextAvailableIndex("DW", SOURCE)).thenReturn(new OrganisationId("DW", 10, SOURCE)); final OrganisationId organisationId = subject.generate("AUTO-1234567DW", RpslObject.parse("organisation: AUTO\norg-name: name")); assertThat(organisationId.toString(), is("ORG-DW10-RIPE")); } @Test public void generate_unspecified_space_single_word_name() { when(organisationIdRepository.claimNextAvailableIndex("TA", SOURCE)).thenReturn(new OrganisationId("TA", 1, SOURCE)); RpslObject orgObject = RpslObject.parse("organisation: AUTO-1\norg-name: Tesco"); final OrganisationId organisationId = subject.generate("AUTO-1", orgObject); assertThat(organisationId.toString(), is("ORG-TA1-RIPE")); } @Test public void generate_unspecified_space() { when(organisationIdRepository.claimNextAvailableIndex("SATG", SOURCE)).thenReturn(new OrganisationId("SATG", 10, SOURCE)); final OrganisationId organisationId = subject.generate("AUTO-111", RpslObject.parse("organisation: AUTO\norg-name: Satellite advisory Technologies Group Ltd")); assertThat(organisationId.toString(), is("ORG-SATG10-RIPE")); }
### Question: OrganisationIdFactory extends AbstractAutoKeyFactory<OrganisationId> { @Override public AttributeType getAttributeType() { return AttributeType.ORGANISATION; } @Autowired OrganisationIdFactory(final OrganisationIdRepository organisationIdRepository); @Override AttributeType getAttributeType(); @Override OrganisationId generate(final String keyPlaceHolder, final RpslObject object); @Override OrganisationId claim(final String key); }### Answer: @Test public void getAttributeType() { assertThat(subject.getAttributeType(), is(AttributeType.ORGANISATION)); }
### Question: OrganisationIdFactory extends AbstractAutoKeyFactory<OrganisationId> { @Override public OrganisationId claim(final String key) throws ClaimException { throw new ClaimException(ValidationMessages.syntaxError(key, "must be AUTO-nnn for create")); } @Autowired OrganisationIdFactory(final OrganisationIdRepository organisationIdRepository); @Override AttributeType getAttributeType(); @Override OrganisationId generate(final String keyPlaceHolder, final RpslObject object); @Override OrganisationId claim(final String key); }### Answer: @Test public void claim() throws Exception { try { subject.claim("ORG-DW10-RIPE"); fail("claim() supported?"); } catch (ClaimException e) { assertThat(e.getErrorMessage(), is(ValidationMessages.syntaxError("ORG-DW10-RIPE (must be AUTO-nnn for create)"))); } }
### Question: X509CertificateWrapper implements KeyWrapper { static boolean looksLikeX509Key(final RpslObject rpslObject) { final String pgpKey = RpslObjectFilter.getCertificateFromKeyCert(rpslObject); return pgpKey.indexOf(X509_HEADER) != -1 && pgpKey.indexOf(X509_FOOTER) != -1; } private X509CertificateWrapper(final X509Certificate certificate); static X509CertificateWrapper parse(final RpslObject rpslObject); static X509CertificateWrapper parse(final byte[] certificate); @Override boolean equals(final Object o); @Override int hashCode(); X509Certificate getCertificate(); @Override String getMethod(); @Override List<String> getOwners(); @Override String getFingerprint(); boolean isNotYetValid(final DateTimeProvider dateTimeProvider); boolean isExpired(final DateTimeProvider dateTimeProvider); static final String X509_HEADER; static final String X509_FOOTER; }### Answer: @Test public void isX509Key() throws IOException { assertThat(X509CertificateWrapper.looksLikeX509Key(x509Keycert), is(true)); assertThat(X509CertificateWrapper.looksLikeX509Key(pgpKeycert), is(false)); }
### Question: X509CertificateWrapper implements KeyWrapper { @Override public String getMethod() { return METHOD; } private X509CertificateWrapper(final X509Certificate certificate); static X509CertificateWrapper parse(final RpslObject rpslObject); static X509CertificateWrapper parse(final byte[] certificate); @Override boolean equals(final Object o); @Override int hashCode(); X509Certificate getCertificate(); @Override String getMethod(); @Override List<String> getOwners(); @Override String getFingerprint(); boolean isNotYetValid(final DateTimeProvider dateTimeProvider); boolean isExpired(final DateTimeProvider dateTimeProvider); static final String X509_HEADER; static final String X509_FOOTER; }### Answer: @Test public void getMethod() { X509CertificateWrapper subject = X509CertificateWrapper.parse(x509Keycert); assertThat(subject.getMethod(), is("X509")); }
### Question: X509CertificateWrapper implements KeyWrapper { @Override public String getFingerprint() { try { MessageDigest md = MessageDigest.getInstance("MD5"); byte[] der = certificate.getEncoded(); md.update(der); byte[] digest = md.digest(); StringBuilder builder = new StringBuilder(); for (byte next : digest) { if (builder.length() > 0) { builder.append(':'); } builder.append(String.format("%02X", next)); } return builder.toString(); } catch (NoSuchAlgorithmException e) { throw new IllegalArgumentException("Invalid X509 Certificate", e); } catch (CertificateEncodingException e) { throw new IllegalArgumentException("Invalid X509 Certificate", e); } } private X509CertificateWrapper(final X509Certificate certificate); static X509CertificateWrapper parse(final RpslObject rpslObject); static X509CertificateWrapper parse(final byte[] certificate); @Override boolean equals(final Object o); @Override int hashCode(); X509Certificate getCertificate(); @Override String getMethod(); @Override List<String> getOwners(); @Override String getFingerprint(); boolean isNotYetValid(final DateTimeProvider dateTimeProvider); boolean isExpired(final DateTimeProvider dateTimeProvider); static final String X509_HEADER; static final String X509_FOOTER; }### Answer: @Test public void getFingerprint() { X509CertificateWrapper subject = X509CertificateWrapper.parse(x509Keycert); assertThat(subject.getFingerprint(), is("16:4F:B6:A4:D9:BC:0C:92:D4:48:13:FE:B6:EF:E2:82")); }
### Question: X509CertificateWrapper implements KeyWrapper { public boolean isExpired(final DateTimeProvider dateTimeProvider) { final LocalDateTime notAfter = DateUtil.fromDate(certificate.getNotAfter()); return notAfter.isBefore(dateTimeProvider.getCurrentDateTime()); } private X509CertificateWrapper(final X509Certificate certificate); static X509CertificateWrapper parse(final RpslObject rpslObject); static X509CertificateWrapper parse(final byte[] certificate); @Override boolean equals(final Object o); @Override int hashCode(); X509Certificate getCertificate(); @Override String getMethod(); @Override List<String> getOwners(); @Override String getFingerprint(); boolean isNotYetValid(final DateTimeProvider dateTimeProvider); boolean isExpired(final DateTimeProvider dateTimeProvider); static final String X509_HEADER; static final String X509_FOOTER; }### Answer: @Test public void isExpired() { X509CertificateWrapper subject = X509CertificateWrapper.parse(x509Keycert); assertThat(subject.isExpired(dateTimeProvider), is(false)); when(dateTimeProvider.getCurrentDateTime()).thenReturn(LocalDateTime.now().plusYears(100)); assertThat(subject.isExpired(dateTimeProvider), is(true)); }
### Question: FormatHelper { public static String dateTimeToString(final TemporalAccessor temporalAccessor) { if (temporalAccessor == null) { return null; } if (temporalAccessor.isSupported(ChronoField.HOUR_OF_DAY)) { return DATE_TIME_FORMAT.format(temporalAccessor); } return DATE_FORMAT.format(temporalAccessor); } private FormatHelper(); static String dateToString(final TemporalAccessor temporalAccessor); static String dateTimeToString(final TemporalAccessor temporalAccessor); static String dateTimeToUtcString(final TemporalAccessor temporalAccessor); static String prettyPrint(final String prefix, final String value, final int indentation, final int maxLineLength); static String prettyPrint(final String prefix, final String value, final int indentation, final int maxLineLength, boolean repeatPrefix); }### Answer: @Test public void testDateTimeToString_null() { assertNull(FormatHelper.dateTimeToString(null)); } @Test public void testDateTimeToString_date() { assertThat(FormatHelper.dateTimeToString(LocalDate.of(2001, 10, 1)), is("2001-10-01")); } @Test public void testDateTimeToString_dateTime() throws Exception { assertThat(FormatHelper.dateTimeToString(LocalDateTime.of(2001, 10, 1, 12, 13, 14)), is("2001-10-01 12:13:14")); }
### Question: PgpPublicKeyWrapper implements KeyWrapper { static boolean looksLikePgpKey(final RpslObject rpslObject) { final String pgpKey = RpslObjectFilter.getCertificateFromKeyCert(rpslObject); return pgpKey.indexOf(PGP_HEADER) != -1 && pgpKey.indexOf(PGP_FOOTER) != -1; } PgpPublicKeyWrapper(final PGPPublicKey masterKey, final List<PGPPublicKey> subKeys); static PgpPublicKeyWrapper parse(final RpslObject object); PGPPublicKey getPublicKey(); List<PGPPublicKey> getSubKeys(); @Override String getMethod(); @Override List<String> getOwners(); @Override String getFingerprint(); boolean isExpired(final DateTimeProvider dateTimeProvider); boolean isRevoked(); @Override boolean equals(final Object o); @Override int hashCode(); }### Answer: @Test public void isPgpKey() { assertThat(PgpPublicKeyWrapper.looksLikePgpKey(pgpKeycert), is(true)); assertThat(PgpPublicKeyWrapper.looksLikePgpKey(x509Keycert), is(false)); }
### Question: X509SignedMessage { @Override public boolean equals(final Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; final X509SignedMessage that = (X509SignedMessage) o; return Objects.equals(signature, that.signature); } X509SignedMessage(final String signedData, final String signature); boolean verify(final X509Certificate certificate); boolean verifySigningTime(final DateTimeProvider dateTimeProvider); @Override boolean equals(final Object o); @Override int hashCode(); }### Answer: @Test public void isEquals() { X509SignedMessage first = new X509SignedMessage("First Test", "First Signature"); X509SignedMessage second = new X509SignedMessage("Second Test", "Second Signature"); assertThat(first.equals(first), is(true)); assertThat(first.equals(second), is(false)); }
### Question: LoggingHandlerAdapter implements LoggingHandler { @Override public void log(final StatementInfo statementInfo, final ResultInfo resultInfo) { loggerContext.logQuery(statementInfo, resultInfo); } @Autowired LoggingHandlerAdapter(final LoggerContext loggerContext); @Override void log(final StatementInfo statementInfo, final ResultInfo resultInfo); }### Answer: @Test public void log() throws Exception { subject = new LoggingHandlerAdapter(loggerContext); subject.log(statementInfo, resultInfo); verify(loggerContext, times(1)).logQuery(statementInfo, resultInfo); }
### Question: UpdateLog { public void logUpdateResult(final UpdateRequest updateRequest, final UpdateContext updateContext, final Update update, final Stopwatch stopwatch) { logger.info(formatMessage(updateRequest, updateContext, update, stopwatch)); } UpdateLog(); UpdateLog(final Logger logger); void logUpdateResult(final UpdateRequest updateRequest, final UpdateContext updateContext, final Update update, final Stopwatch stopwatch); }### Answer: @Test public void logUpdateResult_create_success() { final RpslObject maintainer = RpslObject.parse("mntner: TST-MNT"); final UpdateResult updateResult = new UpdateResult(maintainer, maintainer, Action.CREATE, UpdateStatus.SUCCESS, new ObjectMessages(), 0, false); when(update.getCredentials()).thenReturn(new Credentials()); when(updateContext.createUpdateResult(update)).thenReturn(updateResult); subject.logUpdateResult(updateRequest, updateContext, update, stopwatch); verify(logger).info(matches("\\[\\s*0\\] 0[,.]000 ns UPD CREATE mntner TST-MNT \\(1\\) SUCCESS : <E0,W0,I0> AUTH - null")); } @Test public void logUpdateResult_create_success_dryRun() { final RpslObject maintainer = RpslObject.parse("mntner: TST-MNT"); final UpdateResult updateResult = new UpdateResult(maintainer, maintainer, Action.CREATE, UpdateStatus.SUCCESS, new ObjectMessages(), 0, true); when(update.getCredentials()).thenReturn(new Credentials()); when(updateContext.createUpdateResult(update)).thenReturn(updateResult); subject.logUpdateResult(updateRequest, updateContext, update, stopwatch); verify(logger).info(matches("\\[\\s*0\\] 0[,.]000 ns DRY CREATE mntner TST-MNT \\(1\\) SUCCESS : <E0,W0,I0> AUTH - null")); }
### Question: AuditLogger { public void logException(final Update update, final Throwable throwable) { final Element updateElement = createOrGetUpdateElement(update); final Element exceptionElement = doc.createElement("exception"); updateElement.appendChild(exceptionElement); exceptionElement.appendChild(keyValue("class", throwable.getClass().getName())); exceptionElement.appendChild(keyValue("message", throwable.getMessage())); final StringWriter stringWriter = new StringWriter(); final PrintWriter stackTraceWriter = new PrintWriter(stringWriter); throwable.printStackTrace(stackTraceWriter); exceptionElement.appendChild(keyValue("stacktrace", stringWriter.getBuffer().toString())); } AuditLogger(final DateTimeProvider dateTimeProvider, final OutputStream outputStream); @SuppressWarnings("ThrowableResultOfMethodCallIgnored" /* Throwable is logged */) void log(final Message message, @Nullable final Throwable t); void logDryRun(); void logBatchUpdate(); void logUpdate(final Update update); void logPreparedUpdate(final PreparedUpdate preparedUpdate); void logException(final Update update, final Throwable throwable); void logDuration(final Update update, final String duration); void logQuery(final Update update, final StatementInfo statementInfo, final ResultInfo resultInfo); void logString(Update update, String element, String auditMessage); void logAuthenticationStrategy(Update update, String authenticationStrategy, Collection<RpslObject> maintainers); void logCredentials(Update update); void logAction(final Update update, final Action action); void logStatus(final Update update, final UpdateStatus status); void logMessage(final Update update, final Message message); void logMessage(final Update update, final RpslAttribute attribute, final Message message); void close(); }### Answer: @Test public void logException() throws Exception { subject.logUpdate(update); subject.logException(update, new NullPointerException()); subject.close(); final String log = outputStream.toString("UTF-8"); assertThat(log, containsString("" + "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n" + "<dbupdate created=\"2012-12-01 00:00:00\">\n" + " <messages/>\n" + " <updates>\n" + " <update attempt=\"1\" time=\"2012-12-01 00:00:00\">\n" + " <key>[mntner] DEV-ROOT-MNT</key>\n" + " <operation>DELETE</operation>\n" + " <reason>reason</reason>\n" + " <paragraph><![CDATA[paragraph]]></paragraph>\n" + " <object><![CDATA[mntner: DEV-ROOT-MNT\n" + "]]></object>\n" + " <exception>\n" + " <class>java.lang.NullPointerException</class>\n" + " <message><![CDATA[null]]></message>\n" + " <stacktrace><![CDATA[java.lang.NullPointerException\n")); }
### Question: AuditLogger { public void logDuration(final Update update, final String duration) { final Element updateElement = createOrGetUpdateElement(update); updateElement.appendChild(keyValue("duration", duration)); } AuditLogger(final DateTimeProvider dateTimeProvider, final OutputStream outputStream); @SuppressWarnings("ThrowableResultOfMethodCallIgnored" /* Throwable is logged */) void log(final Message message, @Nullable final Throwable t); void logDryRun(); void logBatchUpdate(); void logUpdate(final Update update); void logPreparedUpdate(final PreparedUpdate preparedUpdate); void logException(final Update update, final Throwable throwable); void logDuration(final Update update, final String duration); void logQuery(final Update update, final StatementInfo statementInfo, final ResultInfo resultInfo); void logString(Update update, String element, String auditMessage); void logAuthenticationStrategy(Update update, String authenticationStrategy, Collection<RpslObject> maintainers); void logCredentials(Update update); void logAction(final Update update, final Action action); void logStatus(final Update update, final UpdateStatus status); void logMessage(final Update update, final Message message); void logMessage(final Update update, final RpslAttribute attribute, final Message message); void close(); }### Answer: @Test public void logDuration() throws Exception { subject.logUpdate(update); subject.logDuration(update, "1 ns"); subject.close(); final String log = outputStream.toString("UTF-8"); assertThat(log, containsString("" + "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n" + "<dbupdate created=\"2012-12-01 00:00:00\">\n" + " <messages/>\n" + " <updates>\n" + " <update attempt=\"1\" time=\"2012-12-01 00:00:00\">\n" + " <key>[mntner] DEV-ROOT-MNT</key>\n" + " <operation>DELETE</operation>\n" + " <reason>reason</reason>\n" + " <paragraph><![CDATA[paragraph]]></paragraph>\n" + " <object><![CDATA[mntner: DEV-ROOT-MNT\n" + "]]></object>\n" + " <duration>1 ns</duration>\n" + " </update>\n" + " </updates>\n" + "</dbupdate>")); }
### Question: AuditLogger { public void close() { try { writeAndClose(); } catch (IOException e) { LOGGER.error("IO Exception", e); } } AuditLogger(final DateTimeProvider dateTimeProvider, final OutputStream outputStream); @SuppressWarnings("ThrowableResultOfMethodCallIgnored" /* Throwable is logged */) void log(final Message message, @Nullable final Throwable t); void logDryRun(); void logBatchUpdate(); void logUpdate(final Update update); void logPreparedUpdate(final PreparedUpdate preparedUpdate); void logException(final Update update, final Throwable throwable); void logDuration(final Update update, final String duration); void logQuery(final Update update, final StatementInfo statementInfo, final ResultInfo resultInfo); void logString(Update update, String element, String auditMessage); void logAuthenticationStrategy(Update update, String authenticationStrategy, Collection<RpslObject> maintainers); void logCredentials(Update update); void logAction(final Update update, final Action action); void logStatus(final Update update, final UpdateStatus status); void logMessage(final Update update, final Message message); void logMessage(final Update update, final RpslAttribute attribute, final Message message); void close(); }### Answer: @Test public void empty() throws Exception { subject.close(); assertThat(outputStream.toString("UTF-8"), is("" + "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n" + "<dbupdate created=\"2012-12-01 00:00:00\">\n" + " <messages/>\n" + " <updates/>\n" + "</dbupdate>\n" )); verify(outputStream, times(1)).close(); }
### Question: LoggerContext { public void checkDirs() { getCreatedDir(baseDir); } @Autowired LoggerContext(final DateTimeProvider dateTimeProvider); void setBaseDir(final String baseDir); @PostConstruct void start(); void checkDirs(); void init(final String folderName); void remove(); File getFile(final String filename); File log(final String name, final LogCallback callback); void log(final Message message); void log(final Message message, final Throwable t); void logUpdateStarted(final Update update); void logUpdateCompleted(final UpdateContainer updateContainer); void logUpdateFailed(final UpdateContainer updateContainer, final Throwable throwable); void logPreparedUpdate(PreparedUpdate preparedUpdate); void logQuery(final StatementInfo statementInfo, final ResultInfo resultInfo); void logDryRun(); void logBatchUpdate(); void logAction(final UpdateContainer updateContainer, final Action action); void logAuthenticationStrategy(Update update, String authenticationStrategy, Collection<RpslObject> maintainers); void logCredentials(Update update); void logString(final Update update, final String element, final String auditMessage); void logStatus(final UpdateContainer updateContainer, final UpdateStatus action); void logMessage(final UpdateContainer updateContainer, final Message message); void logMessage(final UpdateContainer updateContainer, final RpslAttribute attribute, final Message message); void logException(final UpdateContainer updateContainer, final Throwable throwable); void logMessages(final UpdateContainer updateContainer, ObjectMessages objectMessages); }### Answer: @Test public void checkDirs() { subject.remove(); final File f = new File(folder.getRoot(), "test/"); subject.setBaseDir(f.getAbsolutePath()); subject.checkDirs(); subject.init("folder"); assertThat(f.exists(), is(true)); }
### Question: LoggerContext { public File getFile(final String filename) { final Context tempContext = getContext(); return getFile(tempContext.baseDir, tempContext.nextFileNumber(), filename); } @Autowired LoggerContext(final DateTimeProvider dateTimeProvider); void setBaseDir(final String baseDir); @PostConstruct void start(); void checkDirs(); void init(final String folderName); void remove(); File getFile(final String filename); File log(final String name, final LogCallback callback); void log(final Message message); void log(final Message message, final Throwable t); void logUpdateStarted(final Update update); void logUpdateCompleted(final UpdateContainer updateContainer); void logUpdateFailed(final UpdateContainer updateContainer, final Throwable throwable); void logPreparedUpdate(PreparedUpdate preparedUpdate); void logQuery(final StatementInfo statementInfo, final ResultInfo resultInfo); void logDryRun(); void logBatchUpdate(); void logAction(final UpdateContainer updateContainer, final Action action); void logAuthenticationStrategy(Update update, String authenticationStrategy, Collection<RpslObject> maintainers); void logCredentials(Update update); void logString(final Update update, final String element, final String auditMessage); void logStatus(final UpdateContainer updateContainer, final UpdateStatus action); void logMessage(final UpdateContainer updateContainer, final Message message); void logMessage(final UpdateContainer updateContainer, final RpslAttribute attribute, final Message message); void logException(final UpdateContainer updateContainer, final Throwable throwable); void logMessages(final UpdateContainer updateContainer, ObjectMessages objectMessages); }### Answer: @Test public void getFile() throws Exception { assertThat(subject.getFile("test.txt").getName(), is("001.test.txt.gz")); assertThat(subject.getFile("test.txt").getName(), is("002.test.txt.gz")); assertThat(subject.getFile("test.txt").getName(), is("003.test.txt.gz")); }
### Question: LoggerContext { public File log(final String name, final LogCallback callback) { final File file = getFile(name); OutputStream os = null; try { os = getOutputstream(file); callback.log(os); } catch (IOException e) { throw new IllegalStateException("Unable to write to " + file.getAbsolutePath(), e); } finally { closeOutputStream(os); } return file; } @Autowired LoggerContext(final DateTimeProvider dateTimeProvider); void setBaseDir(final String baseDir); @PostConstruct void start(); void checkDirs(); void init(final String folderName); void remove(); File getFile(final String filename); File log(final String name, final LogCallback callback); void log(final Message message); void log(final Message message, final Throwable t); void logUpdateStarted(final Update update); void logUpdateCompleted(final UpdateContainer updateContainer); void logUpdateFailed(final UpdateContainer updateContainer, final Throwable throwable); void logPreparedUpdate(PreparedUpdate preparedUpdate); void logQuery(final StatementInfo statementInfo, final ResultInfo resultInfo); void logDryRun(); void logBatchUpdate(); void logAction(final UpdateContainer updateContainer, final Action action); void logAuthenticationStrategy(Update update, String authenticationStrategy, Collection<RpslObject> maintainers); void logCredentials(Update update); void logString(final Update update, final String element, final String auditMessage); void logStatus(final UpdateContainer updateContainer, final UpdateStatus action); void logMessage(final UpdateContainer updateContainer, final Message message); void logMessage(final UpdateContainer updateContainer, final RpslAttribute attribute, final Message message); void logException(final UpdateContainer updateContainer, final Throwable throwable); void logMessages(final UpdateContainer updateContainer, ObjectMessages objectMessages); }### Answer: @Test public void log() throws Exception { final File file = subject.log("test.txt", new LogCallback() { @Override public void log(final OutputStream outputStream) throws IOException { outputStream.write("test".getBytes()); } }); final InputStream is = new GZIPInputStream(new BufferedInputStream(new FileInputStream(new File(folder.getRoot(), "001.test.txt.gz")))); final String contents = new String(FileCopyUtils.copyToByteArray(is), StandardCharsets.UTF_8); assertThat(file.getName(), is("001.test.txt.gz")); assertThat(contents, is("test")); } @Test(expected = IllegalStateException.class) public void log_throws_exception() { subject.log("filename", new LogCallback() { @Override public void log(final OutputStream outputStream) throws IOException { throw new IOException(); } }); }
### Question: LoggerContext { public void logQuery(final StatementInfo statementInfo, final ResultInfo resultInfo) { final Context ctx = context.get(); if (ctx != null && ctx.currentUpdate != null) { ctx.auditLogger.logQuery(ctx.currentUpdate, statementInfo, resultInfo); } } @Autowired LoggerContext(final DateTimeProvider dateTimeProvider); void setBaseDir(final String baseDir); @PostConstruct void start(); void checkDirs(); void init(final String folderName); void remove(); File getFile(final String filename); File log(final String name, final LogCallback callback); void log(final Message message); void log(final Message message, final Throwable t); void logUpdateStarted(final Update update); void logUpdateCompleted(final UpdateContainer updateContainer); void logUpdateFailed(final UpdateContainer updateContainer, final Throwable throwable); void logPreparedUpdate(PreparedUpdate preparedUpdate); void logQuery(final StatementInfo statementInfo, final ResultInfo resultInfo); void logDryRun(); void logBatchUpdate(); void logAction(final UpdateContainer updateContainer, final Action action); void logAuthenticationStrategy(Update update, String authenticationStrategy, Collection<RpslObject> maintainers); void logCredentials(Update update); void logString(final Update update, final String element, final String auditMessage); void logStatus(final UpdateContainer updateContainer, final UpdateStatus action); void logMessage(final UpdateContainer updateContainer, final Message message); void logMessage(final UpdateContainer updateContainer, final RpslAttribute attribute, final Message message); void logException(final UpdateContainer updateContainer, final Throwable throwable); void logMessages(final UpdateContainer updateContainer, ObjectMessages objectMessages); }### Answer: @Test public void log_query_no_context_should_not_fail() { subject.logQuery(new StatementInfo("sql"), new ResultInfo(Collections.<List<String>>emptyList())); }
### Question: LoggerContext { public void logUpdateCompleted(final UpdateContainer updateContainer) { logUpdateComplete(updateContainer, null); } @Autowired LoggerContext(final DateTimeProvider dateTimeProvider); void setBaseDir(final String baseDir); @PostConstruct void start(); void checkDirs(); void init(final String folderName); void remove(); File getFile(final String filename); File log(final String name, final LogCallback callback); void log(final Message message); void log(final Message message, final Throwable t); void logUpdateStarted(final Update update); void logUpdateCompleted(final UpdateContainer updateContainer); void logUpdateFailed(final UpdateContainer updateContainer, final Throwable throwable); void logPreparedUpdate(PreparedUpdate preparedUpdate); void logQuery(final StatementInfo statementInfo, final ResultInfo resultInfo); void logDryRun(); void logBatchUpdate(); void logAction(final UpdateContainer updateContainer, final Action action); void logAuthenticationStrategy(Update update, String authenticationStrategy, Collection<RpslObject> maintainers); void logCredentials(Update update); void logString(final Update update, final String element, final String auditMessage); void logStatus(final UpdateContainer updateContainer, final UpdateStatus action); void logMessage(final UpdateContainer updateContainer, final Message message); void logMessage(final UpdateContainer updateContainer, final RpslAttribute attribute, final Message message); void logException(final UpdateContainer updateContainer, final Throwable throwable); void logMessages(final UpdateContainer updateContainer, ObjectMessages objectMessages); }### Answer: @Test(expected = IllegalStateException.class) public void logUpdateComplete_no_context_should_fail() { subject.logUpdateCompleted(update); }
### Question: LoggerContext { public void logException(final UpdateContainer updateContainer, final Throwable throwable) { getContext().auditLogger.logException(updateContainer.getUpdate(), throwable); } @Autowired LoggerContext(final DateTimeProvider dateTimeProvider); void setBaseDir(final String baseDir); @PostConstruct void start(); void checkDirs(); void init(final String folderName); void remove(); File getFile(final String filename); File log(final String name, final LogCallback callback); void log(final Message message); void log(final Message message, final Throwable t); void logUpdateStarted(final Update update); void logUpdateCompleted(final UpdateContainer updateContainer); void logUpdateFailed(final UpdateContainer updateContainer, final Throwable throwable); void logPreparedUpdate(PreparedUpdate preparedUpdate); void logQuery(final StatementInfo statementInfo, final ResultInfo resultInfo); void logDryRun(); void logBatchUpdate(); void logAction(final UpdateContainer updateContainer, final Action action); void logAuthenticationStrategy(Update update, String authenticationStrategy, Collection<RpslObject> maintainers); void logCredentials(Update update); void logString(final Update update, final String element, final String auditMessage); void logStatus(final UpdateContainer updateContainer, final UpdateStatus action); void logMessage(final UpdateContainer updateContainer, final Message message); void logMessage(final UpdateContainer updateContainer, final RpslAttribute attribute, final Message message); void logException(final UpdateContainer updateContainer, final Throwable throwable); void logMessages(final UpdateContainer updateContainer, ObjectMessages objectMessages); }### Answer: @Test public void logException() throws IOException { final String content = "mntner: DEV-ROOT-MNT"; final RpslObject object = RpslObject.parse(content); when(update.getOperation()).thenReturn(Operation.DELETE); when(update.getParagraph()).thenReturn(new Paragraph(content)); when(update.getSubmittedObject()).thenReturn(object); subject.logUpdateStarted(update); subject.logUpdateFailed(update, new NullPointerException()); subject.remove(); final InputStream is = new GZIPInputStream(new BufferedInputStream(new FileInputStream(new File(folder.getRoot(), "000.audit.xml.gz")))); final String contents = new String(FileCopyUtils.copyToByteArray(is), StandardCharsets.UTF_8); assertThat(contents, containsString("" + " <exception>\n" + " <class>java.lang.NullPointerException</class>\n" + " <message><![CDATA[null]]></message>\n" + " <stacktrace><![CDATA[java.lang.NullPointerException\n")); }
### Question: MailMessageLogCallback implements LogCallback { @Override public void log(final OutputStream outputStream) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { message.writeTo(baos); String messageData = new String( baos.toByteArray(), "UTF-8" ); String filtered = PasswordFilter.filterPasswordsInContents(messageData); outputStream.write(filtered.getBytes("UTF-8")); } catch (MessagingException e) { LOGGER.warn("Writing message", e); } } MailMessageLogCallback(final Message message); @Override void log(final OutputStream outputStream); }### Answer: @Test public void log() throws IOException, MessagingException { final MailMessageLogCallback subject = new MailMessageLogCallback(message); subject.log(outputStream); verify(outputStream).write("".getBytes()); } @Test public void log_never_throws_exception() throws IOException, MessagingException { final MailMessageLogCallback subject = new MailMessageLogCallback(message); doThrow(MessagingException.class).when(message).writeTo(outputStream); subject.log(outputStream); verify(outputStream).write("".getBytes()); }
### Question: IterableTransformer implements Iterable<T> { @Override public Iterator<T> iterator() { return new IteratorTransformer(head); } IterableTransformer(final Iterable<? extends T> wrap); IterableTransformer<T> setHeader(T... header); IterableTransformer<T> setHeader(Collection<T> header); abstract void apply(final T input, final Deque<T> result); @Override Iterator<T> iterator(); }### Answer: @Test public void empty_input_test() { final Iterable subject = getSimpleIterable(); final Iterator<Integer> iterator = subject.iterator(); assertFalse(iterator.hasNext()); } @Test(expected = NullPointerException.class) public void null_test() { final Iterable<Integer> subject = getSimpleIterable(1, null, 2, null); final Iterator<Integer> iterator = subject.iterator(); assertTrue(iterator.hasNext()); assertThat(iterator.next(), is(1)); assertTrue(iterator.hasNext()); assertNull(iterator.next()); assertTrue(iterator.hasNext()); assertThat(iterator.next(), is(2)); assertTrue(iterator.hasNext()); assertNull(iterator.next()); assertFalse(iterator.hasNext()); } @Test public void simple_test() { final Iterable<Integer> subject = getSimpleIterable(1,2,3); final Iterator<Integer> iterator = subject.iterator(); assertTrue(iterator.hasNext()); assertThat(iterator.next(), is(1)); assertTrue(iterator.hasNext()); assertThat(iterator.next(), is(2)); assertTrue(iterator.hasNext()); assertThat(iterator.next(), is(3)); assertFalse(iterator.hasNext()); } @Test public void iterable_resettable() { final Iterable<Integer> subject = getSimpleIterable(1,2,3); Iterator<Integer> iterator = subject.iterator(); assertTrue(iterator.hasNext()); assertThat(iterator.next(), is(1)); iterator = subject.iterator(); assertTrue(iterator.hasNext()); assertThat(iterator.next(), is(1)); assertTrue(iterator.hasNext()); assertThat(iterator.next(), is(2)); assertTrue(iterator.hasNext()); assertThat(iterator.next(), is(3)); assertFalse(iterator.hasNext()); } @Test public void odd_filter_test() { final Iterable<Integer> subject = getOddFilteringIterable(1, 2, 3); final Iterator<Integer> iterator = subject.iterator(); assertTrue(iterator.hasNext()); assertThat(iterator.next(), is(2)); assertFalse(iterator.hasNext()); } @Test public void multiple_results_filter_test() { final Iterable<Integer> subject = getOddFilteringEvenDoublingIterable(1, 2, 3); final Iterator<Integer> iterator = subject.iterator(); assertTrue(iterator.hasNext()); assertThat(iterator.next(), is(2)); assertTrue(iterator.hasNext()); assertThat(iterator.next(), is(2)); assertFalse(iterator.hasNext()); }
### Question: GrsImporter implements DailyScheduledTask { @Override @Scheduled(cron = "0 0 0 * * *") @SchedulerLock(name = "GrsImporter") public void run() { if (!grsImportEnabled) { LOGGER.info("GRS import is not enabled"); return; } List<Future> futures = grsImport(defaultSources, false); for (Future future : futures) { try { future.get(); } catch (InterruptedException | ExecutionException e) { LOGGER.error(e.getMessage(), e); } } } @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); }### Answer: @Test public void run() { subject = spy(subject); subject.setGrsImportEnabled(false); subject.run(); verify(subject, times(0)).grsImport(anyString(), anyBoolean()); }
### Question: MailGatewaySmtp implements MailGateway { @Override public void sendEmail(final String to, final ResponseMessage responseMessage) { sendEmail(to, responseMessage.getSubject(), responseMessage.getMessage(), responseMessage.getReplyTo()); } @Autowired MailGatewaySmtp(final LoggerContext loggerContext, final MailConfiguration mailConfiguration, final JavaMailSender mailSender); @Override void sendEmail(final String to, final ResponseMessage responseMessage); @Override void sendEmail(final String to, final String subject, final String text, @Nullable final String replyTo); }### Answer: @Test public void sendResponse() throws Exception { subject.sendEmail("to", "subject", "test", ""); verify(mailSender, times(1)).send(any(MimeMessagePreparator.class)); } @Test public void sendResponse_disabled() throws Exception { ReflectionTestUtils.setField(subject, "outgoingMailEnabled", false); subject.sendEmail("to", "subject", "test", ""); verifyZeroInteractions(mailSender); } @Test public void send_invoked_only_once_on_permanent_negative_response() { Mockito.doAnswer(invocation -> { throw new SendFailedException("550 rejected: mail rejected for policy reasons"); }).when(mailSender).send(any(MimeMessagePreparator.class)); try { subject.sendEmail("to", "subject", "test", ""); fail(); } catch (Exception e) { assertThat(e, instanceOf(SendFailedException.class)); verify(mailSender, times(1)).send(any(MimeMessagePreparator.class)); } } @Test public void sendResponseAndCheckForReplyTo() throws Exception { final String replyToAddress = "test@ripe.net"; setExpectReplyToField(replyToAddress); subject.sendEmail("to", "subject", "test", replyToAddress); } @Test public void sendResponseAndCheckForEmptyReplyTo() throws Exception { final String replyToAddress = ""; setExpectReplyToField(replyToAddress); subject.sendEmail("to", "subject", "test", ""); }
### Question: OverrideCredential implements Credential { @Override public String toString() { if (!overrideValues.isPresent()){ return "OverrideCredential{NOT_VALID}"; } if (StringUtils.isBlank(overrideValues.get().getRemarks())){ return String.format("OverrideCredential{%s,FILTERED}", overrideValues.get().getUsername()); } return String.format("OverrideCredential{%s,FILTERED,%s}", overrideValues.get().getUsername(), overrideValues.get().getRemarks()); } private OverrideCredential(final String value, final Optional<OverrideValues> overrideValues); Optional<OverrideValues> getOverrideValues(); @Override boolean equals(final Object o); @Override int hashCode(); @Override String toString(); static OverrideCredential parse(final String value); }### Answer: @Test public void testToString() { assertThat(OverrideCredential.parse("").toString(), is("OverrideCredential{NOT_VALID}")); assertThat(OverrideCredential.parse("user").toString(), is("OverrideCredential{NOT_VALID}")); assertThat(OverrideCredential.parse("user,password").toString(), is("OverrideCredential{user,FILTERED}")); assertThat(OverrideCredential.parse("user, password").toString(), is("OverrideCredential{user,FILTERED}")); assertThat(OverrideCredential.parse("user, password, remarks").toString(), is("OverrideCredential{user,FILTERED,remarks}")); assertThat(OverrideCredential.parse("user,password,remarks,more remarks").toString(), is("OverrideCredential{user,FILTERED,remarks,more remarks}")); }
### Question: LegacyAutnum { public boolean contains(final CIString autnum) { return cachedLegacyAutnums.contains(autnum); } @Autowired LegacyAutnum(final LegacyAutnumDao legacyAutnumDao); @PostConstruct synchronized void init(); boolean contains(final CIString autnum); int getTotal(); }### Answer: @Test public void contains() { assertThat(subject.contains(ciString("AS100")), is(false)); assertThat(subject.contains(ciString("AS102")), is(true)); }
### Question: OrganisationId extends AutoKey { @Override public String toString() { return new StringBuilder() .append("ORG-") .append(getSpace().toUpperCase()) .append(getIndex()) .append("-") .append(getSuffix()) .toString(); } OrganisationId(final String space, final int index, final String suffix); @Override String toString(); }### Answer: @Test public void string() { final OrganisationId subject = new OrganisationId("SAT", 1, "RIPE"); assertThat(subject.toString(), is("ORG-SAT1-RIPE")); }
### Question: NicHandle extends AutoKey { public static NicHandle parse(final String nicHdl, final CIString source, final Set<CIString> countryCodes) { if (StringUtils.startsWithIgnoreCase(nicHdl, "AUTO-")) { throw new NicHandleParseException("Primary key generation request cannot be parsed as NIC-HDL: " + nicHdl); } final Matcher matcher = NIC_HDL_PATTERN.matcher(nicHdl.trim()); if (!matcher.matches()) { throw new NicHandleParseException("Invalid NIC-HDL: " + nicHdl); } final String characterSpace = matcher.group(1); final int index = getIndex(matcher.group(2)); final String suffix = getSuffix(matcher.group(3), source, countryCodes); return new NicHandle(characterSpace, index, suffix); } NicHandle(final String space, final Integer index, final String suffix); static NicHandle parse(final String nicHdl, final CIString source, final Set<CIString> countryCodes); @Override String toString(); }### Answer: @Test public void parse_auto() { try { NicHandle.parse("AUTO-1", source, countryCodes); fail("AUTO- should not be supported as NIC-HDL"); } catch (NicHandleParseException e) { assertThat(e.getMessage(), is("Primary key generation request cannot be parsed as NIC-HDL: AUTO-1")); } } @Test public void parse_auto_lowercase() { try { NicHandle.parse("auto-1", source, countryCodes); fail("AUTO- should not be supported as NIC-HDL"); } catch (NicHandleParseException e) { assertThat(e.getMessage(), is("Primary key generation request cannot be parsed as NIC-HDL: auto-1")); } } @Test public void parse_empty() { try { NicHandle.parse("", source, countryCodes); fail("Empty should not be supported as NIC-HDL"); } catch (NicHandleParseException e) { assertThat(e.getMessage(), is("Invalid NIC-HDL: ")); } } @Test(expected = NicHandleParseException.class) public void parse_space_too_long() { NicHandle.parse("SPACE", source, countryCodes); } @Test(expected = NicHandleParseException.class) public void parse_suffix_too_long() { NicHandle.parse("DW-VERYLONGSUFFIX", source, countryCodes); } @Test(expected = NicHandleParseException.class) public void parse_suffix_invalid() { NicHandle.parse("DW-SOMETHING", source, countryCodes); } @Test public void equal_null() { final NicHandle nicHandle = NicHandle.parse("DW", source, countryCodes); assertFalse(nicHandle.equals(null)); } @Test public void equal_otherClass() { final NicHandle nicHandle = NicHandle.parse("DW", source, countryCodes); assertFalse(nicHandle.equals("")); } @Test public void equal_self() { final NicHandle nicHandle = NicHandle.parse("DW", source, countryCodes); assertTrue(nicHandle.equals(nicHandle)); } @Test public void equal_same() { final NicHandle nicHandle = NicHandle.parse("DW", source, countryCodes); assertTrue(nicHandle.equals(NicHandle.parse("DW", source, countryCodes))); } @Test public void equal_different() { final NicHandle nicHandle = NicHandle.parse("DW", source, countryCodes); assertFalse(nicHandle.equals(NicHandle.parse("AB", source, countryCodes))); } @Test public void hashCode_check() { NicHandle.parse("DW", source, countryCodes).hashCode(); }
### Question: UpdateContext { public Messages getGlobalMessages() { return globalMessages; } UpdateContext(final LoggerContext loggerContext); boolean isDryRun(); void dryRun(); int getNrSinceRestart(); boolean isBatchUpdate(); void setBatchUpdate(); void addDnsCheckResponse(final DnsCheckRequest request, final DnsCheckResponse response); void addSsoTranslationResult(final String username, final String uuid); boolean hasSsoTranslationResult(String usernameOrUuid); @CheckForNull String getSsoTranslationResult(final String usernameOrUuid); @CheckForNull DnsCheckResponse getCachedDnsCheckResponse(final DnsCheckRequest dnsCheckRequest); void addMessage(final UpdateContainer updateContainer, final Message message); void addMessage(final UpdateContainer updateContainer, final RpslAttribute attribute, final Message message); ObjectMessages getMessages(final UpdateContainer updateContainer); void setAction(final UpdateContainer updateContainer, final Action action); Action getAction(final UpdateContainer updateContainer); void setOrigin(final UpdateContainer updateContainer, final Origin origin); Origin getOrigin(final UpdateContainer updateContainer); PreparedUpdate getPreparedUpdate(final UpdateContainer updateContainer); boolean hasErrors(final UpdateContainer updateContainer); int getErrorCount(final UpdateContainer updateContainer); void status(final UpdateContainer updateContainer, final UpdateStatus status); UpdateStatus getStatus(final UpdateContainer updateContainer); void subject(final UpdateContainer updateContainer, final Subject subject); Subject getSubject(final UpdateContainer updateContainer); void updateInfo(final UpdateContainer updateContainer, final RpslObjectUpdateInfo updateInfo); RpslObjectUpdateInfo getUpdateInfo(final UpdateContainer updateContainer); void versionId(final UpdateContainer updateContainer, final int versionId); int getVersionId(final UpdateContainer updateContainer); void setPreparedUpdate(final PreparedUpdate preparedUpdate); void ignore(final Paragraph paragraph); void addGlobalMessage(final Message message); Messages getGlobalMessages(); String printGlobalMessages(); void addGeneratedKey(final UpdateContainer updateContainer, final CIString keyPlaceholder, final GeneratedKey generatedKey); void failedUpdate(final UpdateContainer updateContainer, final Message... messages); @CheckForNull GeneratedKey getGeneratedKey(final CIString keyPlaceholder); Ack createAck(); UpdateResult createUpdateResult(final UpdateContainer updateContainer); void prepareForReattempt(final UpdateContainer update); void setUserSession(final UserSession userSession); UserSession getUserSession(); void setClientCertificate(final Optional<X509CertificateWrapper> clientCertificate); Optional<X509CertificateWrapper> getClientCertificate(); }### Answer: @Test public void no_warnings() { assertThat(subject.getGlobalMessages().getAllMessages(), hasSize(0)); }
### Question: UpdateContext { public boolean hasErrors(final UpdateContainer updateContainer) { return getOrCreateContext(updateContainer).objectMessages.hasErrors(); } UpdateContext(final LoggerContext loggerContext); boolean isDryRun(); void dryRun(); int getNrSinceRestart(); boolean isBatchUpdate(); void setBatchUpdate(); void addDnsCheckResponse(final DnsCheckRequest request, final DnsCheckResponse response); void addSsoTranslationResult(final String username, final String uuid); boolean hasSsoTranslationResult(String usernameOrUuid); @CheckForNull String getSsoTranslationResult(final String usernameOrUuid); @CheckForNull DnsCheckResponse getCachedDnsCheckResponse(final DnsCheckRequest dnsCheckRequest); void addMessage(final UpdateContainer updateContainer, final Message message); void addMessage(final UpdateContainer updateContainer, final RpslAttribute attribute, final Message message); ObjectMessages getMessages(final UpdateContainer updateContainer); void setAction(final UpdateContainer updateContainer, final Action action); Action getAction(final UpdateContainer updateContainer); void setOrigin(final UpdateContainer updateContainer, final Origin origin); Origin getOrigin(final UpdateContainer updateContainer); PreparedUpdate getPreparedUpdate(final UpdateContainer updateContainer); boolean hasErrors(final UpdateContainer updateContainer); int getErrorCount(final UpdateContainer updateContainer); void status(final UpdateContainer updateContainer, final UpdateStatus status); UpdateStatus getStatus(final UpdateContainer updateContainer); void subject(final UpdateContainer updateContainer, final Subject subject); Subject getSubject(final UpdateContainer updateContainer); void updateInfo(final UpdateContainer updateContainer, final RpslObjectUpdateInfo updateInfo); RpslObjectUpdateInfo getUpdateInfo(final UpdateContainer updateContainer); void versionId(final UpdateContainer updateContainer, final int versionId); int getVersionId(final UpdateContainer updateContainer); void setPreparedUpdate(final PreparedUpdate preparedUpdate); void ignore(final Paragraph paragraph); void addGlobalMessage(final Message message); Messages getGlobalMessages(); String printGlobalMessages(); void addGeneratedKey(final UpdateContainer updateContainer, final CIString keyPlaceholder, final GeneratedKey generatedKey); void failedUpdate(final UpdateContainer updateContainer, final Message... messages); @CheckForNull GeneratedKey getGeneratedKey(final CIString keyPlaceholder); Ack createAck(); UpdateResult createUpdateResult(final UpdateContainer updateContainer); void prepareForReattempt(final UpdateContainer update); void setUserSession(final UserSession userSession); UserSession getUserSession(); void setClientCertificate(final Optional<X509CertificateWrapper> clientCertificate); Optional<X509CertificateWrapper> getClientCertificate(); }### Answer: @Test public void no_errors() { final RpslObject mntner = RpslObject.parse(MAINTAINER); final Update update = new Update(new Paragraph(MAINTAINER), Operation.DELETE, Lists.<String>newArrayList(), mntner); final PreparedUpdate preparedUpdate = new PreparedUpdate(update, null, mntner, Action.DELETE); assertThat(subject.hasErrors(preparedUpdate), is(false)); }
### Question: UpdateContext { public void status(final UpdateContainer updateContainer, final UpdateStatus status) { getOrCreateContext(updateContainer).status = status; loggerContext.logStatus(updateContainer, status); } UpdateContext(final LoggerContext loggerContext); boolean isDryRun(); void dryRun(); int getNrSinceRestart(); boolean isBatchUpdate(); void setBatchUpdate(); void addDnsCheckResponse(final DnsCheckRequest request, final DnsCheckResponse response); void addSsoTranslationResult(final String username, final String uuid); boolean hasSsoTranslationResult(String usernameOrUuid); @CheckForNull String getSsoTranslationResult(final String usernameOrUuid); @CheckForNull DnsCheckResponse getCachedDnsCheckResponse(final DnsCheckRequest dnsCheckRequest); void addMessage(final UpdateContainer updateContainer, final Message message); void addMessage(final UpdateContainer updateContainer, final RpslAttribute attribute, final Message message); ObjectMessages getMessages(final UpdateContainer updateContainer); void setAction(final UpdateContainer updateContainer, final Action action); Action getAction(final UpdateContainer updateContainer); void setOrigin(final UpdateContainer updateContainer, final Origin origin); Origin getOrigin(final UpdateContainer updateContainer); PreparedUpdate getPreparedUpdate(final UpdateContainer updateContainer); boolean hasErrors(final UpdateContainer updateContainer); int getErrorCount(final UpdateContainer updateContainer); void status(final UpdateContainer updateContainer, final UpdateStatus status); UpdateStatus getStatus(final UpdateContainer updateContainer); void subject(final UpdateContainer updateContainer, final Subject subject); Subject getSubject(final UpdateContainer updateContainer); void updateInfo(final UpdateContainer updateContainer, final RpslObjectUpdateInfo updateInfo); RpslObjectUpdateInfo getUpdateInfo(final UpdateContainer updateContainer); void versionId(final UpdateContainer updateContainer, final int versionId); int getVersionId(final UpdateContainer updateContainer); void setPreparedUpdate(final PreparedUpdate preparedUpdate); void ignore(final Paragraph paragraph); void addGlobalMessage(final Message message); Messages getGlobalMessages(); String printGlobalMessages(); void addGeneratedKey(final UpdateContainer updateContainer, final CIString keyPlaceholder, final GeneratedKey generatedKey); void failedUpdate(final UpdateContainer updateContainer, final Message... messages); @CheckForNull GeneratedKey getGeneratedKey(final CIString keyPlaceholder); Ack createAck(); UpdateResult createUpdateResult(final UpdateContainer updateContainer); void prepareForReattempt(final UpdateContainer update); void setUserSession(final UserSession userSession); UserSession getUserSession(); void setClientCertificate(final Optional<X509CertificateWrapper> clientCertificate); Optional<X509CertificateWrapper> getClientCertificate(); }### Answer: @Test public void status() { final String content = "mntner: DEV-ROOT-MNT"; final RpslObject mntner = RpslObject.parse(content); final Update update = new Update(new Paragraph(content), Operation.DELETE, Lists.<String>newArrayList(), mntner); final PreparedUpdate preparedUpdate = new PreparedUpdate(update, null, mntner, Action.DELETE); subject.status(preparedUpdate, UpdateStatus.FAILED_AUTHENTICATION); assertThat(subject.getStatus(preparedUpdate), is(UpdateStatus.FAILED_AUTHENTICATION)); }
### Question: ContentWithCredentials { public List<Credential> getCredentials() { return credentials; } ContentWithCredentials(final String content); ContentWithCredentials(final String content, final Charset charset); ContentWithCredentials(final String content, final List<Credential> credentials); ContentWithCredentials(final String content, final List<Credential> credentials, final Charset charset); String getContent(); List<Credential> getCredentials(); Charset getCharset(); }### Answer: @Test(expected = UnsupportedOperationException.class) public void credentials_are_immutable() { final ContentWithCredentials subject = new ContentWithCredentials("test", Lists.newArrayList(credential)); subject.getCredentials().add(mock(Credential.class)); }
### Question: PreparedUpdate implements UpdateContainer { @Override public Update getUpdate() { return update; } PreparedUpdate(final Update update, @Nullable final RpslObject originalObject, @Nullable final RpslObject updatedObject, final Action action); PreparedUpdate(final Update update, @Nullable final RpslObject originalObject, @Nullable final RpslObject updatedObject, final Action action, final OverrideOptions overrideOptions); @Override Update getUpdate(); Paragraph getParagraph(); boolean hasOriginalObject(); @Nullable RpslObject getReferenceObject(); @Nullable RpslObject getUpdatedObject(); RpslObject getSubmittedObject(); Action getAction(); Credentials getCredentials(); boolean isOverride(); OverrideOptions getOverrideOptions(); ObjectType getType(); String getKey(); String getFormattedKey(); Set<CIString> getNewValues(final AttributeType attributeType); Set<CIString> getDifferences(final AttributeType attributeType); @Override String toString(); }### Answer: @Test public void getUpdate() { assertThat(subject.getUpdate(), is(update)); }
### Question: PreparedUpdate implements UpdateContainer { public Paragraph getParagraph() { return update.getParagraph(); } PreparedUpdate(final Update update, @Nullable final RpslObject originalObject, @Nullable final RpslObject updatedObject, final Action action); PreparedUpdate(final Update update, @Nullable final RpslObject originalObject, @Nullable final RpslObject updatedObject, final Action action, final OverrideOptions overrideOptions); @Override Update getUpdate(); Paragraph getParagraph(); boolean hasOriginalObject(); @Nullable RpslObject getReferenceObject(); @Nullable RpslObject getUpdatedObject(); RpslObject getSubmittedObject(); Action getAction(); Credentials getCredentials(); boolean isOverride(); OverrideOptions getOverrideOptions(); ObjectType getType(); String getKey(); String getFormattedKey(); Set<CIString> getNewValues(final AttributeType attributeType); Set<CIString> getDifferences(final AttributeType attributeType); @Override String toString(); }### Answer: @Test public void getParagraph() { subject.getParagraph(); verify(update).getParagraph(); }
### Question: PreparedUpdate implements UpdateContainer { @Nullable public RpslObject getReferenceObject() { if (originalObject != null) { return originalObject; } return updatedObject; } PreparedUpdate(final Update update, @Nullable final RpslObject originalObject, @Nullable final RpslObject updatedObject, final Action action); PreparedUpdate(final Update update, @Nullable final RpslObject originalObject, @Nullable final RpslObject updatedObject, final Action action, final OverrideOptions overrideOptions); @Override Update getUpdate(); Paragraph getParagraph(); boolean hasOriginalObject(); @Nullable RpslObject getReferenceObject(); @Nullable RpslObject getUpdatedObject(); RpslObject getSubmittedObject(); Action getAction(); Credentials getCredentials(); boolean isOverride(); OverrideOptions getOverrideOptions(); ObjectType getType(); String getKey(); String getFormattedKey(); Set<CIString> getNewValues(final AttributeType attributeType); Set<CIString> getDifferences(final AttributeType attributeType); @Override String toString(); }### Answer: @Test public void getOriginalObject() { assertThat(subject.getReferenceObject(), is(originalObject)); }
### Question: PreparedUpdate implements UpdateContainer { @Nullable public RpslObject getUpdatedObject() { return updatedObject; } PreparedUpdate(final Update update, @Nullable final RpslObject originalObject, @Nullable final RpslObject updatedObject, final Action action); PreparedUpdate(final Update update, @Nullable final RpslObject originalObject, @Nullable final RpslObject updatedObject, final Action action, final OverrideOptions overrideOptions); @Override Update getUpdate(); Paragraph getParagraph(); boolean hasOriginalObject(); @Nullable RpslObject getReferenceObject(); @Nullable RpslObject getUpdatedObject(); RpslObject getSubmittedObject(); Action getAction(); Credentials getCredentials(); boolean isOverride(); OverrideOptions getOverrideOptions(); ObjectType getType(); String getKey(); String getFormattedKey(); Set<CIString> getNewValues(final AttributeType attributeType); Set<CIString> getDifferences(final AttributeType attributeType); @Override String toString(); }### Answer: @Test public void getUpdatedObject() { assertThat(subject.getUpdatedObject(), is(updatedObject)); }
### Question: PreparedUpdate implements UpdateContainer { public Action getAction() { return action; } PreparedUpdate(final Update update, @Nullable final RpslObject originalObject, @Nullable final RpslObject updatedObject, final Action action); PreparedUpdate(final Update update, @Nullable final RpslObject originalObject, @Nullable final RpslObject updatedObject, final Action action, final OverrideOptions overrideOptions); @Override Update getUpdate(); Paragraph getParagraph(); boolean hasOriginalObject(); @Nullable RpslObject getReferenceObject(); @Nullable RpslObject getUpdatedObject(); RpslObject getSubmittedObject(); Action getAction(); Credentials getCredentials(); boolean isOverride(); OverrideOptions getOverrideOptions(); ObjectType getType(); String getKey(); String getFormattedKey(); Set<CIString> getNewValues(final AttributeType attributeType); Set<CIString> getDifferences(final AttributeType attributeType); @Override String toString(); }### Answer: @Test public void getAction() { assertThat(subject.getAction(), is(Action.MODIFY)); }
### Question: PreparedUpdate implements UpdateContainer { public Credentials getCredentials() { return update.getCredentials(); } PreparedUpdate(final Update update, @Nullable final RpslObject originalObject, @Nullable final RpslObject updatedObject, final Action action); PreparedUpdate(final Update update, @Nullable final RpslObject originalObject, @Nullable final RpslObject updatedObject, final Action action, final OverrideOptions overrideOptions); @Override Update getUpdate(); Paragraph getParagraph(); boolean hasOriginalObject(); @Nullable RpslObject getReferenceObject(); @Nullable RpslObject getUpdatedObject(); RpslObject getSubmittedObject(); Action getAction(); Credentials getCredentials(); boolean isOverride(); OverrideOptions getOverrideOptions(); ObjectType getType(); String getKey(); String getFormattedKey(); Set<CIString> getNewValues(final AttributeType attributeType); Set<CIString> getDifferences(final AttributeType attributeType); @Override String toString(); }### Answer: @Test public void getCredentials() { subject.getCredentials(); verify(update).getCredentials(); }
### Question: PreparedUpdate implements UpdateContainer { public ObjectType getType() { return update.getType(); } PreparedUpdate(final Update update, @Nullable final RpslObject originalObject, @Nullable final RpslObject updatedObject, final Action action); PreparedUpdate(final Update update, @Nullable final RpslObject originalObject, @Nullable final RpslObject updatedObject, final Action action, final OverrideOptions overrideOptions); @Override Update getUpdate(); Paragraph getParagraph(); boolean hasOriginalObject(); @Nullable RpslObject getReferenceObject(); @Nullable RpslObject getUpdatedObject(); RpslObject getSubmittedObject(); Action getAction(); Credentials getCredentials(); boolean isOverride(); OverrideOptions getOverrideOptions(); ObjectType getType(); String getKey(); String getFormattedKey(); Set<CIString> getNewValues(final AttributeType attributeType); Set<CIString> getDifferences(final AttributeType attributeType); @Override String toString(); }### Answer: @Test public void getType() { subject.getType(); verify(update).getType(); }
### Question: PreparedUpdate implements UpdateContainer { public String getKey() { return updatedObject.getKey().toString(); } PreparedUpdate(final Update update, @Nullable final RpslObject originalObject, @Nullable final RpslObject updatedObject, final Action action); PreparedUpdate(final Update update, @Nullable final RpslObject originalObject, @Nullable final RpslObject updatedObject, final Action action, final OverrideOptions overrideOptions); @Override Update getUpdate(); Paragraph getParagraph(); boolean hasOriginalObject(); @Nullable RpslObject getReferenceObject(); @Nullable RpslObject getUpdatedObject(); RpslObject getSubmittedObject(); Action getAction(); Credentials getCredentials(); boolean isOverride(); OverrideOptions getOverrideOptions(); ObjectType getType(); String getKey(); String getFormattedKey(); Set<CIString> getNewValues(final AttributeType attributeType); Set<CIString> getDifferences(final AttributeType attributeType); @Override String toString(); }### Answer: @Test public void getKey() { assertThat(subject.getFormattedKey(), is("[mntner] DEV-TST-MNT")); }
### Question: ObjectKey { @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; final ObjectKey that = (ObjectKey) o; return Objects.equals(objectType, that.objectType) && Objects.equals(pkey, that.pkey); } ObjectKey(final ObjectType objectType, final String pkey); ObjectKey(final ObjectType objectType, final CIString pkey); ObjectType getObjectType(); CIString getPkey(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer: @Test public void equals() { final ObjectKey subject = new ObjectKey(ObjectType.MNTNER, "key"); assertThat(subject.equals(null), is(false)); assertThat(subject.equals(""), is(false)); assertThat(subject.equals(subject), is(true)); assertThat(subject.equals(new ObjectKey(ObjectType.MNTNER, "key")), is(true)); assertThat(subject.equals(new ObjectKey(ObjectType.MNTNER, "KEY")), is(true)); assertThat(subject.equals(new ObjectKey(ObjectType.MNTNER, "key2")), is(false)); assertThat(subject.equals(new ObjectKey(ObjectType.ORGANISATION, "key")), is(false)); }
### Question: ObjectKey { @Override public int hashCode() { return Objects.hash(objectType, pkey); } ObjectKey(final ObjectType objectType, final String pkey); ObjectKey(final ObjectType objectType, final CIString pkey); ObjectType getObjectType(); CIString getPkey(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer: @Test public void hash() { final ObjectKey subject = new ObjectKey(ObjectType.MNTNER, "key"); assertThat(subject.hashCode(), is(new ObjectKey(ObjectType.MNTNER, "key").hashCode())); assertThat(subject.hashCode(), not(is(new ObjectKey(ObjectType.ORGANISATION, "key").hashCode()))); } @Test public void hash_uppercase() { final ObjectKey subject = new ObjectKey(ObjectType.MNTNER, "key"); assertThat(subject.hashCode(), is(new ObjectKey(ObjectType.MNTNER, "KEY").hashCode())); }
### Question: ObjectKey { @Override public String toString() { return String.format("[%s] %s", objectType.getName(), pkey); } ObjectKey(final ObjectType objectType, final String pkey); ObjectKey(final ObjectType objectType, final CIString pkey); ObjectType getObjectType(); CIString getPkey(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer: @Test public void string() { final ObjectKey subject = new ObjectKey(ObjectType.MNTNER, "key"); assertThat(subject.toString(), is("[mntner] key")); } @Test public void string_uppercase() { final ObjectKey subject = new ObjectKey(ObjectType.MNTNER, "KeY"); assertThat(subject.toString(), is("[mntner] KeY")); }
### Question: Notification { public String getEmail() { return email; } Notification(final String email); void add(final Type type, final PreparedUpdate update, UpdateContext updateContext); String getEmail(); Set<Update> getUpdates(final Type type); boolean has(final Type type); }### Answer: @Test public void getEmail() { assertThat(subject.getEmail(), is("test@me.now")); }
### Question: Notification { public Set<Update> getUpdates(final Type type) { return updates.get(type); } Notification(final String email); void add(final Type type, final PreparedUpdate update, UpdateContext updateContext); String getEmail(); Set<Update> getUpdates(final Type type); boolean has(final Type type); }### Answer: @Test public void getUpdates_empty() { for (final Notification.Type type : Notification.Type.values()) { assertThat(subject.getUpdates(type), hasSize(0)); } }
### Question: Notification { public boolean has(final Type type) { return !updates.get(type).isEmpty(); } Notification(final String email); void add(final Type type, final PreparedUpdate update, UpdateContext updateContext); String getEmail(); Set<Update> getUpdates(final Type type); boolean has(final Type type); }### Answer: @Test public void has_empty() { for (final Notification.Type type : Notification.Type.values()) { assertThat(subject.has(type), is(false)); } }
### Question: 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); }### Answer: @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")); }
### Question: Credentials { public boolean has(final Class<? extends Credential> clazz) { return !ofType(clazz).isEmpty(); } Credentials(); Credentials(final Set<? extends Credential> credentials); Credentials add(final Collection<Credential> addedCredentials); Set<Credential> all(); T single(final Class<T> clazz); Set<T> ofType(final Class<T> clazz); boolean has(final Class<? extends Credential> clazz); }### Answer: @Test public void pgp_credentials() { final Credential credential1 = Mockito.mock(Credential.class); final Credential credential2 = Mockito.mock(Credential.class); final PgpCredential pgpCredential = Mockito.mock(PgpCredential.class); final Credentials subject = new Credentials(Sets.newHashSet(credential1, credential2, pgpCredential)); assertThat(subject.has(PgpCredential.class), is(true)); }
### Question: Update implements UpdateContainer { public boolean isSigned() { return paragraph.getCredentials().has(PgpCredential.class) || paragraph.getCredentials().has(X509Credential.class); } Update(final Paragraph paragraph, final Operation operation, @Nullable final List<String> deleteReasons, final RpslObject submittedObject); @Override Update getUpdate(); Paragraph getParagraph(); Operation getOperation(); @Nullable List<String> getDeleteReasons(); ObjectType getType(); RpslObject getSubmittedObject(); boolean isSigned(); boolean isOverride(); Credentials getCredentials(); @Override String toString(); void setEffectiveCredential(final String effectiveCredential, final EffectiveCredentialType effectiveCredentialType); String getEffectiveCredential(); EffectiveCredentialType getEffectiveCredentialType(); }### Answer: @Test public void is_signed_with_one_pgp_credential() { final Paragraph paragraph = new Paragraph(content, new Credentials(Sets.newHashSet(PgpCredential.createKnownCredential("PGPKEY-AAAAAAAA")))); Update subject = new Update(paragraph, Operation.UNSPECIFIED, Lists.<String>newArrayList(), rpslObject); assertThat(subject.isSigned(), is(true)); } @Test public void is_signed_with_one_x509_credential() { final Paragraph paragraph = new Paragraph(content, new Credentials(Sets.newHashSet(X509Credential.createKnownCredential("X509-1")))); Update subject = new Update(paragraph, Operation.UNSPECIFIED, Lists.<String>newArrayList(), rpslObject); assertThat(subject.isSigned(), is(true)); } @Test public void is_not_signed_with_one_password_credential() { final Paragraph paragraph = new Paragraph(content, new Credentials(Sets.newHashSet(new PasswordCredential("password")))); Update subject = new Update(paragraph, Operation.UNSPECIFIED, Lists.<String>newArrayList(), rpslObject); assertThat(subject.isSigned(), is(false)); }
### Question: Update implements UpdateContainer { public boolean isOverride() { return paragraph.getCredentials().has(OverrideCredential.class); } Update(final Paragraph paragraph, final Operation operation, @Nullable final List<String> deleteReasons, final RpslObject submittedObject); @Override Update getUpdate(); Paragraph getParagraph(); Operation getOperation(); @Nullable List<String> getDeleteReasons(); ObjectType getType(); RpslObject getSubmittedObject(); boolean isSigned(); boolean isOverride(); Credentials getCredentials(); @Override String toString(); void setEffectiveCredential(final String effectiveCredential, final EffectiveCredentialType effectiveCredentialType); String getEffectiveCredential(); EffectiveCredentialType getEffectiveCredentialType(); }### Answer: @Test public void is_override() { final Paragraph paragraph = new Paragraph(content, new Credentials(Sets.newHashSet(OverrideCredential.parse("username,password")))); Update subject = new Update(paragraph, Operation.UNSPECIFIED, Lists.<String>newArrayList(), rpslObject); assertThat(subject.isOverride(), is(true)); } @Test public void is_not_override() { final Paragraph paragraph = new Paragraph(content, new Credentials(Sets.newHashSet(new PasswordCredential("password")))); Update subject = new Update(paragraph, Operation.UNSPECIFIED, Lists.<String>newArrayList(), rpslObject); assertThat(subject.isOverride(), is(false)); }
### Question: ProxyIterable implements Iterable<R> { @Override public Iterator<R> iterator() { return new Iterator<R>() { private final Iterator<P> sourceIterator = source.iterator(); private List<R> batch = initialBatch; private int idx; @Override public boolean hasNext() { return idx < batch.size() || sourceIterator.hasNext(); } @Override public R next() { if (idx == batch.size()) { idx = 0; batch = load(nextBatch(sourceIterator)); } if (idx >= batch.size()) { throw new NoSuchElementException(); } return batch.get(idx++); } @Override public void remove() { throw new UnsupportedOperationException(); } }; } ProxyIterable(final Iterable<P> source, final ProxyLoader<P, R> loader, final int prefetch); @Override Iterator<R> iterator(); }### Answer: @Test(expected = UnsupportedOperationException.class) public void test_remove() throws Exception { ProxyLoader<Integer, String> proxyLoader = Mockito.mock(ProxyLoader.class); subject = new ProxyIterable<>(Collections.<Integer>emptyList(), proxyLoader, 1); subject.iterator().remove(); } @Test(expected = NoSuchElementException.class) public void test_empty_next() { ProxyLoader<Integer, String> proxyLoader = Mockito.mock(ProxyLoader.class); subject = new ProxyIterable<>(Collections.<Integer>emptyList(), proxyLoader, 1); subject.iterator().next(); } @Test public void test_load_empty() { ProxyLoader<Integer, String> proxyLoader = Mockito.mock(ProxyLoader.class); subject = new ProxyIterable<>(Arrays.asList(1, 2, 3), proxyLoader, 1); final Iterator<String> iterator = subject.iterator(); assertTrue(iterator.hasNext()); assertNull(iterator.next()); }
### Question: NrtmConnectionPerIpLimitHandler extends SimpleChannelUpstreamHandler { private boolean connectionsExceeded(final InetAddress remoteAddresss) { final Integer count = connectionCounter.increment(remoteAddresss); return (count != null && count > maxConnectionsPerIp); } @Autowired NrtmConnectionPerIpLimitHandler( @Value("${whois.limit.connectionsPerIp:3}") final int maxConnectionsPerIp, final NrtmLog nrtmLog); @Override void channelOpen(final ChannelHandlerContext ctx, final ChannelStateEvent e); @Override void channelClosed(final ChannelHandlerContext ctx, final ChannelStateEvent e); }### Answer: @Test public void multiple_connected_same_ip() throws Exception { final InetSocketAddress remoteAddress = new InetSocketAddress("10.0.0.0", 43); when(channel.getRemoteAddress()).thenReturn(remoteAddress); final ChannelEvent openEvent = new UpstreamChannelStateEvent(channel, ChannelState.OPEN, Boolean.TRUE); subject.handleUpstream(ctx, openEvent); subject.handleUpstream(ctx, openEvent); subject.handleUpstream(ctx, openEvent); verify(ctx, times(2)).sendUpstream(openEvent); verify(channel, times(1)).write(argThat(new ArgumentMatcher<Object>() { @Override public boolean matches(Object argument) { return NrtmMessages.connectionsExceeded(MAX_CONNECTIONS_PER_IP).equals(argument); } })); verify(channelFuture, times(1)).addListener(ChannelFutureListener.CLOSE); verify(nrtmLog).log(Inet4Address.getByName("10.0.0.0"), "REJECTED"); verify(ctx, times(2)).sendUpstream(openEvent); }
### Question: SocketChannelFactory { public static Reader createReader(final SocketChannel socketChannel) { return new Reader(socketChannel); } private SocketChannelFactory(); static SocketChannel createSocketChannel(final String host, final int port); static Reader createReader(final SocketChannel socketChannel); static Writer createWriter(final SocketChannel socketChannel); }### Answer: @Test public void read_one_line() throws Exception { mockRead("aaa\n"); SocketChannelFactory.Reader reader = SocketChannelFactory.createReader(socketChannel); assertThat(reader.readLine(), is("aaa")); } @Test public void read_empty_line() throws Exception { mockRead("\n"); SocketChannelFactory.Reader reader = SocketChannelFactory.createReader(socketChannel); assertThat(reader.readLine(), is("")); } @Test public void read_multiple_lines() throws Exception { mockRead("aaa\nbbb\nccc\n"); SocketChannelFactory.Reader reader = SocketChannelFactory.createReader(socketChannel); assertThat(reader.readLine(), is("aaa")); assertThat(reader.readLine(), is("bbb")); assertThat(reader.readLine(), is("ccc")); }
### Question: SocketChannelFactory { public static Writer createWriter(final SocketChannel socketChannel) { return new Writer(socketChannel); } private SocketChannelFactory(); static SocketChannel createSocketChannel(final String host, final int port); static Reader createReader(final SocketChannel socketChannel); static Writer createWriter(final SocketChannel socketChannel); }### Answer: @Test public void write_line() throws Exception { mockWrite("aaa\n"); SocketChannelFactory.Writer writer = SocketChannelFactory.createWriter(socketChannel); writer.writeLine("aaa"); }
### Question: NrtmImporter implements EmbeddedValueResolverAware, ApplicationService { @PostConstruct void checkSources() { for (final CIString source : sources) { if (sourceContext.isVirtual(source)) { throw new IllegalArgumentException(String.format("Cannot use NRTM with virtual source: %s", source)); } JdbcRpslObjectOperations.sanityCheck(sourceContext.getSourceConfiguration(Source.master(source)).getJdbcTemplate()); } } @Autowired NrtmImporter(final NrtmClientFactory nrtmClientFactory, final SourceContext sourceContext, @Value("${nrtm.import.enabled:false}") final boolean enabled, @Value("${nrtm.import.sources:}") final String sources); @Override void setEmbeddedValueResolver(final StringValueResolver resolver); @Override void start(); @Override void stop(final boolean force); }### Answer: @Test(expected = IllegalArgumentException.class) public void invalid_source() { when(sourceContext.isVirtual(CIString.ciString("1-GRS"))).thenReturn(true); subject.checkSources(); }
### Question: 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); }### Answer: @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)); }
### Question: NrtmQueryHandler extends SimpleChannelUpstreamHandler { @Override public void channelConnected(final ChannelHandlerContext ctx, final ChannelStateEvent e) throws Exception { PendingWrites.add(ctx.getChannel()); writeMessage(ctx.getChannel(), NrtmMessages.termsAndConditions()); super.channelConnected(ctx, e); } NrtmQueryHandler( @Qualifier("jdbcSlaveSerialDao") final SerialDao serialDao, @Qualifier("dummifierNrtm") final Dummifier dummifier, @Qualifier("clientSynchronisationScheduler") final TaskScheduler clientSynchronisationScheduler, final NrtmLog nrtmLog, final ApplicationVersion applicationVersion, @Value("${whois.source}") final String source, @Value("${whois.nonauth.source}") final String nonAuthSource, @Value("${nrtm.update.interval:60}") final long updateInterval, @Value("${nrtm.keepalive.end.of.stream:false}") final boolean keepaliveEndOfStream); @Override void messageReceived(final ChannelHandlerContext ctx, final MessageEvent e); @Override void channelConnected(final ChannelHandlerContext ctx, final ChannelStateEvent e); @Override void channelDisconnected(final ChannelHandlerContext ctx, final ChannelStateEvent e); }### Answer: @Test public void channelConnected() throws Exception { subject.channelConnected(contextMock, channelStateEventMock); verify(channelMock).write(NrtmMessages.termsAndConditions() + "\n\n"); }
### Question: NrtmExceptionHandler extends SimpleChannelUpstreamHandler { @Override public void exceptionCaught(final ChannelHandlerContext ctx, final ExceptionEvent event) { final Channel channel = event.getChannel(); final Throwable exception = event.getCause(); if (!channel.isOpen()) { return; } if (exception instanceof IllegalArgumentException) { channel.write(exception.getMessage() + "\n\n").addListener(ChannelFutureListener.CLOSE); } else if (exception instanceof IOException) { LOGGER.debug("IO exception", exception); } else { LOGGER.error("Caught exception on channel id = {}, from = {}", channel.getId(), ChannelUtil.getRemoteAddress(channel), exception ); channel.write(MESSAGE).addListener(ChannelFutureListener.CLOSE); } } @Override void exceptionCaught(final ChannelHandlerContext ctx, final ExceptionEvent event); }### Answer: @Test public void handle_illegal_argument_exception() { when(exceptionEventMock.getCause()).thenReturn(new IllegalArgumentException(QUERY)); subject.exceptionCaught(channelHandlerContextMock, exceptionEventMock); verify(channelMock, times(1)).write(QUERY + "\n\n"); verify(channelFutureMock, times(1)).addListener(ChannelFutureListener.CLOSE); } @Test public void handle_exception() { when(exceptionEventMock.getCause()).thenReturn(new Exception()); subject.exceptionCaught(channelHandlerContextMock, exceptionEventMock); verify(channelMock, times(1)).write(NrtmExceptionHandler.MESSAGE); verify(channelFutureMock, times(1)).addListener(ChannelFutureListener.CLOSE); }
### Question: CollectionHelper { public static <T> T uniqueResult(final Collection<T> c) { switch (c.size()) { case 0: return null; case 1: return c.iterator().next(); default: throw new IllegalStateException("Unexpected number of elements in collection: " + c.size()); } } private CollectionHelper(); static T uniqueResult(final Collection<T> c); static Iterable<ResponseObject> iterateProxy( final ProxyLoader<Identifiable, RpslObject> rpslObjectLoader, final Iterable<? extends Identifiable> identifiables); static final byte[] EMPTY_BYTE_ARRAY; }### Answer: @Test public void uniqueResult_no_results() { final Object result = CollectionHelper.uniqueResult(Arrays.asList()); assertNull(result); } @Test public void uniqueResult_single_result() { final Integer result = CollectionHelper.uniqueResult(Arrays.asList(1)); assertThat(result, is(1)); } @Test(expected = IllegalStateException.class) public void uniqueResult_multiple_results() { CollectionHelper.uniqueResult(Arrays.asList(1, 2)); }
### Question: 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); }### Answer: @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)); }
### Question: 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; }### Answer: @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)); }
### Question: 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(); }### Answer: @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")); }
### Question: IndexStrategyAdapter implements IndexStrategy { @Override public final AttributeType getAttributeType() { return attributeType; } IndexStrategyAdapter(final AttributeType attributeType); @Override final AttributeType getAttributeType(); @Override final int addToIndex(final JdbcTemplate jdbcTemplate, final RpslObjectInfo objectInfo, final RpslObject object, final CIString value); @Override int addToIndex(final JdbcTemplate jdbcTemplate, final RpslObjectInfo objectInfo, final RpslObject object, final String value); @Override final List<RpslObjectInfo> findInIndex(final JdbcTemplate jdbcTemplate, final CIString value); @Override List<RpslObjectInfo> findInIndex(final JdbcTemplate jdbcTemplate, final String value); @Override final List<RpslObjectInfo> findInIndex(final JdbcTemplate jdbcTemplate, final CIString value, final ObjectType type); @Override List<RpslObjectInfo> findInIndex(final JdbcTemplate jdbcTemplate, final String value, final ObjectType type); @Override List<RpslObjectInfo> findInIndex(final JdbcTemplate jdbcTemplate, final RpslObjectInfo value); @Override List<RpslObjectInfo> findInIndex(final JdbcTemplate jdbcTemplate, final RpslObjectInfo value, final ObjectType type); @Override void removeFromIndex(final JdbcTemplate jdbcTemplate, final RpslObjectInfo objectInfo); @Override String getLookupTableName(); @Override void cleanupMissingObjects(final JdbcTemplate jdbcTemplate); @Override String getLookupColumnName(); }### Answer: @Test public void getAttributeType() { assertThat(subject.getAttributeType(), is(ATTRIBUTE_TYPE)); }
### Question: IndexStrategyAdapter implements IndexStrategy { @Override public final int addToIndex(final JdbcTemplate jdbcTemplate, final RpslObjectInfo objectInfo, final RpslObject object, final CIString value) { return addToIndex(jdbcTemplate, objectInfo, object, value.toString()); } IndexStrategyAdapter(final AttributeType attributeType); @Override final AttributeType getAttributeType(); @Override final int addToIndex(final JdbcTemplate jdbcTemplate, final RpslObjectInfo objectInfo, final RpslObject object, final CIString value); @Override int addToIndex(final JdbcTemplate jdbcTemplate, final RpslObjectInfo objectInfo, final RpslObject object, final String value); @Override final List<RpslObjectInfo> findInIndex(final JdbcTemplate jdbcTemplate, final CIString value); @Override List<RpslObjectInfo> findInIndex(final JdbcTemplate jdbcTemplate, final String value); @Override final List<RpslObjectInfo> findInIndex(final JdbcTemplate jdbcTemplate, final CIString value, final ObjectType type); @Override List<RpslObjectInfo> findInIndex(final JdbcTemplate jdbcTemplate, final String value, final ObjectType type); @Override List<RpslObjectInfo> findInIndex(final JdbcTemplate jdbcTemplate, final RpslObjectInfo value); @Override List<RpslObjectInfo> findInIndex(final JdbcTemplate jdbcTemplate, final RpslObjectInfo value, final ObjectType type); @Override void removeFromIndex(final JdbcTemplate jdbcTemplate, final RpslObjectInfo objectInfo); @Override String getLookupTableName(); @Override void cleanupMissingObjects(final JdbcTemplate jdbcTemplate); @Override String getLookupColumnName(); }### Answer: @Test public void addToIndex() { assertThat(subject.addToIndex(null, null, null, (String) null), is(1)); }
### Question: IndexStrategyAdapter implements IndexStrategy { @Override public final List<RpslObjectInfo> findInIndex(final JdbcTemplate jdbcTemplate, final CIString value) { return findInIndex(jdbcTemplate, value.toString()); } IndexStrategyAdapter(final AttributeType attributeType); @Override final AttributeType getAttributeType(); @Override final int addToIndex(final JdbcTemplate jdbcTemplate, final RpslObjectInfo objectInfo, final RpslObject object, final CIString value); @Override int addToIndex(final JdbcTemplate jdbcTemplate, final RpslObjectInfo objectInfo, final RpslObject object, final String value); @Override final List<RpslObjectInfo> findInIndex(final JdbcTemplate jdbcTemplate, final CIString value); @Override List<RpslObjectInfo> findInIndex(final JdbcTemplate jdbcTemplate, final String value); @Override final List<RpslObjectInfo> findInIndex(final JdbcTemplate jdbcTemplate, final CIString value, final ObjectType type); @Override List<RpslObjectInfo> findInIndex(final JdbcTemplate jdbcTemplate, final String value, final ObjectType type); @Override List<RpslObjectInfo> findInIndex(final JdbcTemplate jdbcTemplate, final RpslObjectInfo value); @Override List<RpslObjectInfo> findInIndex(final JdbcTemplate jdbcTemplate, final RpslObjectInfo value, final ObjectType type); @Override void removeFromIndex(final JdbcTemplate jdbcTemplate, final RpslObjectInfo objectInfo); @Override String getLookupTableName(); @Override void cleanupMissingObjects(final JdbcTemplate jdbcTemplate); @Override String getLookupColumnName(); }### Answer: @Test public void findInIndex() { assertThat(subject.findInIndex(null, (String) null), hasSize(0)); assertThat(subject.findInIndex(null, new RpslObjectInfo(1, ObjectType.AUT_NUM, "AS000")), hasSize(0)); assertThat(subject.findInIndex(null, new RpslObjectInfo(1, ObjectType.AUT_NUM, "AS000"), ObjectType.AUT_NUM), hasSize(0)); }
### Question: IndexStrategyAdapter implements IndexStrategy { @Override public void removeFromIndex(final JdbcTemplate jdbcTemplate, final RpslObjectInfo objectInfo) { } IndexStrategyAdapter(final AttributeType attributeType); @Override final AttributeType getAttributeType(); @Override final int addToIndex(final JdbcTemplate jdbcTemplate, final RpslObjectInfo objectInfo, final RpslObject object, final CIString value); @Override int addToIndex(final JdbcTemplate jdbcTemplate, final RpslObjectInfo objectInfo, final RpslObject object, final String value); @Override final List<RpslObjectInfo> findInIndex(final JdbcTemplate jdbcTemplate, final CIString value); @Override List<RpslObjectInfo> findInIndex(final JdbcTemplate jdbcTemplate, final String value); @Override final List<RpslObjectInfo> findInIndex(final JdbcTemplate jdbcTemplate, final CIString value, final ObjectType type); @Override List<RpslObjectInfo> findInIndex(final JdbcTemplate jdbcTemplate, final String value, final ObjectType type); @Override List<RpslObjectInfo> findInIndex(final JdbcTemplate jdbcTemplate, final RpslObjectInfo value); @Override List<RpslObjectInfo> findInIndex(final JdbcTemplate jdbcTemplate, final RpslObjectInfo value, final ObjectType type); @Override void removeFromIndex(final JdbcTemplate jdbcTemplate, final RpslObjectInfo objectInfo); @Override String getLookupTableName(); @Override void cleanupMissingObjects(final JdbcTemplate jdbcTemplate); @Override String getLookupColumnName(); }### Answer: @Test public void removeFromIndex() { subject.removeFromIndex(null, null); }
### Question: IndexStrategyAdapter implements IndexStrategy { @Override public String getLookupTableName() { return null; } IndexStrategyAdapter(final AttributeType attributeType); @Override final AttributeType getAttributeType(); @Override final int addToIndex(final JdbcTemplate jdbcTemplate, final RpslObjectInfo objectInfo, final RpslObject object, final CIString value); @Override int addToIndex(final JdbcTemplate jdbcTemplate, final RpslObjectInfo objectInfo, final RpslObject object, final String value); @Override final List<RpslObjectInfo> findInIndex(final JdbcTemplate jdbcTemplate, final CIString value); @Override List<RpslObjectInfo> findInIndex(final JdbcTemplate jdbcTemplate, final String value); @Override final List<RpslObjectInfo> findInIndex(final JdbcTemplate jdbcTemplate, final CIString value, final ObjectType type); @Override List<RpslObjectInfo> findInIndex(final JdbcTemplate jdbcTemplate, final String value, final ObjectType type); @Override List<RpslObjectInfo> findInIndex(final JdbcTemplate jdbcTemplate, final RpslObjectInfo value); @Override List<RpslObjectInfo> findInIndex(final JdbcTemplate jdbcTemplate, final RpslObjectInfo value, final ObjectType type); @Override void removeFromIndex(final JdbcTemplate jdbcTemplate, final RpslObjectInfo objectInfo); @Override String getLookupTableName(); @Override void cleanupMissingObjects(final JdbcTemplate jdbcTemplate); @Override String getLookupColumnName(); }### Answer: @Test public void getLookupTableName() { assertNull(subject.getLookupTableName()); }
### Question: IndexStrategyAdapter implements IndexStrategy { @Override public String getLookupColumnName() { return null; } IndexStrategyAdapter(final AttributeType attributeType); @Override final AttributeType getAttributeType(); @Override final int addToIndex(final JdbcTemplate jdbcTemplate, final RpslObjectInfo objectInfo, final RpslObject object, final CIString value); @Override int addToIndex(final JdbcTemplate jdbcTemplate, final RpslObjectInfo objectInfo, final RpslObject object, final String value); @Override final List<RpslObjectInfo> findInIndex(final JdbcTemplate jdbcTemplate, final CIString value); @Override List<RpslObjectInfo> findInIndex(final JdbcTemplate jdbcTemplate, final String value); @Override final List<RpslObjectInfo> findInIndex(final JdbcTemplate jdbcTemplate, final CIString value, final ObjectType type); @Override List<RpslObjectInfo> findInIndex(final JdbcTemplate jdbcTemplate, final String value, final ObjectType type); @Override List<RpslObjectInfo> findInIndex(final JdbcTemplate jdbcTemplate, final RpslObjectInfo value); @Override List<RpslObjectInfo> findInIndex(final JdbcTemplate jdbcTemplate, final RpslObjectInfo value, final ObjectType type); @Override void removeFromIndex(final JdbcTemplate jdbcTemplate, final RpslObjectInfo objectInfo); @Override String getLookupTableName(); @Override void cleanupMissingObjects(final JdbcTemplate jdbcTemplate); @Override String getLookupColumnName(); }### Answer: @Test public void getLookupColumnName() { assertNull(subject.getLookupColumnName()); }
### Question: IndexStrategies { public static IndexStrategy get(final AttributeType attributeType) { return INDEX_BY_ATTRIBUTE.get(attributeType); } private IndexStrategies(); static IndexStrategy get(final AttributeType attributeType); static List<IndexStrategy> getReferencing(final ObjectType objectType); }### Answer: @Test public void check_index_strategied_for_lookup_attributes() { final Set<AttributeType> attibutesWithrequiredIndex = Sets.newHashSet(); for (final ObjectType objectType : ObjectType.values()) { final ObjectTemplate objectTemplate = ObjectTemplate.getTemplate(objectType); attibutesWithrequiredIndex.addAll(objectTemplate.getInverseLookupAttributes()); } for (final AttributeType attributeType : attibutesWithrequiredIndex) { assertThat(attributeType.getName(), IndexStrategies.get(attributeType) instanceof Unindexed, is(false)); } }
### Question: ObjectTypeIds { public static ObjectType getType(final int serialType) throws IllegalArgumentException { final ObjectType objectType = BY_TYPE_ID.get(serialType); if (objectType == null) { throw new IllegalArgumentException("Object type with objectTypeId " + serialType + " not found"); } return objectType; } private ObjectTypeIds(); static Integer getId(final ObjectType objectType); static ObjectType getType(final int serialType); }### Answer: @Test public void getBySerialType() { for (Integer objectTypeId : ImmutableList.of(0, 1, 2, 3, 4, 5, 6, 7, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21)) { assertThat(ObjectTypeIds.getType(objectTypeId), Matchers.instanceOf(ObjectType.class)); } } @Test(expected = IllegalArgumentException.class) public void getBySerialType_unknown() { ObjectTypeIds.getType(-1000); }
### Question: SourceAwareDataSource extends AbstractDataSource { @Override public Connection getConnection() throws SQLException { return getActualDataSource().getConnection(); } @Autowired SourceAwareDataSource(final BasicSourceContext sourceContext); @Override Connection getConnection(); @Override Connection getConnection(final String username, final String password); }### Answer: @Test public void test_getConnection() throws Exception { subject.getConnection(); verify(dataSource, times(1)).getConnection(); } @Test public void test_getConnection_with_user() throws Exception { subject.getConnection("username", "password"); verify(dataSource, times(1)).getConnection("username", "password"); }
### Question: 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); }### Answer: @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)); }
### Question: 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); }### Answer: @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"); }
### Question: DateUtil { public static LocalDateTime fromDate(final Date date) { return Instant.ofEpochMilli(date.getTime()) .atZone(ZoneOffset.systemDefault()) .toLocalDateTime(); } private DateUtil(); static Date toDate(final LocalDateTime localDateTime); static Date toDate(final LocalDate localDate); static LocalDateTime fromDate(final Date date); }### Answer: @Test public void fromDate() { assertThat(DateUtil.fromDate(new Date(EPOCH_TIMESTAMP)), is(EPOCH_LOCAL_DATE_TIME)); assertThat(DateUtil.fromDate(new Date(RECENT_TIMESTAMP)), is(RECENT_LOCAL_DATE_TIME)); }
### Question: DateUtil { public static Date toDate(final LocalDateTime localDateTime) { return Date.from(localDateTime.atZone(ZoneOffset.systemDefault()) .toInstant()); } private DateUtil(); static Date toDate(final LocalDateTime localDateTime); static Date toDate(final LocalDate localDate); static LocalDateTime fromDate(final Date date); }### Answer: @Test public void toDate() { assertThat(DateUtil.toDate(EPOCH_LOCAL_DATE_TIME), is(new Date(EPOCH_TIMESTAMP))); assertThat(DateUtil.toDate(RECENT_LOCAL_DATE_TIME), is(new Date(RECENT_TIMESTAMP))); }
### Question: BlockEvent { @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; final BlockEvent that = (BlockEvent) o; return Objects.equals(time, that.time) && Objects.equals(type, that.type); } BlockEvent(final LocalDateTime time, final int limit, final Type type); @Override boolean equals(Object o); @Override int hashCode(); LocalDateTime getTime(); int getLimit(); Type getType(); }### Answer: @Test public void equals() { final BlockEvent subject = new BlockEvent(LocalDateTime.of(2012, 2, 16, 12, 0), 1, BlockEvent.Type.BLOCK_TEMPORARY); final BlockEvent clone = new BlockEvent(LocalDateTime.of(2012, 2, 16, 12, 0), 1, BlockEvent.Type.BLOCK_TEMPORARY); final BlockEvent newDate = new BlockEvent(LocalDateTime.of(2011, 2, 16, 12, 0), 1, BlockEvent.Type.BLOCK_TEMPORARY); final BlockEvent newType = new BlockEvent(LocalDateTime.of(2012, 2, 16, 12, 0), 1, BlockEvent.Type.UNBLOCK); assertEquals("same", subject, subject); assertEquals("equal", subject, clone); assertEquals("hashcode", subject.hashCode(), clone.hashCode()); assertFalse("null", subject.equals(null)); assertFalse("different class", subject.equals(1)); assertFalse("different date", subject.equals(newDate)); assertFalse("different type", subject.equals(newType)); }
### Question: BlockEvents { public 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; }### Answer: @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)); }
### Question: BlockEvents { public boolean isPermanentBlockRequired() { return getTemporaryBlockCount() >= NR_TEMP_BLOCKS_BEFORE_PERMANENT; } BlockEvents(final String prefix, final List<BlockEvent> blockEvents); String getPrefix(); int getTemporaryBlockCount(); boolean isPermanentBlockRequired(); static final int NR_TEMP_BLOCKS_BEFORE_PERMANENT; }### Answer: @Test public void test_permanent_block_limit_reached_9() { final BlockEvents blockEvents = createBlockEvents(prefix, 9); assertThat(blockEvents.isPermanentBlockRequired(), is(false)); } @Test public void test_permanent_block_limit_reached_10() { final BlockEvents blockEvents = createBlockEvents(prefix, 10); assertThat(blockEvents.isPermanentBlockRequired(), is(true)); } @Test public void test_permanent_block_limit_reached_50() { final BlockEvents blockEvents = createBlockEvents(prefix, 50); assertThat(blockEvents.isPermanentBlockRequired(), is(true)); }
### Question: ConcurrentState { public void set(final Boolean value) { updates.add(value); } void set(final Boolean value); void waitUntil(final Boolean value); }### Answer: @Test public void set_and_unset_state() { Counter counter = new Counter(); new Thread(counter).start(); subject.set(true); waitForExpectedValue(counter, 1); subject.set(false); subject.set(false); subject.set(false); waitForExpectedValue(counter, 2); subject.set(true); waitForExpectedValue(counter, 3); } @Test public void set_and_unset_state_multiple_updates() { subject.set(true); subject.set(false); subject.set(false); subject.set(false); subject.set(true); Counter counter = new Counter(); new Thread(counter).start(); waitForExpectedValue(counter, 1); }
### Question: IpResourceTree { public V getValue(IpInterval<?> ipInterval) { List<V> list = getTree(ipInterval).findExactOrFirstLessSpecific(ipInterval); return CollectionHelper.uniqueResult(list); } @SuppressWarnings({"unchecked", "rawtypes"}) IpResourceTree(); void add(IpInterval<?> ipInterval, V value); V getValue(IpInterval<?> ipInterval); }### Answer: @Test public void test_getValue_ipv4_exact() { assertThat(subject.getValue(ipv4Resource), is(41)); } @Test public void test_getValue_ipv4_lessSpecific() { assertThat(subject.getValue(ipv4ResourceMoreSpecific), is(41)); } @Test public void test_getValue_ipv4_unknown() { assertThat(subject.getValue(ipv4ResourceUnknown), is(nullValue())); } @Test public void test_getValue_ipv6_exact() { assertThat(subject.getValue(ipv6Resource), is(61)); } @Test public void test_getValue_ipv6_lessSpecific() { assertThat(subject.getValue(ipv6ResourceMoreSpecific), is(61)); } @Test public void test_getValue_ipv6_unknown() { assertThat(subject.getValue(ipv6ResourceUnknown), is(nullValue())); }
### Question: 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); }### Answer: @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: hm-changed@apnic.net 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: hm-changed@apnic.net 20021220\n", "changed: hostmaster@twnic.net.tw 20050624\n", "source: APNIC\n") )); }
### Question: AutomaticPermanentBlocks implements DailyScheduledTask { @Override @Scheduled(cron = "0 0 0 * * *") @SchedulerLock(name = "AutomaticPermanentBlocks") public void run() { final LocalDate now = dateTimeProvider.getCurrentDate(); final LocalDate checkTemporaryBlockTime = now.minusDays(30); final List<BlockEvents> temporaryBlocks = accessControlListDao.getTemporaryBlocks(checkTemporaryBlockTime); for (final BlockEvents blockEvents : temporaryBlocks) { handleBlockEvents(now, blockEvents); } } @Autowired AutomaticPermanentBlocks(final DateTimeProvider dateTimeProvider, final AccessControlListDao accessControlListDao, final IpResourceConfiguration ipResourceConfiguration); @Override @Scheduled(cron = "0 0 0 * * *") @SchedulerLock(name = "AutomaticPermanentBlocks") void run(); }### Answer: @Test public void test_date() throws Exception { subject.run(); verify(accessControlListDao, times(1)).getTemporaryBlocks(now.minusDays(30)); } @Test public void test_run_no_temporary_blocks() throws Exception { when(accessControlListDao.getTemporaryBlocks(now)).thenReturn(Collections.<BlockEvents>emptyList()); subject.run(); verify(accessControlListDao, never()).savePermanentBlock(any(IpInterval.class), any(LocalDate.class), anyInt(), anyString()); } @Test public void test_run_temporary_blocks_already_denied() throws Exception { when(accessControlListDao.getTemporaryBlocks(now.minusDays(30))).thenReturn(Arrays.asList(createBlockEvents(IPV4_PREFIX, 20))); when(ipResourceConfiguration.isDenied(any(InetAddress.class))).thenReturn(true); subject.run(); verify(ipResourceConfiguration).isDenied(any(InetAddress.class)); verify(accessControlListDao, never()).savePermanentBlock(any(IpInterval.class), any(LocalDate.class), anyInt(), anyString()); }
### Question: SynchronizedIntervalMap implements IntervalMap<K, V> { @Override public void put(K key, V value) { synchronized (mutex) { wrapped.put(key, value); } } private SynchronizedIntervalMap(final IntervalMap<K, V> wrapped); private SynchronizedIntervalMap(final IntervalMap<K, V> wrapped, final Object mutex); static IntervalMap<K, V> synchronizedMap(IntervalMap<K, V> toWrap); static IntervalMap<K, V> synchronizedMap(IntervalMap<K, V> toWrap, final Object mutex); @Override void put(K key, V value); @Override void remove(K key); @Override void remove(K key, V value); @Override List<V> findFirstLessSpecific(K key); @Override List<V> findAllLessSpecific(K key); @Override List<V> findExactAndAllLessSpecific(K key); @Override List<V> findExact(K key); @Override List<V> findExactOrFirstLessSpecific(K key); @Override List<V> findFirstMoreSpecific(K key); @Override List<V> findAllMoreSpecific(K key); @Override List<V> findExactAndAllMoreSpecific(K key); @Override void clear(); }### Answer: @Test public void put() { subject.put(key, value); verify(wrapped, times(1)).put(key, value); }
### Question: SynchronizedIntervalMap implements IntervalMap<K, V> { @Override public void remove(K key) { synchronized (mutex) { wrapped.remove(key); } } private SynchronizedIntervalMap(final IntervalMap<K, V> wrapped); private SynchronizedIntervalMap(final IntervalMap<K, V> wrapped, final Object mutex); static IntervalMap<K, V> synchronizedMap(IntervalMap<K, V> toWrap); static IntervalMap<K, V> synchronizedMap(IntervalMap<K, V> toWrap, final Object mutex); @Override void put(K key, V value); @Override void remove(K key); @Override void remove(K key, V value); @Override List<V> findFirstLessSpecific(K key); @Override List<V> findAllLessSpecific(K key); @Override List<V> findExactAndAllLessSpecific(K key); @Override List<V> findExact(K key); @Override List<V> findExactOrFirstLessSpecific(K key); @Override List<V> findFirstMoreSpecific(K key); @Override List<V> findAllMoreSpecific(K key); @Override List<V> findExactAndAllMoreSpecific(K key); @Override void clear(); }### Answer: @Test public void remove() { subject.remove(key); verify(wrapped, times(1)).remove(key); } @Test public void remove_with_value() { subject.remove(key, value); verify(wrapped, times(1)).remove(key, value); }
### Question: SynchronizedIntervalMap implements IntervalMap<K, V> { @Override public List<V> findFirstLessSpecific(K key) { synchronized (mutex) { return wrapped.findFirstLessSpecific(key); } } private SynchronizedIntervalMap(final IntervalMap<K, V> wrapped); private SynchronizedIntervalMap(final IntervalMap<K, V> wrapped, final Object mutex); static IntervalMap<K, V> synchronizedMap(IntervalMap<K, V> toWrap); static IntervalMap<K, V> synchronizedMap(IntervalMap<K, V> toWrap, final Object mutex); @Override void put(K key, V value); @Override void remove(K key); @Override void remove(K key, V value); @Override List<V> findFirstLessSpecific(K key); @Override List<V> findAllLessSpecific(K key); @Override List<V> findExactAndAllLessSpecific(K key); @Override List<V> findExact(K key); @Override List<V> findExactOrFirstLessSpecific(K key); @Override List<V> findFirstMoreSpecific(K key); @Override List<V> findAllMoreSpecific(K key); @Override List<V> findExactAndAllMoreSpecific(K key); @Override void clear(); }### Answer: @Test public void findFirstLessSpecific() { subject.findFirstLessSpecific(key); verify(wrapped, times(1)).findFirstLessSpecific(key); }
### Question: SynchronizedIntervalMap implements IntervalMap<K, V> { @Override public List<V> findAllLessSpecific(K key) { synchronized (mutex) { return wrapped.findAllLessSpecific(key); } } private SynchronizedIntervalMap(final IntervalMap<K, V> wrapped); private SynchronizedIntervalMap(final IntervalMap<K, V> wrapped, final Object mutex); static IntervalMap<K, V> synchronizedMap(IntervalMap<K, V> toWrap); static IntervalMap<K, V> synchronizedMap(IntervalMap<K, V> toWrap, final Object mutex); @Override void put(K key, V value); @Override void remove(K key); @Override void remove(K key, V value); @Override List<V> findFirstLessSpecific(K key); @Override List<V> findAllLessSpecific(K key); @Override List<V> findExactAndAllLessSpecific(K key); @Override List<V> findExact(K key); @Override List<V> findExactOrFirstLessSpecific(K key); @Override List<V> findFirstMoreSpecific(K key); @Override List<V> findAllMoreSpecific(K key); @Override List<V> findExactAndAllMoreSpecific(K key); @Override void clear(); }### Answer: @Test public void findAllLessSpecific() { subject.findAllLessSpecific(key); verify(wrapped, times(1)).findAllLessSpecific(key); }
### Question: SynchronizedIntervalMap implements IntervalMap<K, V> { @Override public List<V> findExactAndAllLessSpecific(K key) { synchronized (mutex) { return wrapped.findExactAndAllLessSpecific(key); } } private SynchronizedIntervalMap(final IntervalMap<K, V> wrapped); private SynchronizedIntervalMap(final IntervalMap<K, V> wrapped, final Object mutex); static IntervalMap<K, V> synchronizedMap(IntervalMap<K, V> toWrap); static IntervalMap<K, V> synchronizedMap(IntervalMap<K, V> toWrap, final Object mutex); @Override void put(K key, V value); @Override void remove(K key); @Override void remove(K key, V value); @Override List<V> findFirstLessSpecific(K key); @Override List<V> findAllLessSpecific(K key); @Override List<V> findExactAndAllLessSpecific(K key); @Override List<V> findExact(K key); @Override List<V> findExactOrFirstLessSpecific(K key); @Override List<V> findFirstMoreSpecific(K key); @Override List<V> findAllMoreSpecific(K key); @Override List<V> findExactAndAllMoreSpecific(K key); @Override void clear(); }### Answer: @Test public void findExactAndAllLessSpecific() { subject.findExactAndAllLessSpecific(key); verify(wrapped, times(1)).findExactAndAllLessSpecific(key); }
### Question: SynchronizedIntervalMap implements IntervalMap<K, V> { @Override public List<V> findExact(K key) { synchronized (mutex) { return wrapped.findExact(key); } } private SynchronizedIntervalMap(final IntervalMap<K, V> wrapped); private SynchronizedIntervalMap(final IntervalMap<K, V> wrapped, final Object mutex); static IntervalMap<K, V> synchronizedMap(IntervalMap<K, V> toWrap); static IntervalMap<K, V> synchronizedMap(IntervalMap<K, V> toWrap, final Object mutex); @Override void put(K key, V value); @Override void remove(K key); @Override void remove(K key, V value); @Override List<V> findFirstLessSpecific(K key); @Override List<V> findAllLessSpecific(K key); @Override List<V> findExactAndAllLessSpecific(K key); @Override List<V> findExact(K key); @Override List<V> findExactOrFirstLessSpecific(K key); @Override List<V> findFirstMoreSpecific(K key); @Override List<V> findAllMoreSpecific(K key); @Override List<V> findExactAndAllMoreSpecific(K key); @Override void clear(); }### Answer: @Test public void findExact() { subject.findExact(key); verify(wrapped, times(1)).findExact(key); }
### Question: SynchronizedIntervalMap implements IntervalMap<K, V> { @Override public List<V> findExactOrFirstLessSpecific(K key) { synchronized (mutex) { return wrapped.findExactOrFirstLessSpecific(key); } } private SynchronizedIntervalMap(final IntervalMap<K, V> wrapped); private SynchronizedIntervalMap(final IntervalMap<K, V> wrapped, final Object mutex); static IntervalMap<K, V> synchronizedMap(IntervalMap<K, V> toWrap); static IntervalMap<K, V> synchronizedMap(IntervalMap<K, V> toWrap, final Object mutex); @Override void put(K key, V value); @Override void remove(K key); @Override void remove(K key, V value); @Override List<V> findFirstLessSpecific(K key); @Override List<V> findAllLessSpecific(K key); @Override List<V> findExactAndAllLessSpecific(K key); @Override List<V> findExact(K key); @Override List<V> findExactOrFirstLessSpecific(K key); @Override List<V> findFirstMoreSpecific(K key); @Override List<V> findAllMoreSpecific(K key); @Override List<V> findExactAndAllMoreSpecific(K key); @Override void clear(); }### Answer: @Test public void findExactOrFirstLessSpecific() { subject.findExactOrFirstLessSpecific(key); verify(wrapped, times(1)).findExactOrFirstLessSpecific(key); }
### Question: SynchronizedIntervalMap implements IntervalMap<K, V> { @Override public List<V> findFirstMoreSpecific(K key) { synchronized (mutex) { return wrapped.findFirstMoreSpecific(key); } } private SynchronizedIntervalMap(final IntervalMap<K, V> wrapped); private SynchronizedIntervalMap(final IntervalMap<K, V> wrapped, final Object mutex); static IntervalMap<K, V> synchronizedMap(IntervalMap<K, V> toWrap); static IntervalMap<K, V> synchronizedMap(IntervalMap<K, V> toWrap, final Object mutex); @Override void put(K key, V value); @Override void remove(K key); @Override void remove(K key, V value); @Override List<V> findFirstLessSpecific(K key); @Override List<V> findAllLessSpecific(K key); @Override List<V> findExactAndAllLessSpecific(K key); @Override List<V> findExact(K key); @Override List<V> findExactOrFirstLessSpecific(K key); @Override List<V> findFirstMoreSpecific(K key); @Override List<V> findAllMoreSpecific(K key); @Override List<V> findExactAndAllMoreSpecific(K key); @Override void clear(); }### Answer: @Test public void findFirstMoreSpecific() { subject.findFirstMoreSpecific(key); verify(wrapped, times(1)).findFirstMoreSpecific(key); }
### Question: SynchronizedIntervalMap implements IntervalMap<K, V> { @Override public List<V> findAllMoreSpecific(K key) { synchronized (mutex) { return wrapped.findAllMoreSpecific(key); } } private SynchronizedIntervalMap(final IntervalMap<K, V> wrapped); private SynchronizedIntervalMap(final IntervalMap<K, V> wrapped, final Object mutex); static IntervalMap<K, V> synchronizedMap(IntervalMap<K, V> toWrap); static IntervalMap<K, V> synchronizedMap(IntervalMap<K, V> toWrap, final Object mutex); @Override void put(K key, V value); @Override void remove(K key); @Override void remove(K key, V value); @Override List<V> findFirstLessSpecific(K key); @Override List<V> findAllLessSpecific(K key); @Override List<V> findExactAndAllLessSpecific(K key); @Override List<V> findExact(K key); @Override List<V> findExactOrFirstLessSpecific(K key); @Override List<V> findFirstMoreSpecific(K key); @Override List<V> findAllMoreSpecific(K key); @Override List<V> findExactAndAllMoreSpecific(K key); @Override void clear(); }### Answer: @Test public void findAllMoreSpecific() { subject.findAllMoreSpecific(key); verify(wrapped, times(1)).findAllMoreSpecific(key); }
### Question: 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); }### Answer: @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") )); }
### Question: SynchronizedIntervalMap implements IntervalMap<K, V> { @Override public List<V> findExactAndAllMoreSpecific(K key) { synchronized (mutex) { return wrapped.findExactAndAllMoreSpecific(key); } } private SynchronizedIntervalMap(final IntervalMap<K, V> wrapped); private SynchronizedIntervalMap(final IntervalMap<K, V> wrapped, final Object mutex); static IntervalMap<K, V> synchronizedMap(IntervalMap<K, V> toWrap); static IntervalMap<K, V> synchronizedMap(IntervalMap<K, V> toWrap, final Object mutex); @Override void put(K key, V value); @Override void remove(K key); @Override void remove(K key, V value); @Override List<V> findFirstLessSpecific(K key); @Override List<V> findAllLessSpecific(K key); @Override List<V> findExactAndAllLessSpecific(K key); @Override List<V> findExact(K key); @Override List<V> findExactOrFirstLessSpecific(K key); @Override List<V> findFirstMoreSpecific(K key); @Override List<V> findAllMoreSpecific(K key); @Override List<V> findExactAndAllMoreSpecific(K key); @Override void clear(); }### Answer: @Test public void findExactAndAllMoreSpecific() { subject.findExactAndAllMoreSpecific(key); verify(wrapped, times(1)).findExactAndAllMoreSpecific(key); }
### Question: SynchronizedIntervalMap implements IntervalMap<K, V> { @Override public void clear() { synchronized (mutex) { wrapped.clear(); } } private SynchronizedIntervalMap(final IntervalMap<K, V> wrapped); private SynchronizedIntervalMap(final IntervalMap<K, V> wrapped, final Object mutex); static IntervalMap<K, V> synchronizedMap(IntervalMap<K, V> toWrap); static IntervalMap<K, V> synchronizedMap(IntervalMap<K, V> toWrap, final Object mutex); @Override void put(K key, V value); @Override void remove(K key); @Override void remove(K key, V value); @Override List<V> findFirstLessSpecific(K key); @Override List<V> findAllLessSpecific(K key); @Override List<V> findExactAndAllLessSpecific(K key); @Override List<V> findExact(K key); @Override List<V> findExactOrFirstLessSpecific(K key); @Override List<V> findFirstMoreSpecific(K key); @Override List<V> findAllMoreSpecific(K key); @Override List<V> findExactAndAllMoreSpecific(K key); @Override void clear(); }### Answer: @Test public void clear() { subject.clear(); verify(wrapped, times(1)).clear(); }
### Question: InternalNode { void addChild(InternalNode<K, V> nodeToAdd) { if (interval.equals(nodeToAdd.getInterval())) { this.value = nodeToAdd.getValue(); } else if (!interval.contains(nodeToAdd.getInterval())) { throw new IllegalArgumentException(nodeToAdd.getInterval() + " not properly contained in " + interval); } else { if (children == ChildNodeTreeMap.EMPTY) { children = new ChildNodeTreeMap<>(); } children.addChild(nodeToAdd); } } InternalNode(K interval, V value); InternalNode(InternalNode<K, V> source); K getInterval(); V getValue(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); void removeChild(K range); }### Answer: @Test(expected = IllegalArgumentException.class) public void test_intersect_insert_fails() { c.addChild(e); }