method2testcases
stringlengths
118
6.63k
### Question: QueryMessages { public static Message internalErroroccurred() { return new QueryMessage(Type.ERROR, "" + "ERROR:100: internal software error\n" + "\n" + "Please contact ripe-dbm@ripe.net if the problem persists."); } private QueryMessages(); static Message termsAndConditions(); static Message servedByNotice(final CharSequence version); static Message termsAndConditionsDump(); static Message relatedTo(final CharSequence key); static Message noPersonal(); static Message abuseCShown(final CharSequence key, final CharSequence value); static Message unvalidatedAbuseCShown(final CharSequence key, final CharSequence value, final CharSequence orgId); static Message unvalidatedAbuseCShown(final CharSequence key, final CharSequence value); static Message abuseCNotRegistered(final CharSequence key); static Message outputFilterNotice(); static Message primaryKeysOnlyNotice(); static Message versionListStart(final CharSequence type, final CharSequence key); static Message versionInformation(final int version, final boolean isCurrentVersion, final CIString key, final String operation, final String timestamp); static Message versionDifferenceHeader(final int earlierVersion, final int laterVersion, final CIString key); static Message versionDeleted(final CharSequence deletionTime); static Message versionPersonRole(final CharSequence type, final CharSequence key); static Message internalErroroccurred(); static Message noResults(final CharSequence source); static Message unknownSource(final CharSequence source); static Message invalidObjectType(final CharSequence type); static Message invalidAttributeType(final CharSequence type); static Message attributeNotSearchable(final CharSequence type); static Message noSearchKeySpecified(); static Message inputTooLong(); static Message invalidCombinationOfFlags(final CharSequence flag, final CharSequence otherFlag); static Message invalidMultipleFlags(final CharSequence flag); static Message malformedQuery(); static Message malformedQuery(final String reason); static Message illegalRange(); static Message unsupportedQuery(); static Message invalidSearchKey(); static Message unsupportedVersionObjectType(); static Message versionOutOfRange(final int max); static Message tooManyArguments(); static Message accessDeniedPermanently(final InetAddress remoteAddress); static Message accessDeniedTemporarily(final InetAddress remoteAddress); static Message notAllowedToProxy(); static Message timeout(); static Message connectionsExceeded(final int connectionLimit); static Message duplicateIpFlagsPassed(); static Message uselessIpFlagPassed(); static Message tagInfoStart(final CharSequence pkey); static Message tagInfo(final CharSequence tagType, final CharSequence tagValue); static Message unreferencedTagInfo(final CharSequence pkey, final CharSequence value); static Message filterTagNote(final Set<? extends CharSequence> includeArgs, final Set<? extends CharSequence> excludeArgs); static Message invalidSyntax(final CharSequence objectKey); static Message validSyntax(final CharSequence objectKey); static Message inverseSearchNotAllowed(); static Message valueChangedDueToLatin1Conversion(); }### Answer: @Test public void internalErrorMessageShouldContainErrorCode() { assertThat(QueryMessages.internalErroroccurred().toString(), containsString("%ERROR:100:")); }
### Question: QueryMessages { public static Message noSearchKeySpecified() { return new QueryMessage(Type.ERROR, "" + "ERROR:106: no search key specified\n" + "\n" + "No search key specified"); } private QueryMessages(); static Message termsAndConditions(); static Message servedByNotice(final CharSequence version); static Message termsAndConditionsDump(); static Message relatedTo(final CharSequence key); static Message noPersonal(); static Message abuseCShown(final CharSequence key, final CharSequence value); static Message unvalidatedAbuseCShown(final CharSequence key, final CharSequence value, final CharSequence orgId); static Message unvalidatedAbuseCShown(final CharSequence key, final CharSequence value); static Message abuseCNotRegistered(final CharSequence key); static Message outputFilterNotice(); static Message primaryKeysOnlyNotice(); static Message versionListStart(final CharSequence type, final CharSequence key); static Message versionInformation(final int version, final boolean isCurrentVersion, final CIString key, final String operation, final String timestamp); static Message versionDifferenceHeader(final int earlierVersion, final int laterVersion, final CIString key); static Message versionDeleted(final CharSequence deletionTime); static Message versionPersonRole(final CharSequence type, final CharSequence key); static Message internalErroroccurred(); static Message noResults(final CharSequence source); static Message unknownSource(final CharSequence source); static Message invalidObjectType(final CharSequence type); static Message invalidAttributeType(final CharSequence type); static Message attributeNotSearchable(final CharSequence type); static Message noSearchKeySpecified(); static Message inputTooLong(); static Message invalidCombinationOfFlags(final CharSequence flag, final CharSequence otherFlag); static Message invalidMultipleFlags(final CharSequence flag); static Message malformedQuery(); static Message malformedQuery(final String reason); static Message illegalRange(); static Message unsupportedQuery(); static Message invalidSearchKey(); static Message unsupportedVersionObjectType(); static Message versionOutOfRange(final int max); static Message tooManyArguments(); static Message accessDeniedPermanently(final InetAddress remoteAddress); static Message accessDeniedTemporarily(final InetAddress remoteAddress); static Message notAllowedToProxy(); static Message timeout(); static Message connectionsExceeded(final int connectionLimit); static Message duplicateIpFlagsPassed(); static Message uselessIpFlagPassed(); static Message tagInfoStart(final CharSequence pkey); static Message tagInfo(final CharSequence tagType, final CharSequence tagValue); static Message unreferencedTagInfo(final CharSequence pkey, final CharSequence value); static Message filterTagNote(final Set<? extends CharSequence> includeArgs, final Set<? extends CharSequence> excludeArgs); static Message invalidSyntax(final CharSequence objectKey); static Message validSyntax(final CharSequence objectKey); static Message inverseSearchNotAllowed(); static Message valueChangedDueToLatin1Conversion(); }### Answer: @Test public void noSearchKeySpecifiedShouldContainError() { assertThat(QueryMessages.noSearchKeySpecified().toString(), containsString("%ERROR:106:")); }
### Question: QueryMessages { public static Message noResults(final CharSequence source) { return new QueryMessage(Type.ERROR, "" + "ERROR:101: no entries found\n" + "\n" + "No entries found in source %s.", source); } private QueryMessages(); static Message termsAndConditions(); static Message servedByNotice(final CharSequence version); static Message termsAndConditionsDump(); static Message relatedTo(final CharSequence key); static Message noPersonal(); static Message abuseCShown(final CharSequence key, final CharSequence value); static Message unvalidatedAbuseCShown(final CharSequence key, final CharSequence value, final CharSequence orgId); static Message unvalidatedAbuseCShown(final CharSequence key, final CharSequence value); static Message abuseCNotRegistered(final CharSequence key); static Message outputFilterNotice(); static Message primaryKeysOnlyNotice(); static Message versionListStart(final CharSequence type, final CharSequence key); static Message versionInformation(final int version, final boolean isCurrentVersion, final CIString key, final String operation, final String timestamp); static Message versionDifferenceHeader(final int earlierVersion, final int laterVersion, final CIString key); static Message versionDeleted(final CharSequence deletionTime); static Message versionPersonRole(final CharSequence type, final CharSequence key); static Message internalErroroccurred(); static Message noResults(final CharSequence source); static Message unknownSource(final CharSequence source); static Message invalidObjectType(final CharSequence type); static Message invalidAttributeType(final CharSequence type); static Message attributeNotSearchable(final CharSequence type); static Message noSearchKeySpecified(); static Message inputTooLong(); static Message invalidCombinationOfFlags(final CharSequence flag, final CharSequence otherFlag); static Message invalidMultipleFlags(final CharSequence flag); static Message malformedQuery(); static Message malformedQuery(final String reason); static Message illegalRange(); static Message unsupportedQuery(); static Message invalidSearchKey(); static Message unsupportedVersionObjectType(); static Message versionOutOfRange(final int max); static Message tooManyArguments(); static Message accessDeniedPermanently(final InetAddress remoteAddress); static Message accessDeniedTemporarily(final InetAddress remoteAddress); static Message notAllowedToProxy(); static Message timeout(); static Message connectionsExceeded(final int connectionLimit); static Message duplicateIpFlagsPassed(); static Message uselessIpFlagPassed(); static Message tagInfoStart(final CharSequence pkey); static Message tagInfo(final CharSequence tagType, final CharSequence tagValue); static Message unreferencedTagInfo(final CharSequence pkey, final CharSequence value); static Message filterTagNote(final Set<? extends CharSequence> includeArgs, final Set<? extends CharSequence> excludeArgs); static Message invalidSyntax(final CharSequence objectKey); static Message validSyntax(final CharSequence objectKey); static Message inverseSearchNotAllowed(); static Message valueChangedDueToLatin1Conversion(); }### Answer: @Test public void noResultsMessageShouldContainErrorCode() { assertThat(QueryMessages.noResults("RIPE").toString(), containsString("%ERROR:101:")); }
### Question: QueryMessages { public static Message accessDeniedPermanently(final InetAddress remoteAddress) { return new QueryMessage(Type.ERROR, "" + "ERROR:201: access denied for %s\n" + "\n" + "Sorry, access from your host has been permanently\n" + "denied because of a repeated excessive querying.\n" + "For more information, see\n" + "http: remoteAddress.getHostAddress()); } private QueryMessages(); static Message termsAndConditions(); static Message servedByNotice(final CharSequence version); static Message termsAndConditionsDump(); static Message relatedTo(final CharSequence key); static Message noPersonal(); static Message abuseCShown(final CharSequence key, final CharSequence value); static Message unvalidatedAbuseCShown(final CharSequence key, final CharSequence value, final CharSequence orgId); static Message unvalidatedAbuseCShown(final CharSequence key, final CharSequence value); static Message abuseCNotRegistered(final CharSequence key); static Message outputFilterNotice(); static Message primaryKeysOnlyNotice(); static Message versionListStart(final CharSequence type, final CharSequence key); static Message versionInformation(final int version, final boolean isCurrentVersion, final CIString key, final String operation, final String timestamp); static Message versionDifferenceHeader(final int earlierVersion, final int laterVersion, final CIString key); static Message versionDeleted(final CharSequence deletionTime); static Message versionPersonRole(final CharSequence type, final CharSequence key); static Message internalErroroccurred(); static Message noResults(final CharSequence source); static Message unknownSource(final CharSequence source); static Message invalidObjectType(final CharSequence type); static Message invalidAttributeType(final CharSequence type); static Message attributeNotSearchable(final CharSequence type); static Message noSearchKeySpecified(); static Message inputTooLong(); static Message invalidCombinationOfFlags(final CharSequence flag, final CharSequence otherFlag); static Message invalidMultipleFlags(final CharSequence flag); static Message malformedQuery(); static Message malformedQuery(final String reason); static Message illegalRange(); static Message unsupportedQuery(); static Message invalidSearchKey(); static Message unsupportedVersionObjectType(); static Message versionOutOfRange(final int max); static Message tooManyArguments(); static Message accessDeniedPermanently(final InetAddress remoteAddress); static Message accessDeniedTemporarily(final InetAddress remoteAddress); static Message notAllowedToProxy(); static Message timeout(); static Message connectionsExceeded(final int connectionLimit); static Message duplicateIpFlagsPassed(); static Message uselessIpFlagPassed(); static Message tagInfoStart(final CharSequence pkey); static Message tagInfo(final CharSequence tagType, final CharSequence tagValue); static Message unreferencedTagInfo(final CharSequence pkey, final CharSequence value); static Message filterTagNote(final Set<? extends CharSequence> includeArgs, final Set<? extends CharSequence> excludeArgs); static Message invalidSyntax(final CharSequence objectKey); static Message validSyntax(final CharSequence objectKey); static Message inverseSearchNotAllowed(); static Message valueChangedDueToLatin1Conversion(); }### Answer: @Test public void accessDeniedPermanentlyShouldContainErrorCode() throws UnknownHostException { assertThat(QueryMessages.accessDeniedPermanently(InetAddress.getLocalHost()).toString(), containsString("%ERROR:201:")); }
### Question: QueryMessages { public static Message accessDeniedTemporarily(final InetAddress remoteAddress) { return new QueryMessage(Type.ERROR, "" + "ERROR:201: access denied for %s\n" + "\n" + "Queries from your IP address have passed the daily limit of controlled objects.\n" + "Access from your host has been temporarily denied.\n" + "For more information, see\n" + "http: remoteAddress.getHostAddress()); } private QueryMessages(); static Message termsAndConditions(); static Message servedByNotice(final CharSequence version); static Message termsAndConditionsDump(); static Message relatedTo(final CharSequence key); static Message noPersonal(); static Message abuseCShown(final CharSequence key, final CharSequence value); static Message unvalidatedAbuseCShown(final CharSequence key, final CharSequence value, final CharSequence orgId); static Message unvalidatedAbuseCShown(final CharSequence key, final CharSequence value); static Message abuseCNotRegistered(final CharSequence key); static Message outputFilterNotice(); static Message primaryKeysOnlyNotice(); static Message versionListStart(final CharSequence type, final CharSequence key); static Message versionInformation(final int version, final boolean isCurrentVersion, final CIString key, final String operation, final String timestamp); static Message versionDifferenceHeader(final int earlierVersion, final int laterVersion, final CIString key); static Message versionDeleted(final CharSequence deletionTime); static Message versionPersonRole(final CharSequence type, final CharSequence key); static Message internalErroroccurred(); static Message noResults(final CharSequence source); static Message unknownSource(final CharSequence source); static Message invalidObjectType(final CharSequence type); static Message invalidAttributeType(final CharSequence type); static Message attributeNotSearchable(final CharSequence type); static Message noSearchKeySpecified(); static Message inputTooLong(); static Message invalidCombinationOfFlags(final CharSequence flag, final CharSequence otherFlag); static Message invalidMultipleFlags(final CharSequence flag); static Message malformedQuery(); static Message malformedQuery(final String reason); static Message illegalRange(); static Message unsupportedQuery(); static Message invalidSearchKey(); static Message unsupportedVersionObjectType(); static Message versionOutOfRange(final int max); static Message tooManyArguments(); static Message accessDeniedPermanently(final InetAddress remoteAddress); static Message accessDeniedTemporarily(final InetAddress remoteAddress); static Message notAllowedToProxy(); static Message timeout(); static Message connectionsExceeded(final int connectionLimit); static Message duplicateIpFlagsPassed(); static Message uselessIpFlagPassed(); static Message tagInfoStart(final CharSequence pkey); static Message tagInfo(final CharSequence tagType, final CharSequence tagValue); static Message unreferencedTagInfo(final CharSequence pkey, final CharSequence value); static Message filterTagNote(final Set<? extends CharSequence> includeArgs, final Set<? extends CharSequence> excludeArgs); static Message invalidSyntax(final CharSequence objectKey); static Message validSyntax(final CharSequence objectKey); static Message inverseSearchNotAllowed(); static Message valueChangedDueToLatin1Conversion(); }### Answer: @Test public void accessDeniedTemporarilyMessageShouldContainErrorCode() throws UnknownHostException { assertThat(QueryMessages.accessDeniedTemporarily(InetAddress.getLocalHost()).toString(), containsString("%ERROR:201:")); }
### Question: QueryMessages { public static Message inputTooLong() { return new QueryMessage(Type.ERROR, "" + "ERROR:107: input line too long\n" + "\n" + "Input exceeds the maximum line length."); } private QueryMessages(); static Message termsAndConditions(); static Message servedByNotice(final CharSequence version); static Message termsAndConditionsDump(); static Message relatedTo(final CharSequence key); static Message noPersonal(); static Message abuseCShown(final CharSequence key, final CharSequence value); static Message unvalidatedAbuseCShown(final CharSequence key, final CharSequence value, final CharSequence orgId); static Message unvalidatedAbuseCShown(final CharSequence key, final CharSequence value); static Message abuseCNotRegistered(final CharSequence key); static Message outputFilterNotice(); static Message primaryKeysOnlyNotice(); static Message versionListStart(final CharSequence type, final CharSequence key); static Message versionInformation(final int version, final boolean isCurrentVersion, final CIString key, final String operation, final String timestamp); static Message versionDifferenceHeader(final int earlierVersion, final int laterVersion, final CIString key); static Message versionDeleted(final CharSequence deletionTime); static Message versionPersonRole(final CharSequence type, final CharSequence key); static Message internalErroroccurred(); static Message noResults(final CharSequence source); static Message unknownSource(final CharSequence source); static Message invalidObjectType(final CharSequence type); static Message invalidAttributeType(final CharSequence type); static Message attributeNotSearchable(final CharSequence type); static Message noSearchKeySpecified(); static Message inputTooLong(); static Message invalidCombinationOfFlags(final CharSequence flag, final CharSequence otherFlag); static Message invalidMultipleFlags(final CharSequence flag); static Message malformedQuery(); static Message malformedQuery(final String reason); static Message illegalRange(); static Message unsupportedQuery(); static Message invalidSearchKey(); static Message unsupportedVersionObjectType(); static Message versionOutOfRange(final int max); static Message tooManyArguments(); static Message accessDeniedPermanently(final InetAddress remoteAddress); static Message accessDeniedTemporarily(final InetAddress remoteAddress); static Message notAllowedToProxy(); static Message timeout(); static Message connectionsExceeded(final int connectionLimit); static Message duplicateIpFlagsPassed(); static Message uselessIpFlagPassed(); static Message tagInfoStart(final CharSequence pkey); static Message tagInfo(final CharSequence tagType, final CharSequence tagValue); static Message unreferencedTagInfo(final CharSequence pkey, final CharSequence value); static Message filterTagNote(final Set<? extends CharSequence> includeArgs, final Set<? extends CharSequence> excludeArgs); static Message invalidSyntax(final CharSequence objectKey); static Message validSyntax(final CharSequence objectKey); static Message inverseSearchNotAllowed(); static Message valueChangedDueToLatin1Conversion(); }### Answer: @Test public void tooLongInputStringShouldContainErrorCode() { assertThat(QueryMessages.inputTooLong().toString(), containsString("%ERROR:107:")); }
### Question: QueryMessages { public static Message invalidObjectType(final CharSequence type) { return new QueryMessage(Type.ERROR, "ERROR:103: unknown object type '%s'", type); } private QueryMessages(); static Message termsAndConditions(); static Message servedByNotice(final CharSequence version); static Message termsAndConditionsDump(); static Message relatedTo(final CharSequence key); static Message noPersonal(); static Message abuseCShown(final CharSequence key, final CharSequence value); static Message unvalidatedAbuseCShown(final CharSequence key, final CharSequence value, final CharSequence orgId); static Message unvalidatedAbuseCShown(final CharSequence key, final CharSequence value); static Message abuseCNotRegistered(final CharSequence key); static Message outputFilterNotice(); static Message primaryKeysOnlyNotice(); static Message versionListStart(final CharSequence type, final CharSequence key); static Message versionInformation(final int version, final boolean isCurrentVersion, final CIString key, final String operation, final String timestamp); static Message versionDifferenceHeader(final int earlierVersion, final int laterVersion, final CIString key); static Message versionDeleted(final CharSequence deletionTime); static Message versionPersonRole(final CharSequence type, final CharSequence key); static Message internalErroroccurred(); static Message noResults(final CharSequence source); static Message unknownSource(final CharSequence source); static Message invalidObjectType(final CharSequence type); static Message invalidAttributeType(final CharSequence type); static Message attributeNotSearchable(final CharSequence type); static Message noSearchKeySpecified(); static Message inputTooLong(); static Message invalidCombinationOfFlags(final CharSequence flag, final CharSequence otherFlag); static Message invalidMultipleFlags(final CharSequence flag); static Message malformedQuery(); static Message malformedQuery(final String reason); static Message illegalRange(); static Message unsupportedQuery(); static Message invalidSearchKey(); static Message unsupportedVersionObjectType(); static Message versionOutOfRange(final int max); static Message tooManyArguments(); static Message accessDeniedPermanently(final InetAddress remoteAddress); static Message accessDeniedTemporarily(final InetAddress remoteAddress); static Message notAllowedToProxy(); static Message timeout(); static Message connectionsExceeded(final int connectionLimit); static Message duplicateIpFlagsPassed(); static Message uselessIpFlagPassed(); static Message tagInfoStart(final CharSequence pkey); static Message tagInfo(final CharSequence tagType, final CharSequence tagValue); static Message unreferencedTagInfo(final CharSequence pkey, final CharSequence value); static Message filterTagNote(final Set<? extends CharSequence> includeArgs, final Set<? extends CharSequence> excludeArgs); static Message invalidSyntax(final CharSequence objectKey); static Message validSyntax(final CharSequence objectKey); static Message inverseSearchNotAllowed(); static Message valueChangedDueToLatin1Conversion(); }### Answer: @Test public void invalidObjectTypeShouldContainErrorCode() { assertThat(QueryMessages.invalidObjectType("").toString(), containsString("%ERROR:103:")); }
### Question: JpirrGrsSource 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) { if (!lines.isEmpty() && !lines.get(0).startsWith("*xx")) { handler.handle(lines); } } }); } finally { IOUtils.closeQuietly(is); } } @Autowired JpirrGrsSource( @Value("${grs.import.jpirr.source:}") final String source, final SourceContext sourceContext, final DateTimeProvider dateTimeProvider, final AuthoritativeResourceData authoritativeResourceData, final Downloader downloader, @Value("${grs.import.jpirr.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/jpirr.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("" + "route: 219.23.0.0/16\n", "descr: Description\n", "origin: AS76\n", "mnt-by: MNT-AS76\n", "changed: foo@fo.bogus.co.jp 20061016\n", "changed: foo@fo.bogus.co.jp 20070402\n", "changed: foo@fo.bogus.co.jp 20070718\n", "source: JPIRR\n"), Lists.newArrayList("" + "as-set: AS-BOGUS\n", "descr: Description\n", "members: AS74\n", "notify: test@bogus.jp\n", "mnt-by: MNT-AS18\n", "changed: test@bogus.jp 20130109\n", "source: JPIRR\n") )); }
### Question: QueryMessages { public static Message uselessIpFlagPassed() { return new QueryMessage(Type.WARNING, "" + "WARNING:902: useless IP flag passed\n" + "\n" + "An IP flag (-l, -L, -m, -M, -x, -d or -b) used without an IP key."); } private QueryMessages(); static Message termsAndConditions(); static Message servedByNotice(final CharSequence version); static Message termsAndConditionsDump(); static Message relatedTo(final CharSequence key); static Message noPersonal(); static Message abuseCShown(final CharSequence key, final CharSequence value); static Message unvalidatedAbuseCShown(final CharSequence key, final CharSequence value, final CharSequence orgId); static Message unvalidatedAbuseCShown(final CharSequence key, final CharSequence value); static Message abuseCNotRegistered(final CharSequence key); static Message outputFilterNotice(); static Message primaryKeysOnlyNotice(); static Message versionListStart(final CharSequence type, final CharSequence key); static Message versionInformation(final int version, final boolean isCurrentVersion, final CIString key, final String operation, final String timestamp); static Message versionDifferenceHeader(final int earlierVersion, final int laterVersion, final CIString key); static Message versionDeleted(final CharSequence deletionTime); static Message versionPersonRole(final CharSequence type, final CharSequence key); static Message internalErroroccurred(); static Message noResults(final CharSequence source); static Message unknownSource(final CharSequence source); static Message invalidObjectType(final CharSequence type); static Message invalidAttributeType(final CharSequence type); static Message attributeNotSearchable(final CharSequence type); static Message noSearchKeySpecified(); static Message inputTooLong(); static Message invalidCombinationOfFlags(final CharSequence flag, final CharSequence otherFlag); static Message invalidMultipleFlags(final CharSequence flag); static Message malformedQuery(); static Message malformedQuery(final String reason); static Message illegalRange(); static Message unsupportedQuery(); static Message invalidSearchKey(); static Message unsupportedVersionObjectType(); static Message versionOutOfRange(final int max); static Message tooManyArguments(); static Message accessDeniedPermanently(final InetAddress remoteAddress); static Message accessDeniedTemporarily(final InetAddress remoteAddress); static Message notAllowedToProxy(); static Message timeout(); static Message connectionsExceeded(final int connectionLimit); static Message duplicateIpFlagsPassed(); static Message uselessIpFlagPassed(); static Message tagInfoStart(final CharSequence pkey); static Message tagInfo(final CharSequence tagType, final CharSequence tagValue); static Message unreferencedTagInfo(final CharSequence pkey, final CharSequence value); static Message filterTagNote(final Set<? extends CharSequence> includeArgs, final Set<? extends CharSequence> excludeArgs); static Message invalidSyntax(final CharSequence objectKey); static Message validSyntax(final CharSequence objectKey); static Message inverseSearchNotAllowed(); static Message valueChangedDueToLatin1Conversion(); }### Answer: @Test public void invalidInetnumMessageShouldContainErrorCode() { assertThat(QueryMessages.uselessIpFlagPassed().toString(), containsString("%WARNING:902:")); }
### Question: QueryMessages { public static Message malformedQuery() { return malformedQuery(null); } private QueryMessages(); static Message termsAndConditions(); static Message servedByNotice(final CharSequence version); static Message termsAndConditionsDump(); static Message relatedTo(final CharSequence key); static Message noPersonal(); static Message abuseCShown(final CharSequence key, final CharSequence value); static Message unvalidatedAbuseCShown(final CharSequence key, final CharSequence value, final CharSequence orgId); static Message unvalidatedAbuseCShown(final CharSequence key, final CharSequence value); static Message abuseCNotRegistered(final CharSequence key); static Message outputFilterNotice(); static Message primaryKeysOnlyNotice(); static Message versionListStart(final CharSequence type, final CharSequence key); static Message versionInformation(final int version, final boolean isCurrentVersion, final CIString key, final String operation, final String timestamp); static Message versionDifferenceHeader(final int earlierVersion, final int laterVersion, final CIString key); static Message versionDeleted(final CharSequence deletionTime); static Message versionPersonRole(final CharSequence type, final CharSequence key); static Message internalErroroccurred(); static Message noResults(final CharSequence source); static Message unknownSource(final CharSequence source); static Message invalidObjectType(final CharSequence type); static Message invalidAttributeType(final CharSequence type); static Message attributeNotSearchable(final CharSequence type); static Message noSearchKeySpecified(); static Message inputTooLong(); static Message invalidCombinationOfFlags(final CharSequence flag, final CharSequence otherFlag); static Message invalidMultipleFlags(final CharSequence flag); static Message malformedQuery(); static Message malformedQuery(final String reason); static Message illegalRange(); static Message unsupportedQuery(); static Message invalidSearchKey(); static Message unsupportedVersionObjectType(); static Message versionOutOfRange(final int max); static Message tooManyArguments(); static Message accessDeniedPermanently(final InetAddress remoteAddress); static Message accessDeniedTemporarily(final InetAddress remoteAddress); static Message notAllowedToProxy(); static Message timeout(); static Message connectionsExceeded(final int connectionLimit); static Message duplicateIpFlagsPassed(); static Message uselessIpFlagPassed(); static Message tagInfoStart(final CharSequence pkey); static Message tagInfo(final CharSequence tagType, final CharSequence tagValue); static Message unreferencedTagInfo(final CharSequence pkey, final CharSequence value); static Message filterTagNote(final Set<? extends CharSequence> includeArgs, final Set<? extends CharSequence> excludeArgs); static Message invalidSyntax(final CharSequence objectKey); static Message validSyntax(final CharSequence objectKey); static Message inverseSearchNotAllowed(); static Message valueChangedDueToLatin1Conversion(); }### Answer: @Test public void malformedQueryShouldContainError() { assertThat(QueryMessages.malformedQuery().toString(), containsString("%ERROR:111:")); }
### Question: QueryMessages { public static Message notAllowedToProxy() { return new QueryMessage(Type.ERROR, "ERROR:203: you are not allowed to act as a proxy"); } private QueryMessages(); static Message termsAndConditions(); static Message servedByNotice(final CharSequence version); static Message termsAndConditionsDump(); static Message relatedTo(final CharSequence key); static Message noPersonal(); static Message abuseCShown(final CharSequence key, final CharSequence value); static Message unvalidatedAbuseCShown(final CharSequence key, final CharSequence value, final CharSequence orgId); static Message unvalidatedAbuseCShown(final CharSequence key, final CharSequence value); static Message abuseCNotRegistered(final CharSequence key); static Message outputFilterNotice(); static Message primaryKeysOnlyNotice(); static Message versionListStart(final CharSequence type, final CharSequence key); static Message versionInformation(final int version, final boolean isCurrentVersion, final CIString key, final String operation, final String timestamp); static Message versionDifferenceHeader(final int earlierVersion, final int laterVersion, final CIString key); static Message versionDeleted(final CharSequence deletionTime); static Message versionPersonRole(final CharSequence type, final CharSequence key); static Message internalErroroccurred(); static Message noResults(final CharSequence source); static Message unknownSource(final CharSequence source); static Message invalidObjectType(final CharSequence type); static Message invalidAttributeType(final CharSequence type); static Message attributeNotSearchable(final CharSequence type); static Message noSearchKeySpecified(); static Message inputTooLong(); static Message invalidCombinationOfFlags(final CharSequence flag, final CharSequence otherFlag); static Message invalidMultipleFlags(final CharSequence flag); static Message malformedQuery(); static Message malformedQuery(final String reason); static Message illegalRange(); static Message unsupportedQuery(); static Message invalidSearchKey(); static Message unsupportedVersionObjectType(); static Message versionOutOfRange(final int max); static Message tooManyArguments(); static Message accessDeniedPermanently(final InetAddress remoteAddress); static Message accessDeniedTemporarily(final InetAddress remoteAddress); static Message notAllowedToProxy(); static Message timeout(); static Message connectionsExceeded(final int connectionLimit); static Message duplicateIpFlagsPassed(); static Message uselessIpFlagPassed(); static Message tagInfoStart(final CharSequence pkey); static Message tagInfo(final CharSequence tagType, final CharSequence tagValue); static Message unreferencedTagInfo(final CharSequence pkey, final CharSequence value); static Message filterTagNote(final Set<? extends CharSequence> includeArgs, final Set<? extends CharSequence> excludeArgs); static Message invalidSyntax(final CharSequence objectKey); static Message validSyntax(final CharSequence objectKey); static Message inverseSearchNotAllowed(); static Message valueChangedDueToLatin1Conversion(); }### Answer: @Test public void notAllowedToProxyShouldContainError() { assertThat(QueryMessages.notAllowedToProxy().toString(), containsString("%ERROR:203:")); }
### Question: QueryParser { public static boolean hasFlags(final String queryString) { return PARSER.parse(Iterables.toArray(SPACE_SPLITTER.split(queryString), String.class)).hasOptions(); } QueryParser(final String query); String getSearchKey(); boolean hasOptions(); boolean hasOption(final QueryFlag queryFlag); String getOptionValue(final QueryFlag queryFlag); Set<String> getOptionValues(final QueryFlag queryFlag); Set<CIString> getOptionValuesCI(final QueryFlag queryFlag); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); boolean hasOnlyQueryFlag(final QueryFlag queryFlag); static boolean hasFlags(final String queryString); boolean hasSubstitutions(); static final Pattern FLAG_PATTERN; }### Answer: @Test public void hasflags() { assertThat(QueryParser.hasFlags("--abuse-contact 193.0.0.1"), is(true)); assertThat(QueryParser.hasFlags("-L 193.0.0.1"), is(true)); assertThat(QueryParser.hasFlags("193.0.0.1"), is(false)); } @Test public void hasflags_invalid_option_supplied() { try { QueryParser.hasFlags("--this-is-an-invalid-flag"); fail(); } catch (IllegalArgumentExceptionMessage e) { assertThat(e.getExceptionMessage(), is(QueryMessages.malformedQuery("Invalid option: --this-is-an-invalid-flag"))); } }
### Question: StreamingRestClient implements Iterator<WhoisObject>, Closeable { public static WhoisResources unMarshalError(final InputStream inputStream) { return (WhoisResources) (new StreamingRestClient(inputStream)).unmarshal(); } StreamingRestClient(final InputStream inputStream); @Override boolean hasNext(); @Override WhoisObject next(); @Override void remove(); @Override void close(); static WhoisResources unMarshalError(final InputStream inputStream); }### Answer: @Test public void read_error_response() { final WhoisResources whoisResources = StreamingRestClient.unMarshalError( new ByteArrayInputStream(( "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>" + "<whois-resources xmlns:xlink=\"http: "<link xlink:type=\"locator\" xlink:href=\"http: "<errormessages><errormessage severity=\"Error\" text=\"Query param 'query-string' cannot be empty\"/></errormessages>" + "<terms-and-conditions xlink:type=\"locator\" xlink:href=\"http: "</whois-resources>\n").getBytes())); assertThat(whoisResources.getErrorMessages(), hasSize(1)); assertThat(whoisResources.getErrorMessages().get(0).getText(), is("Query param 'query-string' cannot be empty")); }
### Question: ErrorMessage implements Comparable<ErrorMessage> { @Override public String toString() { return (args == null || args.isEmpty() || text == null) ? text : String.format(text, args.toArray()); } ErrorMessage(final String severity, final Attribute attribute, final String text, final List<Arg> args); ErrorMessage(final Message message); ErrorMessage(final Message message, final RpslAttribute attribute); ErrorMessage(); @Nullable String getSeverity(); @Nullable Attribute getAttribute(); @Nullable String getText(); @Nullable List<Arg> getArgs(); @Override String toString(); @Override boolean equals(final Object o); @Override int hashCode(); @Override int compareTo(final ErrorMessage errorMessage); }### Answer: @Test public void to_string_no_arguments() { assertThat(new ErrorMessage(new Message(Messages.Type.INFO, "message")).toString(), is("message")); } @Test public void to_string_with_single_argument() { assertThat(new ErrorMessage(new Message(Messages.Type.INFO, "message with %s", "argument")).toString(), is("message with argument")); } @Test public void to_string_with_multiple_arguments() { assertThat(new ErrorMessage(new Message(Messages.Type.INFO, "message with %s %s", "argument", "ending")).toString(), is("message with argument ending")); } @Test public void to_string_default_constructor() { assertThat(new ErrorMessage().toString(), is(nullValue())); }
### Question: GrsImporterJmx extends JmxBase { @ManagedAttribute(description = "Comma separated list of default GRS sources") public String getGrsDefaultSources() { return grsDefaultSources; } @Autowired GrsImporterJmx(final GrsImporter grsImporter); @ManagedAttribute(description = "Comma separated list of default GRS sources") String getGrsDefaultSources(); @ManagedOperation(description = "Download new dumps and update GRS sources") @ManagedOperationParameters({ @ManagedOperationParameter(name = "sources", description = "Comma separated list of GRS sources to import (or 'all')"), @ManagedOperationParameter(name = "comment", description = "Optional comment for invoking the operation") }) String grsImport(final String sources, final String comment); @ManagedOperation(description = "Download new dumps and rebuild GRS sources") @ManagedOperationParameters({ @ManagedOperationParameter(name = "sources", description = "Comma separated list of GRS sources to import (or 'all')"), @ManagedOperationParameter(name = "passphrase", description = "The passphrase to prevent accidental invocation"), @ManagedOperationParameter(name = "comment", description = "Optional comment for invoking the operation") }) String grsRebuild(final String sources, final String passphrase, final String comment); }### Answer: @Test public void getGrsDefaultSources() { final String defaultSources = subject.getGrsDefaultSources(); assertThat(defaultSources, is("ARIN-GRS,APNIC-GRS")); }
### Question: ErrorMessage implements Comparable<ErrorMessage> { @Override public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || (o.getClass() != getClass())) { return false; } final ErrorMessage errorMessage = (ErrorMessage)o; return (Objects.equals(severity, errorMessage.getSeverity()) && Objects.equals(attribute, errorMessage.getAttribute()) && Objects.equals(text, errorMessage.getText()) && Objects.equals(args, errorMessage.getArgs())); } ErrorMessage(final String severity, final Attribute attribute, final String text, final List<Arg> args); ErrorMessage(final Message message); ErrorMessage(final Message message, final RpslAttribute attribute); ErrorMessage(); @Nullable String getSeverity(); @Nullable Attribute getAttribute(); @Nullable String getText(); @Nullable List<Arg> getArgs(); @Override String toString(); @Override boolean equals(final Object o); @Override int hashCode(); @Override int compareTo(final ErrorMessage errorMessage); }### Answer: @Test public void equals() { final ErrorMessage errorMessage1 = new ErrorMessage("Error", new Attribute("name", "value"), "text", Lists.newArrayList(new Arg("value"))); assertThat(errorMessage1.equals(null), is(false)); assertThat(errorMessage1.equals("String"), is(false)); assertThat(errorMessage1.equals(errorMessage1), is(true)); assertThat(errorMessage1.equals(new ErrorMessage("Error", new Attribute("name", "value"), "text", Lists.newArrayList(new Arg("value")))), is(true)); final ErrorMessage errorMessage2 = new ErrorMessage(new Message(Messages.Type.ERROR, "text")); assertThat(errorMessage2.equals(null), is(false)); assertThat(errorMessage2.equals("String"), is(false)); assertThat(errorMessage2.equals(errorMessage2), is(true)); assertThat(errorMessage2.equals(new ErrorMessage(new Message(Messages.Type.ERROR, "text"))), is(true)); final ErrorMessage errorMessage3 = new ErrorMessage(new Message(Messages.Type.ERROR, "text"), new RpslAttribute("key", "value")); assertThat(errorMessage3.equals(null), is(false)); assertThat(errorMessage3.equals("String"), is(false)); assertThat(errorMessage3.equals(errorMessage3), is(true)); assertThat(errorMessage3.equals(new ErrorMessage(new Message(Messages.Type.ERROR, "text"), new RpslAttribute("key", "value"))), is(true)); assertThat(errorMessage1.equals(errorMessage2), is(false)); assertThat(errorMessage1.equals(errorMessage3), is(false)); }
### Question: SyncUpdateUtils { public static String encode(final String value) { return encode(value, StandardCharsets.UTF_8); } private SyncUpdateUtils(); static String encode(final String value); static String encode(final String value, final Charset charset); }### Answer: @Test public void encode() { assertThat(SyncUpdateUtils.encode(""), is("")); assertThat(SyncUpdateUtils.encode("123"), is("123")); assertThat(SyncUpdateUtils.encode("{}"), is("%7B%7D")); assertThat(SyncUpdateUtils.encode("{"), is("%7B")); assertThat(SyncUpdateUtils.encode("{%7D"), is("%7B%257D")); assertThat(SyncUpdateUtils.encode("a b c"), is("a+b+c")); assertThat(SyncUpdateUtils.encode("a+b+c"), is("a%2Bb%2Bc")); }
### Question: CrowdClient { public String login(final String username, final String password) throws CrowdClientException { final CrowdAuthenticationContext crowdAuth = new CrowdAuthenticationContext(username, password); try { final CrowdSession session = client.target(restUrl) .path(CROWD_SESSION_PATH) .request(MediaType.APPLICATION_XML) .post(Entity.entity(crowdAuth, MediaType.APPLICATION_XML), CrowdSession.class); return session.getToken(); } catch (WebApplicationException | ProcessingException e) { throw new CrowdClientException(e); } } @Autowired CrowdClient(@Value("${crowd.rest.url}") final String translatorUrl, @Value("${crowd.rest.user}") final String crowdAuthUser, @Value("${crowd.rest.password}") final String crowdAuthPassword); String login(final String username, final String password); void logout(final String username); void invalidateToken(final String token); String getUuid(final String username); String getUsername(final String uuid); String getDisplayName(final String uuid); UserSession getUserSession(final String token); }### Answer: @Test public void login_success() { final String token = "xyz"; when(builder.<CrowdSession>post(any(Entity.class), any(Class.class))).then( invocation -> new CrowdSession(new CrowdUser("test@ripe.net", "Test User", true), token, "2033-01-30T16:38:27.369+11:00") ); assertThat(subject.login("test@ripe.net", "password"), is(token)); } @Test public void login_not_authorized() { when(builder.<CrowdSession>post(any(Entity.class), any(Class.class))).then( invocation -> { when(response.getStatus()).thenReturn(401); when(response.getStatusInfo()).thenReturn(Response.Status.UNAUTHORIZED); when(response.readEntity(CrowdClient.CrowdError.class)).thenReturn(new CrowdClient.CrowdError("reason", "message")); throw new NotAuthorizedException(response); }); try { subject.login("test@ripe.net", "password"); fail(); } catch (CrowdClientException expected) { assertThat(expected.getMessage(), is("message")); } }
### Question: CrowdClient { public UserSession getUserSession(final String token) throws CrowdClientException { try { final CrowdSession crowdSession = client.target(restUrl) .path(CROWD_SESSION_PATH) .path(token) .queryParam("validate-password", "false") .queryParam("expand", "user") .request(MediaType.APPLICATION_XML) .post(Entity.xml("<?xml version=\"1.0\" encoding=\"UTF-8\"?><validation-factors/>"), CrowdSession.class); final CrowdUser user = crowdSession.getUser(); return new UserSession(user.getName(), user.getDisplayName(), user.getActive(), crowdSession.getExpiryDate()); } catch (BadRequestException e) { throw new CrowdClientException("Unknown RIPE NCC Access token: " + token); } catch (WebApplicationException | ProcessingException e) { throw new CrowdClientException(e); } catch (Exception e) { LOGGER.error(e.getMessage(), e); throw new CrowdClientException(e); } } @Autowired CrowdClient(@Value("${crowd.rest.url}") final String translatorUrl, @Value("${crowd.rest.user}") final String crowdAuthUser, @Value("${crowd.rest.password}") final String crowdAuthPassword); String login(final String username, final String password); void logout(final String username); void invalidateToken(final String token); String getUuid(final String username); String getUsername(final String uuid); String getDisplayName(final String uuid); UserSession getUserSession(final String token); }### Answer: @Test public void get_user_session_bad_request() { when(builder.<CrowdSession>post(any(Entity.class), any(Class.class))).then(invocation -> {throw new BadRequestException("Not valid sso");}); try { subject.getUserSession("token"); fail(); } catch (CrowdClientException expected) { assertThat(expected.getMessage(), is("Unknown RIPE NCC Access token: token")); } }
### Question: CrowdClient { public String getUsername(final String uuid) throws CrowdClientException { try { final List<CrowdUser> users = client.target(restUrl) .path(CROWD_UUID_SEARCH_PATH) .queryParam("restriction", "uuid=" + uuid) .queryParam("entity-type", "user") .queryParam("expand", "user") .request(MediaType.APPLICATION_XML) .get(CrowdUsers.class).getUsers(); if(users == null || users.isEmpty()) { throw new CrowdClientException("Unknown RIPE NCC Access uuid: " + uuid); } return users.get(0).getName(); } catch (NotFoundException e) { throw new CrowdClientException("Unknown RIPE NCC Access uuid: " + uuid); } catch (WebApplicationException | ProcessingException e) { throw new CrowdClientException(e); } } @Autowired CrowdClient(@Value("${crowd.rest.url}") final String translatorUrl, @Value("${crowd.rest.user}") final String crowdAuthUser, @Value("${crowd.rest.password}") final String crowdAuthPassword); String login(final String username, final String password); void logout(final String username); void invalidateToken(final String token); String getUuid(final String username); String getUsername(final String uuid); String getDisplayName(final String uuid); UserSession getUserSession(final String token); }### Answer: @Test public void get_username_success() { when(builder.get(CrowdClient.CrowdUsers.class)) .then(invocation -> new CrowdClient.CrowdUsers( Arrays.asList(new CrowdClient.CrowdUser("test@ripe.net", "Test User", true))) ); assertThat(subject.getUsername("uuid"), is("test@ripe.net")); } @Test public void get_username_not_found() { when(builder.get(CrowdClient.CrowdUsers.class)).then(invocation -> {throw new NotFoundException("message");}); try { subject.getUsername("madeup-uuid"); fail(); } catch (CrowdClientException expected) { assertThat(expected.getMessage(), is("Unknown RIPE NCC Access uuid: madeup-uuid")); } }
### Question: CrowdClient { public String getDisplayName(final String uuid) throws CrowdClientException { try { final List<CrowdUser> users = client.target(restUrl) .path(CROWD_UUID_SEARCH_PATH) .queryParam("restriction", "uuid=" + uuid) .queryParam("entity-type", "user") .queryParam("expand", "user") .request(MediaType.APPLICATION_XML) .get(CrowdUsers.class).getUsers(); if(users == null || users.isEmpty()) { throw new CrowdClientException("Unknown RIPE NCC Access uuid: " + uuid); } return users.get(0).getDisplayName(); } catch (NotFoundException e) { throw new CrowdClientException("Unknown RIPE NCC Access uuid: " + uuid); } catch (WebApplicationException | ProcessingException e) { throw new CrowdClientException(e); } } @Autowired CrowdClient(@Value("${crowd.rest.url}") final String translatorUrl, @Value("${crowd.rest.user}") final String crowdAuthUser, @Value("${crowd.rest.password}") final String crowdAuthPassword); String login(final String username, final String password); void logout(final String username); void invalidateToken(final String token); String getUuid(final String username); String getUsername(final String uuid); String getDisplayName(final String uuid); UserSession getUserSession(final String token); }### Answer: @Test public void get_display_name_success() { when(builder.get(CrowdClient.CrowdUsers.class)) .then(invocation -> new CrowdClient.CrowdUsers( Arrays.asList(new CrowdClient.CrowdUser("test@ripe.net", "Test User", true))) ); assertThat(subject.getDisplayName("uuid"), is("Test User")); } @Test public void get_display_name_not_found() { when(builder.get(CrowdClient.CrowdUsers.class)).then(invocation -> {throw new NotFoundException("message");}); try { subject.getDisplayName("madeup-uuid"); fail(); } catch (CrowdClientException expected) { assertThat(expected.getMessage(), is("Unknown RIPE NCC Access uuid: madeup-uuid")); } }
### Question: GrsImporterJmx extends JmxBase { @ManagedOperation(description = "Download new dumps and update GRS sources") @ManagedOperationParameters({ @ManagedOperationParameter(name = "sources", description = "Comma separated list of GRS sources to import (or 'all')"), @ManagedOperationParameter(name = "comment", description = "Optional comment for invoking the operation") }) public String grsImport(final String sources, final String comment) { return invokeOperation("GRS import sources", comment, new Callable<String>() { @Override public String call() { grsImporter.grsImport("all".equals(sources) ? grsDefaultSources : sources, false); return "GRS import started"; } }); } @Autowired GrsImporterJmx(final GrsImporter grsImporter); @ManagedAttribute(description = "Comma separated list of default GRS sources") String getGrsDefaultSources(); @ManagedOperation(description = "Download new dumps and update GRS sources") @ManagedOperationParameters({ @ManagedOperationParameter(name = "sources", description = "Comma separated list of GRS sources to import (or 'all')"), @ManagedOperationParameter(name = "comment", description = "Optional comment for invoking the operation") }) String grsImport(final String sources, final String comment); @ManagedOperation(description = "Download new dumps and rebuild GRS sources") @ManagedOperationParameters({ @ManagedOperationParameter(name = "sources", description = "Comma separated list of GRS sources to import (or 'all')"), @ManagedOperationParameter(name = "passphrase", description = "The passphrase to prevent accidental invocation"), @ManagedOperationParameter(name = "comment", description = "Optional comment for invoking the operation") }) String grsRebuild(final String sources, final String passphrase, final String comment); }### Answer: @Test public void grsImport() { final String result = subject.grsImport("ARIN-GRS,APNIC-GRS", "comment"); verify(grsImporter).grsImport("ARIN-GRS,APNIC-GRS", false); assertThat(result, is("GRS import started")); } @Test public void grsImport_throws_exception() { doThrow(new RuntimeException("Oops")).when(grsImporter).grsImport(anyString(), anyBoolean()); final String result = subject.grsImport("ARIN-GRS,APNIC-GRS", "comment"); verify(grsImporter).grsImport("ARIN-GRS,APNIC-GRS", false); assertNull(result); }
### Question: ObjectLoader { public void checkForReservedNicHandle(final RpslObject object) throws ClaimException { if (object.getType() != ObjectType.PERSON && object.getType() != ObjectType.ROLE) { return; } final CIString pkey = object.getKey(); if (pkey.equals("AUTO-1")){ throw new ClaimException(new Message(Messages.Type.ERROR, "AUTO-1 in nic-hdl is not available in Bootstrap/LoadDump mode")); } if (!nicHandleFactory.isAvailable(object.getKey().toString())){ throw new ClaimException(UpdateMessages.nicHandleNotAvailable(object.getKey())); } } @Autowired ObjectLoader(RpslObjectDao rpslObjectDao, RpslObjectUpdateDao rpslObjectUpdateDao, AttributeSanitizer attributeSanitizer, NicHandleFactory nicHandleFactory, OrganisationIdRepository organisationIdRepository, X509Repository x509Repository); void processObject(final String fullObject, final Result result, final int pass, final LoaderMode loaderMode); @Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRES_NEW) void addObjectRisky(RpslObject rpslObject, Result result, int pass); void checkForReservedNicHandle(final RpslObject object); void claimIds(RpslObject rpslObject); }### Answer: @Test public void nic_hdl_is_auto1() { final RpslObject object = RpslObject.parse("person: test person\nnic-hdl: AUTO-1"); try { subject.checkForReservedNicHandle(object); fail(); } catch (ClaimException e) { assertThat(e.getErrorMessage().getText(), is("AUTO-1 in nic-hdl is not available in Bootstrap/LoadDump mode")); } } @Test public void nic_hdl_is_reserved() throws ClaimException { when(nicHandleFactory.isAvailable("TR1-TEST")).thenReturn(false); final RpslObject object = RpslObject.parse("role: test role\nnic-hdl: TR1-TEST"); try { subject.checkForReservedNicHandle(object); fail(); } catch (ClaimException e) { assertThat(e.getErrorMessage().getFormattedText(), is("The nic-hdl \"TR1-TEST\" is not available")); } } @Test public void no_check_for_non_person_role() throws ClaimException { final RpslObject object = RpslObject.parse("mntner: test-mnt"); subject.checkForReservedNicHandle(object); verifyZeroInteractions(nicHandleFactory); }
### Question: CrowdClient { public String getUuid(final String username) throws CrowdClientException { try { return client.target(restUrl) .path(CROWD_USER_ATTRIBUTE_PATH) .queryParam("username", username) .request(MediaType.APPLICATION_XML) .get(CrowdResponse.class) .getUUID(); } catch (NoSuchElementException e) { throw new CrowdClientException("Cannot find UUID for: " + username); } catch (NotFoundException e) { throw new CrowdClientException("Unknown RIPE NCC Access user: " + username); } catch (WebApplicationException | ProcessingException e) { throw new CrowdClientException(e); } } @Autowired CrowdClient(@Value("${crowd.rest.url}") final String translatorUrl, @Value("${crowd.rest.user}") final String crowdAuthUser, @Value("${crowd.rest.password}") final String crowdAuthPassword); String login(final String username, final String password); void logout(final String username); void invalidateToken(final String token); String getUuid(final String username); String getUsername(final String uuid); String getDisplayName(final String uuid); UserSession getUserSession(final String token); }### Answer: @Test public void get_uuid_success() { when(builder.get(CrowdResponse.class)).then(invocation -> new CrowdResponse(Lists.newArrayList( new CrowdClient.CrowdAttribute(Lists.newArrayList( new CrowdClient.CrowdValue("1-2-3-4")), "uuid")))); assertThat(subject.getUuid("test@ripe.net"), is("1-2-3-4")); } @Test public void get_uuid_not_found() { when(builder.get(CrowdResponse.class)).then(invocation -> {throw new NotFoundException("message");}); try { subject.getUuid("test@ripe.net"); fail(); } catch (CrowdClientException expected) { assertThat(expected.getMessage(), is("Unknown RIPE NCC Access user: test@ripe.net")); } } @Test public void get_uuid_no_attribute() { final CrowdResponse crowdResponse = mock(CrowdResponse.class); when(crowdResponse.getUUID()).then(invocation -> {throw new NoSuchElementException();}); when(builder.get(CrowdResponse.class)).thenReturn(crowdResponse); try { subject.getUuid("test@ripe.net"); fail(); } catch (CrowdClientException expected) { assertThat(expected.getMessage(), is("Cannot find UUID for: test@ripe.net")); } }
### Question: SsoTokenTranslator { public UserSession translateSsoToken(final String ssoToken) throws CrowdClientException { final UserSession userSession = crowdClient.getUserSession(ssoToken); userSession.setUuid(crowdClient.getUuid(userSession.getUsername())); return userSession; } @Autowired SsoTokenTranslator(final CrowdClient crowdClient); UserSession translateSsoToken(final String ssoToken); }### Answer: @Test public void translateSsoToken() { final String ssotoken = "ssotoken"; final String username = "username"; final String displayName = "Test User"; final String uuid = "uuid"; when(crowdClient.getUserSession(ssotoken)).thenReturn(new UserSession(username, displayName, true, "2033-01-30T16:38:27.369+11:00")); when(crowdClient.getUuid(username)).thenReturn(uuid); final UserSession userSession = subject.translateSsoToken(ssotoken); assertThat(userSession.getUsername(), is(username)); assertThat(userSession.getUuid(), is(uuid)); assertThat(userSession.isActive(), is(true)); } @Test(expected = CrowdClientException.class) public void translateSsoToken_invalid_session() { final String ssotoken = "ssotoken"; when(crowdClient.getUserSession(ssotoken)).thenThrow(new CrowdClientException("Unknown RIPE NCC Access token: " + ssotoken)); subject.translateSsoToken(ssotoken); } @Test(expected = CrowdClientException.class) public void translateSsoToken_invalid_username() { final String ssotoken = "ssotoken"; final String username = "username"; final String displayName = "Test User"; when(crowdClient.getUserSession(ssotoken)).thenReturn(new UserSession(username, displayName, true, "2033-01-30T16:38:27.369+11:00")); when(crowdClient.getUuid(username)).thenThrow(new CrowdClientException("Unknown RIPE NCC Access user: " + username)); subject.translateSsoToken(ssotoken); }
### Question: UserSession { public LocalDateTime getExpiryDate() { return expiryDate; } UserSession(final String username, final String displayName, final boolean isActive, final String expiryDate); String getDisplayName(); String getUsername(); boolean isActive(); LocalDateTime getExpiryDate(); String getUuid(); void setUuid(final String uuid); @Override String toString(); }### Answer: @Test public void testTimestampParsingNoMillis() { UserSession userSession = new UserSession("username", "displayName", true, "2019-09-19T14:51:05+02:00"); assertThat(userSession.getExpiryDate().getYear(), is(2019)); assertThat(userSession.getExpiryDate().getMonth(), is(Month.SEPTEMBER)); assertThat(userSession.getExpiryDate().getDayOfMonth(), is(19)); assertThat(userSession.getExpiryDate().getHour(), is(14)); assertThat(userSession.getExpiryDate().getMinute(), is(51)); assertThat(userSession.getExpiryDate().getSecond(), is(5)); } @Test public void testTimestampParsingWithMillis() { UserSession userSession = new UserSession("username", "displayName", true, "2019-09-19T20:16:43.835+02:00"); assertThat(userSession.getExpiryDate().getYear(), is(2019)); assertThat(userSession.getExpiryDate().getMonth(), is(Month.SEPTEMBER)); assertThat(userSession.getExpiryDate().getDayOfMonth(), is(19)); assertThat(userSession.getExpiryDate().getHour(), is(20)); assertThat(userSession.getExpiryDate().getMinute(), is(16)); assertThat(userSession.getExpiryDate().getSecond(), is(43)); assertThat(userSession.getExpiryDate().get(ChronoField.MILLI_OF_SECOND), is(835)); } @Test public void testTimestampParsingNoOffset() { UserSession userSession = new UserSession("username", "displayName", true, "2019-09-19T20:16:43.835Z"); assertThat(userSession.getExpiryDate().getYear(), is(2019)); assertThat(userSession.getExpiryDate().getMonth(), is(Month.SEPTEMBER)); assertThat(userSession.getExpiryDate().getDayOfMonth(), is(19)); assertThat(userSession.getExpiryDate().getHour(), is(20)); assertThat(userSession.getExpiryDate().getMinute(), is(16)); assertThat(userSession.getExpiryDate().getSecond(), is(43)); assertThat(userSession.getExpiryDate().get(ChronoField.MILLI_OF_SECOND), is(835)); }
### Question: AbuseCFinder { public Optional<AbuseContact> getAbuseContact(final RpslObject rpslObject) { final RpslObject role = getAbuseContactRole(rpslObject); if (role == null) { return Optional.empty(); } final boolean suspect = abuseValidationStatusDao.isSuspect(role.getValueForAttribute(AttributeType.ABUSE_MAILBOX)); return Optional.of(new AbuseContact( role, suspect, getOrgToContact(rpslObject, suspect) )); } @Autowired AbuseCFinder(@Qualifier("jdbcRpslObjectSlaveDao") final RpslObjectDao objectDao, @Value("${whois.source}") final String mainSource, @Value("${whois.nonauth.source}") final String nonAuthSource, @Value("${grs.sources}") final String grsSource, final Ipv4Tree ipv4Tree, final Ipv6Tree ipv6Tree, final Maintainers maintainers, final AbuseValidationStatusDao abuseValidationStatusDao); Optional<AbuseContact> getAbuseContact(final RpslObject rpslObject); }### Answer: @Test public void inetnum_without_org_reference() { final RpslObject inetnum = RpslObject.parse("inetnum: 10.0.0.0\nsource: RIPE"); assertThat(subject.getAbuseContact(inetnum).isPresent(), is(false)); } @Test public void getAbuseContacts_rootObject() { final RpslObject inetnum = RpslObject.parse("inetnum: 10.0.0.0\nsource: RIPE"); assertThat(subject.getAbuseContact(inetnum).isPresent(), is(false)); verifyZeroInteractions(maintainers); }
### Question: AbuseCInfoDecorator implements ResponseDecorator { @Override public Iterable<? extends ResponseObject> decorate(Query query, Iterable<? extends ResponseObject> input) { if (query.via(Query.Origin.REST) || query.isBriefAbuseContact() || !sourceContext.isMain()) { return input; } return new IterableTransformer<ResponseObject>(input) { @Override public void apply(ResponseObject input, Deque<ResponseObject> result) { if (!(input instanceof RpslObject)) { result.add(input); return; } final RpslObject object = (RpslObject) input; if (!ABUSE_LOOKUP_OBJECT_TYPES.contains(object.getType())) { result.add(input); return; } final Optional<AbuseContact> optionalAbuseContact = abuseCFinder.getAbuseContact(object); if (optionalAbuseContact.isPresent()) { optionalAbuseContact.ifPresent(abuseContact -> { if (abuseContact.isSuspect()) { if (abuseContact.getOrgId() != null) { result.add(new MessageObject(QueryMessages.unvalidatedAbuseCShown(object.getKey(), abuseContact.getAbuseMailbox(), abuseContact.getOrgId()))); } else { result.add(new MessageObject(QueryMessages.unvalidatedAbuseCShown(object.getKey(), abuseContact.getAbuseMailbox()))); } } else { result.add(new MessageObject(QueryMessages.abuseCShown(object.getKey(), abuseContact.getAbuseMailbox()))); } }); } else { result.add(new MessageObject(QueryMessages.abuseCNotRegistered(object.getKey()))); } result.add(input); } }; } @Autowired AbuseCInfoDecorator(final AbuseCFinder abuseCFinder, SourceContext sourceContext); @Override Iterable<? extends ResponseObject> decorate(Query query, Iterable<? extends ResponseObject> input); }### Answer: @Test public void notApplicable() { final RpslObject object = RpslObject.parse("person: Someone\nnic-hdl: NIC-TEST"); final Iterator<? extends ResponseObject> iterator = subject.decorate(Query.parse("--abuse-contact AS3333"), Collections.singletonList(object)).iterator(); final ResponseObject result = iterator.next(); assertThat(result, is(object)); assertThat(iterator.hasNext(), is(false)); } @Test public void inet6num_with_abuse_contact() { final RpslObject object = RpslObject.parse("inet6num: ffc::0/64\norg: ORG-TEST"); final RpslObject abuseRole = RpslObject.parse("role: Abuse Role\n" + "nic-hdl: AA1-TEST\n" + "abuse-mailbox: abuse@ripe.net" ); when(abuseCFinder.getAbuseContact(object)).thenReturn(Optional.of(new AbuseContact(abuseRole, false, ciString("")))); when(sourceContext.isMain()).thenReturn(true); final Iterator<? extends ResponseObject> iterator = subject.decorate(Query.parse("AS3333"), Collections.singletonList(object)).iterator(); final MessageObject result = (MessageObject) iterator.next(); assertThat(result.toString(), is("% Abuse contact for 'ffc::0/64' is 'abuse@ripe.net'\n")); assertThat(iterator.hasNext(), is(true)); assertThat(iterator.next(), is(instanceOf(ResponseObject.class))); assertThat(iterator.hasNext(), is(false)); } @Test public void autnum_without_abuse_contact() { final RpslObject autnum = RpslObject.parse("aut-num: AS333\nas-name: TEST-NAME\norg: ORG-TOL1-TEST"); when(abuseCFinder.getAbuseContact(autnum)).thenReturn(Optional.empty()); when(sourceContext.isMain()).thenReturn(true); final Iterator<? extends ResponseObject> iterator = subject.decorate(Query.parse("AS3333"), Collections.singletonList(autnum)).iterator(); final MessageObject result = (MessageObject) iterator.next(); assertThat(result.toString(), is(QueryMessages.abuseCNotRegistered("AS333").getFormattedText())); }
### Question: GrsImporterJmx extends JmxBase { @ManagedOperation(description = "Download new dumps and rebuild GRS sources") @ManagedOperationParameters({ @ManagedOperationParameter(name = "sources", description = "Comma separated list of GRS sources to import (or 'all')"), @ManagedOperationParameter(name = "passphrase", description = "The passphrase to prevent accidental invocation"), @ManagedOperationParameter(name = "comment", description = "Optional comment for invoking the operation") }) public String grsRebuild(final String sources, final String passphrase, final String comment) { return invokeOperation("GRS rebuild sources", comment, new Callable<String>() { @Override public String call() { final String validPassphrase = "grsrebuildnow"; if (!passphrase.equals(validPassphrase)) { return String.format("" + "Warning:\n\n" + "Rebuild will delete all content in the specified\n" + "sources, when unsure use the grsImport() operation,\n" + "which will update the sources using diff.\n\n" + "When you are absolutely sure, specify the\n" + "passphrase: %s", validPassphrase); } grsImporter.grsImport("all".equals(sources) ? grsDefaultSources : sources, true); return "GRS rebuild started"; } }); } @Autowired GrsImporterJmx(final GrsImporter grsImporter); @ManagedAttribute(description = "Comma separated list of default GRS sources") String getGrsDefaultSources(); @ManagedOperation(description = "Download new dumps and update GRS sources") @ManagedOperationParameters({ @ManagedOperationParameter(name = "sources", description = "Comma separated list of GRS sources to import (or 'all')"), @ManagedOperationParameter(name = "comment", description = "Optional comment for invoking the operation") }) String grsImport(final String sources, final String comment); @ManagedOperation(description = "Download new dumps and rebuild GRS sources") @ManagedOperationParameters({ @ManagedOperationParameter(name = "sources", description = "Comma separated list of GRS sources to import (or 'all')"), @ManagedOperationParameter(name = "passphrase", description = "The passphrase to prevent accidental invocation"), @ManagedOperationParameter(name = "comment", description = "Optional comment for invoking the operation") }) String grsRebuild(final String sources, final String passphrase, final String comment); }### Answer: @Test public void grsRebuild() { final String result = subject.grsRebuild("ARIN-GRS,APNIC-GRS", "grsrebuildnow", "comment"); verify(grsImporter).grsImport("ARIN-GRS,APNIC-GRS", true); assertThat(result, is("GRS rebuild started")); } @Test public void grsRebuild_invalid_passphrase() { final String result = subject.grsRebuild("ARIN-GRS,APNIC-GRS", "??", "comment"); assertThat(result, containsString("passphrase: grsrebuildnow")); }
### Question: RelatedToDecorator implements PrimaryObjectDecorator { @Override public boolean appliesToQuery(final Query query) { return query.isReturningReferencedObjects(); } @Autowired RelatedToDecorator(final RpslObjectDao rpslObjectDao); @Override boolean appliesToQuery(final Query query); @Override Collection<RpslObjectInfo> decorate(final Query query, final RpslObject rpslObject); }### Answer: @Test public void appliesToQuery_empty() { assertThat(subject.appliesToQuery(Query.parse("foo")), is(true)); } @Test public void appliesToQuery_related() { assertThat(subject.appliesToQuery(Query.parse("-T inetnum 10.0.0.0")), is(true)); } @Test public void appliesToQuery_not_related() { assertThat(subject.appliesToQuery(Query.parse("-r -T inetnum 10.0.0.0")), is(false)); }
### Question: RelatedToDecorator implements PrimaryObjectDecorator { @Override public Collection<RpslObjectInfo> decorate(final Query query, final RpslObject rpslObject) { final Set<ObjectType> excludeObjectTypes = query.hasOption(QueryFlag.NO_PERSONAL) ? NO_PERSONAL_EXCLUDES : Collections.<ObjectType>emptySet(); return rpslObjectDao.relatedTo(rpslObject, excludeObjectTypes); } @Autowired RelatedToDecorator(final RpslObjectDao rpslObjectDao); @Override boolean appliesToQuery(final Query query); @Override Collection<RpslObjectInfo> decorate(final Query query, final RpslObject rpslObject); }### Answer: @Test public void decorate() { RpslObject rpslObject = RpslObject.parse("mntner: DEV-MNT"); subject.decorate(Query.parse("DEV-MNT"), rpslObject); verify(rpslObjectDao, times(1)).relatedTo(rpslObject, Collections.<ObjectType>emptySet()); } @Test public void decorate_no_personal() { RpslObject rpslObject = RpslObject.parse("mntner: DEV-MNT"); subject.decorate(Query.parse("--no-personal DEV-MNT"), rpslObject); verify(rpslObjectDao, times(1)).relatedTo(rpslObject, Sets.newEnumSet(Lists.newArrayList(ObjectType.PERSON, ObjectType.ROLE), ObjectType.class)); }
### Question: HierarchyLookupIpv6 extends HierarchyLookup<Ipv6Resource, Ipv6Entry> { @Override public ObjectType getSupportedType() { return ObjectType.INET6NUM; } @Autowired HierarchyLookupIpv6(final Ipv6Tree ipv6Tree, final RpslObjectDao rpslObjectDao); @Override ObjectType getSupportedType(); @Override Ipv6Resource createResource(final String key); }### Answer: @Test public void getSupportedType() { assertThat(subject.getSupportedType(), is(ObjectType.INET6NUM)); }
### Question: HierarchyLookupIpv6 extends HierarchyLookup<Ipv6Resource, Ipv6Entry> { @Override public Ipv6Resource createResource(final String key) { return Ipv6Resource.parse(key); } @Autowired HierarchyLookupIpv6(final Ipv6Tree ipv6Tree, final RpslObjectDao rpslObjectDao); @Override ObjectType getSupportedType(); @Override Ipv6Resource createResource(final String key); }### Answer: @Test public void createResource() { final String resource = "::0"; assertThat(subject.createResource(resource), is(Ipv6Resource.parse(resource))); }
### Question: ToKeysFunction implements Function<ResponseObject, ResponseObject> { @Override public ResponseObject apply(final @Nullable ResponseObject input) { if (!(input instanceof RpslObject)) { return input; } final RpslObject rpslObject = (RpslObject) input; final List<RpslAttribute> attributes = rpslObject.getAttributes(); final List<RpslAttribute> newAttributes = new ArrayList<>(attributes.size()); final ObjectTemplate template = ObjectTemplate.getTemplate(rpslObject.getType()); final RpslAttribute typeAttribute = rpslObject.getTypeAttribute(); final Set<AttributeType> keyAttributes = template.getKeyAttributes(); if (keyAttributes.size() == 1 && keyAttributes.contains(typeAttribute.getType()) && !template.isSet()) { newAttributes.add(typeAttribute); } else { for (final RpslAttribute attribute : attributes) { final AttributeType attributeType = attribute.getType(); if (keyAttributes.contains(attributeType) || (template.isSet() && (AttributeType.MEMBERS.equals(attributeType) || AttributeType.MP_MEMBERS.equals(attributeType)))) { newAttributes.add(attribute); } } } return new RpslAttributes(newAttributes); } @Override ResponseObject apply(final @Nullable ResponseObject input); }### Answer: @Test public void apply_resonseObject() { final ResponseObject object = new MessageObject("text"); final ResponseObject response = subject.apply(object); assertThat(response, is(object)); } @Test public void apply_inetnum() { RpslObject rpslObject = RpslObject.parse("" + "inetnum: 10.0.0.0\n" + "mnt-by: BAR\n" + "source: QUX\n" + "abuse-mailbox: abuse@me.now"); final ResponseObject response = subject.apply(rpslObject); assertThat(response.toString(), is("" + "inetnum: 10.0.0.0\n")); } @Test public void keys_route() { RpslObject rpslObject = RpslObject.parse("" + "route: 193.0.0.0/21\n" + "descr: RIPE-NCC\n" + "origin: AS3333\n" + "mnt-by: RIPE-NCC-MNT\n" + "source: RIPE # Filtered"); final ResponseObject response = subject.apply(rpslObject); assertThat(response.toString(), is("" + "route: 193.0.0.0/21\n" + "origin: AS3333\n")); } @Test public void keys_as_set() { RpslObject rpslObject = RpslObject.parse("" + "as-set: AS-TEST\n" + "descr: Description\n" + "members: AS2602, AS42909, AS51966\n" + "tech-c: PN-RIPE\n" + "admin-c: PN-RIPE\n" + "mnt-by: TEST-MNT\n" + "source: RIPE # Filtered"); final ResponseObject response = subject.apply(rpslObject); assertThat(response.toString(), is("" + "as-set: AS-TEST\n" + "members: AS2602, AS42909, AS51966\n")); }
### Question: RipeGrsSource extends GrsSource { @Override 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 RipeGrsSource( @Value("${grs.import.ripe.source:}") final String source, final SourceContext sourceContext, final DateTimeProvider dateTimeProvider, final AuthoritativeResourceData authoritativeResourceData, final Downloader downloader, @Value("${grs.import.ripe.download:}") final String download); }### Answer: @Test public void handleObjects() throws Exception { final File file = new File(getClass().getResource("/grs/ripe.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: AS1877 - AS1901\n", "descr: RIPE NCC ASN block\n", "remarks: These AS Numbers are further assigned to network\n", "remarks: operators in the RIPE NCC service region. AS\n", "remarks: assignment policy is documented in:\n", "remarks: <http: "remarks: RIPE NCC members can request AS Numbers using the\n", "remarks: form available in the LIR Portal or at:\n", "remarks: <http: "org: ORG-NCC1-RIPE\n", "admin-c: DUMY-RIPE\n", "tech-c: DUMY-RIPE\n", "mnt-by: RIPE-DBM-MNT\n", "mnt-lower: RIPE-NCC-HM-MNT\n", "changed: hostmaster@ripe.net 20090529\n", "source: RIPE\n", "remarks: ****************************\n", "remarks: * THIS OBJECT IS MODIFIED\n", "remarks: * Please note that all data that is generally regarded as personal\n", "remarks: * data has been removed from this object.\n", "remarks: * To view the original object, please query the RIPE Database at:\n", "remarks: * http: "remarks: ****************************\n"), Lists.newArrayList( "as-block: AS2043 - AS2043\n", "descr: RIPE NCC ASN block\n", "remarks: These AS Numbers are further assigned to network\n", "remarks: operators in the RIPE NCC service region. AS\n", "remarks: assignment policy is documented in:\n", "remarks: <http: "remarks: RIPE NCC members can request AS Numbers using the\n", "remarks: form available in the LIR Portal or at:\n", "remarks: <http: "org: ORG-NCC1-RIPE\n", "admin-c: DUMY-RIPE\n", "tech-c: DUMY-RIPE\n", "mnt-by: RIPE-DBM-MNT\n", "mnt-lower: RIPE-NCC-HM-MNT\n", "changed: hostmaster@ripe.net 20090529\n", "source: RIPE\n", "remarks: ****************************\n", "remarks: * THIS OBJECT IS MODIFIED\n", "remarks: * Please note that all data that is generally regarded as personal\n", "remarks: * data has been removed from this object.\n", "remarks: * To view the original object, please query the RIPE Database at:\n", "remarks: * http: "remarks: ****************************\n") )); }
### Question: RelatedIrtDecorator implements PrimaryObjectDecorator { @Override public boolean appliesToQuery(final Query query) { return query.isReturningIrt(); } @Autowired RelatedIrtDecorator(final HierarchyLookupIpv4 hierarchyLookupIpv4, final HierarchyLookupIpv6 hierarchyLookupIpv6); @Override boolean appliesToQuery(final Query query); @Override Collection<RpslObjectInfo> decorate(final Query query, final RpslObject rpslObject); }### Answer: @Test public void appliesToQuery_empty() { assertThat(subject.appliesToQuery(Query.parse("foo")), is(false)); } @Test public void appliesToQuery_no_irt() { assertThat(subject.appliesToQuery(Query.parse("-T inetnum 10.0.0.0")), is(false)); } @Test public void appliesToQuery_capital_C() { assertThat(subject.appliesToQuery(Query.parse("-C -T inetnum 10.0.0.0")), is(false)); } @Test public void appliesToQuery_irt() { assertThat(subject.appliesToQuery(Query.parse("-c -T inetnum 10.0.0.0")), is(true)); }
### Question: RelatedIrtDecorator implements PrimaryObjectDecorator { @Override public Collection<RpslObjectInfo> decorate(final Query query, final RpslObject rpslObject) { for (final HierarchyLookup hierarchyLookup : hierarchyLookups) { if (hierarchyLookup.supports(rpslObject)) { return hierarchyLookup.getReferencedIrtsInHierarchy(rpslObject); } } return Collections.emptyList(); } @Autowired RelatedIrtDecorator(final HierarchyLookupIpv4 hierarchyLookupIpv4, final HierarchyLookupIpv6 hierarchyLookupIpv6); @Override boolean appliesToQuery(final Query query); @Override Collection<RpslObjectInfo> decorate(final Query query, final RpslObject rpslObject); }### Answer: @Test public void decorate_not_supported() { final RpslObject rpslObject = RpslObject.parse("poem:RIPE"); final Collection<RpslObjectInfo> infos = subject.decorate(Query.parse("RIPE"), rpslObject); verify(hierarchyLookupIpv4, times(1)).supports(rpslObject); verify(hierarchyLookupIpv6, times(1)).supports(rpslObject); assertThat(infos, hasSize(0)); } @Test public void decorate_inetnum() { final RpslObject rpslObject = RpslObject.parse("inetnum:0.0.0.0"); final RpslObjectInfo rpslObjectInfo = new RpslObjectInfo(0, ObjectType.IRT, "IRT"); final List<RpslObjectInfo> result = Arrays.asList(rpslObjectInfo); when(hierarchyLookupIpv4.supports(rpslObject)).thenReturn(true); when(hierarchyLookupIpv4.getReferencedIrtsInHierarchy(rpslObject)).thenReturn(result); final Collection<RpslObjectInfo> infos = subject.decorate(Query.parse("0.0.0.0"), rpslObject); verify(hierarchyLookupIpv4, times(1)).supports(rpslObject); assertThat(infos, contains(rpslObjectInfo)); } @Test public void decorate_inet6num() { final RpslObject rpslObject = RpslObject.parse("inetnum: ::0"); final RpslObjectInfo rpslObjectInfo = new RpslObjectInfo(0, ObjectType.IRT, "IRT"); final List<RpslObjectInfo> result = Arrays.asList(rpslObjectInfo); when(hierarchyLookupIpv6.supports(rpslObject)).thenReturn(true); when(hierarchyLookupIpv6.getReferencedIrtsInHierarchy(rpslObject)).thenReturn(result); final Collection<RpslObjectInfo> infos = subject.decorate(Query.parse("::0"), rpslObject); verify(hierarchyLookupIpv6, times(1)).supports(rpslObject); assertThat(infos, contains(rpslObjectInfo)); }
### Question: HierarchyLookupIpv4 extends HierarchyLookup<Ipv4Resource, Ipv4Entry> { @Override public ObjectType getSupportedType() { return ObjectType.INETNUM; } @Autowired HierarchyLookupIpv4(final Ipv4Tree ipv4Tree, final RpslObjectDao rpslObjectDao); @Override ObjectType getSupportedType(); @Override Ipv4Resource createResource(final String key); }### Answer: @Test public void getSupportedType() { assertThat(subject.getSupportedType(), is(ObjectType.INETNUM)); }
### Question: AfrinicGrsSource 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 AfrinicGrsSource( @Value("${grs.import.afrinic.source:}") final String source, final SourceContext sourceContext, final DateTimeProvider dateTimeProvider, final AuthoritativeResourceData authoritativeResourceData, final Downloader downloader, @Value("${grs.import.afrinic.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/afrinic.test.gz").toURI()); subject.handleObjects(file, objectHandler); assertThat(objectHandler.getObjects(), hasSize(0)); assertThat(objectHandler.getLines(), hasSize(5)); assertThat(objectHandler.getLines().get(0), contains( "as-block: AS30980 - AS30980\n", "descr: AfriNIC ASN block\n", "remarks: These AS Numbers are further assigned to network\n" + " operators in the AfriNIC service region. AS\n" + " assignment policy is documented in:\n" + " <http: " AfriNIC members can request AS Numbers using the\n" + " form located at:\n" + " http: "org: ORG-AFNC1-AFRINIC\n", "admin-c: TEAM-AFRINIC\n", "tech-c: TEAM-AFRINIC\n", "mnt-by: AFRINIC-HM-MNT\n", "mnt-lower: AFRINIC-HM-MNT\n", "changed: hostmaster@afrinic.net 20050101\n", "changed: hostmaster@afrinic.net 20050205\n", "remarks: data has been transferred from RIPE Whois Database 20050221\n", "source: AFRINIC\n")); assertThat(objectHandler.getLines().get(1), hasItem("inetnum: 196.207.3.172 - 196.207.3.175\n")); assertThat(objectHandler.getLines().get(2), hasItem("inetnum: 196.204.208.1 - 196.204.208.255\n")); assertThat(objectHandler.getLines().get(3), hasItem("as-block: AS30720 - AS30979\n")); assertThat(objectHandler.getLines().get(4), hasItem("as-block: AS31000 - AS31743\n")); }
### Question: HierarchyLookupIpv4 extends HierarchyLookup<Ipv4Resource, Ipv4Entry> { @Override public Ipv4Resource createResource(final String key) { return Ipv4Resource.parse(key); } @Autowired HierarchyLookupIpv4(final Ipv4Tree ipv4Tree, final RpslObjectDao rpslObjectDao); @Override ObjectType getSupportedType(); @Override Ipv4Resource createResource(final String key); }### Answer: @Test public void createResource() { final String resource = "0.0.0.0"; assertThat(subject.createResource(resource), is(Ipv4Resource.parse(resource))); }
### Question: SyntaxFilterFunction implements Function<ResponseObject, Iterable<? extends ResponseObject>> { @Override public Iterable<? extends ResponseObject> apply(final ResponseObject input) { if (input instanceof RpslObject) { final RpslObject object = (RpslObject) input; if (!validSyntax(object) && isValidSyntaxQuery) { return Arrays.asList(new MessageObject(QueryMessages.invalidSyntax(object.getKey()))); } else if (validSyntax(object) && !isValidSyntaxQuery) { return Arrays.asList(new MessageObject(QueryMessages.validSyntax(object.getKey()))); } } return Collections.singletonList(input); } SyntaxFilterFunction(final boolean validSyntaxQuery); @Override Iterable<? extends ResponseObject> apply(final ResponseObject input); }### Answer: @Test public void validSyntax_valid_flag() { final RpslObject object = RpslObject.parse("" + "mntner: TST-MNT\n" + "descr: description\n" + "admin-c: TEST-RIPE\n" + "mnt-by: TST-MNT\n" + "upd-to: dbtest@ripe.net\n" + "auth: MD5-PW $1$fU9ZMQN9$QQtm3kRqZXWAuLpeOiLN7. # update\n" + "source: TEST"); final Iterable<? extends ResponseObject> result = validSyntaxFilterFunction.apply(object); final ResponseObject responseObject = Iterables.find(result, input -> input instanceof RpslObject); assertThat(responseObject, is(not(nullValue()))); } @Test public void invalidSyntax_valid_flag() { final RpslObject object = RpslObject.parse("" + "person: Admin Person\n" + "address: Admin Road\n" + "address: Town\n" + "address: UK\n" + "phone: wrong@address.net\n" + "nic-hdl: tst-ripe\n" + "mnt-by: TST-MNT\n" + "source: TEST"); final Iterable<? extends ResponseObject> result = validSyntaxFilterFunction.apply(object); assertThat(Iterables.size(result), is(1)); assertThat(Iterables.getFirst(result, null), is(new MessageObject(QueryMessages.invalidSyntax("tst-ripe")))); } @Test public void invalidSyntax_novalid_flag() { final RpslObject object = RpslObject.parse("" + "person: Admin Person\n" + "address: Admin Road\n" + "address: Town\n" + "address: UK\n" + "phone: wrong@address.net\n" + "nic-hdl: tst-ripe\n" + "mnt-by: TST-MNT\n" + "source: TEST"); final Iterable<? extends ResponseObject> result = novalidSyntaxFilterFunction.apply(object); final ResponseObject responseObject = Iterables.find(result, input -> input instanceof RpslObject); assertThat(responseObject, is(not(nullValue()))); }
### Question: ToShorthandFunction implements Function<ResponseObject, ResponseObject> { @Override public ResponseObject apply(final @Nullable ResponseObject input) { if (!(input instanceof RpslObject)) { return input; } final RpslObject rpslObject = (RpslObject) input; final List<RpslAttribute> attributes = rpslObject.getAttributes(); final List<RpslAttribute> newAttributes = new ArrayList<>(attributes.size()); for (RpslAttribute attribute : attributes) { final AttributeType type = attribute.getType(); final String key = type != null ? "*" + type.getFlag() : attribute.getKey(); newAttributes.add(new RpslAttribute(key, RpslAttributeFilter.getValueForShortHand(attribute.getValue()))); } return new RpslObject(rpslObject, newAttributes); } @Override ResponseObject apply(final @Nullable ResponseObject input); }### Answer: @Test public void apply_resonseObject() { final ResponseObject object = new MessageObject("text"); final ResponseObject response = subject.apply(object); assertThat(response, is(object)); } @Test public void apply_mntner() { RpslObject rpslObject = RpslObject.parse("" + "mntner: FOO\n" + "mnt-by: BAR\n" + "source: QUX"); final ResponseObject response = subject.apply(rpslObject); assertThat(response.toString(), is("" + "*mt: FOO\n" + "*mb: BAR\n" + "*so: QUX\n")); } @Test public void apply_unknown() { RpslObject rpslObject = RpslObject.parse("" + "mntner:FOO\n" + "IREALLYDUNNO:BAR\n" + "source:QUX"); final ResponseObject response = subject.apply(rpslObject); assertThat(response.toString(), is("" + "*mt: FOO\n" + "ireallydunno: BAR\n" + "*so: QUX\n")); } @Test public void apply_can_be_parsed_back() { RpslObject rpslObject = RpslObject.parse("" + "mntner:FOO\n" + "IREALLYDUNNO:BAR\n" + "source:QUX"); final ResponseObject response = subject.apply(rpslObject); assertThat(RpslObject.parse(response.toString()), is(rpslObject)); } @Test public void shorthand_empty_attribute() { RpslObject rpslObject = RpslObject.parse("" + "mntner: FOO\n" + "address:\n" + "source: QUX"); final ResponseObject response = subject.apply(rpslObject); assertThat(response.toString(), is("" + "*mt: FOO\n" + "*ad:\n" + "*so: QUX\n")); }
### Question: SystemInfoQueryExecutor implements QueryExecutor { @Override public boolean supports(final Query query) { return query.isSystemInfo(); } @Autowired SystemInfoQueryExecutor(final ApplicationVersion applicationVersion, final SourceContext sourceContext); @Override boolean isAclSupported(); @Override boolean supports(final Query query); @Override void execute(final Query query, final ResponseHandler responseHandler); }### Answer: @Test public void supports_version_ignore_case() { assertThat(subject.supports(Query.parse("-q Version")), is(true)); } @Test public void supports_types_ignore_case() { assertThat(subject.supports(Query.parse("-q Types")), is(true)); } @Test public void supports_sources_ignore_case() { assertThat(subject.supports(Query.parse("-q Sources")), is(true)); }
### Question: SystemInfoQueryExecutor implements QueryExecutor { @Override public void execute(final Query query, final ResponseHandler responseHandler) { final Query.SystemInfoOption systemInfoOption = query.getSystemInfoOption(); final String responseString; switch (systemInfoOption) { case VERSION: responseString = "% whois-server-" + applicationVersion.getVersion(); break; case TYPES: { final StringBuilder builder = new StringBuilder(); for (ObjectType type : ORDERED_TYPES) { builder.append(type.getName()); builder.append('\n'); } responseString = builder.toString(); break; } case SOURCES: { StringBuilder builder = new StringBuilder(); for (final CIString source : sourceContext.getAllSourceNames()) { builder.append(String.format("%s:3:N:0-0\n", source)); if (sourceContext.getNonauthSource() != null && sourceContext.getWhoisMasterSource().getName().equals(source)) { builder.append(String.format("%s:3:N:0-0\n", sourceContext.getNonauthSource().getName())); } } responseString = builder.toString(); break; } default: throw new QueryException(QueryCompletionInfo.PARAMETER_ERROR, QueryMessages.malformedQuery()); } responseHandler.handle(new MessageObject(responseString)); } @Autowired SystemInfoQueryExecutor(final ApplicationVersion applicationVersion, final SourceContext sourceContext); @Override boolean isAclSupported(); @Override boolean supports(final Query query); @Override void execute(final Query query, final ResponseHandler responseHandler); }### Answer: @Test public void types_query() { final CaptureResponseHandler responseHandler = new CaptureResponseHandler(); subject.execute(Query.parse("-q types"), responseHandler); Iterator<? extends ResponseObject> iterator = responseHandler.getResponseObjects().iterator(); String responseString = iterator.next().toString(); assertThat(iterator.hasNext(), is(false)); for (ObjectType objectType : ObjectType.values()) { assertThat(responseString, containsString(objectType.getName())); } } @Test public void types_query_invalid_argument() { try { subject.execute(Query.parse("-q invalid"), new CaptureResponseHandler()); fail("expected QueryException to be thrown"); } catch (QueryException qe) { assertThat(qe.getMessage(), containsString(QueryMessages.malformedQuery().toString())); } } @Test public void version_query() { final CaptureResponseHandler responseHandler = new CaptureResponseHandler(); subject.execute(Query.parse("-q version"), responseHandler); Iterator<? extends ResponseObject> iterator = responseHandler.getResponseObjects().iterator(); String responseString = iterator.next().toString(); assertThat(iterator.hasNext(), is(false)); assertThat(responseString, containsString("% whois-server")); } @Test public void sources_query() { when(sourceContext.getAllSourceNames()).thenReturn(ciSet("RIPE")); final CaptureResponseHandler responseHandler = new CaptureResponseHandler(); subject.execute(Query.parse("-q sources"), responseHandler); Iterator<? extends ResponseObject> iterator = responseHandler.getResponseObjects().iterator(); String responseString = iterator.next().toString(); assertThat(iterator.hasNext(), is(false)); assertThat(responseString, containsString("RIPE:3:N:0-0\n")); }
### Question: HelpQueryExecutor implements QueryExecutor { @Override public boolean supports(final Query query) { return !query.hasOptions() && query.isHelp(); } @Override boolean isAclSupported(); @Override boolean supports(final Query query); @Override void execute(final Query query, final ResponseHandler responseHandler); }### Answer: @Test public void supports_help() { assertThat(subject.supports(Query.parse("help")), is(true)); } @Test public void supports_help_ignore_case() { assertThat(subject.supports(Query.parse("HeLp")), is(true)); } @Test public void supports_help_with_other_argument() { assertThat(subject.supports(Query.parse("help invalid")), is(false)); } @Test public void supports_help_with_other_flags() { assertThat(subject.supports(Query.parse("help -T person")), is(false)); }
### Question: HelpQueryExecutor implements QueryExecutor { @Override public void execute(final Query query, final ResponseHandler responseHandler) { responseHandler.handle(HELP_RESPONSE); } @Override boolean isAclSupported(); @Override boolean supports(final Query query); @Override void execute(final Query query, final ResponseHandler responseHandler); }### Answer: @Test public void getResponse() { final CaptureResponseHandler responseHandler = new CaptureResponseHandler(); subject.execute(null, responseHandler); final String helpText = responseHandler.getResponseObjects().get(0).toString(); assertThat(helpText, containsString("NAME")); assertThat(helpText, containsString("DESCRIPTION")); for (final QueryFlag queryFlag : QueryFlag.values()) { if (!HelpQueryExecutor.SKIPPED.contains(queryFlag)) { assertThat(helpText, containsString(queryFlag.toString())); } } for (final String line : Splitter.on('\n').split(helpText)) { if (line.length() > 0) { assertThat(line, startsWith("%")); } } assertThat(helpText, containsString("RIPE Database Reference Manual")); }
### Question: FilterPersonalDecorator implements ResponseDecorator { @Override public Iterable<? extends ResponseObject> decorate(final Query query, final Iterable<? extends ResponseObject> input) { if (query.hasOption(QueryFlag.SHOW_PERSONAL) || !query.hasOption(QueryFlag.NO_PERSONAL)) { return input; } return new IterableTransformer<ResponseObject>(input) { @Override public void apply(ResponseObject input, Deque<ResponseObject> result) { if (!(input instanceof RpslObject) || !PERSONAL.contains(((RpslObject) input).getType())) { result.add(input); } } }.setHeader(new MessageObject(QueryMessages.noPersonal())); } @Override Iterable<? extends ResponseObject> decorate(final Query query, final Iterable<? extends ResponseObject> input); }### Answer: @Test public void no_personal_filters_personal_objects() { List<ResponseObject> input = Lists.newArrayList(relatedMessage, maintainer, role, person, abuseRole); final Query query = Query.parse(String.format("%s test", QueryFlag.NO_PERSONAL)); final Set<ResponseObject> response = Sets.newLinkedHashSet(subject.decorate(query, input)); assertThat(response, hasSize(3)); assertThat(response, contains(filterMessage, relatedMessage, maintainer)); } @Test public void no_personal_message_only() { List<ResponseObject> input = Lists.newArrayList(filterMessage); final Query query = Query.parse(String.format("%s unknown", QueryFlag.NO_PERSONAL)); final Set<ResponseObject> response = Sets.newLinkedHashSet(subject.decorate(query, input)); assertThat(response, hasSize(1)); assertThat(response, contains(filterMessage)); } @Test public void show_personal_filters_nothing() { List<ResponseObject> input = Lists.newArrayList(relatedMessage, maintainer, role, person, abuseRole); final Query query = Query.parse(String.format("%s test", QueryFlag.SHOW_PERSONAL)); final Set<ResponseObject> response = Sets.newLinkedHashSet(subject.decorate(query, input)); assertThat(response, hasSize(5)); assertThat(response, contains(relatedMessage, maintainer, role, person, abuseRole)); } @Test public void show_personal_and_no_personal() { List<ResponseObject> input = Lists.newArrayList(relatedMessage, maintainer, role, person, abuseRole); final Query query = Query.parse(String.format("%s %s test", QueryFlag.NO_PERSONAL, QueryFlag.SHOW_PERSONAL)); final Set<ResponseObject> response = Sets.newLinkedHashSet(subject.decorate(query, input)); assertThat(response, hasSize(5)); assertThat(response, contains(relatedMessage, maintainer, role, person, abuseRole)); }
### Question: FilterTagsDecorator implements ResponseDecorator { public Iterable<? extends ResponseObject> decorate(final Query query, final Iterable<? extends ResponseObject> input) { final boolean showTagInfo = query.hasOption(QueryFlag.SHOW_TAG_INFO); final boolean hasInclude = query.hasOption(QueryFlag.FILTER_TAG_INCLUDE); final boolean hasExclude = query.hasOption(QueryFlag.FILTER_TAG_EXCLUDE); if (!(showTagInfo || hasInclude || hasExclude)) { return input; } final Set<CIString> includeArguments = query.getOptionValuesCI(QueryFlag.FILTER_TAG_INCLUDE); final Set<CIString> excludeArguments = query.getOptionValuesCI(QueryFlag.FILTER_TAG_EXCLUDE); final IterableTransformer<ResponseObject> responseObjects = new IterableTransformer<ResponseObject>(input) { @Override public void apply(final ResponseObject input, final Deque<ResponseObject> result) { if (!(input instanceof RpslObject)) { result.add(input); return; } final RpslObject object = (RpslObject) input; final List<Tag> tags = tagsDao.getTags(object.getObjectId()); if (hasInclude && !containsTag(tags, includeArguments)) { return; } if (hasExclude && containsTag(tags, excludeArguments)) { return; } result.add(object); if (showTagInfo && !tags.isEmpty()) { result.add(new TagResponseObject(object.getKey(), tags)); } } }; if (hasInclude || hasExclude) { responseObjects.setHeader(new MessageObject(QueryMessages.filterTagNote(includeArguments, excludeArguments))); } return responseObjects; } @Autowired FilterTagsDecorator(TagsDao tagsDao); Iterable<? extends ResponseObject> decorate(final Query query, final Iterable<? extends ResponseObject> input); }### Answer: @Test public void unrefInfo_for_unreferenced_role() { when(tagsDao.getTags(1)).thenReturn(Lists.newArrayList(new Tag(CIString.ciString("unref"), 1, "34"))); final RpslObject role = RpslObject.parse(1, "role: Test Role\nnic-hdl: TR1-TEST"); final Query query = Query.parse("--show-tag-info TR1-TEST"); final Iterable<? extends ResponseObject> result = subject.decorate(query, ImmutableList.of(role)); final Iterator<? extends ResponseObject> iterator = result.iterator(); assertThat(iterator.next() instanceof RpslObject, is(true)); assertThat(iterator.next().toString(), is("% Tags relating to 'TR1-TEST'\n" + "% Unreferenced # 'TR1-TEST' will be deleted in 34 days\n")); assertThat(iterator.hasNext(), is(false)); } @Test public void no_unrefInfo_for_referenced_mntner() { when(tagsDao.getTags(1)).thenReturn(Lists.<Tag>newArrayList()); final Query query = Query.parse("--show-tag-info TEST-MNT"); final RpslObject mntner = RpslObject.parse(1, "mntner: TEST-MNT"); final Iterable<? extends ResponseObject> result = subject.decorate(query, ImmutableList.of(mntner)); final Iterator<? extends ResponseObject> iterator = result.iterator(); final RpslObject object = (RpslObject) iterator.next(); assertThat(mntner, is(object)); assertFalse(iterator.hasNext()); }
### Question: TemplateQueryExecutor implements QueryExecutor { @Override public boolean supports(final Query query) { return (query.isTemplate() || query.isVerbose()); } @Override boolean isAclSupported(); @Override boolean supports(final Query query); @Override void execute(final Query query, final ResponseHandler responseHandler); }### Answer: @Test public void supports_template() { assertThat(subject.supports(Query.parse("-t inetnum")), is(true)); } @Test public void supports_template_case_insensitive() { assertThat(subject.supports(Query.parse("-t iNeTnUm")), is(true)); } @Test public void supports_template_multiple() { assertThat(subject.supports(Query.parse("-t inetnum,inet6num")), is(true)); } @Test public void supports_template_with_type() { assertThat(subject.supports(Query.parse("-t inetnum,inet6num -T inetnum 0/0")), is(true)); } @Test public void supports_template_with_type_invalid() { assertThat(subject.supports(Query.parse("-t inetnum,inet6num -T inetnum")), is(true)); } @Test public void supports_template_with_searchValue() { assertThat(subject.supports(Query.parse("-t inetnum,inet6num query")), is(true)); } @Test public void supports_verbose() { assertThat(subject.supports(Query.parse("-v inetnum")), is(true)); } @Test public void supports_verbose_case_insensitive() { assertThat(subject.supports(Query.parse("-v InEtNuM")), is(true)); } @Test public void supports_verbose_multiple() { assertThat(subject.supports(Query.parse("-v inetnum,inetn6num")), is(true)); } @Test public void supports_verbose_with_type() { assertThat(subject.supports(Query.parse("-v inetnum,inet6num -T inetnum 0/0")), is(true)); } @Test public void supports_verbose_with_searchValue() { assertThat(subject.supports(Query.parse("-v inetnum,inet6num query")), is(true)); } @Test public void supports_template_with_other_arguments() { assertThat(subject.supports(Query.parse("-V ripews -t person")), is(true)); }
### Question: TemplateQueryExecutor implements QueryExecutor { @Override public void execute(final Query query, final ResponseHandler responseHandler) { final String objectTypeString = query.isTemplate() ? query.getTemplateOption() : query.getVerboseOption(); final ObjectType objectType = ObjectType.getByNameOrNull(objectTypeString); final MessageObject messageObject; if (objectType == null) { messageObject = new MessageObject(QueryMessages.invalidObjectType(objectTypeString)); } else { messageObject = new MessageObject(query.isTemplate() ? getTemplate(objectType) : getVerbose(objectType)); } responseHandler.handle(messageObject); } @Override boolean isAclSupported(); @Override boolean supports(final Query query); @Override void execute(final Query query, final ResponseHandler responseHandler); }### Answer: @Test public void getResponse() { for (final ObjectType objectType : ObjectType.values()) { final String name = objectType.getName(); final CaptureResponseHandler templateResponseHandler = new CaptureResponseHandler(); subject.execute(Query.parse("-t " + name), templateResponseHandler); final String templateText = templateResponseHandler.getResponseObjects().iterator().next().toString(); assertThat(templateText, containsString(name)); final CaptureResponseHandler verboseResponseHandler = new CaptureResponseHandler(); subject.execute(Query.parse("-v " + name), verboseResponseHandler); final String verboseText = verboseResponseHandler.getResponseObjects().iterator().next().toString(); assertThat(verboseText, containsString(name)); assertThat(verboseText, not(is(templateText))); } }
### Question: RpslObjectSearcher { public Iterable<? extends ResponseObject> search(final Query query, final SourceContext sourceContext) { Iterable<? extends ResponseObject> result = Collections.emptyList(); if (query.hasSubstitutions()) { result = Collections.singleton(new MessageObject(QueryMessages.valueChangedDueToLatin1Conversion())); } if (query.isInverse()) { result = indexLookupReverse(query); } else if (query.isMatchPrimaryKeyOnly()) { result = indexLookupDirect(query); } else { for (final ObjectType objectType : query.getObjectTypes()) { result = Iterables.concat(result, executeForObjectType(query, objectType)); } } for (AttributeFilter attributeFilter : attributeFilters) { result = attributeFilter.filter(result, query.getSources(), sourceContext); } return result; } @Autowired RpslObjectSearcher( final RpslObjectDao rpslObjectDao, final InetnumDao inetnumDao, final Inet6numDao inet6numDao, final Ipv4Tree ipv4Tree, final Ipv6Tree ipv6Tree, final Ipv4RouteTree route4Tree, final Ipv6RouteTree route6Tree, final Ipv4DomainTree ipv4DomainTree, final Ipv6DomainTree ipv6DomainTree, final Set<AttributeFilter> attributeFilters); Iterable<? extends ResponseObject> search(final Query query, final SourceContext sourceContext); }### Answer: @Test public void inverse_lookup_never_returns_null() { for (final AttributeType attributeType : AttributeType.values()) { assertNotNull(subject.search(Query.parse("-i " + attributeType.getName() + " query"), sourceContext)); } } @Test public void inverse_lookup_unsupported_attribute() { final Iterator<? extends ResponseObject> responseIterator = subject.search(Query.parse("-i e-mail,phone something"), sourceContext).iterator(); assertThat(responseIterator.next().toString(), is(QueryMessages.attributeNotSearchable("e-mail").toString())); assertThat(responseIterator.next().toString(), is(QueryMessages.attributeNotSearchable("phone").toString())); assertThat(responseIterator.hasNext(), is(false)); }
### Question: VersionQueryExecutor implements QueryExecutor { @Override public boolean supports(final Query query) { return query.isVersionList() || query.isObjectVersion() || query.isVersionDiff(); } @Autowired VersionQueryExecutor(final BasicSourceContext sourceContext, @Qualifier("jdbcVersionDao") final VersionDao versionDao); @Override boolean isAclSupported(); @Override boolean supports(final Query query); @Override void execute(final Query query, final ResponseHandler responseHandler); Collection<VersionLookupResult> getVersionInfo(final Query query); static final Set<ObjectType> NO_VERSION_HISTORY_FOR; }### Answer: @Test public void supportTest() { assertThat(subject.supports(Query.parse("10.0.0.0")), is(false)); assertThat(subject.supports(Query.parse("--list-versions 10.0.0.0")), is(true)); assertThat(subject.supports(Query.parse("--show-version 2 10.0.0.0")), is(true)); }
### Question: SearchQueryExecutor implements QueryExecutor { @Override public boolean supports(final Query query) { if ((!query.hasOptions() && query.isHelp()) || query.isSystemInfo() || query.isTemplate() || query.isVerbose() || query.isVersionList() || query.isObjectVersion() || query.isVersionDiff()) { return false; } return true; } @Autowired SearchQueryExecutor(final SourceContext sourceContext, final RpslObjectSearcher rpslObjectSearcher, final RpslResponseDecorator rpslResponseDecorator); @Override boolean isAclSupported(); @Override boolean supports(final Query query); @Override void execute(final Query query, final ResponseHandler responseHandler); }### Answer: @Test public void all_attributes_handled() { for (final AttributeType attributeType : AttributeType.values()) { assertTrue(subject.supports(Query.parse("-i " + attributeType.getName() + " query"))); } } @Test(expected = QueryException.class) public void test_supports_no_attributes() { assertThat(subject.supports(Query.parse("-i")), is(false)); } @Test public void test_supports_inverse_with_filter() { assertThat(subject.supports(Query.parse("-T inetnum -i mnt-by aardvark-mnt")), is(true)); } @Test public void test_supports_inverse_recursive() { assertThat(subject.supports(Query.parse("-i mnt-by aardvark-mnt")), is(true)); } @Test public void test_supports_inverse() { assertThat(subject.supports(Query.parse("-r -i mnt-by aardvark-mnt")), is(true)); } @Test public void test_supports_inverse_multiple() { assertThat(subject.supports(Query.parse("-r -i mnt-by,mnt-ref aardvark-mnt")), is(true)); } @Test public void test_supports_inverse_multiple_unknown() { assertThat(subject.supports(Query.parse("-r -i mnt-by,mnt-ref,mnt-lower aardvark-mnt")), is(true)); }
### Question: QueryDecoder extends OneToOneDecoder { @Override protected Object decode(final ChannelHandlerContext ctx, final Channel channel, final Object msg) { final Query query = Query.parse((String) msg, Query.Origin.LEGACY, isTrusted(channel)); for (final Message warning : query.getWarnings()) { channel.write(warning); } return query; } @Autowired QueryDecoder(final AccessControlListManager accessControlListManager); }### Answer: @Test public void validDecodedStringShouldReturnQuery() throws Exception { String queryString = "-Tperson DW-RIPE"; Query expectedQuery = Query.parse(queryString); when(channelMock.getRemoteAddress()).thenReturn(new InetSocketAddress(InetAddresses.forString("10.0.0.1"), 80)); Query actualQuery = (Query) subject.decode(channelHandlerContextMock, channelMock, queryString); assertEquals(expectedQuery, actualQuery); } @Test public void invalidOptionQuery() { String queryString = "-Yperson DW-RIPE"; when(channelMock.getRemoteAddress()).thenReturn(new InetSocketAddress(InetAddresses.forString("10.0.0.1"), 80)); try { subject.decode(null, channelMock, queryString); fail("Expected query exception"); } catch (QueryException e) { assertThat(e.getCompletionInfo(), is(QueryCompletionInfo.PARAMETER_ERROR)); } } @Test public void invalidProxyQuery() throws Exception { String queryString = "-Vone,two,three DW-RIPE"; when(channelMock.getRemoteAddress()).thenReturn(new InetSocketAddress(InetAddresses.forString("10.0.0.1"), 80)); try { subject.decode(null, channelMock, queryString); fail("Expected query exception"); } catch (QueryException e) { assertThat(e.getCompletionInfo(), is(QueryCompletionInfo.PARAMETER_ERROR)); } }
### Question: WhoisEncoder extends OneToOneEncoder { @Override protected Object encode(final ChannelHandlerContext ctx, final Channel channel, final Object msg) throws IOException { if (msg instanceof ResponseObject) { final ChannelBuffer result = ChannelBuffers.dynamicBuffer(DEFAULT_BUFFER_SIZE); final ChannelBufferOutputStream out = new ChannelBufferOutputStream(result); ((ResponseObject) msg).writeTo(out); out.write(OBJECT_TERMINATOR); return result; } else if (msg instanceof Message) { return ChannelBuffers.wrappedBuffer(msg.toString().getBytes(StandardCharsets.UTF_8), OBJECT_TERMINATOR); } return msg; } }### Answer: @Test public void encode_null() throws IOException { Object result = encode(null); assertThat(result, is(nullValue())); } @Test public void encode_Message() throws IOException { Message message = QueryMessages.inputTooLong(); ChannelBuffer result = encode(message); assertThat(toString(result), is(message.toString() + "\n")); } @Test public void encode_ResponseObject() throws IOException { ChannelBuffer result = encode(objectMock); verify(objectMock, times(1)).writeTo(any(OutputStream.class)); assertThat(toString(result), is("\n")); }
### Question: ServedByHandler implements ChannelDownstreamHandler { @Override public void handleDownstream(final ChannelHandlerContext ctx, final ChannelEvent e) { if (e instanceof QueryCompletedEvent) { e.getChannel().write(QueryMessages.servedByNotice(version)); } ctx.sendDownstream(e); } ServedByHandler(final String version); @Override void handleDownstream(final ChannelHandlerContext ctx, final ChannelEvent e); }### Answer: @Test public void test_handleDownstream_whois() { when(messageEventMock.getMessage()).thenReturn(new MessageObject("")); subject.handleDownstream(ctxMock, messageEventMock); verify(ctxMock, times(1)).sendDownstream(messageEventMock); subject.handleDownstream(ctxMock, queryCompletedEventMock); verify(ctxMock, times(1)).sendDownstream(queryCompletedEventMock); verify(channelMock, times(1)).write(QueryMessages.servedByNotice(anyString())); }
### Question: ConnectionStateHandler extends SimpleChannelUpstreamHandler implements ChannelDownstreamHandler { @Override public void handleDownstream(final ChannelHandlerContext ctx, final ChannelEvent e) { ctx.sendDownstream(e); if (e instanceof QueryCompletedEvent) { final Channel channel = e.getChannel(); if (keepAlive && !((QueryCompletedEvent) e).isForceClose()) { channel.write(NEWLINE); channel.write(QueryMessages.termsAndConditions()); } else { closed = true; channel.write(NEWLINE).addListener(ChannelFutureListener.CLOSE); } } } @Override void messageReceived(final ChannelHandlerContext ctx, final MessageEvent e); @Override void handleDownstream(final ChannelHandlerContext ctx, final ChannelEvent e); }### Answer: @Test public void sendingNoKFlagShouldNotEnableKeepAlive() throws Exception { when(messageMock.getMessage()).thenReturn(Query.parse("help")); subject.handleUpstream(contextMock, messageMock); verify(contextMock, times(1)).sendUpstream(messageMock); subject.handleDownstream(contextMock, new QueryCompletedEvent(channelMock)); verify(channelMock, times(1)).write(ConnectionStateHandler.NEWLINE); verify(futureMock, times(1)).addListener(ChannelFutureListener.CLOSE); } @Test public void sendingNoKFlagButConnectionStateIsKeepAliveKeepItThatWay() throws Exception { when(messageMock.getMessage()).thenReturn(Query.parse("-k")); subject.handleUpstream(contextMock, messageMock); when(messageMock.getMessage()).thenReturn(Query.parse("help")); subject.handleUpstream(contextMock, messageMock); verify(contextMock, times(1)).sendUpstream(messageMock); subject.handleDownstream(contextMock, new QueryCompletedEvent(channelMock)); verify(channelMock, times(1)).write(QueryMessages.termsAndConditions()); verify(futureMock, times(0)).addListener(ChannelFutureListener.CLOSE); } @Test public void firstSingleKShouldKeepConnectionOpen() throws Exception { when(messageMock.getMessage()).thenReturn(Query.parse("-k")); subject.handleUpstream(contextMock, messageMock); verify(contextMock, times(0)).sendUpstream(messageMock); subject.handleDownstream(contextMock, new QueryCompletedEvent(channelMock)); verify(futureMock, times(0)).addListener(ChannelFutureListener.CLOSE); } @Test public void firstKWithArgumentsShouldKeepConnectionOpen() throws Exception { when(messageMock.getMessage()).thenReturn(Query.parse("-k -r -T inetnum 10.0.0.0")); subject.handleUpstream(contextMock, messageMock); verify(contextMock, times(1)).sendUpstream(messageMock); when(contextMock.getAttachment()).thenReturn(Boolean.TRUE); subject.handleDownstream(contextMock, new QueryCompletedEvent(channelMock)); verify(futureMock, times(0)).addListener(ChannelFutureListener.CLOSE); verify(channelMock, times(2)).write(any()); } @Test public void secondKWithArgumentsShouldKeepConnectionOpen() throws Exception { when(messageMock.getMessage()).thenReturn(Query.parse("-k -r -T inetnum 10.0.0.0")); subject.handleUpstream(contextMock, messageMock); verify(contextMock, times(1)).sendUpstream(messageMock); subject.handleDownstream(contextMock, new QueryCompletedEvent(channelMock)); verify(futureMock, times(0)).addListener(ChannelFutureListener.CLOSE); } @Test public void forceCloseShouldCloseConnection() throws Exception { when(messageMock.getMessage()).thenReturn(Query.parse("-k -r -T inetnum 10.0.0.0")); subject.handleUpstream(contextMock, messageMock); verify(contextMock, times(1)).sendUpstream(messageMock); subject.handleDownstream(contextMock, new QueryCompletedEvent(channelMock, QueryCompletionInfo.DISCONNECTED)); verify(channelMock, times(0)).write(QueryMessages.termsAndConditions()); verify(channelMock, times(1)).write(ConnectionStateHandler.NEWLINE); verify(futureMock, times(1)).addListener(ChannelFutureListener.CLOSE); } @Test public void dontActOnDownstreamNonQueryCompletedEvents() throws Exception { subject.handleDownstream(contextMock, null); verify(channelMock, times(0)).write(any()); }
### Question: ExceptionHandler extends SimpleChannelUpstreamHandler { @Override public void messageReceived(final ChannelHandlerContext ctx, final MessageEvent e) { query = e.getMessage().toString(); ctx.sendUpstream(e); } @Override void messageReceived(final ChannelHandlerContext ctx, final MessageEvent e); @Override void exceptionCaught(final ChannelHandlerContext ctx, final ExceptionEvent event); }### Answer: @Test public void record_incoming_queries() throws Exception { subject.messageReceived(channelHandlerContextMock, messageEventMock); verify(channelHandlerContextMock, times(1)).sendUpstream(messageEventMock); }
### Question: ExceptionHandler extends SimpleChannelUpstreamHandler { @Override public void exceptionCaught(final ChannelHandlerContext ctx, final ExceptionEvent event) { final Throwable cause = event.getCause(); LOGGER.debug("Caught exception", cause); final Channel channel = event.getChannel(); if (cause instanceof ClosedChannelException) { LOGGER.debug("Channel closed", cause); } else if (cause instanceof QueryException) { handleException(channel, ((QueryException) cause).getMessages(), ((QueryException) cause).getCompletionInfo()); } else if (cause instanceof TimeoutException) { handleException(channel, Collections.singletonList(QueryMessages.timeout()), QueryCompletionInfo.EXCEPTION); } else if (cause instanceof TooLongFrameException) { handleException(channel, Collections.singletonList(QueryMessages.inputTooLong()), QueryCompletionInfo.EXCEPTION); } else if (cause instanceof IOException) { handleException(channel, Collections.<Message>emptyList(), QueryCompletionInfo.EXCEPTION); } else if (cause instanceof DataAccessException) { LOGGER.error("Caught exception on channel id = {}, from = {} for query = {}\n{}", channel.getId(), ChannelUtil.getRemoteAddress(channel), query, cause.toString()); handleException(channel, Collections.singletonList(QueryMessages.internalErroroccurred()), QueryCompletionInfo.EXCEPTION); } else { LOGGER.error("Caught exception on channel id = {}, from = {} for query = {}", channel.getId(), ChannelUtil.getRemoteAddress(channel), query, cause); handleException(channel, Collections.singletonList(QueryMessages.internalErroroccurred()), QueryCompletionInfo.EXCEPTION); } } @Override void messageReceived(final ChannelHandlerContext ctx, final MessageEvent e); @Override void exceptionCaught(final ChannelHandlerContext ctx, final ExceptionEvent event); }### Answer: @Test public void handle_unknown_exceptions() throws Exception { subject.exceptionCaught(channelHandlerContextMock, exceptionEventMock); verify(channelMock, times(1)).write(QueryMessages.internalErroroccurred()); } @Test public void handle_timeout_exception() throws Exception { when(exceptionEventMock.getCause()).thenReturn(new TimeoutException()); subject.exceptionCaught(null, exceptionEventMock); verify(channelMock, times(1)).write(QueryMessages.timeout()); } @Test public void handle_too_long_frame_exception() throws Exception { when(exceptionEventMock.getCause()).thenReturn(new TooLongFrameException()); subject.exceptionCaught(null, exceptionEventMock); verify(channelMock, times(1)).write(QueryMessages.inputTooLong()); } @Test public void handle_io_exception() throws Exception { when(exceptionEventMock.getCause()).thenReturn(new IOException()); subject.exceptionCaught(null, exceptionEventMock); verify(channelPipelineMock, times(1)).sendDownstream(new QueryCompletedEvent(channelMock, QueryCompletionInfo.EXCEPTION)); } @Test public void no_write_if_channel_closed() { when(channelMock.isOpen()).thenReturn(false); when(exceptionEventMock.getCause()).thenReturn(new TimeoutException()); subject.exceptionCaught(null, exceptionEventMock); verify(channelMock, times(0)).write(QueryMessages.timeout()); }
### Question: TermsAndConditionsHandler extends SimpleChannelUpstreamHandler { @Override public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) { e.getChannel().write(TERMS_AND_CONDITIONS); ctx.sendUpstream(e); } @Override void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e); }### Answer: @Test public void test_terms_and_conditions() { subject.channelConnected(ctxMock, channelStateEventMock); verify(ctxMock, times(1)).sendUpstream(channelStateEventMock); verify(channelMock, times(1)).write(QueryMessages.termsAndConditions()); }
### Question: WhoisServerHandler extends SimpleChannelUpstreamHandler { @Override public void messageReceived(final ChannelHandlerContext ctx, final MessageEvent event) { final Query query = (Query) event.getMessage(); final Channel channel = event.getChannel(); queryHandler.streamResults(query, ChannelUtil.getRemoteAddress(channel), channel.getId(), new ResponseHandler() { @Override public String getApi() { return "QRY"; } @Override public void handle(final ResponseObject responseObject) { if (closed) { throw new QueryException(QueryCompletionInfo.DISCONNECTED); } channel.write(responseObject); } }); channel.getPipeline().sendDownstream(new QueryCompletedEvent(channel)); } WhoisServerHandler(final QueryHandler queryHandler); @Override void messageReceived(final ChannelHandlerContext ctx, final MessageEvent event); @Override void channelClosed(final ChannelHandlerContext ctx, final ChannelStateEvent e); }### Answer: @Test public void messageReceived_no_proxy_no_personal_object() throws Exception { final Query query = Query.parse("10.0.0.0"); when(messageEvent.getMessage()).thenReturn(query); subject.messageReceived(ctx, messageEvent); verify(channel).write(responseObject); final ArgumentCaptor<QueryCompletedEvent> channelEventCapture = ArgumentCaptor.forClass(QueryCompletedEvent.class); verify(pipeline).sendDownstream(channelEventCapture.capture()); assertNull(channelEventCapture.getValue().getCompletionInfo()); }
### Question: ConnectionPerIpLimitHandler extends SimpleChannelUpstreamHandler { private boolean connectionsExceeded(final InetAddress remoteAddress) { final Integer count = connectionCounter.increment(remoteAddress); return (count != null && count >= maxConnectionsPerIp); } @Autowired ConnectionPerIpLimitHandler( final IpResourceConfiguration ipResourceConfiguration, final WhoisLog whoisLog, @Value("${whois.limit.connectionsPerIp:3}") final int maxConnectionsPerIp, final ApplicationVersion applicationVersion); @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 QueryMessages.connectionsExceeded(MAX_CONNECTIONS_PER_IP).equals(argument); } })); verify(channelFuture, times(1)).addListener(ChannelFutureListener.CLOSE); verify(whoisLog).logQueryResult(anyString(), eq(0), eq(0), eq(QueryCompletionInfo.REJECTED), eq(0L), (InetAddress) Mockito.anyObject(), Mockito.anyInt(), eq("")); verify(ctx, times(2)).sendUpstream(openEvent); }
### Question: TagValidator implements QueryValidator { @Override public void validate(final Query query, final Messages messages) { if (query.hasOption(QueryFlag.FILTER_TAG_INCLUDE) && query.hasOption(QueryFlag.FILTER_TAG_EXCLUDE)) { final Sets.SetView<String> intersection = Sets.intersection(query.getOptionValues(QueryFlag.FILTER_TAG_INCLUDE), query.getOptionValues(QueryFlag.FILTER_TAG_EXCLUDE)); if (!intersection.isEmpty()) { final String args = " (" + Joiner.on(',').join(intersection.iterator()) + ")"; messages.add(QueryMessages.invalidCombinationOfFlags( QueryFlag.FILTER_TAG_INCLUDE.toString() + args, QueryFlag.FILTER_TAG_EXCLUDE.toString() + args)); } } } @Override void validate(final Query query, final Messages messages); }### Answer: @Test public void both_filter_tag_include_and_exclude() { try { subject.validate(Query.parse("--filter-tag-include unref --filter-tag-exclude unref TEST-MNT"), messages); } catch (QueryException e) { assertThat(e.getMessage(), containsString(QueryMessages.invalidCombinationOfFlags("--filter-tag-include (unref)", "--filter-tag-exclude (unref)").toString())); } } @Test public void both_filter_tag_include_and_exclude_different_arguments() { subject.validate(Query.parse("--filter-tag-include foo --filter-tag-exclude unref TEST-MNT"), messages); } @Test public void filter_tag_include_correct() { subject.validate(Query.parse("--filter-tag-include unref TEST-MNT"), messages); } @Test public void filter_tag_exclude_correct() { subject.validate(Query.parse("--filter-tag-exclude unref TEST-MNT"), messages); }
### Question: SearchKey { public String getValue() { return value; } SearchKey(final String value); String getValue(); IpInterval<?> getIpKeyOrNull(); IpInterval<?> getIpKeyOrNullReverse(); AsBlockRange getAsBlockRangeOrNull(); @Override String toString(); String getOrigin(); static final Pattern WHITESPACE_PATTERN; }### Answer: @Test public void parse_and_value() { subject = new SearchKey("test"); assertThat(subject.getValue(), is("test")); }
### Question: SearchKey { public IpInterval<?> getIpKeyOrNull() { return ipKey; } SearchKey(final String value); String getValue(); IpInterval<?> getIpKeyOrNull(); IpInterval<?> getIpKeyOrNullReverse(); AsBlockRange getAsBlockRangeOrNull(); @Override String toString(); String getOrigin(); static final Pattern WHITESPACE_PATTERN; }### Answer: @Test public void comma_in_search_key() { subject = new SearchKey("10,10"); assertNull(subject.getIpKeyOrNull()); } @Test public void parse_ipv6_with_v4() { final SearchKey searchKey = new SearchKey("::ffff:0.0.0.0"); final IpInterval<?> ipKeyOrNull = searchKey.getIpKeyOrNull(); assertNull(ipKeyOrNull); } @Test public void parse_ipv6_with_v4_prefix() { final SearchKey searchKey = new SearchKey("::ffff:0.0.0.0/72"); final IpInterval<?> ipKeyOrNull = searchKey.getIpKeyOrNull(); assertNull(ipKeyOrNull); }
### Question: InverseValidator implements QueryValidator { @Override public void validate(final Query query, final Messages messages) { if (query.isInverse()) { final String auth = query.getSearchValue().toUpperCase(); if ((!query.isTrusted() && auth.startsWith("SSO ")) || auth.startsWith("MD5-PW ")) { messages.add(net.ripe.db.whois.query.QueryMessages.inverseSearchNotAllowed()); } } } @Override void validate(final Query query, final Messages messages); }### Answer: @Test public void not_inverse_query() { when(query.isInverse()).thenReturn(FALSE); subject.validate(query, messages); assertThat(messages.hasMessages(), is(false)); } @Test public void searchValue_not_SSO_nor_MD5() { when(query.isInverse()).thenReturn(TRUE); when(query.getSearchValue()).thenReturn("ORG-TP1-TEST"); subject.validate(query, messages); assertThat(messages.hasMessages(), is(false)); } @Test public void searchValue_SSO() { when(query.isInverse()).thenReturn(TRUE); when(query.getSearchValue()).thenReturn("SSO test@test.net"); subject.validate(query, messages); assertThat(messages.getErrors(), contains(QueryMessages.inverseSearchNotAllowed())); } @Test public void searchValue_MD5() { when(query.isInverse()).thenReturn(TRUE); when(query.getSearchValue()).thenReturn("MD5-PW \\$1\\$fU9ZMQN9\\$QQtm3kRqZXWAuLpeOiLN7."); subject.validate(query, messages); assertThat(messages.getErrors(), contains(QueryMessages.inverseSearchNotAllowed())); }
### Question: Query { public boolean isReturningIrt() { return isBriefAbuseContact() || (!isKeysOnly() && queryParser.hasOption(QueryFlag.IRT)); } private Query(final String query, final Origin origin, final boolean trusted); static Query parse(final String args); static Query parse(final String args, final Origin origin, final boolean trusted); static Query parse(final String args, final String ssoToken, final List<String> passwords, final boolean trusted); List<String> getPasswords(); String getSsoToken(); boolean isTrusted(); boolean hasSubstitutions(); boolean via(Origin origin); Collection<Message> getWarnings(); boolean isAllSources(); boolean isResource(); boolean isLookupInBothDirections(); boolean isReturningIrt(); boolean isGrouping(); boolean isBriefAbuseContact(); boolean isKeysOnly(); boolean isPrimaryObjectsOnly(); boolean isFiltered(); boolean isHelp(); boolean isSystemInfo(); boolean isReturningReferencedObjects(); boolean isInverse(); boolean isTemplate(); boolean isVersionList(); boolean isVersionDiff(); boolean isObjectVersion(); int getObjectVersion(); int[] getObjectVersions(); String getTemplateOption(); boolean isVerbose(); boolean isValidSyntax(); boolean isNoValidSyntax(); SystemInfoOption getSystemInfoOption(); String getVerboseOption(); boolean hasObjectTypesSpecified(); Set<ObjectType> getObjectTypes(); Set<AttributeType> getAttributeTypes(); MatchOperation matchOperation(); boolean hasIpFlags(); boolean hasObjectTypeFilter(ObjectType objectType); String getSearchValue(); Set<ObjectType> getSuppliedObjectTypes(); IpInterval<?> getIpKeyOrNull(); IpInterval<?> getIpKeyOrNullReverse(); String getRouteOrigin(); AsBlockRange getAsBlockRangeOrNull(); String getProxy(); boolean hasProxy(); boolean hasProxyWithIp(); boolean hasKeepAlive(); boolean isShortHand(); boolean hasOnlyKeepAlive(); boolean isProxyValid(); String getProxyIp(); boolean hasOptions(); boolean hasOption(QueryFlag queryFlag); @Deprecated Set<String> getOptionValues(QueryFlag queryFlag); @Deprecated Set<CIString> getOptionValuesCI(QueryFlag queryFlag); boolean hasSources(); Set<String> getSources(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); boolean matchesObjectTypeAndAttribute(final ObjectType objectType, final AttributeType attributeType); boolean isMatchPrimaryKeyOnly(); Query setMatchPrimaryKeyOnly(boolean matchPrimaryKeyOnly); static final EnumSet<ObjectType> ABUSE_CONTACT_OBJECT_TYPES; }### Answer: @Test public void isReturningIrt() { Query query = Query.parse("-c 10.0.0.0"); assertTrue(query.isReturningIrt()); }
### Question: Query { public boolean hasSources() { return !sources.isEmpty(); } private Query(final String query, final Origin origin, final boolean trusted); static Query parse(final String args); static Query parse(final String args, final Origin origin, final boolean trusted); static Query parse(final String args, final String ssoToken, final List<String> passwords, final boolean trusted); List<String> getPasswords(); String getSsoToken(); boolean isTrusted(); boolean hasSubstitutions(); boolean via(Origin origin); Collection<Message> getWarnings(); boolean isAllSources(); boolean isResource(); boolean isLookupInBothDirections(); boolean isReturningIrt(); boolean isGrouping(); boolean isBriefAbuseContact(); boolean isKeysOnly(); boolean isPrimaryObjectsOnly(); boolean isFiltered(); boolean isHelp(); boolean isSystemInfo(); boolean isReturningReferencedObjects(); boolean isInverse(); boolean isTemplate(); boolean isVersionList(); boolean isVersionDiff(); boolean isObjectVersion(); int getObjectVersion(); int[] getObjectVersions(); String getTemplateOption(); boolean isVerbose(); boolean isValidSyntax(); boolean isNoValidSyntax(); SystemInfoOption getSystemInfoOption(); String getVerboseOption(); boolean hasObjectTypesSpecified(); Set<ObjectType> getObjectTypes(); Set<AttributeType> getAttributeTypes(); MatchOperation matchOperation(); boolean hasIpFlags(); boolean hasObjectTypeFilter(ObjectType objectType); String getSearchValue(); Set<ObjectType> getSuppliedObjectTypes(); IpInterval<?> getIpKeyOrNull(); IpInterval<?> getIpKeyOrNullReverse(); String getRouteOrigin(); AsBlockRange getAsBlockRangeOrNull(); String getProxy(); boolean hasProxy(); boolean hasProxyWithIp(); boolean hasKeepAlive(); boolean isShortHand(); boolean hasOnlyKeepAlive(); boolean isProxyValid(); String getProxyIp(); boolean hasOptions(); boolean hasOption(QueryFlag queryFlag); @Deprecated Set<String> getOptionValues(QueryFlag queryFlag); @Deprecated Set<CIString> getOptionValuesCI(QueryFlag queryFlag); boolean hasSources(); Set<String> getSources(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); boolean matchesObjectTypeAndAttribute(final ObjectType objectType, final AttributeType attributeType); boolean isMatchPrimaryKeyOnly(); Query setMatchPrimaryKeyOnly(boolean matchPrimaryKeyOnly); static final EnumSet<ObjectType> ABUSE_CONTACT_OBJECT_TYPES; }### Answer: @Test public void hasSources() { Query query = Query.parse("-s RIPE,TEST 10.0.0.0"); assertTrue(query.hasSources()); assertThat(query.getSources(), contains("RIPE", "TEST")); }
### Question: Query { public boolean isPrimaryObjectsOnly() { return !(isReturningReferencedObjects() || isReturningIrt() || isGrouping()); } private Query(final String query, final Origin origin, final boolean trusted); static Query parse(final String args); static Query parse(final String args, final Origin origin, final boolean trusted); static Query parse(final String args, final String ssoToken, final List<String> passwords, final boolean trusted); List<String> getPasswords(); String getSsoToken(); boolean isTrusted(); boolean hasSubstitutions(); boolean via(Origin origin); Collection<Message> getWarnings(); boolean isAllSources(); boolean isResource(); boolean isLookupInBothDirections(); boolean isReturningIrt(); boolean isGrouping(); boolean isBriefAbuseContact(); boolean isKeysOnly(); boolean isPrimaryObjectsOnly(); boolean isFiltered(); boolean isHelp(); boolean isSystemInfo(); boolean isReturningReferencedObjects(); boolean isInverse(); boolean isTemplate(); boolean isVersionList(); boolean isVersionDiff(); boolean isObjectVersion(); int getObjectVersion(); int[] getObjectVersions(); String getTemplateOption(); boolean isVerbose(); boolean isValidSyntax(); boolean isNoValidSyntax(); SystemInfoOption getSystemInfoOption(); String getVerboseOption(); boolean hasObjectTypesSpecified(); Set<ObjectType> getObjectTypes(); Set<AttributeType> getAttributeTypes(); MatchOperation matchOperation(); boolean hasIpFlags(); boolean hasObjectTypeFilter(ObjectType objectType); String getSearchValue(); Set<ObjectType> getSuppliedObjectTypes(); IpInterval<?> getIpKeyOrNull(); IpInterval<?> getIpKeyOrNullReverse(); String getRouteOrigin(); AsBlockRange getAsBlockRangeOrNull(); String getProxy(); boolean hasProxy(); boolean hasProxyWithIp(); boolean hasKeepAlive(); boolean isShortHand(); boolean hasOnlyKeepAlive(); boolean isProxyValid(); String getProxyIp(); boolean hasOptions(); boolean hasOption(QueryFlag queryFlag); @Deprecated Set<String> getOptionValues(QueryFlag queryFlag); @Deprecated Set<CIString> getOptionValuesCI(QueryFlag queryFlag); boolean hasSources(); Set<String> getSources(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); boolean matchesObjectTypeAndAttribute(final ObjectType objectType, final AttributeType attributeType); boolean isMatchPrimaryKeyOnly(); Query setMatchPrimaryKeyOnly(boolean matchPrimaryKeyOnly); static final EnumSet<ObjectType> ABUSE_CONTACT_OBJECT_TYPES; }### Answer: @Test public void isPrimaryObjectsOnly() { Query query = Query.parse("-rG 10.0.0.0"); assertTrue(query.isPrimaryObjectsOnly()); }
### Question: Query { public boolean isAllSources() { return queryParser.hasOption(QueryFlag.ALL_SOURCES); } private Query(final String query, final Origin origin, final boolean trusted); static Query parse(final String args); static Query parse(final String args, final Origin origin, final boolean trusted); static Query parse(final String args, final String ssoToken, final List<String> passwords, final boolean trusted); List<String> getPasswords(); String getSsoToken(); boolean isTrusted(); boolean hasSubstitutions(); boolean via(Origin origin); Collection<Message> getWarnings(); boolean isAllSources(); boolean isResource(); boolean isLookupInBothDirections(); boolean isReturningIrt(); boolean isGrouping(); boolean isBriefAbuseContact(); boolean isKeysOnly(); boolean isPrimaryObjectsOnly(); boolean isFiltered(); boolean isHelp(); boolean isSystemInfo(); boolean isReturningReferencedObjects(); boolean isInverse(); boolean isTemplate(); boolean isVersionList(); boolean isVersionDiff(); boolean isObjectVersion(); int getObjectVersion(); int[] getObjectVersions(); String getTemplateOption(); boolean isVerbose(); boolean isValidSyntax(); boolean isNoValidSyntax(); SystemInfoOption getSystemInfoOption(); String getVerboseOption(); boolean hasObjectTypesSpecified(); Set<ObjectType> getObjectTypes(); Set<AttributeType> getAttributeTypes(); MatchOperation matchOperation(); boolean hasIpFlags(); boolean hasObjectTypeFilter(ObjectType objectType); String getSearchValue(); Set<ObjectType> getSuppliedObjectTypes(); IpInterval<?> getIpKeyOrNull(); IpInterval<?> getIpKeyOrNullReverse(); String getRouteOrigin(); AsBlockRange getAsBlockRangeOrNull(); String getProxy(); boolean hasProxy(); boolean hasProxyWithIp(); boolean hasKeepAlive(); boolean isShortHand(); boolean hasOnlyKeepAlive(); boolean isProxyValid(); String getProxyIp(); boolean hasOptions(); boolean hasOption(QueryFlag queryFlag); @Deprecated Set<String> getOptionValues(QueryFlag queryFlag); @Deprecated Set<CIString> getOptionValuesCI(QueryFlag queryFlag); boolean hasSources(); Set<String> getSources(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); boolean matchesObjectTypeAndAttribute(final ObjectType objectType, final AttributeType attributeType); boolean isMatchPrimaryKeyOnly(); Query setMatchPrimaryKeyOnly(boolean matchPrimaryKeyOnly); static final EnumSet<ObjectType> ABUSE_CONTACT_OBJECT_TYPES; }### Answer: @Test public void isAllSources() { Query query = Query.parse("-a foo"); assertThat(query.isAllSources(), is(true)); }
### Question: Query { public boolean isKeysOnly() { return queryParser.hasOption(QueryFlag.PRIMARY_KEYS); } private Query(final String query, final Origin origin, final boolean trusted); static Query parse(final String args); static Query parse(final String args, final Origin origin, final boolean trusted); static Query parse(final String args, final String ssoToken, final List<String> passwords, final boolean trusted); List<String> getPasswords(); String getSsoToken(); boolean isTrusted(); boolean hasSubstitutions(); boolean via(Origin origin); Collection<Message> getWarnings(); boolean isAllSources(); boolean isResource(); boolean isLookupInBothDirections(); boolean isReturningIrt(); boolean isGrouping(); boolean isBriefAbuseContact(); boolean isKeysOnly(); boolean isPrimaryObjectsOnly(); boolean isFiltered(); boolean isHelp(); boolean isSystemInfo(); boolean isReturningReferencedObjects(); boolean isInverse(); boolean isTemplate(); boolean isVersionList(); boolean isVersionDiff(); boolean isObjectVersion(); int getObjectVersion(); int[] getObjectVersions(); String getTemplateOption(); boolean isVerbose(); boolean isValidSyntax(); boolean isNoValidSyntax(); SystemInfoOption getSystemInfoOption(); String getVerboseOption(); boolean hasObjectTypesSpecified(); Set<ObjectType> getObjectTypes(); Set<AttributeType> getAttributeTypes(); MatchOperation matchOperation(); boolean hasIpFlags(); boolean hasObjectTypeFilter(ObjectType objectType); String getSearchValue(); Set<ObjectType> getSuppliedObjectTypes(); IpInterval<?> getIpKeyOrNull(); IpInterval<?> getIpKeyOrNullReverse(); String getRouteOrigin(); AsBlockRange getAsBlockRangeOrNull(); String getProxy(); boolean hasProxy(); boolean hasProxyWithIp(); boolean hasKeepAlive(); boolean isShortHand(); boolean hasOnlyKeepAlive(); boolean isProxyValid(); String getProxyIp(); boolean hasOptions(); boolean hasOption(QueryFlag queryFlag); @Deprecated Set<String> getOptionValues(QueryFlag queryFlag); @Deprecated Set<CIString> getOptionValuesCI(QueryFlag queryFlag); boolean hasSources(); Set<String> getSources(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); boolean matchesObjectTypeAndAttribute(final ObjectType objectType, final AttributeType attributeType); boolean isMatchPrimaryKeyOnly(); Query setMatchPrimaryKeyOnly(boolean matchPrimaryKeyOnly); static final EnumSet<ObjectType> ABUSE_CONTACT_OBJECT_TYPES; }### Answer: @Test public void isKeysOnly() { Query query = Query.parse("-K 10.0.0.0"); assertThat(query.isKeysOnly(), is(true)); }
### Question: Query { public boolean hasOption(QueryFlag queryFlag) { return queryParser.hasOption(queryFlag); } private Query(final String query, final Origin origin, final boolean trusted); static Query parse(final String args); static Query parse(final String args, final Origin origin, final boolean trusted); static Query parse(final String args, final String ssoToken, final List<String> passwords, final boolean trusted); List<String> getPasswords(); String getSsoToken(); boolean isTrusted(); boolean hasSubstitutions(); boolean via(Origin origin); Collection<Message> getWarnings(); boolean isAllSources(); boolean isResource(); boolean isLookupInBothDirections(); boolean isReturningIrt(); boolean isGrouping(); boolean isBriefAbuseContact(); boolean isKeysOnly(); boolean isPrimaryObjectsOnly(); boolean isFiltered(); boolean isHelp(); boolean isSystemInfo(); boolean isReturningReferencedObjects(); boolean isInverse(); boolean isTemplate(); boolean isVersionList(); boolean isVersionDiff(); boolean isObjectVersion(); int getObjectVersion(); int[] getObjectVersions(); String getTemplateOption(); boolean isVerbose(); boolean isValidSyntax(); boolean isNoValidSyntax(); SystemInfoOption getSystemInfoOption(); String getVerboseOption(); boolean hasObjectTypesSpecified(); Set<ObjectType> getObjectTypes(); Set<AttributeType> getAttributeTypes(); MatchOperation matchOperation(); boolean hasIpFlags(); boolean hasObjectTypeFilter(ObjectType objectType); String getSearchValue(); Set<ObjectType> getSuppliedObjectTypes(); IpInterval<?> getIpKeyOrNull(); IpInterval<?> getIpKeyOrNullReverse(); String getRouteOrigin(); AsBlockRange getAsBlockRangeOrNull(); String getProxy(); boolean hasProxy(); boolean hasProxyWithIp(); boolean hasKeepAlive(); boolean isShortHand(); boolean hasOnlyKeepAlive(); boolean isProxyValid(); String getProxyIp(); boolean hasOptions(); boolean hasOption(QueryFlag queryFlag); @Deprecated Set<String> getOptionValues(QueryFlag queryFlag); @Deprecated Set<CIString> getOptionValuesCI(QueryFlag queryFlag); boolean hasSources(); Set<String> getSources(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); boolean matchesObjectTypeAndAttribute(final ObjectType objectType, final AttributeType attributeType); boolean isMatchPrimaryKeyOnly(); Query setMatchPrimaryKeyOnly(boolean matchPrimaryKeyOnly); static final EnumSet<ObjectType> ABUSE_CONTACT_OBJECT_TYPES; }### Answer: @Test public void hasOption() { Query query = Query.parse("-s RIPE -T inetnum 10.0.0.0"); assertThat(query.hasOption(QueryFlag.SOURCES), is(true)); assertThat(query.hasOption(QueryFlag.SELECT_TYPES), is(true)); assertThat(query.hasOption(QueryFlag.NO_REFERENCED), is(false)); }
### Question: FilterEmailFunction implements FilterFunction { @Override @Nonnull public RpslObject apply(RpslObject rpslObject) { RpslObjectBuilder builder = new RpslObjectBuilder(rpslObject).removeAttributeTypes(filterAttributes); return rpslObject.size() == builder.size() ? rpslObject : RpslObjectFilter.setFiltered(builder).get(); } @Override @Nonnull RpslObject apply(RpslObject rpslObject); }### Answer: @Test public void apply_no_email_attribute() { final RpslObject rpslObject = RpslObject.parse("" + "irt: DEV-IRT\n" + "auth: MD5-PW $1$YmPozTxJ$s3eGZRVrKVGdSDTeEZJu\n" + "source: RIPE" ); final RpslObject response = subject.apply(rpslObject); assertThat(response, is(rpslObject)); } @Test public void apply_email_attributes() { final RpslObject rpslObject = RpslObject.parse("" + "mntner: WEIRD-MNT\n" + "e-mail: value\n" + "e-mail: value\n" + "notify: value\n" + "notify: value\n" + "ref-nfy: value\n" + "ref-nfy: value\n" + "mnt-nfy: value\n" + "mnt-nfy: value\n" + "upd-to: value\n" + "upd-to: value\n" + "source: RIPE\n" ); final RpslObject response = subject.apply(rpslObject); assertThat(response.toString(), is("" + "mntner: WEIRD-MNT\n" + "source: RIPE # Filtered\n")); } @Test public void apply_email_attributes_not_filtered() { final RpslObject rpslObject = RpslObject.parse("" + "mntner: WEIRD-MNT\n" + "source: RIPE\n" ); final RpslObject response = subject.apply(rpslObject); assertThat(response.toString(), is("" + "mntner: WEIRD-MNT\n" + "source: RIPE\n")); } @Test public void apply_filtered_only_once() { final RpslObject rpslObject = RpslObject.parse("" + "mntner: WEIRD-MNT\n" + "source:RIPE # Filtered\n" + "e-mail:some@one.com\n" ); final RpslObject response = subject.apply(rpslObject); assertThat(response.toString(), is("" + "mntner: WEIRD-MNT\n" + "source: RIPE # Filtered\n")); }
### Question: IpResourceConfiguration { public int getLimit(final InetAddress address) { final Integer result = limit.getValue(IpInterval.asIpInterval(address)); return result == null ? DEFAULT_LIMIT : result; } @Autowired IpResourceConfiguration(final Loader loader); boolean isDenied(final InetAddress address); boolean isDenied(final IpInterval address); boolean isProxy(final InetAddress address); boolean isProxy(final IpInterval address); int getLimit(final InetAddress address); int getLimit(final IpInterval address); boolean isUnlimitedConnections(final InetAddress address); boolean isUnlimitedConnections(final IpInterval address); @PostConstruct @Scheduled(fixedDelay = TREE_UPDATE_IN_SECONDS * 1000) synchronized void reload(); }### Answer: @Test public void test_limit_default() throws Exception { assertThat(subject.getLimit(inetAddress), is(5000)); }
### Question: IpResourceConfiguration { public boolean isProxy(final InetAddress address) { final Boolean result = proxy.getValue(IpInterval.asIpInterval(address)); return result != null && result; } @Autowired IpResourceConfiguration(final Loader loader); boolean isDenied(final InetAddress address); boolean isDenied(final IpInterval address); boolean isProxy(final InetAddress address); boolean isProxy(final IpInterval address); int getLimit(final InetAddress address); int getLimit(final IpInterval address); boolean isUnlimitedConnections(final InetAddress address); boolean isUnlimitedConnections(final IpInterval address); @PostConstruct @Scheduled(fixedDelay = TREE_UPDATE_IN_SECONDS * 1000) synchronized void reload(); }### Answer: @Test public void test_proxy_default() throws Exception { assertThat(subject.isProxy(inetAddress), is(false)); }
### Question: IpResourceConfiguration { public boolean isDenied(final InetAddress address) { final Boolean result = denied.getValue(IpInterval.asIpInterval(address)); return result != null && result; } @Autowired IpResourceConfiguration(final Loader loader); boolean isDenied(final InetAddress address); boolean isDenied(final IpInterval address); boolean isProxy(final InetAddress address); boolean isProxy(final IpInterval address); int getLimit(final InetAddress address); int getLimit(final IpInterval address); boolean isUnlimitedConnections(final InetAddress address); boolean isUnlimitedConnections(final IpInterval address); @PostConstruct @Scheduled(fixedDelay = TREE_UPDATE_IN_SECONDS * 1000) synchronized void reload(); }### Answer: @Test public void test_denied_default() throws Exception { assertThat(subject.isDenied(inetAddress), is(false)); }
### Question: IpResourceConfiguration { public boolean isUnlimitedConnections(final InetAddress address) { final Boolean result = unlimitedConnections.getValue(IpInterval.asIpInterval(address)); return result != null && result; } @Autowired IpResourceConfiguration(final Loader loader); boolean isDenied(final InetAddress address); boolean isDenied(final IpInterval address); boolean isProxy(final InetAddress address); boolean isProxy(final IpInterval address); int getLimit(final InetAddress address); int getLimit(final IpInterval address); boolean isUnlimitedConnections(final InetAddress address); boolean isUnlimitedConnections(final IpInterval address); @PostConstruct @Scheduled(fixedDelay = TREE_UPDATE_IN_SECONDS * 1000) synchronized void reload(); }### Answer: @Test public void test_unlimitedConnections_default() throws Exception { assertThat(subject.isUnlimitedConnections(inetAddress), is(false)); }
### Question: AccessControlListManager { public boolean isDenied(final InetAddress remoteAddress) { return resourceConfiguration.isDenied(remoteAddress); } @Autowired AccessControlListManager(final DateTimeProvider dateTimeProvider, final IpResourceConfiguration resourceConfiguration, final AccessControlListDao accessControlListDao, final PersonalObjectAccounting personalObjectAccounting, final IpRanges ipRanges); boolean requiresAcl(final RpslObject rpslObject, final Source source); boolean isDenied(final InetAddress remoteAddress); boolean isAllowedToProxy(final InetAddress remoteAddress); boolean isUnlimited(final InetAddress remoteAddress); boolean canQueryPersonalObjects(final InetAddress remoteAddress); boolean isTrusted(final InetAddress remoteAddress); int getPersonalObjects(final InetAddress remoteAddress); void accountPersonalObjects(final InetAddress remoteAddress, final int amount); void blockTemporary(final InetAddress hostAddress, final int limit); static InetAddress mask(final InetAddress address, final int mask); }### Answer: @Test public void check_denied_restricted() throws Exception { assertTrue(subject.isDenied(ipv4Restricted)); assertTrue(subject.isDenied(ipv6Restricted)); } @Test public void check_denied_unrestricted() throws Exception { assertFalse(subject.isDenied(ipv4Unrestricted)); assertFalse(subject.isDenied(ipv6Unrestricted)); } @Test public void check_denied_unknown() throws Exception { assertFalse(subject.isDenied(ipv4Unknown)); assertFalse(subject.isDenied(ipv6Unknown)); }
### Question: AccessControlListManager { public boolean isAllowedToProxy(final InetAddress remoteAddress) { return resourceConfiguration.isProxy(remoteAddress); } @Autowired AccessControlListManager(final DateTimeProvider dateTimeProvider, final IpResourceConfiguration resourceConfiguration, final AccessControlListDao accessControlListDao, final PersonalObjectAccounting personalObjectAccounting, final IpRanges ipRanges); boolean requiresAcl(final RpslObject rpslObject, final Source source); boolean isDenied(final InetAddress remoteAddress); boolean isAllowedToProxy(final InetAddress remoteAddress); boolean isUnlimited(final InetAddress remoteAddress); boolean canQueryPersonalObjects(final InetAddress remoteAddress); boolean isTrusted(final InetAddress remoteAddress); int getPersonalObjects(final InetAddress remoteAddress); void accountPersonalObjects(final InetAddress remoteAddress, final int amount); void blockTemporary(final InetAddress hostAddress, final int limit); static InetAddress mask(final InetAddress address, final int mask); }### Answer: @Test public void check_proxy_restricted() throws Exception { assertFalse(subject.isAllowedToProxy(ipv4Restricted)); assertFalse(subject.isAllowedToProxy(ipv6Restricted)); } @Test public void check_proxy_unrestricted() throws Exception { assertTrue(subject.isAllowedToProxy(ipv4Unrestricted)); assertTrue(subject.isAllowedToProxy(ipv6Unrestricted)); } @Test public void check_proxy_unknown() throws Exception { assertFalse(subject.isAllowedToProxy(ipv4Unknown)); assertFalse(subject.isAllowedToProxy(ipv6Unknown)); }
### Question: AccessControlListManager { int getPersonalDataLimit(final InetAddress remoteAddress) { return resourceConfiguration.getLimit(remoteAddress); } @Autowired AccessControlListManager(final DateTimeProvider dateTimeProvider, final IpResourceConfiguration resourceConfiguration, final AccessControlListDao accessControlListDao, final PersonalObjectAccounting personalObjectAccounting, final IpRanges ipRanges); boolean requiresAcl(final RpslObject rpslObject, final Source source); boolean isDenied(final InetAddress remoteAddress); boolean isAllowedToProxy(final InetAddress remoteAddress); boolean isUnlimited(final InetAddress remoteAddress); boolean canQueryPersonalObjects(final InetAddress remoteAddress); boolean isTrusted(final InetAddress remoteAddress); int getPersonalObjects(final InetAddress remoteAddress); void accountPersonalObjects(final InetAddress remoteAddress, final int amount); void blockTemporary(final InetAddress hostAddress, final int limit); static InetAddress mask(final InetAddress address, final int mask); }### Answer: @Test public void check_getLimit_restricted() throws Exception { assertThat(subject.getPersonalDataLimit(ipv4Restricted), is(PERSONAL_DATA_LIMIT)); assertThat(subject.getPersonalDataLimit(ipv6Restricted), is(PERSONAL_DATA_LIMIT)); } @Test public void check_getLimit_unrestricted() throws Exception { assertThat(subject.getPersonalDataLimit(ipv4Unrestricted), is(PERSONAL_DATA_NO_LIMIT)); assertThat(subject.getPersonalDataLimit(ipv6Unrestricted), is(PERSONAL_DATA_NO_LIMIT)); } @Test public void check_getLimit_unknown() throws Exception { assertThat(subject.getPersonalDataLimit(ipv4Unknown), is(PERSONAL_DATA_LIMIT_UNKNOWN)); assertThat(subject.getPersonalDataLimit(ipv6Unknown), is(PERSONAL_DATA_LIMIT_UNKNOWN)); }
### Question: AccessControlListManager { public void blockTemporary(final InetAddress hostAddress, final int limit) { IpInterval<?> maskedAddress; if (hostAddress instanceof Inet6Address) { maskedAddress = Ipv6Resource.parse(mask(hostAddress, IPV6_NETMASK).getHostAddress() + "/" + IPV6_NETMASK); } else { maskedAddress = Ipv4Resource.asIpInterval(hostAddress); } accessControlListDao.saveAclEvent(maskedAddress, dateTimeProvider.getCurrentDate(), limit, BlockEvent.Type.BLOCK_TEMPORARY); } @Autowired AccessControlListManager(final DateTimeProvider dateTimeProvider, final IpResourceConfiguration resourceConfiguration, final AccessControlListDao accessControlListDao, final PersonalObjectAccounting personalObjectAccounting, final IpRanges ipRanges); boolean requiresAcl(final RpslObject rpslObject, final Source source); boolean isDenied(final InetAddress remoteAddress); boolean isAllowedToProxy(final InetAddress remoteAddress); boolean isUnlimited(final InetAddress remoteAddress); boolean canQueryPersonalObjects(final InetAddress remoteAddress); boolean isTrusted(final InetAddress remoteAddress); int getPersonalObjects(final InetAddress remoteAddress); void accountPersonalObjects(final InetAddress remoteAddress, final int amount); void blockTemporary(final InetAddress hostAddress, final int limit); static InetAddress mask(final InetAddress address, final int mask); }### Answer: @Test public void test_if_block_temporary_is_logged() { subject.blockTemporary(ipv6Restricted, PERSONAL_DATA_LIMIT); verify(accessControlListDao).saveAclEvent(ipv6ResourceCaptor.capture(), eq(now), eq(PERSONAL_DATA_LIMIT), eq(BlockEvent.Type.BLOCK_TEMPORARY)); Ipv6Resource ipv6Resource = ipv6ResourceCaptor.getValue(); assertThat(ipv6Resource.toString(), is("2001::/64")); }
### Question: AccessControlListManager { public boolean requiresAcl(final RpslObject rpslObject, final Source source) { if (source.isGrs()) { return false; } final ObjectType objectType = rpslObject.getType(); return ObjectType.PERSON.equals(objectType) || (ObjectType.ROLE.equals(objectType) && rpslObject.findAttributes(AttributeType.ABUSE_MAILBOX).isEmpty()); } @Autowired AccessControlListManager(final DateTimeProvider dateTimeProvider, final IpResourceConfiguration resourceConfiguration, final AccessControlListDao accessControlListDao, final PersonalObjectAccounting personalObjectAccounting, final IpRanges ipRanges); boolean requiresAcl(final RpslObject rpslObject, final Source source); boolean isDenied(final InetAddress remoteAddress); boolean isAllowedToProxy(final InetAddress remoteAddress); boolean isUnlimited(final InetAddress remoteAddress); boolean canQueryPersonalObjects(final InetAddress remoteAddress); boolean isTrusted(final InetAddress remoteAddress); int getPersonalObjects(final InetAddress remoteAddress); void accountPersonalObjects(final InetAddress remoteAddress, final int amount); void blockTemporary(final InetAddress hostAddress, final int limit); static InetAddress mask(final InetAddress address, final int mask); }### Answer: @Test public void requiresAcl_withRipeSource() { assertTrue(subject.requiresAcl(person, Source.slave("RIPE"))); assertTrue(subject.requiresAcl(role, Source.slave("RIPE"))); assertFalse(subject.requiresAcl(roleWithAbuseMailbox, Source.slave("RIPE"))); assertFalse(subject.requiresAcl(autNum, Source.slave("RIPE"))); assertFalse(subject.requiresAcl(inetnum, Source.slave("RIPE"))); assertFalse(subject.requiresAcl(domain, Source.slave("RIPE"))); } @Test public void requiresAcl_withNonRipeSource() { assertFalse(subject.requiresAcl(autNum, Source.slave("APNIC-GRS"))); assertFalse(subject.requiresAcl(person, Source.slave("APNIC-GRS"))); assertFalse(subject.requiresAcl(role, Source.slave("AFRINIC-GRS"))); assertFalse(subject.requiresAcl(person, Source.slave("AFRINIC-GRS"))); assertFalse(subject.requiresAcl(role, Source.slave("JPIRR-GRS"))); assertFalse(subject.requiresAcl(inetnum, Source.slave("JPIRR-GRS"))); assertFalse(subject.requiresAcl(autNum, Source.slave("RADB-GRS"))); } @Test public void requiresAcl_withTest() { assertTrue(subject.requiresAcl(person, Source.slave("TEST"))); assertTrue(subject.requiresAcl(role, Source.slave("TEST"))); assertFalse(subject.requiresAcl(roleWithAbuseMailbox, Source.slave("TEST"))); assertFalse(subject.requiresAcl(autNum, Source.slave("TEST"))); assertFalse(subject.requiresAcl(inetnum, Source.slave("TEST"))); assertFalse(subject.requiresAcl(domain, Source.slave("TEST"))); }
### Question: AccessControlListManager { public boolean isTrusted(final InetAddress remoteAddress) { return ipRanges.isTrusted(IpInterval.asIpInterval(remoteAddress)); } @Autowired AccessControlListManager(final DateTimeProvider dateTimeProvider, final IpResourceConfiguration resourceConfiguration, final AccessControlListDao accessControlListDao, final PersonalObjectAccounting personalObjectAccounting, final IpRanges ipRanges); boolean requiresAcl(final RpslObject rpslObject, final Source source); boolean isDenied(final InetAddress remoteAddress); boolean isAllowedToProxy(final InetAddress remoteAddress); boolean isUnlimited(final InetAddress remoteAddress); boolean canQueryPersonalObjects(final InetAddress remoteAddress); boolean isTrusted(final InetAddress remoteAddress); int getPersonalObjects(final InetAddress remoteAddress); void accountPersonalObjects(final InetAddress remoteAddress, final int amount); void blockTemporary(final InetAddress hostAddress, final int limit); static InetAddress mask(final InetAddress address, final int mask); }### Answer: @Test public void override_from_trusted_range() { when(ipRanges.isTrusted(any(IpInterval.class))).thenReturn(true); assertThat(subject.isTrusted(InetAddresses.forString("10.0.0.1")), is(true)); } @Test public void override_from_untrusted_range() { when(ipRanges.isTrusted(any(IpInterval.class))).thenReturn(false); assertThat(subject.isTrusted(InetAddresses.forString("10.0.0.1")), is(false)); }
### Question: HazelcastPersonalObjectAccounting implements PersonalObjectAccounting { @Override public int getQueriedPersonalObjects(final InetAddress remoteAddress) { Integer count = null; try { count = counterMap.get(remoteAddress); } catch (OperationTimeoutException | IllegalStateException e) { LOGGER.debug("{}: {}", e.getClass().getName(), e.getMessage()); } if (count == null) { return 0; } return count; } @PostConstruct void startService(); @PreDestroy void stopService(); @Override int getQueriedPersonalObjects(final InetAddress remoteAddress); @Override int accountPersonalObject(final InetAddress remoteAddress, final int amount); @Override void resetAccounting(); }### Answer: @Test public void test_queried_personal_objects() { assertThat(subject.getQueriedPersonalObjects(ipv4Address), is(0)); }
### Question: HazelcastPersonalObjectAccounting implements PersonalObjectAccounting { @Override public int accountPersonalObject(final InetAddress remoteAddress, final int amount) { try { Integer count = counterMap.tryLockAndGet(remoteAddress, 3, TimeUnit.SECONDS); if (count == null) { count = amount; } else { count += amount; } counterMap.putAndUnlock(remoteAddress, count); return count; } catch (TimeoutException | IllegalStateException e) { LOGGER.info("Unable to account personal object, allowed by default. Threw " + e.getClass().getName() + ": " + e.getMessage()); } return 0; } @PostConstruct void startService(); @PreDestroy void stopService(); @Override int getQueriedPersonalObjects(final InetAddress remoteAddress); @Override int accountPersonalObject(final InetAddress remoteAddress, final int amount); @Override void resetAccounting(); }### Answer: @Test public void test_account_personal_object_amount_1() { for (int i = 1; i < 100; i++) { int balance = subject.accountPersonalObject(ipv4Address, 1); assertThat(balance, is(i)); } }
### Question: DummifierNrtm implements Dummifier { public boolean isAllowed(final int version, final RpslObject rpslObject) { return version <= 2 || !usePlaceHolder(rpslObject); } RpslObject dummify(final int version, final RpslObject rpslObject); boolean isAllowed(final int version, final RpslObject rpslObject); static RpslObject getPlaceholderPersonObject(); static RpslObject getPlaceholderRoleObject(); }### Answer: @Test public void allow_objects_version_3() { for (ObjectType objectType : ObjectType.values()) { if (DummifierNrtm.SKIPPED_OBJECT_TYPES.contains(objectType)) { continue; } final RpslObject rpslObject = createObject(objectType, "YAY", new RpslAttribute(AttributeType.REMARKS, "Remark!")); assertThat(subject.isAllowed(3, rpslObject), is(true)); } } @Test public void allow_role_with_abuse_mailbox() { final RpslObject role = RpslObject.parse( "role: Test Role\n" + "created: 2001-02-04T17:00:00Z\n" + "last-modified: 2001-02-04T17:00:00Z\n" + "nic-hdl: TR1-TEST\n" + "abuse-mailbox: abuse@mailbox.com\n" + "source: TEST"); assertThat(subject.isAllowed(3, role), is(true)); }
### Question: WhoisRestApi implements Origin { @Override public String getId() { return remoteAddress; } WhoisRestApi(final DateTimeProvider dateTimeProvider, final String remoteAddress); @Override boolean isDefaultOverride(); @Override boolean allowAdminOperations(); @Override String getId(); @Override String getFrom(); @Override String getResponseHeader(); @Override String getNotificationHeader(); @Override String getName(); @Override String toString(); }### Answer: @Test public void getId() { assertThat(subject.getId(), is("127.0.0.1")); }
### Question: WhoisRestApi implements Origin { @Override public String getFrom() { return remoteAddress; } WhoisRestApi(final DateTimeProvider dateTimeProvider, final String remoteAddress); @Override boolean isDefaultOverride(); @Override boolean allowAdminOperations(); @Override String getId(); @Override String getFrom(); @Override String getResponseHeader(); @Override String getNotificationHeader(); @Override String getName(); @Override String toString(); }### Answer: @Test public void getFrom() { assertThat(subject.getFrom(), is("127.0.0.1")); }
### Question: WhoisRestApi implements Origin { @Override public String getName() { return "rest api"; } WhoisRestApi(final DateTimeProvider dateTimeProvider, final String remoteAddress); @Override boolean isDefaultOverride(); @Override boolean allowAdminOperations(); @Override String getId(); @Override String getFrom(); @Override String getResponseHeader(); @Override String getNotificationHeader(); @Override String getName(); @Override String toString(); }### Answer: @Test public void getName() { assertThat(subject.getName(), is("rest api")); }
### Question: WhoisRestApi implements Origin { @Override public String getResponseHeader() { return getHeader(); } WhoisRestApi(final DateTimeProvider dateTimeProvider, final String remoteAddress); @Override boolean isDefaultOverride(); @Override boolean allowAdminOperations(); @Override String getId(); @Override String getFrom(); @Override String getResponseHeader(); @Override String getNotificationHeader(); @Override String getName(); @Override String toString(); }### Answer: @Test public void response_header_for_any_request() { when(dateTimeProvider.getCurrentDateTime()).thenReturn(LocalDateTime.of(2013, 3, 3, 12, 55)); assertThat(subject.getResponseHeader(), is(" - From-Host: 127.0.0.1\n - Date/Time: Sun Mar 3 12:55:00 2013\n")); }
### Question: WhoisRestApi implements Origin { @Override public String getNotificationHeader() { return getHeader(); } WhoisRestApi(final DateTimeProvider dateTimeProvider, final String remoteAddress); @Override boolean isDefaultOverride(); @Override boolean allowAdminOperations(); @Override String getId(); @Override String getFrom(); @Override String getResponseHeader(); @Override String getNotificationHeader(); @Override String getName(); @Override String toString(); }### Answer: @Test public void notification_header_for_any_request() { when(dateTimeProvider.getCurrentDateTime()).thenReturn(LocalDateTime.of(2013, 3, 3, 12, 55)); assertThat(subject.getNotificationHeader(), is(" - From-Host: 127.0.0.1\n - Date/Time: Sun Mar 3 12:55:00 2013\n")); }
### Question: FormattedServerAttributeMapper implements FormattedAttributeMapper { @Override public Collection<Attribute> map(final RpslAttribute rpslAttribute, final String source) { final List<Attribute> result = Lists.newArrayList(); for (CIString value : rpslAttribute.getCleanValues()) { final String referencedType = (rpslAttribute.getType() != null) ? referencedTypeResolver.getReferencedType(rpslAttribute.getType(), value) : null; final Link link = (referencedType != null) ? Link.create(baseUrl, sourceResolver.getSource(referencedType, value, source), referencedType, getLinkValue(rpslAttribute.getType(), value)) : null; result.add(new Attribute(rpslAttribute.getKey(), value.toString(), rpslAttribute.getCleanComment(), referencedType, link, null)); } return result; } @Autowired FormattedServerAttributeMapper(final ReferencedTypeResolver referencedTypeResolver, final SourceResolver sourceResolver, @Value("${api.rest.baseurl}") final String baseUrl); @Override Collection<Attribute> map(final RpslAttribute rpslAttribute, final String source); }### Answer: @Test public void map_rpslAttribute_lacking_attributeType() { final Collection<Attribute> attributes = subject.map( new RpslAttribute("key", CIString.ciString("value")), "TEST"); assertThat(attributes, hasSize(1)); final Attribute attribute = attributes.iterator().next(); assertThat(attribute.getLink(), is(nullValue())); assertThat(attribute.getValue(), is("value")); assertThat(attribute.getName(), is("key")); } @Test public void map_rpslAttribute_attributeType_given() { when(referencedTypeResolver.getReferencedType(AttributeType.NIC_HDL, CIString.ciString("TP-TEST"))).thenReturn(AttributeType.ROLE.getName()); final Collection<Attribute> attributes = subject.map( new RpslAttribute(AttributeType.NIC_HDL, CIString.ciString("TP-TEST")), "TEST"); assertThat(attributes, hasSize(1)); final Attribute attribute = attributes.iterator().next(); assertThat(attribute.getLink().toString(), is("locator: http: assertThat(attribute.getName(), is("nic-hdl")); assertThat(attribute.getValue(), is("TP-TEST")); } @Test public void map_rpslAttribute_multiple_values() { when(referencedTypeResolver.getReferencedType(AttributeType.MEMBERS, CIString.ciString("AS1"))).thenReturn(AttributeType.AUT_NUM.getName()); when(referencedTypeResolver.getReferencedType(AttributeType.MEMBERS, CIString.ciString("AS2"))).thenReturn(AttributeType.AUT_NUM.getName()); when(referencedTypeResolver.getReferencedType(AttributeType.MEMBERS, CIString.ciString("AS3"))).thenReturn(AttributeType.AUT_NUM.getName()); final Collection<Attribute> attributes = subject.map(new RpslAttribute(AttributeType.MEMBERS, "AS1, AS2,AS3"), "TEST"); assertThat(attributes, contains( new Attribute("members", "AS1", null, "aut-num", new Link("locator", "http: new Attribute("members", "AS2", null, "aut-num", new Link("locator", "http: new Attribute("members", "AS3", null, "aut-num", new Link("locator", "http: )); } @Test public void map_rpslAttribute_mntRoutes_prefix() { when(referencedTypeResolver.getReferencedType(AttributeType.MNT_ROUTES, CIString.ciString("OWNER-MNT {10.0.0.0/8}"))).thenReturn(AttributeType.MNTNER.getName()); final Collection<Attribute> attributes = subject.map(new RpslAttribute(AttributeType.MNT_ROUTES, "OWNER-MNT {10.0.0.0/8}"), "TEST"); assertThat(attributes, contains( new Attribute("mnt-routes", "OWNER-MNT {10.0.0.0/8}", null, "mntner", new Link("locator", "http: }
### Question: WhoisObjectServerMapper { public List<WhoisVersion> mapVersions(final List<DeletedVersionResponseObject> deleted, final List<VersionResponseObject> versions) { final List<WhoisVersion> whoisVersions = Lists.newArrayList(); for (final DeletedVersionResponseObject deletedVersion : deleted) { whoisVersions.add(new WhoisVersion(deletedVersion.getDeletedDate().toString())); } for (final VersionResponseObject version : versions) { whoisVersions.add(new WhoisVersion(version.getOperation() == Operation.UPDATE ? "ADD/UPD" : "DEL", version.getDateTime().toString(), version.getVersion())); } return whoisVersions; } @Autowired WhoisObjectServerMapper( final WhoisObjectMapper whoisObjectMapper, final ResourceHolderSearch resourceHolderSearch, final AbuseContactSearch abuseContactSearch, final ManagedAttributeSearch managedAttributeSearch); List<WhoisVersion> mapVersions(final List<DeletedVersionResponseObject> deleted, final List<VersionResponseObject> versions); WhoisObject map(final RpslObject rpslObject, final Parameters parameters); void mapTags(final WhoisObject whoisObject, final TagResponseObject tagResponseObject); void mapResourceHolder(final WhoisObject whoisObject, final Parameters parameters, final RpslObject rpslObject); void mapAbuseContact(final WhoisObject whoisObject, final Parameters parameters, final RpslObject rpslObject); void mapManagedAttributes(final WhoisObject whoisObject, final Parameters parameters, final RpslObject rpslObject); }### Answer: @Test public void map_versions() { final DeletedVersionResponseObject deleted = new DeletedVersionResponseObject(new VersionDateTime(LocalDateTime.now()), ObjectType.AUT_NUM, "AS102"); final List<VersionResponseObject> versionInfos = Lists.newArrayList( new VersionResponseObject(2, Operation.UPDATE, 3, new VersionDateTime(LocalDateTime.now()), ObjectType.AUT_NUM, "AS102"), new VersionResponseObject(2, Operation.UPDATE, 4, new VersionDateTime(LocalDateTime.now()), ObjectType.AUT_NUM, "AS102")); final List<WhoisVersion> whoisVersions = whoisObjectServerMapper.mapVersions(Lists.newArrayList(deleted), versionInfos); assertThat(whoisVersions, hasSize(3)); final WhoisVersion deletedVersion = whoisVersions.get(0); assertThat(deletedVersion.getOperation(), nullValue()); assertThat(deletedVersion.getRevision(), nullValue()); assertThat(deletedVersion.getDeletedDate(), is(not(nullValue()))); final WhoisVersion whoisVersion1 = whoisVersions.get(1); assertThat(whoisVersion1.getOperation(), is("ADD/UPD")); assertThat(whoisVersion1.getRevision(), is(3)); assertThat(whoisVersion1.getDate(), is(not(nullValue()))); final WhoisVersion whoisVersion2 = whoisVersions.get(2); assertThat(whoisVersion2.getOperation(), is("ADD/UPD")); assertThat(whoisVersion2.getRevision(), is(4)); assertThat(whoisVersion2.getDate(), is(not(nullValue()))); }
### Question: RestServiceHelper { public static String getRequestURL(final HttpServletRequest request) { return request.getRequestURL().toString() + filter(request.getQueryString()); } private RestServiceHelper(); static String getRequestURL(final HttpServletRequest request); static String getRequestURI(final HttpServletRequest request); static boolean isQueryParamSet(final String queryString, final String key); static boolean isQueryParamSet(final String queryParam); static Class<? extends AttributeMapper> getServerAttributeMapper(final boolean unformatted); static Class<? extends AttributeMapper> getRestResponseAttributeMapper(String queryString); static WhoisResources createErrorEntity(final HttpServletRequest request, final Message... errorMessage); static WhoisResources createErrorEntity(final HttpServletRequest request, final List<Message> errorMessages); static List<ErrorMessage> createErrorMessages(final List<Message> messages); static WebApplicationException createWebApplicationException(final RuntimeException exception, final HttpServletRequest request); static WebApplicationException createWebApplicationException(final RuntimeException exception, final HttpServletRequest request, final List<Message> messages); }### Answer: @Test public void getRequestUrl() { assertThat(getRequestURL("http: assertThat(getRequestURL("http: assertThat(getRequestURL("http: assertThat(getRequestURL("http: assertThat(getRequestURL("http: assertThat(getRequestURL("http: assertThat(getRequestURL("http: assertThat(getRequestURL("http: assertThat(getRequestURL("http: assertThat(getRequestURL("http: assertThat(getRequestURL("http: assertThat(getRequestURL("http: assertThat(getRequestURL("http: assertThat(getRequestURL("http: assertThat(getRequestURL("http: }
### Question: ClientCertificateExtractor { public static Optional<X509CertificateWrapper> getClientCertificate(final HttpServletRequest request, final DateTimeProvider dateTimeProvider) { final String sslClientCert = request.getHeader(HEADER_SSL_CLIENT_CERT); if (StringUtils.isBlank(sslClientCert)) { return Optional.empty(); } if (!hasAcceptableVerifyHeader(request)) { return Optional.empty(); } return getX509Certificate(sslClientCert, dateTimeProvider); } static Optional<X509CertificateWrapper> getClientCertificate(final HttpServletRequest request, final DateTimeProvider dateTimeProvider); }### Answer: @Test public void testValidCertificate() { final HttpServletRequest request = mock(HttpServletRequest.class); when(request.getHeader(HEADER_SSL_CLIENT_CERT)).thenReturn(cert); when(request.getHeader(HEADER_SSL_CLIENT_VERIFY)).thenReturn("GENEROUS"); assertThat(ClientCertificateExtractor.getClientCertificate(request, new ClockDateTimeProvider()).isPresent(), is(true)); } @Test public void testInvalidVerifyHeader() { final HttpServletRequest request = mock(HttpServletRequest.class); when(request.getHeader(HEADER_SSL_CLIENT_CERT)).thenReturn(cert); when(request.getHeader(HEADER_SSL_CLIENT_VERIFY)).thenReturn("NOT-ACCEPTED"); assertThat(ClientCertificateExtractor.getClientCertificate(request, new ClockDateTimeProvider()).isPresent(), is(false)); } @Test public void testNoCertificate() { final HttpServletRequest request = mock(HttpServletRequest.class); when(request.getHeader(HEADER_SSL_CLIENT_VERIFY)).thenReturn("GENEROUS"); assertThat(ClientCertificateExtractor.getClientCertificate(request, new ClockDateTimeProvider()).isPresent(), is(false)); } @Test public void testCertificateExpired() { final HttpServletRequest request = mock(HttpServletRequest.class); when(request.getHeader(HEADER_SSL_CLIENT_CERT)).thenReturn(cert); when(request.getHeader(HEADER_SSL_CLIENT_VERIFY)).thenReturn("GENEROUS"); final TestDateTimeProvider testDateTimeProvider = new TestDateTimeProvider(); testDateTimeProvider.setTime(LocalDateTime.now().plusYears(5)); assertThat(ClientCertificateExtractor.getClientCertificate(request, testDateTimeProvider).isPresent(), is(false)); } @Test public void testCertificateNotYetValid() { final HttpServletRequest request = mock(HttpServletRequest.class); when(request.getHeader(HEADER_SSL_CLIENT_CERT)).thenReturn(cert); when(request.getHeader(HEADER_SSL_CLIENT_VERIFY)).thenReturn("GENEROUS"); final TestDateTimeProvider testDateTimeProvider = new TestDateTimeProvider(); testDateTimeProvider.setTime(LocalDateTime.now().minusMonths(1)); assertThat(ClientCertificateExtractor.getClientCertificate(request, testDateTimeProvider).isPresent(), is(false)); }
### Question: HttpRequestMessage extends Message { private static String toString(final HttpServletRequest request) { return String.format("%s %s\n%s", request.getMethod(), formatUri(request), formatHttpHeaders(request)); } HttpRequestMessage(final HttpServletRequest request); }### Answer: @Test public void log_no_headers() { assertThat(toString(request), is("GET /some/path\n")); } @Test public void log_single_header() { request.addHeader("name", "value"); assertThat(toString(request), is("GET /some/path\nHeader: name=value\n")); } @Test public void log_multiple_headers() { request.addHeader("header1", "value1"); request.addHeader("header2", "value2"); request.addHeader("header3", "value3"); assertThat(toString(request), is("GET /some/path\nHeader: header1=value1\nHeader: header2=value2\nHeader: header3=value3\n")); } @Test public void log_empty_query_string() { request.setQueryString(""); assertThat(toString(request), is("GET /some/path\n")); } @Test public void log_encoded_query_parameter() { request.setQueryString("password=p%3Fssword%26"); assertThat(toString(request), is("GET /some/path?password=FILTERED\n")); } @Test public void log_query_parameters_including_password() { request.setQueryString("password=secret"); assertThat(toString(request), is("GET /some/path?password=FILTERED\n")); request.setQueryString("password=secret&param"); assertThat(toString(request), is("GET /some/path?password=FILTERED&param\n")); request.setQueryString("password=secret&password=other"); assertThat(toString(request), is("GET /some/path?password=FILTERED&password=FILTERED\n")); request.setQueryString("password=secret&password=other&param=value"); assertThat(toString(request), is("GET /some/path?password=FILTERED&password=FILTERED&param=value\n")); request.setQueryString("param=value&password=secret&password=other"); assertThat(toString(request), is("GET /some/path?param=value&password=FILTERED&password=FILTERED\n")); request.setQueryString("param=value&password=secret&param=password"); assertThat(toString(request), is("GET /some/path?param=value&password=FILTERED&param=password\n")); }
### Question: InternalUpdatePerformer { public Origin createOrigin(final HttpServletRequest request) { return new WhoisRestApi(dateTimeProvider, request.getRemoteAddr()); } @Autowired InternalUpdatePerformer(final UpdateRequestHandler updateRequestHandler, final DateTimeProvider dateTimeProvider, final WhoisObjectMapper whoisObjectMapper, final LoggerContext loggerContext, final SsoTokenTranslator ssoTokenTranslator); UpdateContext initContext(final Origin origin, final String ssoToken, final HttpServletRequest request); void closeContext(); WhoisResources performUpdate(final UpdateContext updateContext, final Origin origin, final Update update, final Keyword keyword, final HttpServletRequest request); WhoisResources performUpdates(final UpdateContext updateContext, final Origin origin, final Collection<Update> updates, final Keyword keyword, final HttpServletRequest request); Response createResponse(final UpdateContext updateContext, final WhoisResources whoisResources, final Update update, final HttpServletRequest request); Update createUpdate(final UpdateContext updateContext, final RpslObject rpslObject, final List<String> passwords, final String deleteReason, final String override); Origin createOrigin(final HttpServletRequest request); void setSsoSessionToContext(final UpdateContext updateContext, final String ssoToken); void logInfo(final String message); void logWarning(final String message); void logError(final Throwable t); }### Answer: @Test public void create_origin() { when(requestMock.getRemoteAddr()).thenReturn("127.0.0.1"); when(dateTimeProviderMock.getCurrentDateTime()).thenReturn(ZonedDateTime.parse("2146-01-31T06:49:37.888+00:00").toLocalDateTime()); final Origin origin = subject.createOrigin(requestMock); assertThat(origin.getFrom(), is("127.0.0.1")); assertThat(origin.getId(), is("127.0.0.1")); assertThat(origin.getName(), is("rest api")); assertThat(origin.getNotificationHeader(), containsString("" + "- From-Host: 127.0.0.1\n" + " - Date/Time: Mon Jan 31 06:49:37")); assertThat(origin.getResponseHeader(), containsString("" + "- From-Host: 127.0.0.1\n" + " - Date/Time: Mon Jan 31 06:49:37")); }
### Question: InternalUpdatePerformer { public void setSsoSessionToContext(final UpdateContext updateContext, final String ssoToken) { if (!StringUtils.isBlank(ssoToken)) { try { updateContext.setUserSession(ssoTokenTranslator.translateSsoToken(ssoToken)); } catch (CrowdClientException e) { logError(e); updateContext.addGlobalMessage(RestMessages.ssoAuthIgnored()); } } } @Autowired InternalUpdatePerformer(final UpdateRequestHandler updateRequestHandler, final DateTimeProvider dateTimeProvider, final WhoisObjectMapper whoisObjectMapper, final LoggerContext loggerContext, final SsoTokenTranslator ssoTokenTranslator); UpdateContext initContext(final Origin origin, final String ssoToken, final HttpServletRequest request); void closeContext(); WhoisResources performUpdate(final UpdateContext updateContext, final Origin origin, final Update update, final Keyword keyword, final HttpServletRequest request); WhoisResources performUpdates(final UpdateContext updateContext, final Origin origin, final Collection<Update> updates, final Keyword keyword, final HttpServletRequest request); Response createResponse(final UpdateContext updateContext, final WhoisResources whoisResources, final Update update, final HttpServletRequest request); Update createUpdate(final UpdateContext updateContext, final RpslObject rpslObject, final List<String> passwords, final String deleteReason, final String override); Origin createOrigin(final HttpServletRequest request); void setSsoSessionToContext(final UpdateContext updateContext, final String ssoToken); void logInfo(final String message); void logWarning(final String message); void logError(final Throwable t); }### Answer: @Test public void setSsoSessionToContext_no_sso_token() { subject.setSsoSessionToContext(updateContextMock, ""); verifyZeroInteractions(ssoTokenTranslatorMock); verifyZeroInteractions(loggerContextMock); subject.setSsoSessionToContext(updateContextMock, null); verifyZeroInteractions(ssoTokenTranslatorMock); verifyZeroInteractions(loggerContextMock); } @Test public void setSsoSessionToContext_successful_sso_translation() { final UserSession userSession = new UserSession("test@ripe.net", "Test User", true, "2033-01-30T16:38:27.369+11:00"); when(ssoTokenTranslatorMock.translateSsoToken("test-token")).thenReturn(userSession); subject.setSsoSessionToContext(updateContextMock, "test-token"); verify(ssoTokenTranslatorMock).translateSsoToken("test-token"); verifyZeroInteractions(loggerContextMock); verify(updateContextMock).setUserSession(userSession); } @Test public void setSsoSessionToContext_exception_is_logged() { when(ssoTokenTranslatorMock.translateSsoToken("test-token")).thenThrow(new CrowdClientException("exception")); try { subject.setSsoSessionToContext(updateContextMock, "test-token"); } catch (CrowdClientException e) { verify(ssoTokenTranslatorMock.translateSsoToken("test-token")); verify(loggerContextMock).log(new Message(Messages.Type.ERROR, "exception")); verify(updateContextMock).addGlobalMessage(RestMessages.ssoAuthIgnored()); } }
### Question: SyncUpdate implements Origin { @Override public String getId() { return getFrom(); } SyncUpdate(final DateTimeProvider dateTimeProvider, final String remoteAddress); @Override boolean isDefaultOverride(); @Override boolean allowAdminOperations(); @Override String getId(); @Override String getFrom(); @Override String getResponseHeader(); @Override String getNotificationHeader(); @Override String getName(); @Override String toString(); }### Answer: @Test public void getId() { assertThat(subject.getId(), is(LOCALHOST)); }
### Question: SyncUpdate implements Origin { @Override public String getFrom() { return remoteAddress; } SyncUpdate(final DateTimeProvider dateTimeProvider, final String remoteAddress); @Override boolean isDefaultOverride(); @Override boolean allowAdminOperations(); @Override String getId(); @Override String getFrom(); @Override String getResponseHeader(); @Override String getNotificationHeader(); @Override String getName(); @Override String toString(); }### Answer: @Test public void getFrom() { assertThat(subject.getFrom(), is(LOCALHOST)); }