src_fm_fc_ms_ff
stringlengths 43
86.8k
| target
stringlengths 20
276k
|
---|---|
RpslObject implements Identifiable, ResponseObject { public List<RpslAttribute> findAttributes(final AttributeType attributeType) { final List<RpslAttribute> list = getOrCreateCache().get(attributeType); return list == null ? Collections.<RpslAttribute>emptyList() : Collections.unmodifiableList(list); } RpslObject(final RpslObject oldObject, final List<RpslAttribute> attributes); RpslObject(final Integer objectId, final List<RpslAttribute> attributes); RpslObject(final Integer objectId, final RpslObject rpslObject); RpslObject(final List<RpslAttribute> attributes); static RpslObject parse(final String input); static RpslObject parse(final byte[] input); static RpslObject parse(final Integer objectId, final String input); static RpslObject parse(final Integer objectId, final byte[] input); @Override int getObjectId(); ObjectType getType(); List<RpslAttribute> getAttributes(); int size(); final CIString getKey(); String getFormattedKey(); @Override boolean equals(final Object obj); @Override int hashCode(); RpslAttribute getTypeAttribute(); RpslAttribute findAttribute(final AttributeType attributeType); List<RpslAttribute> findAttributes(final AttributeType attributeType); List<RpslAttribute> findAttributes(final Iterable<AttributeType> attributeTypes); List<RpslAttribute> findAttributes(final AttributeType... attributeTypes); boolean containsAttributes(final Collection<AttributeType> attributeTypes); boolean containsAttribute(final AttributeType attributeType); @Override void writeTo(final OutputStream out); void writeTo(final Writer writer); @Override byte[] toByteArray(); @Override String toString(); CIString getValueForAttribute(final AttributeType attributeType); @Nullable CIString getValueOrNullForAttribute(final AttributeType attributeType); Set<CIString> getValuesForAttribute(final AttributeType... attributeType); } | @Test public void checkThatUtf8CharactersGetThroughAndConverted() { parseAndAssign("person: New Test Person\n" + "address: Flughafenstraße 120/Σ\n" + "address: D - 40474 Düsseldorf\n" + "nic-hdl: ABC-RIPE\n"); List<RpslAttribute> addresses = subject.findAttributes(AttributeType.ADDRESS); assertThat(addresses, hasSize(2)); assertThat(addresses.get(0).getValue(), containsString("Flughafenstraße 120/?")); assertThat(addresses.get(1).getValue(), containsString("Düsseldorf")); }
@Test public void checkThatUtf8CharactersGetConverted() { parseAndAssign("person: New Test Person\n" + "address: Тверская улица,москва\n" + "nic-hdl: ABC-RIPE\n"); List<RpslAttribute> addresses = subject.findAttributes(AttributeType.ADDRESS); assertThat(addresses, hasSize(1)); assertThat(addresses.get(0).getValue(), containsString("???????? ?????,??????")); }
@Test public void parseMultipleIdenticalKeys() { String key = "descr"; int amount = 1000; parseAndAssign("mntner: DEV-MNT\n" + StringUtils.repeat(key + ": value", "\n", amount)); assertThat(subject.findAttributes(AttributeType.DESCR), hasSize(amount)); }
@Test public void findAttributes_multiple() { parseAndAssign(maintainer); assertThat(subject.findAttributes(AttributeType.MNTNER, AttributeType.ADMIN_C, AttributeType.TECH_C), hasSize(3)); } |
RpslObject implements Identifiable, ResponseObject { public final CIString getKey() { return key; } RpslObject(final RpslObject oldObject, final List<RpslAttribute> attributes); RpslObject(final Integer objectId, final List<RpslAttribute> attributes); RpslObject(final Integer objectId, final RpslObject rpslObject); RpslObject(final List<RpslAttribute> attributes); static RpslObject parse(final String input); static RpslObject parse(final byte[] input); static RpslObject parse(final Integer objectId, final String input); static RpslObject parse(final Integer objectId, final byte[] input); @Override int getObjectId(); ObjectType getType(); List<RpslAttribute> getAttributes(); int size(); final CIString getKey(); String getFormattedKey(); @Override boolean equals(final Object obj); @Override int hashCode(); RpslAttribute getTypeAttribute(); RpslAttribute findAttribute(final AttributeType attributeType); List<RpslAttribute> findAttributes(final AttributeType attributeType); List<RpslAttribute> findAttributes(final Iterable<AttributeType> attributeTypes); List<RpslAttribute> findAttributes(final AttributeType... attributeTypes); boolean containsAttributes(final Collection<AttributeType> attributeTypes); boolean containsAttribute(final AttributeType attributeType); @Override void writeTo(final OutputStream out); void writeTo(final Writer writer); @Override byte[] toByteArray(); @Override String toString(); CIString getValueForAttribute(final AttributeType attributeType); @Nullable CIString getValueOrNullForAttribute(final AttributeType attributeType); Set<CIString> getValuesForAttribute(final AttributeType... attributeType); } | @Test(expected = IllegalArgumentException.class) public void test_get_key_person_empty() { parseAndAssign("person: foo # Comment \n"); subject.getKey(); } |
RpslObject implements Identifiable, ResponseObject { public boolean containsAttribute(final AttributeType attributeType) { return getOrCreateCache().containsKey(attributeType); } RpslObject(final RpslObject oldObject, final List<RpslAttribute> attributes); RpslObject(final Integer objectId, final List<RpslAttribute> attributes); RpslObject(final Integer objectId, final RpslObject rpslObject); RpslObject(final List<RpslAttribute> attributes); static RpslObject parse(final String input); static RpslObject parse(final byte[] input); static RpslObject parse(final Integer objectId, final String input); static RpslObject parse(final Integer objectId, final byte[] input); @Override int getObjectId(); ObjectType getType(); List<RpslAttribute> getAttributes(); int size(); final CIString getKey(); String getFormattedKey(); @Override boolean equals(final Object obj); @Override int hashCode(); RpslAttribute getTypeAttribute(); RpslAttribute findAttribute(final AttributeType attributeType); List<RpslAttribute> findAttributes(final AttributeType attributeType); List<RpslAttribute> findAttributes(final Iterable<AttributeType> attributeTypes); List<RpslAttribute> findAttributes(final AttributeType... attributeTypes); boolean containsAttributes(final Collection<AttributeType> attributeTypes); boolean containsAttribute(final AttributeType attributeType); @Override void writeTo(final OutputStream out); void writeTo(final Writer writer); @Override byte[] toByteArray(); @Override String toString(); CIString getValueForAttribute(final AttributeType attributeType); @Nullable CIString getValueOrNullForAttribute(final AttributeType attributeType); Set<CIString> getValuesForAttribute(final AttributeType... attributeType); } | @Test public void containsAttribute_works() { parseAndAssign(maintainer); assertThat(subject.containsAttribute(AttributeType.SOURCE), is(true)); }
@Test public void containsAttribute_unknown() { parseAndAssign(maintainer); assertThat(subject.containsAttribute(AttributeType.PERSON), is(false)); } |
RpslObject implements Identifiable, ResponseObject { public CIString getValueForAttribute(final AttributeType attributeType) { return findAttribute(attributeType).getCleanValue(); } RpslObject(final RpslObject oldObject, final List<RpslAttribute> attributes); RpslObject(final Integer objectId, final List<RpslAttribute> attributes); RpslObject(final Integer objectId, final RpslObject rpslObject); RpslObject(final List<RpslAttribute> attributes); static RpslObject parse(final String input); static RpslObject parse(final byte[] input); static RpslObject parse(final Integer objectId, final String input); static RpslObject parse(final Integer objectId, final byte[] input); @Override int getObjectId(); ObjectType getType(); List<RpslAttribute> getAttributes(); int size(); final CIString getKey(); String getFormattedKey(); @Override boolean equals(final Object obj); @Override int hashCode(); RpslAttribute getTypeAttribute(); RpslAttribute findAttribute(final AttributeType attributeType); List<RpslAttribute> findAttributes(final AttributeType attributeType); List<RpslAttribute> findAttributes(final Iterable<AttributeType> attributeTypes); List<RpslAttribute> findAttributes(final AttributeType... attributeTypes); boolean containsAttributes(final Collection<AttributeType> attributeTypes); boolean containsAttribute(final AttributeType attributeType); @Override void writeTo(final OutputStream out); void writeTo(final Writer writer); @Override byte[] toByteArray(); @Override String toString(); CIString getValueForAttribute(final AttributeType attributeType); @Nullable CIString getValueOrNullForAttribute(final AttributeType attributeType); Set<CIString> getValuesForAttribute(final AttributeType... attributeType); } | @Test public void getValueForAttribute() { assertThat(RpslObject.parse("mntner: DEV-MNT\n").getValueForAttribute(AttributeType.MNTNER).toString(), is("DEV-MNT")); } |
RpslObject implements Identifiable, ResponseObject { public Set<CIString> getValuesForAttribute(final AttributeType... attributeType) { final Set<CIString> values = Sets.newLinkedHashSet(); for (AttributeType attrType : attributeType) { final List<RpslAttribute> rpslAttributes = getOrCreateCache().get(attrType); if (rpslAttributes != null && !rpslAttributes.isEmpty()) { for (RpslAttribute rpslAttribute : rpslAttributes) { values.addAll(rpslAttribute.getCleanValues()); } } } return values; } RpslObject(final RpslObject oldObject, final List<RpslAttribute> attributes); RpslObject(final Integer objectId, final List<RpslAttribute> attributes); RpslObject(final Integer objectId, final RpslObject rpslObject); RpslObject(final List<RpslAttribute> attributes); static RpslObject parse(final String input); static RpslObject parse(final byte[] input); static RpslObject parse(final Integer objectId, final String input); static RpslObject parse(final Integer objectId, final byte[] input); @Override int getObjectId(); ObjectType getType(); List<RpslAttribute> getAttributes(); int size(); final CIString getKey(); String getFormattedKey(); @Override boolean equals(final Object obj); @Override int hashCode(); RpslAttribute getTypeAttribute(); RpslAttribute findAttribute(final AttributeType attributeType); List<RpslAttribute> findAttributes(final AttributeType attributeType); List<RpslAttribute> findAttributes(final Iterable<AttributeType> attributeTypes); List<RpslAttribute> findAttributes(final AttributeType... attributeTypes); boolean containsAttributes(final Collection<AttributeType> attributeTypes); boolean containsAttribute(final AttributeType attributeType); @Override void writeTo(final OutputStream out); void writeTo(final Writer writer); @Override byte[] toByteArray(); @Override String toString(); CIString getValueForAttribute(final AttributeType attributeType); @Nullable CIString getValueOrNullForAttribute(final AttributeType attributeType); Set<CIString> getValuesForAttribute(final AttributeType... attributeType); } | @Test public void getValuesForAttribute() { final RpslObject object = RpslObject.parse("" + "mntner: DEV-MNT\n" + "mnt-by: DEV-MNT5\n" + "mnt-by: DEV-MNT4, DEV-MNT4\n" + "mnt-by: DEV-MNT3, DEV-MNT2\n" + "mnt-by: DEV-MNT1, DEV-MNT2\n"); assertThat(convertToString(object.getValuesForAttribute(AttributeType.MNT_BY)), contains("DEV-MNT5", "DEV-MNT4", "DEV-MNT3", "DEV-MNT2", "DEV-MNT1")); assertThat(object.getValuesForAttribute(AttributeType.ADMIN_C), hasSize(0)); } |
RpslAttribute { public String getValue() { return value; } RpslAttribute(final AttributeType attributeType, final CIString value); RpslAttribute(final AttributeType attributeType, final String value); RpslAttribute(final String key, final CIString value); RpslAttribute(final String key, final String value); String getKey(); String getValue(); String getCleanComment(); CIString getCleanValue(); Set<CIString> getCleanValues(); Set<CIString> getReferenceValues(); CIString getReferenceValue(); void validateSyntax(final ObjectType objectType, final ObjectMessages objectMessages); void writeTo(final Writer writer); String getFormattedValue(); void writeAttributeValueTo(final Writer writer); @Override boolean equals(Object o); @Override int hashCode(); @CheckForNull AttributeType getType(); @Override String toString(); } | @Test public void short_hand_plain() { subject = new RpslAttribute("domain", "foobar"); assertThat(RpslAttributeFilter.getValueForShortHand(subject.getValue()), is(" foobar")); }
@Test public void short_hand_spaced_prefix() { subject = new RpslAttribute("domain", " foobar"); assertThat(RpslAttributeFilter.getValueForShortHand(subject.getValue()), is(" foobar")); }
@Test public void short_hand_any_continuation() { subject = new RpslAttribute("domain", "foo\n bar\n+qux\n\tzot"); assertThat(RpslAttributeFilter.getValueForShortHand(subject.getValue()), is(" foo\n+ bar\n+ qux\n+ zot")); }
@Test public void short_hand_only_touches_continuation_whitespace() { subject = new RpslAttribute("domain", "foo\t # \t\n bar\n+ qux\n\tzot"); assertThat(RpslAttributeFilter.getValueForShortHand(subject.getValue()), is(" foo\t # \t\n+ bar\n+ qux\n+ zot")); }
@Test public void short_hand_continuation_spaces() { subject = new RpslAttribute("domain", "foo\n bar\n+ qux\n\t zot"); assertThat(RpslAttributeFilter.getValueForShortHand(subject.getValue()), is(" foo\n+ bar\n+ qux\n+ zot")); } |
RpslAttribute { @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final RpslAttribute attribute = (RpslAttribute) o; if (type == null) { if (attribute.type != null) { return false; } return key.equals(attribute.key); } else { if (type != attribute.type) { return false; } return Iterables.elementsEqual(getCleanValues(), attribute.getCleanValues()); } } RpslAttribute(final AttributeType attributeType, final CIString value); RpslAttribute(final AttributeType attributeType, final String value); RpslAttribute(final String key, final CIString value); RpslAttribute(final String key, final String value); String getKey(); String getValue(); String getCleanComment(); CIString getCleanValue(); Set<CIString> getCleanValues(); Set<CIString> getReferenceValues(); CIString getReferenceValue(); void validateSyntax(final ObjectType objectType, final ObjectMessages objectMessages); void writeTo(final Writer writer); String getFormattedValue(); void writeAttributeValueTo(final Writer writer); @Override boolean equals(Object o); @Override int hashCode(); @CheckForNull AttributeType getType(); @Override String toString(); } | @Test public void equals_is_case_insensitive() { subject = new RpslAttribute("remarks", "The quick brown fox."); assertThat(subject.equals(new RpslAttribute("remarks", "THE QUICK BROWN FOX.")), is(true)); }
@Test public void equals_unknown_type() { subject = new RpslAttribute("unknown", "The quick brown fox."); assertThat(subject.equals(new RpslAttribute("unknown", "THE QUICK BROWN FOX.")), is(true)); }
@Test public void equals_Integer() { subject = new RpslAttribute("remarks", "The quick brown fox."); assertFalse(subject.equals(1)); }
@Test public void equals_null() { subject = new RpslAttribute("remarks", "The quick brown fox."); assertThat(subject, not(is(nullValue()))); assertFalse(subject.equals(null)); }
@Test public void equals_shorthand() { subject = new RpslAttribute("remarks", "The quick brown fox."); assertThat(subject.equals(new RpslAttribute("*rm", "THE QUICK BROWN FOX.")), is(true)); } |
RpslAttribute { public void validateSyntax(final ObjectType objectType, final ObjectMessages objectMessages) { for (final CIString cleanValue : getCleanValues()) { if (!type.getSyntax().matches(objectType, cleanValue.toString())) { objectMessages.addMessage(this, ValidationMessages.syntaxError(cleanValue.toString())); } } } RpslAttribute(final AttributeType attributeType, final CIString value); RpslAttribute(final AttributeType attributeType, final String value); RpslAttribute(final String key, final CIString value); RpslAttribute(final String key, final String value); String getKey(); String getValue(); String getCleanComment(); CIString getCleanValue(); Set<CIString> getCleanValues(); Set<CIString> getReferenceValues(); CIString getReferenceValue(); void validateSyntax(final ObjectType objectType, final ObjectMessages objectMessages); void writeTo(final Writer writer); String getFormattedValue(); void writeAttributeValueTo(final Writer writer); @Override boolean equals(Object o); @Override int hashCode(); @CheckForNull AttributeType getType(); @Override String toString(); } | @Test public void validateSyntax_syntax_error_and_invalid_email() { final ObjectMessages objectMessages = new ObjectMessages(); final RpslAttribute rpslAttribute = new RpslAttribute("inetnum", "[email protected]"); rpslAttribute.validateSyntax(ObjectType.INETNUM, objectMessages); assertThat(objectMessages.getMessages(rpslAttribute).getAllMessages(), contains(ValidationMessages.syntaxError("[email protected]"))); } |
RpslAttribute { @Override public String toString() { try { final StringWriter writer = new StringWriter(); writeTo(writer); return writer.toString(); } catch (IOException e) { throw new IllegalStateException("Should never occur", e); } } RpslAttribute(final AttributeType attributeType, final CIString value); RpslAttribute(final AttributeType attributeType, final String value); RpslAttribute(final String key, final CIString value); RpslAttribute(final String key, final String value); String getKey(); String getValue(); String getCleanComment(); CIString getCleanValue(); Set<CIString> getCleanValues(); Set<CIString> getReferenceValues(); CIString getReferenceValue(); void validateSyntax(final ObjectType objectType, final ObjectMessages objectMessages); void writeTo(final Writer writer); String getFormattedValue(); void writeAttributeValueTo(final Writer writer); @Override boolean equals(Object o); @Override int hashCode(); @CheckForNull AttributeType getType(); @Override String toString(); } | @Test public void format_single_line_no_spaces() { final RpslAttribute subject = new RpslAttribute("person", "Brian Riddle"); assertThat(subject.toString(), is("person: Brian Riddle\n")); }
@Test public void format_single_line_some_spaces() { final RpslAttribute subject = new RpslAttribute("person", " Brian Riddle"); assertThat(subject.toString(), is("person: Brian Riddle\n")); }
@Test public void format_single_line_too_many_spaces() { final RpslAttribute subject = new RpslAttribute("person", " Brian Riddle"); assertThat(subject.toString(), is("person: Brian Riddle\n")); } |
RpslAttribute { public String getCleanComment() { if (cleanValues == null) { extractCleanValueAndComment(value); } return cleanComment; } RpslAttribute(final AttributeType attributeType, final CIString value); RpslAttribute(final AttributeType attributeType, final String value); RpslAttribute(final String key, final CIString value); RpslAttribute(final String key, final String value); String getKey(); String getValue(); String getCleanComment(); CIString getCleanValue(); Set<CIString> getCleanValues(); Set<CIString> getReferenceValues(); CIString getReferenceValue(); void validateSyntax(final ObjectType objectType, final ObjectMessages objectMessages); void writeTo(final Writer writer); String getFormattedValue(); void writeAttributeValueTo(final Writer writer); @Override boolean equals(Object o); @Override int hashCode(); @CheckForNull AttributeType getType(); @Override String toString(); } | @Test public void get_comment_in_second_line() { subject = new RpslAttribute("remarks", "remark1\n remark2 # comment"); assertThat(subject.getCleanComment(), is("comment")); subject = new RpslAttribute("remarks", "foo\t # comment1 \n bar # \t comment2\n+ bla"); assertThat(subject.getCleanComment(), is("comment1 comment2")); } |
ParserHelper { public static void validateMoreSpecificsOperator(final String yytext) { int val = Integer.valueOf(yytext.substring(1)); if (val > MAX_BIT_LENGTH_IPV4) { syntaxError("more specifics operator " + yytext.substring(1) + " not 0 to 32 bits"); } } private ParserHelper(); static void check16bit(final String number); static void check32bit(final String number); static void checkMaskLength(final String maskLength); static void checkMaskLengthv6(final String maskLength); static void checkStringLength(final String ip, final int maxAllowedLength); static void validateMoreSpecificsOperator(final String yytext); static void validateRangeMoreSpecificsOperators(final String yytext); static void validateAsNumber(final String yytext); static void validateIpv4PrefixRange(final String yytext); static void validateIpv6PrefixRange(final String yytext); static void validateIpv4Prefix(final String yytext); static void validateIpv6Prefix(final String yytext); static void validateIpv4(final String yytext); static void validateIpv6(final String yytext); static void validateCommunity(final String yytext); static void validateDomainName(final String yytext); static void validateDomainNameLabel(final String yytext); static void validateSmallInt(final String yytext); static void validateAsRange(final String yytext); static void log(final String message); static void log(final Exception exception); static void syntaxError(final String message); static void parserError(final String message); } | @Test public void validateMoreSpecificsOperator() { ParserHelper.validateMoreSpecificsOperator("^0"); ParserHelper.validateMoreSpecificsOperator("^32"); }
@Test(expected = IllegalArgumentException.class) public void validateMoreSpecificsOperatorFailsTooLarge() { ParserHelper.validateMoreSpecificsOperator("^33"); } |
ParserHelper { public static void validateRangeMoreSpecificsOperators(final String yytext) { final int dash = yytext.indexOf('-'); int from = Integer.valueOf(yytext.substring(1, dash)); if (from > MAX_BIT_LENGTH_IPV4) { syntaxError("more specifics operator " + yytext + " not 0 to 32 bits"); } int to = Integer.valueOf(yytext.substring(dash + 1)); if (to > MAX_BIT_LENGTH_IPV4) { syntaxError("more specifics operator " + yytext + " not 0 to 32 bits"); } if (to < from) { syntaxError("more specifics operator " + yytext + " not 0 to 32 bits"); } } private ParserHelper(); static void check16bit(final String number); static void check32bit(final String number); static void checkMaskLength(final String maskLength); static void checkMaskLengthv6(final String maskLength); static void checkStringLength(final String ip, final int maxAllowedLength); static void validateMoreSpecificsOperator(final String yytext); static void validateRangeMoreSpecificsOperators(final String yytext); static void validateAsNumber(final String yytext); static void validateIpv4PrefixRange(final String yytext); static void validateIpv6PrefixRange(final String yytext); static void validateIpv4Prefix(final String yytext); static void validateIpv6Prefix(final String yytext); static void validateIpv4(final String yytext); static void validateIpv6(final String yytext); static void validateCommunity(final String yytext); static void validateDomainName(final String yytext); static void validateDomainNameLabel(final String yytext); static void validateSmallInt(final String yytext); static void validateAsRange(final String yytext); static void log(final String message); static void log(final Exception exception); static void syntaxError(final String message); static void parserError(final String message); } | @Test public void validateRangeMoreSpecificsOperators() { ParserHelper.validateRangeMoreSpecificsOperators("^0-0"); ParserHelper.validateRangeMoreSpecificsOperators("^0-1"); ParserHelper.validateRangeMoreSpecificsOperators("^0-32"); ParserHelper.validateRangeMoreSpecificsOperators("^31-32"); }
@Test(expected = IllegalArgumentException.class) public void validateRangeMoreSpecificsOperatorsInverseRange() { ParserHelper.validateRangeMoreSpecificsOperators("^1-0"); }
@Test(expected = IllegalArgumentException.class) public void validateRangeMoreSpecificsOperatorsOutOfRange() { ParserHelper.validateRangeMoreSpecificsOperators("^0-33"); } |
ParserHelper { public static void validateAsNumber(final String yytext) { final long value = Long.valueOf(yytext.substring(2)); if (value > MAX_32BIT_NUMBER) { syntaxError("AS Number " + yytext + " length is invalid"); } } private ParserHelper(); static void check16bit(final String number); static void check32bit(final String number); static void checkMaskLength(final String maskLength); static void checkMaskLengthv6(final String maskLength); static void checkStringLength(final String ip, final int maxAllowedLength); static void validateMoreSpecificsOperator(final String yytext); static void validateRangeMoreSpecificsOperators(final String yytext); static void validateAsNumber(final String yytext); static void validateIpv4PrefixRange(final String yytext); static void validateIpv6PrefixRange(final String yytext); static void validateIpv4Prefix(final String yytext); static void validateIpv6Prefix(final String yytext); static void validateIpv4(final String yytext); static void validateIpv6(final String yytext); static void validateCommunity(final String yytext); static void validateDomainName(final String yytext); static void validateDomainNameLabel(final String yytext); static void validateSmallInt(final String yytext); static void validateAsRange(final String yytext); static void log(final String message); static void log(final Exception exception); static void syntaxError(final String message); static void parserError(final String message); } | @Test public void validateAsNumber() { ParserHelper.validateAsNumber("AS0"); ParserHelper.validateAsNumber("AS" + ParserHelper.MAX_32BIT_NUMBER); }
@Test(expected = IllegalArgumentException.class) public void validateAsNumberOutOfRange() { ParserHelper.validateAsNumber("AS" + (ParserHelper.MAX_32BIT_NUMBER + 1L)); } |
ParserHelper { public static void validateIpv4PrefixRange(final String yytext) { Matcher m = ADDRESS_PREFIX_RANGE_PATTERN.matcher(yytext); if (m.matches()) { try { Ipv4Resource.parse(m.group(1)); } catch (IllegalArgumentException e) { syntaxError("IP prefix " + yytext + " contains an invalid octet"); } int prefix = Integer.valueOf(m.group(2)); if (prefix > MAX_BIT_LENGTH_IPV4) { syntaxError("IP prefix range " + yytext + " contains an invalid prefix length"); } String fromString = m.group(3); int from = 0; if (fromString != null) { from = Integer.valueOf(fromString); if (from > MAX_BIT_LENGTH_IPV4) { syntaxError("IP prefix range " + yytext + " contains an invalid range"); } } String toString = m.group(4); if (toString != null) { int to = Integer.valueOf(toString); if (to > MAX_BIT_LENGTH_IPV4) { syntaxError("IP prefix range " + yytext + " contains an invalid range"); } if (to < from) { syntaxError("IP prefix " + yytext + " range end is less than range start"); } } } } private ParserHelper(); static void check16bit(final String number); static void check32bit(final String number); static void checkMaskLength(final String maskLength); static void checkMaskLengthv6(final String maskLength); static void checkStringLength(final String ip, final int maxAllowedLength); static void validateMoreSpecificsOperator(final String yytext); static void validateRangeMoreSpecificsOperators(final String yytext); static void validateAsNumber(final String yytext); static void validateIpv4PrefixRange(final String yytext); static void validateIpv6PrefixRange(final String yytext); static void validateIpv4Prefix(final String yytext); static void validateIpv6Prefix(final String yytext); static void validateIpv4(final String yytext); static void validateIpv6(final String yytext); static void validateCommunity(final String yytext); static void validateDomainName(final String yytext); static void validateDomainNameLabel(final String yytext); static void validateSmallInt(final String yytext); static void validateAsRange(final String yytext); static void log(final String message); static void log(final Exception exception); static void syntaxError(final String message); static void parserError(final String message); } | @Test public void validateIpv4PrefixRange() { ParserHelper.validateIpv4PrefixRange("128.9.0.0/16^-"); ParserHelper.validateIpv4PrefixRange("5.0.0.0/8^+"); ParserHelper.validateIpv4PrefixRange("30.0.0.0/8^16"); ParserHelper.validateIpv4PrefixRange("30.0.0.0/8^24-32"); }
@Test(expected = IllegalArgumentException.class) public void validateIpv4PrefixRangeInvalidPrefix() { ParserHelper.validateIpv4PrefixRange("128.9.0.0/33^-"); }
@Test(expected = IllegalArgumentException.class) public void validateIpv4PrefixRangeInvalidPrefixPlus() { ParserHelper.validateIpv4PrefixRange("128.9.0.0/33^+"); }
@Test(expected = IllegalArgumentException.class) public void validateIpv4PrefixRangeInvalidPrefixCaretLength() { ParserHelper.validateIpv4PrefixRange("128.9.0.0/8^33"); }
@Test(expected = IllegalArgumentException.class) public void validateIpv4PrefixRangeInvalidPrefixCaretLengthEndRange() { ParserHelper.validateIpv4PrefixRange("128.9.0.0/8^24-33"); }
@Test(expected = IllegalArgumentException.class) public void validateIpv4PrefixRangeInvalidPrefixCaretLengthInverseRange() { ParserHelper.validateIpv4PrefixRange("128.9.0.0/8^32-24"); } |
ParserHelper { public static void validateIpv6PrefixRange(final String yytext) { Matcher m = ADDRESS_PREFIX_RANGE_PATTERN.matcher(yytext); if (m.matches()) { try { Ipv6Resource.parse(m.group(1)); } catch (IllegalArgumentException e) { syntaxError("IP prefix " + yytext + " contains an invalid quad"); } int prefix = Integer.valueOf(m.group(2)); if (prefix > MAX_BIT_LENGTH_IPV6) { syntaxError("IP prefix range " + yytext + " contains an invalid prefix length"); } String fromString = m.group(3); int from = 0; if (fromString != null) { from = Integer.valueOf(fromString); if (from > MAX_BIT_LENGTH_IPV6) { syntaxError("IP prefix range " + yytext + " contains an invalid range"); } } String toString = m.group(4); if (toString != null) { int to = Integer.valueOf(toString); if (to > MAX_BIT_LENGTH_IPV6) { syntaxError("IP prefix range " + yytext + " contains an invalid range"); } if (to < from) { syntaxError("IP prefix " + yytext + " range end is less than range start"); } } } } private ParserHelper(); static void check16bit(final String number); static void check32bit(final String number); static void checkMaskLength(final String maskLength); static void checkMaskLengthv6(final String maskLength); static void checkStringLength(final String ip, final int maxAllowedLength); static void validateMoreSpecificsOperator(final String yytext); static void validateRangeMoreSpecificsOperators(final String yytext); static void validateAsNumber(final String yytext); static void validateIpv4PrefixRange(final String yytext); static void validateIpv6PrefixRange(final String yytext); static void validateIpv4Prefix(final String yytext); static void validateIpv6Prefix(final String yytext); static void validateIpv4(final String yytext); static void validateIpv6(final String yytext); static void validateCommunity(final String yytext); static void validateDomainName(final String yytext); static void validateDomainNameLabel(final String yytext); static void validateSmallInt(final String yytext); static void validateAsRange(final String yytext); static void log(final String message); static void log(final Exception exception); static void syntaxError(final String message); static void parserError(final String message); } | @Test public void validateIpv6PrefixRange() { ParserHelper.validateIpv6PrefixRange("2001:0DB8::/32^+"); ParserHelper.validateIpv6PrefixRange("2001:0DB8:0100::/48^+"); ParserHelper.validateIpv6PrefixRange("2001:0DB8:0200::/48^64"); ParserHelper.validateIpv6PrefixRange("2001:0DB8:0200::/48^48-64"); ParserHelper.validateIpv6PrefixRange("0::/0^0-128"); ParserHelper.validateIpv6PrefixRange("::/0^0-48"); ParserHelper.validateIpv6PrefixRange("::/0^0-64"); ParserHelper.validateIpv6PrefixRange("::/0^0"); }
@Test(expected = IllegalArgumentException.class) public void validateIpv6PrefixRangeInvalidPrefix() { ParserHelper.validateIpv6PrefixRange("2001:0DB8::/129^-"); }
@Test(expected = IllegalArgumentException.class) public void validateIpv6PrefixRangeInvalidPrefixPlus() { ParserHelper.validateIpv6PrefixRange("2001:0DB8::/129^+"); }
@Test(expected = IllegalArgumentException.class) public void validateIpv6PrefixRangeInvalidPrefixCaretLength() { ParserHelper.validateIpv6PrefixRange("2001:0DB8::/32^129"); }
@Test(expected = IllegalArgumentException.class) public void validateIpv6PrefixRangeInvalidPrefixCaretLengthEndRange() { ParserHelper.validateIpv6PrefixRange("2001:0DB8::/32^32-129"); }
@Test(expected = IllegalArgumentException.class) public void validateIpv6PrefixRangeInvalidPrefixCaretLengthInverseRange() { ParserHelper.validateIpv6PrefixRange("2001:0DB8::/32^32-24"); } |
RadbGrsSource 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 RadbGrsSource(
@Value("${grs.import.radb.source:}") final String source,
final SourceContext sourceContext,
final DateTimeProvider dateTimeProvider,
final AuthoritativeResourceData authoritativeResourceData,
final Downloader downloader,
@Value("${grs.import.radb.download:}") final String download); @Override void acquireDump(final Path path); @Override void handleObjects(final File file, final ObjectHandler handler); } | @Test public void handleObjects() throws Exception { final File file = new File(getClass().getResource("/grs/radb.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( "aut-num: AS1263\n", "as-name: TEST-AS\n", "descr: TEST-AS\n", "admin-c: Not available\n", "tech-c: See TEST-MNT\n", "mnt-by: TEST-MNT\n", "changed: [email protected] 19950201\n", "source: RADB\n"), Lists.newArrayList( "route: 167.96.0.0/16\n", "" + "descr: Company 2\n" + " Address 2\n" + " Postcode\n" + " State\n" + " Country\n", "origin: AS2900\n", "member-of: RS-TEST\n", "mnt-by: TEST-MNT\n", "changed: [email protected] 19950506\n", "source: RADB\n") )); } |
ParserHelper { public static void validateIpv4Prefix(final String yytext) { final int slash = yytext.indexOf('/'); try { Ipv4Resource.parse(yytext.substring(0, slash)); } catch (IllegalArgumentException e) { syntaxError("IP prefix " + yytext + " contains an invalid octet"); } final int length = Integer.valueOf(yytext.substring(slash + 1)); if (length > MAX_BIT_LENGTH_IPV4) { syntaxError("IP prefix " + yytext + " contains an invalid prefix length"); } } private ParserHelper(); static void check16bit(final String number); static void check32bit(final String number); static void checkMaskLength(final String maskLength); static void checkMaskLengthv6(final String maskLength); static void checkStringLength(final String ip, final int maxAllowedLength); static void validateMoreSpecificsOperator(final String yytext); static void validateRangeMoreSpecificsOperators(final String yytext); static void validateAsNumber(final String yytext); static void validateIpv4PrefixRange(final String yytext); static void validateIpv6PrefixRange(final String yytext); static void validateIpv4Prefix(final String yytext); static void validateIpv6Prefix(final String yytext); static void validateIpv4(final String yytext); static void validateIpv6(final String yytext); static void validateCommunity(final String yytext); static void validateDomainName(final String yytext); static void validateDomainNameLabel(final String yytext); static void validateSmallInt(final String yytext); static void validateAsRange(final String yytext); static void log(final String message); static void log(final Exception exception); static void syntaxError(final String message); static void parserError(final String message); } | @Test public void validateIpv4Prefix() { ParserHelper.validateIpv4Prefix("0.0.0.0/0"); ParserHelper.validateIpv4Prefix("1.2.3.4/32"); }
@Test(expected = IllegalArgumentException.class) public void validateIpv4PrefixOutOfRange() { ParserHelper.validateIpv4Prefix("1.2.3.4/33"); } |
ParserHelper { public static void validateIpv6Prefix(final String yytext) { final int slash = yytext.indexOf('/'); try { Ipv6Resource.parse(yytext.substring(0, slash)); } catch (IllegalArgumentException e) { syntaxError("IPv6 prefix " + yytext + " contains an invalid quad"); } final int length = Integer.valueOf(yytext.substring(slash + 1)); if (length > MAX_BIT_LENGTH_IPV6) { syntaxError("IPv6 prefix " + yytext + " contains an invalid prefix length"); } } private ParserHelper(); static void check16bit(final String number); static void check32bit(final String number); static void checkMaskLength(final String maskLength); static void checkMaskLengthv6(final String maskLength); static void checkStringLength(final String ip, final int maxAllowedLength); static void validateMoreSpecificsOperator(final String yytext); static void validateRangeMoreSpecificsOperators(final String yytext); static void validateAsNumber(final String yytext); static void validateIpv4PrefixRange(final String yytext); static void validateIpv6PrefixRange(final String yytext); static void validateIpv4Prefix(final String yytext); static void validateIpv6Prefix(final String yytext); static void validateIpv4(final String yytext); static void validateIpv6(final String yytext); static void validateCommunity(final String yytext); static void validateDomainName(final String yytext); static void validateDomainNameLabel(final String yytext); static void validateSmallInt(final String yytext); static void validateAsRange(final String yytext); static void log(final String message); static void log(final Exception exception); static void syntaxError(final String message); static void parserError(final String message); } | @Test public void validateIpv6Prefix() { ParserHelper.validateIpv6Prefix("2001:0DB8::/32"); ParserHelper.validateIpv6Prefix("2001:06f0:0041:0000:0000:0000:3c00:0004/128"); ParserHelper.validateIpv6Prefix("::/0"); ParserHelper.validateIpv6Prefix("2001:503:231d::/48"); }
@Test(expected = IllegalArgumentException.class) public void validateIpv6PrefixOutOfRange() { ParserHelper.validateIpv6Prefix("2001:0DB8::/129"); }
@Test(expected = IllegalArgumentException.class) public void validateIpv6PrefixDoubleColonOutOfRange() { ParserHelper.validateIpv6Prefix("2001:503:231d::/129"); } |
ArinGrsSource extends GrsSource { @Override public void handleObjects(final File file, final ObjectHandler handler) throws IOException { ZipFile zipFile = null; try { zipFile = new ZipFile(file, ZipFile.OPEN_READ); final ZipEntry zipEntry = zipFile.getEntry(zipEntryName); if (zipEntry == null) { logger.error("Zipfile {} does not contain dump {}", file, zipEntryName); return; } final BufferedReader reader = new BufferedReader(new InputStreamReader(zipFile.getInputStream(zipEntry), StandardCharsets.UTF_8)); handleLines(reader, new LineHandler() { @Override public void handleLines(final List<String> lines) { if (lines.isEmpty() || IGNORED_OBJECTS.contains(ciString(StringUtils.substringBefore(lines.get(0), ":")))) { logger.debug("Ignoring:\n\n{}\n", lines); return; } final RpslObjectBuilder rpslObjectBuilder = new RpslObjectBuilder(Joiner.on("").join(lines)); for (RpslObject next : expand(rpslObjectBuilder.getAttributes())) { handler.handle(next); } } private List<RpslObject> expand(final List<RpslAttribute> attributes) { if (attributes.get(0).getKey().equals("ashandle")) { final String asnumber = findAttributeValue(attributes, "asnumber"); if (asnumber != null) { final Matcher rangeMatcher = AS_NUMBER_RANGE.matcher(asnumber); if (rangeMatcher.find()) { final List<RpslObject> objects = Lists.newArrayList(); final int begin = Integer.parseInt(rangeMatcher.group(1)); final int end = Integer.parseInt(rangeMatcher.group(2)); for (int index = begin; index <= end; index++) { attributes.set(0, new RpslAttribute(AttributeType.AUT_NUM, String.format("AS%d", index))); objects.add(new RpslObject(transform(attributes))); } return objects; } } } return Lists.newArrayList(new RpslObject(transform(attributes))); } private List<RpslAttribute> transform(final List<RpslAttribute> attributes) { final List<RpslAttribute> newAttributes = Lists.newArrayList(); for (RpslAttribute attribute : attributes) { final Function<RpslAttribute, RpslAttribute> transformFunction = TRANSFORM_FUNCTIONS.get(ciString(attribute.getKey())); if (transformFunction != null) { attribute = transformFunction.apply(attribute); } final AttributeType attributeType = attribute.getType(); if (attributeType == null) { continue; } else if (AttributeType.INETNUM.equals(attributeType) || AttributeType.INET6NUM.equals(attributeType)) { newAttributes.add(0, attribute); } else { newAttributes.add(attribute); } } return newAttributes; } @Nullable private String findAttributeValue(final List<RpslAttribute> attributes, final String key) { for (RpslAttribute attribute : attributes) { if (attribute.getKey().equals(key)) { return attribute.getCleanValue().toString(); } } return null; } }); } finally { if (zipFile != null) { zipFile.close(); } } } @Autowired ArinGrsSource(
@Value("${grs.import.arin.source:}") final String source,
final SourceContext sourceContext,
final DateTimeProvider dateTimeProvider,
final AuthoritativeResourceData authoritativeResourceData,
final Downloader downloader,
@Value("${grs.import.arin.download:}") final String download,
@Value("${grs.import.arin.zipEntryName:}") final String zipEntryName); @Override void acquireDump(final Path path); @Override void handleObjects(final File file, final ObjectHandler handler); } | @Test public void handleObjects() throws Exception { final File file = new File(getClass().getResource("/grs/arin.test.zip").toURI()); subject.handleObjects(file, objectHandler); assertThat(objectHandler.getLines(), hasSize(0)); assertThat(objectHandler.getObjects(), hasSize(4)); assertThat(objectHandler.getObjects(), contains( RpslObject.parse("" + "aut-num: AS0\n" + "org: IANA\n" + "as-name: IANA-RSVD-0\n" + "remarks: Reserved - May be used to identify non-routed networks\n" + "source: ARIN\n"), RpslObject.parse("" + "inetnum: 192.104.33.0 - 192.104.33.255\n" + "org: THESPI\n" + "netname: SPINK\n" + "status: assignment\n" + "source: ARIN\n"), RpslObject.parse("" + "inet6num: 2001:4d0::/32\n" + "org: NASA\n" + "netname: NASA-PCCA-V6\n" + "status: allocation\n" + "tech-c: ZN7-ARIN\n" + "source: ARIN\n"), RpslObject.parse("" + "inet6num: 2001:468:400::/40\n" + "org: V6IU\n" + "netname: ABILENE-IU-V6\n" + "status: reallocation\n" + "tech-c: BS69-ARIN\n" + "source: ARIN\n") )); }
@Test public void as_number_range() throws Exception { File zipFile = FileHelper.addToZipFile("arin.test", "arin_db.txt", "ASHandle: AS701\n" + "OrgID: MCICS\n" + "ASName: UUNET\n" + "ASNumber: 701 - 705\n" + "RegDate: 1990-08-03\n" + "Updated: 2012-03-20\n" + "Source: ARIN\n"); try { subject.handleObjects(zipFile, objectHandler); assertThat(objectHandler.getLines(), hasSize(0)); assertThat(objectHandler.getObjects(), hasSize(5)); assertThat(objectHandler.getObjects(), contains( RpslObject.parse( "aut-num: AS701\n" + "org: MCICS\n" + "as-name: UUNET\n" + "source: ARIN"), RpslObject.parse( "aut-num: AS702\n" + "org: MCICS\n" + "as-name: UUNET\n" + "source: ARIN"), RpslObject.parse( "aut-num: AS703\n" + "org: MCICS\n" + "as-name: UUNET\n" + "source: ARIN"), RpslObject.parse( "aut-num: AS704\n" + "org: MCICS\n" + "as-name: UUNET\n" + "source: ARIN"), RpslObject.parse( "aut-num: AS705\n" + "org: MCICS\n" + "as-name: UUNET\n" + "source: ARIN") )); } finally { zipFile.delete(); } }
@Test public void single_as_number() throws Exception { File zipFile = FileHelper.addToZipFile("arin.test", "arin_db.txt", "ASHandle: AS701\n" + "OrgID: MCICS\n" + "ASName: UUNET\n" + "ASNumber: 701\n" + "RegDate: 1990-08-03\n" + "Updated: 2012-03-20\n" + "Source: ARIN\n"); try { subject.handleObjects(zipFile, objectHandler); assertThat(objectHandler.getLines(), hasSize(0)); assertThat(objectHandler.getObjects(), hasSize(1)); assertThat(objectHandler.getObjects(), contains( RpslObject.parse( "aut-num: AS701\n" + "org: MCICS\n" + "as-name: UUNET\n" + "source: ARIN"))); } finally { zipFile.delete(); } }
@Test public void as_number_without_range() throws Exception { File zipFile = FileHelper.addToZipFile("arin.test", "arin_db.txt", "ASHandle: AS701\n" + "OrgID: MCICS\n" + "ASName: UUNET\n" + "RegDate: 1990-08-03\n" + "Updated: 2012-03-20\n" + "Source: ARIN\n"); try { subject.handleObjects(zipFile, objectHandler); assertThat(objectHandler.getLines(), hasSize(0)); assertThat(objectHandler.getObjects(), hasSize(1)); assertThat(objectHandler.getObjects(), contains( RpslObject.parse( "aut-num: AS701\n" + "org: MCICS\n" + "as-name: UUNET\n" + "source: ARIN"))); } finally { zipFile.delete(); } } |
ParserHelper { public static void validateIpv4(final String yytext) { try { Ipv4Resource.parse(yytext); } catch (IllegalArgumentException e) { syntaxError("IP address " + yytext + " contains an invalid octet"); } } private ParserHelper(); static void check16bit(final String number); static void check32bit(final String number); static void checkMaskLength(final String maskLength); static void checkMaskLengthv6(final String maskLength); static void checkStringLength(final String ip, final int maxAllowedLength); static void validateMoreSpecificsOperator(final String yytext); static void validateRangeMoreSpecificsOperators(final String yytext); static void validateAsNumber(final String yytext); static void validateIpv4PrefixRange(final String yytext); static void validateIpv6PrefixRange(final String yytext); static void validateIpv4Prefix(final String yytext); static void validateIpv6Prefix(final String yytext); static void validateIpv4(final String yytext); static void validateIpv6(final String yytext); static void validateCommunity(final String yytext); static void validateDomainName(final String yytext); static void validateDomainNameLabel(final String yytext); static void validateSmallInt(final String yytext); static void validateAsRange(final String yytext); static void log(final String message); static void log(final Exception exception); static void syntaxError(final String message); static void parserError(final String message); } | @Test public void validateIpv4() { ParserHelper.validateIpv4("1.2.3.4/32"); }
@Test(expected = IllegalArgumentException.class) public void validateIpv4InvalidPrefixLength() { ParserHelper.validateIpv4("1.2.3.4/33"); } |
ParserHelper { public static void validateIpv6(final String yytext) { try { Ipv6Resource.parse(yytext); } catch (IllegalArgumentException e) { syntaxError("IP address " + yytext + " contains an invalid quad"); } } private ParserHelper(); static void check16bit(final String number); static void check32bit(final String number); static void checkMaskLength(final String maskLength); static void checkMaskLengthv6(final String maskLength); static void checkStringLength(final String ip, final int maxAllowedLength); static void validateMoreSpecificsOperator(final String yytext); static void validateRangeMoreSpecificsOperators(final String yytext); static void validateAsNumber(final String yytext); static void validateIpv4PrefixRange(final String yytext); static void validateIpv6PrefixRange(final String yytext); static void validateIpv4Prefix(final String yytext); static void validateIpv6Prefix(final String yytext); static void validateIpv4(final String yytext); static void validateIpv6(final String yytext); static void validateCommunity(final String yytext); static void validateDomainName(final String yytext); static void validateDomainNameLabel(final String yytext); static void validateSmallInt(final String yytext); static void validateAsRange(final String yytext); static void log(final String message); static void log(final Exception exception); static void syntaxError(final String message); static void parserError(final String message); } | @Test public void validateIpv6() { ParserHelper.validateIpv6("2001:0DB8::/32"); ParserHelper.validateIpv6("2001:06f0:0041:0000:0000:0000:3c00:0004/128"); ParserHelper.validateIpv6("2001:470:1:35e::1"); ParserHelper.validateIpv6("2001:7F8:14::58:2"); ParserHelper.validateIpv6("2001:7f8:13::a500:8587:1"); ParserHelper.validateIpv6("2001:504:1::"); }
@Test(expected = IllegalArgumentException.class) public void validateIpv6InvalidPrefixLength() { ParserHelper.validateIpv6("2001:0DB8::/129"); } |
ParserHelper { public static void validateCommunity(final String yytext) { final int colon = yytext.indexOf(':'); final long from = Long.valueOf(yytext.substring(0, colon)); if (from > MAX_16BIT_NUMBER) { syntaxError("Community number " + yytext + " contains an invalid number"); } final long to = Long.valueOf(yytext.substring(colon + 1)); if (to > MAX_16BIT_NUMBER) { syntaxError("Community number " + yytext + " contains an invalid number"); } } private ParserHelper(); static void check16bit(final String number); static void check32bit(final String number); static void checkMaskLength(final String maskLength); static void checkMaskLengthv6(final String maskLength); static void checkStringLength(final String ip, final int maxAllowedLength); static void validateMoreSpecificsOperator(final String yytext); static void validateRangeMoreSpecificsOperators(final String yytext); static void validateAsNumber(final String yytext); static void validateIpv4PrefixRange(final String yytext); static void validateIpv6PrefixRange(final String yytext); static void validateIpv4Prefix(final String yytext); static void validateIpv6Prefix(final String yytext); static void validateIpv4(final String yytext); static void validateIpv6(final String yytext); static void validateCommunity(final String yytext); static void validateDomainName(final String yytext); static void validateDomainNameLabel(final String yytext); static void validateSmallInt(final String yytext); static void validateAsRange(final String yytext); static void log(final String message); static void log(final Exception exception); static void syntaxError(final String message); static void parserError(final String message); } | @Test public void validateCommunity() { ParserHelper.validateCommunity("1:1"); ParserHelper.validateCommunity("65535:65535"); }
@Test(expected = IllegalArgumentException.class) public void validateCommunityBeforeColonOutOfRange() { ParserHelper.validateCommunity("65536:1"); }
@Test(expected = IllegalArgumentException.class) public void validateCommunityAfterColonOutOfRange() { ParserHelper.validateCommunity("1:65536"); } |
ParserHelper { public static void validateDomainName(final String yytext) { if (yytext.length() > DOMAIN_NAME_MAX_LENGTH) { syntaxError("Domain name " + yytext + " is longer than 255 characters"); } } private ParserHelper(); static void check16bit(final String number); static void check32bit(final String number); static void checkMaskLength(final String maskLength); static void checkMaskLengthv6(final String maskLength); static void checkStringLength(final String ip, final int maxAllowedLength); static void validateMoreSpecificsOperator(final String yytext); static void validateRangeMoreSpecificsOperators(final String yytext); static void validateAsNumber(final String yytext); static void validateIpv4PrefixRange(final String yytext); static void validateIpv6PrefixRange(final String yytext); static void validateIpv4Prefix(final String yytext); static void validateIpv6Prefix(final String yytext); static void validateIpv4(final String yytext); static void validateIpv6(final String yytext); static void validateCommunity(final String yytext); static void validateDomainName(final String yytext); static void validateDomainNameLabel(final String yytext); static void validateSmallInt(final String yytext); static void validateAsRange(final String yytext); static void log(final String message); static void log(final Exception exception); static void syntaxError(final String message); static void parserError(final String message); } | @Test public void validateDomainName() { ParserHelper.validateDomainName("12345678901234567890123456789012345678901234567890" + "12345678901234567890123456789012345678901234567890" + "12345678901234567890123456789012345678901234567890" + "12345678901234567890123456789012345678901234567890" + "1234567890123456789012345678901234567890123456789012345"); }
@Test(expected = IllegalArgumentException.class) public void validateDomainNameTooLong() { ParserHelper.validateDomainName("12345678901234567890123456789012345678901234567890" + "12345678901234567890123456789012345678901234567890" + "12345678901234567890123456789012345678901234567890" + "12345678901234567890123456789012345678901234567890" + "12345678901234567890123456789012345678901234567890123456"); } |
ParserHelper { public static void validateDomainNameLabel(final String yytext) { if (yytext.length() > DOMAIN_NAME_LABEL_MAX_LENGTH) { syntaxError("Domain name label " + yytext + " is longer than 63 characters"); } } private ParserHelper(); static void check16bit(final String number); static void check32bit(final String number); static void checkMaskLength(final String maskLength); static void checkMaskLengthv6(final String maskLength); static void checkStringLength(final String ip, final int maxAllowedLength); static void validateMoreSpecificsOperator(final String yytext); static void validateRangeMoreSpecificsOperators(final String yytext); static void validateAsNumber(final String yytext); static void validateIpv4PrefixRange(final String yytext); static void validateIpv6PrefixRange(final String yytext); static void validateIpv4Prefix(final String yytext); static void validateIpv6Prefix(final String yytext); static void validateIpv4(final String yytext); static void validateIpv6(final String yytext); static void validateCommunity(final String yytext); static void validateDomainName(final String yytext); static void validateDomainNameLabel(final String yytext); static void validateSmallInt(final String yytext); static void validateAsRange(final String yytext); static void log(final String message); static void log(final Exception exception); static void syntaxError(final String message); static void parserError(final String message); } | @Test public void validateDomainNameLabel() { ParserHelper.validateDomainNameLabel("abcdefghijklmnopqrstuvwxyz"); ParserHelper.validateDomainNameLabel("ABCDEFGHIJKLMNOPQRSTUVWXYZ"); ParserHelper.validateDomainNameLabel("123456789012345678901234567890123456789012345678901234567890123"); }
@Test(expected = IllegalArgumentException.class) public void validateDomainNameLabelTooLong() { ParserHelper.validateDomainNameLabel("1234567890123456789012345678901234567890123456789012345678901234"); } |
ParserHelper { public static void validateAsRange(final String yytext) { Matcher matcher = AS_RANGE_PATTERN.matcher(yytext); if (matcher.find()) { long begin = Long.valueOf(matcher.group(1)); if (begin > MAX_32BIT_NUMBER) { syntaxError("AS Number " + yytext + " is invalid"); } long end = Long.valueOf(matcher.group(2)); if (end > MAX_32BIT_NUMBER) { syntaxError("AS Number " + yytext + " is invalid"); } if (end < begin) { syntaxError("AS Range " + yytext + " is invalid"); } } } private ParserHelper(); static void check16bit(final String number); static void check32bit(final String number); static void checkMaskLength(final String maskLength); static void checkMaskLengthv6(final String maskLength); static void checkStringLength(final String ip, final int maxAllowedLength); static void validateMoreSpecificsOperator(final String yytext); static void validateRangeMoreSpecificsOperators(final String yytext); static void validateAsNumber(final String yytext); static void validateIpv4PrefixRange(final String yytext); static void validateIpv6PrefixRange(final String yytext); static void validateIpv4Prefix(final String yytext); static void validateIpv6Prefix(final String yytext); static void validateIpv4(final String yytext); static void validateIpv6(final String yytext); static void validateCommunity(final String yytext); static void validateDomainName(final String yytext); static void validateDomainNameLabel(final String yytext); static void validateSmallInt(final String yytext); static void validateAsRange(final String yytext); static void log(final String message); static void log(final Exception exception); static void syntaxError(final String message); static void parserError(final String message); } | @Test public void validateAsRange() { ParserHelper.validateAsRange("AS1 - AS2"); ParserHelper.validateAsRange("AS1 - AS2"); }
@Test(expected = IllegalArgumentException.class) public void validateAsRangeInverseRange() { ParserHelper.validateAsRange("AS2 - AS1"); }
@Test(expected = IllegalArgumentException.class) public void validateAsRangeInvalidToNoSpaces() { ParserHelper.validateAsRange("AS1-AS" + (1L << 32)); }
@Test(expected = IllegalArgumentException.class) public void validateAsRangeInvalidToWithSpaces() { ParserHelper.validateAsRange("AS1 - AS" + (1L << 32)); } |
ByteArrayOutput extends OutputStream { public void write(final int b) { final int newcount = count + 1; if (newcount > buf.length) { buf = Arrays.copyOf(buf, Math.max(buf.length << 1, newcount)); } buf[count] = (byte) b; count = newcount; } ByteArrayOutput(); ByteArrayOutput(final int initialCapacity); void write(final int b); void write(final byte b[]); void write(final byte b[], final int off, final int len); void reset(); byte[] toByteArray(); int size(); } | @Test(expected = IndexOutOfBoundsException.class) public void write_bytes_offset_out_of_bounds() { subject.write(buffer, 2, buffer.length); } |
ByteArrayOutput extends OutputStream { public void reset() { count = 0; } ByteArrayOutput(); ByteArrayOutput(final int initialCapacity); void write(final int b); void write(final byte b[]); void write(final byte b[], final int off, final int len); void reset(); byte[] toByteArray(); int size(); } | @Test public void reset() { subject.write(buffer); subject.reset(); assertThat(subject.toByteArray(), is(new byte[]{})); subject.write(buffer); assertThat(subject.toByteArray(), is(buffer)); } |
ByteArrayOutput extends OutputStream { public int size() { return count; } ByteArrayOutput(); ByteArrayOutput(final int initialCapacity); void write(final int b); void write(final byte b[]); void write(final byte b[], final int off, final int len); void reset(); byte[] toByteArray(); int size(); } | @Test public void size() { subject.write(buffer); assertThat(subject.size(), is(buffer.length)); } |
Latin1Conversion { public static String convertString(@Nonnull final String value) { final CharsetEncoder charsetEncoder = StandardCharsets.ISO_8859_1.newEncoder(); charsetEncoder.onMalformedInput(CodingErrorAction.REPLACE); charsetEncoder.onUnmappableCharacter(CodingErrorAction.REPLACE); try { final ByteBuffer encoded = charsetEncoder.encode(CharBuffer.wrap(value)); convert(encoded); return new String(encoded.array(), StandardCharsets.ISO_8859_1); } catch (CharacterCodingException e) { LOGGER.error(value, e); throw new IllegalStateException(e); } } private Latin1Conversion(); static Latin1ConversionResult convert(@Nonnull final String value); static String convertString(@Nonnull final String value); } | @Test public void convert_ascii_string() { final String ascii = "!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_`abcdefghijklmnopqrstuvwxyz{|}~"; assertThat(Latin1Conversion.convertString(ascii), is(ascii)); }
@Test public void convert_supplement_latin1_string() { assertThat(Latin1Conversion.convertString(SUPPLEMENT), is(SUPPLEMENT)); }
@Test public void convert_control_characters_string() { final String control = new String(new byte[]{0x0, 0x0a}, StandardCharsets.ISO_8859_1); assertThat(Latin1Conversion.convertString(control), is("?\n")); }
@Test public void convert_non_break_space_string() { final String control = new String(new byte[]{(byte)0xa0}, StandardCharsets.ISO_8859_1); assertThat(Latin1Conversion.convertString(control), is(" ")); }
@Test public void convert_silent_hyphen_string() { final String control = new String(new byte[]{(byte)0xad}, StandardCharsets.ISO_8859_1); assertThat(Latin1Conversion.convertString(control), is("-")); }
@Test public void convert_non_latin1_string() { assertThat(Latin1Conversion.convertString("ΣΔ"), is("??") ); assertThat(Latin1Conversion.convertString("привет"), is("??????") ); assertThat(Latin1Conversion.convertString("مرحبا"), is("?????") ); assertThat(Latin1Conversion.convertString("你好ا"), is("???") ); }
@Test public void convert_empty_input_string() { assertThat(Latin1Conversion.convertString(""), is("") ); } |
Latin1Conversion { private static byte[] convert(@Nonnull final byte[] input) { for (int offset = 0; offset < input.length; offset++) { input[offset] = SUBSTITUTIONS[((int) input[offset]) & 0xff]; } return input; } private Latin1Conversion(); static Latin1ConversionResult convert(@Nonnull final String value); static String convertString(@Nonnull final String value); } | @Test public void convert_rpsl_with_supplement() { assertThat( Latin1Conversion.convert("person: test\nnic-hdl: TP1-TEST\ndescr: " + SUPPLEMENT).getRpslObject(), is(RpslObject.parse("person: test\nnic-hdl: TP1-TEST\ndescr: " + SUPPLEMENT)) ); }
@Test public void convert_control_characters_rpsl() { assertThat( Latin1Conversion.convert( "person: Test\u0000 Person\nnic-hdl: TP1-TEST\nsource: TEST").getRpslObject(), is( RpslObject.parse("person: Test? Person\nnic-hdl: TP1-TEST\nsource: TEST"))); }
@Test public void convert_non_break_space_rpsl() { assertThat( Latin1Conversion.convert( "person: Test\u00a0Person\nnic-hdl: TP1-TEST\nsource: TEST").getRpslObject(), is( RpslObject.parse("person: Test Person\nnic-hdl: TP1-TEST\nsource: TEST"))); }
@Test public void unicode_umlaut_substituted_correctly() { assertThat( Latin1Conversion.convert( "person: Test P\u00FCrson\nnic-hdl: TP1-TEST\nsource: TEST").getRpslObject(), is( RpslObject.parse("person: Test Pürson\nnic-hdl: TP1-TEST\nsource: TEST"))); }
@Test public void utf16_umlaut_not_substituted_rpsl() { assertThat( Latin1Conversion.convert( "person: Test Pürson\nnic-hdl: TP1-TEST\nsource: TEST").getRpslObject(), is( RpslObject.parse("person: Test Pürson\nnic-hdl: TP1-TEST\nsource: TEST"))); } |
Ipv4Resource extends IpInterval<Ipv4Resource> implements Comparable<Ipv4Resource> { public static Ipv4Resource parse(final CIString resource) { return parse(resource.toString()); } private Ipv4Resource(final int begin, final int end); Ipv4Resource(final long begin, final long end); Ipv4Resource(final InetAddress inetAddress); static Ipv4Resource parse(final CIString resource); static Ipv4Resource parse(final String resource); static Ipv4Resource parseIPv4Resource(final String resource); static Ipv4Resource parsePrefixWithLength(final long prefix, final int prefixLength); static Ipv4Resource parseReverseDomain(final String address); @Override AttributeType getAttributeType(); long begin(); long end(); @Override boolean contains(final Ipv4Resource that); @Override boolean intersects(final Ipv4Resource that); @Override int hashCode(); @Override boolean equals(final Object obj); @Override String toString(); String toRangeString(); @Override int compareTo(final Ipv4Resource that); @Override Ipv4Resource singletonIntervalAtLowerBound(); @Override int compareUpperBound(final Ipv4Resource that); @Override InetAddress beginAsInetAddress(); @Override InetAddress endAsInetAddress(); @Override int getPrefixLength(); static final String IPV4_REVERSE_DOMAIN; static final Ipv4Resource MAX_RANGE; } | @Test(expected=IllegalArgumentException.class) public void ipv4_with_prefix_21_fails() { subject = Ipv4Resource.parse("151.64.0.1/21\r\n"); }
@Test(expected=IllegalArgumentException.class) public void ipv4_with_prefix_23_fails() { subject = Ipv4Resource.parse("109.73.65.0/23\r\n"); }
@Test(expected=IllegalArgumentException.class) public void ipv4_with_prefix_28_fails() { subject = Ipv4Resource.parse("62.219.43.72/28\r\n"); }
@Test(expected=IllegalArgumentException.class) public void ipv4_with_huge_prefix_fails() { subject = Ipv4Resource.parse("128.0.0.0/0\r\n"); }
@Test(expected=IllegalArgumentException.class) public void ipv4_with_tiny_prefix_fails() { subject = Ipv4Resource.parse("192.192.192.1/31\r\n"); }
@Test(expected=IllegalArgumentException.class) public void ipv4_with_prefix_21() { subject = Ipv4Resource.parse("151.64.0.1/21\r\n"); }
@Test(expected = IllegalArgumentException.class) public void invalidResource() { Ipv4Resource.parse("invalid resource"); }
@Test(expected = IllegalArgumentException.class) public void invalidResourceType() { Ipv4Resource.parse("::0"); } |
Ipv4Resource extends IpInterval<Ipv4Resource> implements Comparable<Ipv4Resource> { @Override public Ipv4Resource singletonIntervalAtLowerBound() { return new Ipv4Resource(this.begin(), this.begin()); } private Ipv4Resource(final int begin, final int end); Ipv4Resource(final long begin, final long end); Ipv4Resource(final InetAddress inetAddress); static Ipv4Resource parse(final CIString resource); static Ipv4Resource parse(final String resource); static Ipv4Resource parseIPv4Resource(final String resource); static Ipv4Resource parsePrefixWithLength(final long prefix, final int prefixLength); static Ipv4Resource parseReverseDomain(final String address); @Override AttributeType getAttributeType(); long begin(); long end(); @Override boolean contains(final Ipv4Resource that); @Override boolean intersects(final Ipv4Resource that); @Override int hashCode(); @Override boolean equals(final Object obj); @Override String toString(); String toRangeString(); @Override int compareTo(final Ipv4Resource that); @Override Ipv4Resource singletonIntervalAtLowerBound(); @Override int compareUpperBound(final Ipv4Resource that); @Override InetAddress beginAsInetAddress(); @Override InetAddress endAsInetAddress(); @Override int getPrefixLength(); static final String IPV4_REVERSE_DOMAIN; static final Ipv4Resource MAX_RANGE; } | @Test public void singletonIntervalAtLowerBound() { assertEquals(Ipv4Resource.parse("127.0.0.0/32"), Ipv4Resource.parse("127.0.0.0/8").singletonIntervalAtLowerBound()); } |
Ipv4Resource extends IpInterval<Ipv4Resource> implements Comparable<Ipv4Resource> { @Override public int compareTo(final Ipv4Resource that) { if (this.begin() < that.begin()) { return -1; } else if (this.begin() > that.begin()) { return 1; } else if (that.end() < this.end()) { return -1; } else if (that.end() > this.end()) { return 1; } else { return 0; } } private Ipv4Resource(final int begin, final int end); Ipv4Resource(final long begin, final long end); Ipv4Resource(final InetAddress inetAddress); static Ipv4Resource parse(final CIString resource); static Ipv4Resource parse(final String resource); static Ipv4Resource parseIPv4Resource(final String resource); static Ipv4Resource parsePrefixWithLength(final long prefix, final int prefixLength); static Ipv4Resource parseReverseDomain(final String address); @Override AttributeType getAttributeType(); long begin(); long end(); @Override boolean contains(final Ipv4Resource that); @Override boolean intersects(final Ipv4Resource that); @Override int hashCode(); @Override boolean equals(final Object obj); @Override String toString(); String toRangeString(); @Override int compareTo(final Ipv4Resource that); @Override Ipv4Resource singletonIntervalAtLowerBound(); @Override int compareUpperBound(final Ipv4Resource that); @Override InetAddress beginAsInetAddress(); @Override InetAddress endAsInetAddress(); @Override int getPrefixLength(); static final String IPV4_REVERSE_DOMAIN; static final Ipv4Resource MAX_RANGE; } | @Test public void compareWorks() { subject = new Ipv4Resource(10, 20); assertThat(0, eq(subject.compareTo(subject))); assertThat(1, eq(subject.compareTo(new Ipv4Resource(0, 9)))); assertThat(-1, eq(subject.compareTo(new Ipv4Resource(21, 30)))); assertThat(1, eq(subject.compareTo(new Ipv4Resource(0, 15)))); assertThat(-1, eq(subject.compareTo(new Ipv4Resource(15, 30)))); assertThat(1, eq(subject.compareTo(new Ipv4Resource(0, 20)))); assertThat(1, eq(subject.compareTo(new Ipv4Resource(10, 30)))); assertThat(-1, eq(subject.compareTo(new Ipv4Resource(11, 30)))); assertThat(-1, eq(subject.compareTo(new Ipv4Resource(10, 19)))); assertThat(-1, eq(subject.compareTo(new Ipv4Resource(11, 20)))); } |
ResourceTagger { void tagObjects(final GrsSource grsSource) { final Stopwatch stopwatch = Stopwatch.createStarted(); try { sourceContext.setCurrent(Source.master(grsSource.getName())); if (sourceContext.isTagRoutes()) { tagRouteObjectsInContext(grsSource); } tagsDao.deleteOrphanedTags(); } finally { sourceContext.removeCurrentSource(); grsSource.getLogger().info("Tagging objects complete in {}", stopwatch.stop()); } } @Autowired ResourceTagger(final SourceContext sourceContext, final TagsDao tagsDao); } | @Test public void tagObjects() { subject.tagObjects(grsSource); verify(sourceContext).setCurrent(any(Source.class)); verify(sourceContext).removeCurrentSource(); verify(tagsDao).updateTags(any(Iterable.class), any(List.class), any(List.class)); verify(tagsDao).deleteOrphanedTags(); } |
Ipv4Resource extends IpInterval<Ipv4Resource> implements Comparable<Ipv4Resource> { @Override public boolean intersects(final Ipv4Resource that) { return (isIPWithinRange(this.begin(), that) || isIPWithinRange(this.end(), that) || isIPWithinRange(that.begin(), this)); } private Ipv4Resource(final int begin, final int end); Ipv4Resource(final long begin, final long end); Ipv4Resource(final InetAddress inetAddress); static Ipv4Resource parse(final CIString resource); static Ipv4Resource parse(final String resource); static Ipv4Resource parseIPv4Resource(final String resource); static Ipv4Resource parsePrefixWithLength(final long prefix, final int prefixLength); static Ipv4Resource parseReverseDomain(final String address); @Override AttributeType getAttributeType(); long begin(); long end(); @Override boolean contains(final Ipv4Resource that); @Override boolean intersects(final Ipv4Resource that); @Override int hashCode(); @Override boolean equals(final Object obj); @Override String toString(); String toRangeString(); @Override int compareTo(final Ipv4Resource that); @Override Ipv4Resource singletonIntervalAtLowerBound(); @Override int compareUpperBound(final Ipv4Resource that); @Override InetAddress beginAsInetAddress(); @Override InetAddress endAsInetAddress(); @Override int getPrefixLength(); static final String IPV4_REVERSE_DOMAIN; static final Ipv4Resource MAX_RANGE; } | @Test public void verifyIntersects() { subject = new Ipv4Resource(10, 20); assertTrue(subject.intersects(subject)); assertTrue(subject.intersects(Ipv4Resource.MAX_RANGE)); assertFalse(subject.intersects(new Ipv4Resource(9, 9))); assertTrue(subject.intersects(new Ipv4Resource(9, 10))); assertTrue(subject.intersects(new Ipv4Resource(10, 11))); assertTrue(subject.intersects(new Ipv4Resource(5, 15))); assertFalse(subject.intersects(new Ipv4Resource(21, 21))); assertTrue(subject.intersects(new Ipv4Resource(19, 20))); assertTrue(subject.intersects(new Ipv4Resource(20, 21))); assertTrue(subject.intersects(new Ipv4Resource(15, 25))); } |
Ipv4Resource extends IpInterval<Ipv4Resource> implements Comparable<Ipv4Resource> { public static Ipv4Resource parseReverseDomain(final String address) { Validate.notEmpty(address); String cleanAddress = removeTrailingDot(address.trim()); Validate.isTrue(cleanAddress.toLowerCase().endsWith(IPV4_REVERSE_DOMAIN), "Invalid reverse domain: ", address); cleanAddress = cleanAddress.substring(0, cleanAddress.length() - IPV4_REVERSE_DOMAIN.length()); final ArrayList<String> reverseParts = Lists.newArrayList(SPLIT_ON_DOT.split(cleanAddress)); Validate.isTrue(!reverseParts.isEmpty() && reverseParts.size() <= 4, "Reverse address doesn't have between 1 and 4 octets: ", address); final List<String> parts = Lists.reverse(reverseParts); boolean hasDash = false; if (cleanAddress.contains("-")) { Validate.isTrue(reverseParts.size() == 4 && reverseParts.get(0).contains("-"), "Dash notation not in 4th octet: ", address); Validate.isTrue(cleanAddress.indexOf('-') == cleanAddress.lastIndexOf('-'), "Only one dash allowed: ", address); hasDash = true; } final StringBuilder builder = new StringBuilder(); for (String part : parts) { if (builder.length() > 0) { builder.append('.'); } Validate.isTrue(OCTET_PATTERN.matcher(part).matches(), "Invalid octet: ", part); builder.append(part); } if (hasDash) { int range = builder.indexOf("-"); if (range != -1) { builder.insert(range + 1, builder.substring(0, builder.lastIndexOf(".") + 1)); } } if (parts.size() < 4) { builder.append('/').append(parts.size() * 8); } return parse(builder.toString()); } private Ipv4Resource(final int begin, final int end); Ipv4Resource(final long begin, final long end); Ipv4Resource(final InetAddress inetAddress); static Ipv4Resource parse(final CIString resource); static Ipv4Resource parse(final String resource); static Ipv4Resource parseIPv4Resource(final String resource); static Ipv4Resource parsePrefixWithLength(final long prefix, final int prefixLength); static Ipv4Resource parseReverseDomain(final String address); @Override AttributeType getAttributeType(); long begin(); long end(); @Override boolean contains(final Ipv4Resource that); @Override boolean intersects(final Ipv4Resource that); @Override int hashCode(); @Override boolean equals(final Object obj); @Override String toString(); String toRangeString(); @Override int compareTo(final Ipv4Resource that); @Override Ipv4Resource singletonIntervalAtLowerBound(); @Override int compareUpperBound(final Ipv4Resource that); @Override InetAddress beginAsInetAddress(); @Override InetAddress endAsInetAddress(); @Override int getPrefixLength(); static final String IPV4_REVERSE_DOMAIN; static final Ipv4Resource MAX_RANGE; } | @Test(expected = IllegalArgumentException.class) public void reverse_empty() { Ipv4Resource.parseReverseDomain(""); }
@Test(expected = IllegalArgumentException.class) public void reverse_null() { Ipv4Resource.parseReverseDomain(null); }
@Test(expected = IllegalArgumentException.class) public void reverse_no_inaddrarpa() { Ipv4Resource.parseReverseDomain("1.2.3.4"); }
@Test(expected = IllegalArgumentException.class) public void reverse_no_octets() { Ipv4Resource.parseReverseDomain(".in-addr.arpa"); }
@Test(expected = IllegalArgumentException.class) public void reverse_more_than_four_octets() { Ipv4Resource.parseReverseDomain("8.7.6.5.4.3.2.1.in-addr.arpa"); }
@Test(expected = IllegalArgumentException.class) public void reverse_dash_not_in_fourth_octet() { Ipv4Resource.parseReverseDomain("1-1.1.1.in-addr.arpa"); }
@Test(expected = IllegalArgumentException.class) public void reverse_non_numeric_input() { Ipv4Resource.parseReverseDomain("1-1.b.a.in-addr.arpa"); }
@Test(expected = IllegalArgumentException.class) public void reverse_multiple_dashes() { Ipv4Resource.parseReverseDomain("1-1.2-2.3-3.4-4.in-addr.arpa"); }
@Test(expected = IllegalArgumentException.class) public void reverse_inverse_range() { Ipv4Resource.parseReverseDomain("80-28.79.198.195.in-addr.arpa"); } |
GrsSource implements InitializingBean { @Override public String toString() { return name.toString(); } GrsSource(final String name, final SourceContext sourceContext, final DateTimeProvider dateTimeProvider, final AuthoritativeResourceData authoritativeResourceData, final Downloader downloader); @Override void afterPropertiesSet(); Logger getLogger(); @Override String toString(); } | @Test public void string() { assertThat(subject.toString(), is("SOME-GRS")); } |
Ipv4Resource extends IpInterval<Ipv4Resource> implements Comparable<Ipv4Resource> { public static Ipv4Resource parsePrefixWithLength(final long prefix, final int prefixLength) { final long mask = (1L << (32 - prefixLength)) - 1; return new Ipv4Resource((prefix & ~mask) & 0xFFFFFFFFL, (prefix | mask) & 0xFFFFFFFFL); } private Ipv4Resource(final int begin, final int end); Ipv4Resource(final long begin, final long end); Ipv4Resource(final InetAddress inetAddress); static Ipv4Resource parse(final CIString resource); static Ipv4Resource parse(final String resource); static Ipv4Resource parseIPv4Resource(final String resource); static Ipv4Resource parsePrefixWithLength(final long prefix, final int prefixLength); static Ipv4Resource parseReverseDomain(final String address); @Override AttributeType getAttributeType(); long begin(); long end(); @Override boolean contains(final Ipv4Resource that); @Override boolean intersects(final Ipv4Resource that); @Override int hashCode(); @Override boolean equals(final Object obj); @Override String toString(); String toRangeString(); @Override int compareTo(final Ipv4Resource that); @Override Ipv4Resource singletonIntervalAtLowerBound(); @Override int compareUpperBound(final Ipv4Resource that); @Override InetAddress beginAsInetAddress(); @Override InetAddress endAsInetAddress(); @Override int getPrefixLength(); static final String IPV4_REVERSE_DOMAIN; static final Ipv4Resource MAX_RANGE; } | @Test public void parsePrefixWithLength() { assertThat(Ipv4Resource.parsePrefixWithLength(0, 0).toString(), is("0.0.0.0/0")); assertThat(Ipv4Resource.parsePrefixWithLength(0xffffffff, 0).toString(), is("0.0.0.0/0")); assertThat(Ipv4Resource.parsePrefixWithLength(0, 32).toString(), is("0.0.0.0/32")); assertThat(Ipv4Resource.parsePrefixWithLength(0xffffffff, 32).toString(), is("255.255.255.255/32")); assertThat(Ipv4Resource.parsePrefixWithLength(0xDEADBEEF, 13).toString(), is("222.168.0.0/13")); assertThat(Ipv4Resource.parsePrefixWithLength(0xCAFEBABE, 26).toString(), is("202.254.186.128/26")); } |
IpInterval implements Interval<K> { public static IpInterval<?> parseReverseDomain(final String reverse) { final String result = removeTrailingDot(reverse).toLowerCase(); if (result.endsWith(Ipv4Resource.IPV4_REVERSE_DOMAIN)) { return Ipv4Resource.parseReverseDomain(result); } return Ipv6Resource.parseReverseDomain(result); } static String removeTrailingDot(final String address); abstract AttributeType getAttributeType(); static IpInterval<?> parse(final CIString prefix); static IpInterval<?> parse(final String prefix); static IpInterval<?> parseReverseDomain(final String reverse); static IpInterval<?> asIpInterval(final InetAddress address); abstract InetAddress beginAsInetAddress(); abstract InetAddress endAsInetAddress(); abstract int getPrefixLength(); } | @Test public void parseReverseDomain() { assertThat(IpInterval.parseReverseDomain("0.0.193.in-ADDR.arpA").toString(), is("193.0.0.0/24")); assertThat(IpInterval.parseReverseDomain("a.b.0.0.1.iP6.arpA").toString(), is("100b:a000::/20")); assertThat(IpInterval.parseReverseDomain("0.0.193.in-ADDR.arpA.").toString(), is("193.0.0.0/24")); assertThat(IpInterval.parseReverseDomain("a.b.0.0.1.iP6.arpA.").toString(), is("100b:a000::/20")); } |
IpInterval implements Interval<K> { public static IpInterval<?> parse(final CIString prefix) { return parse(prefix.toString()); } static String removeTrailingDot(final String address); abstract AttributeType getAttributeType(); static IpInterval<?> parse(final CIString prefix); static IpInterval<?> parse(final String prefix); static IpInterval<?> parseReverseDomain(final String reverse); static IpInterval<?> asIpInterval(final InetAddress address); abstract InetAddress beginAsInetAddress(); abstract InetAddress endAsInetAddress(); abstract int getPrefixLength(); } | @Test public void parse() { assertThat(IpInterval.parse("193.0.0/24").toString(), is("193.0.0.0/24")); assertThat(IpInterval.parse("00ab:cd::").toString(), is("ab:cd::/128")); } |
Ipv6Resource extends IpInterval<Ipv6Resource> implements Comparable<Ipv6Resource> { public static Ipv6Resource parse(final InetAddress ipv6Address) { final long[] res = byteArrayToLongArray(ipv6Address.getAddress()); return new Ipv6Resource(res[0], res[1], IPV6_BITCOUNT); } private Ipv6Resource(final long msb, final long lsb, final int prefixLength); Ipv6Resource(final BigInteger begin, final BigInteger end); static long lsb(final BigInteger begin); static long msb(final BigInteger begin); static Ipv6Resource parseFromStrings(final String msb, final String lsb, final int len); static Ipv6Resource parse(final InetAddress ipv6Address); static Ipv6Resource parse(final CIString prefixOrAddress); static Ipv6Resource parse(final String prefixOrAddress); static Ipv6Resource parseReverseDomain(final String address); @Override final AttributeType getAttributeType(); BigInteger begin(); BigInteger end(); static int compare(final long aMsb, final long aLsb, final long bMsb, final long bLsb); @Override int compareTo(final Ipv6Resource that); @Override boolean contains(final Ipv6Resource that); @Override boolean intersects(final Ipv6Resource that); @Override Ipv6Resource singletonIntervalAtLowerBound(); @Override int compareUpperBound(final Ipv6Resource that); @Override InetAddress beginAsInetAddress(); @Override InetAddress endAsInetAddress(); @Override int getPrefixLength(); @Override String toString(); @Override int hashCode(); @Override boolean equals(final Object obj); static Ipv6Resource parseIPv6Resource(final String resource); static final String IPV6_REVERSE_DOMAIN; static final Ipv6Resource MAX_RANGE; } | @Ignore @Test public void ipv4_mapped_ipv6_address() { subject = Ipv6Resource.parse("::ffff:c16e:370c/128"); }
@Test(expected = IllegalArgumentException.class) public void parseIpv6MappedIpv4Fails() { subject = Ipv6Resource.parse("::ffff:192.0.2.128"); }
@Test(expected = IllegalArgumentException.class) public void invalidResource() { Ipv6Resource.parse("invalid resource"); }
@Test(expected = IllegalArgumentException.class) public void invalidResourceType() { Ipv6Resource.parse("12.0.0.1"); }
@Test(expected = IllegalArgumentException.class) public void Ipv6RangeThrowsIllegalArgumentException() { Ipv6Resource.parse("2001:: - 2020::"); }
@Test(expected = IllegalArgumentException.class) public void invalid_prefix_length() { Ipv6Resource.parse("2001::/129"); } |
Ipv6Resource extends IpInterval<Ipv6Resource> implements Comparable<Ipv6Resource> { @Override public Ipv6Resource singletonIntervalAtLowerBound() { return new Ipv6Resource(beginMsb, beginLsb, IPV6_BITCOUNT); } private Ipv6Resource(final long msb, final long lsb, final int prefixLength); Ipv6Resource(final BigInteger begin, final BigInteger end); static long lsb(final BigInteger begin); static long msb(final BigInteger begin); static Ipv6Resource parseFromStrings(final String msb, final String lsb, final int len); static Ipv6Resource parse(final InetAddress ipv6Address); static Ipv6Resource parse(final CIString prefixOrAddress); static Ipv6Resource parse(final String prefixOrAddress); static Ipv6Resource parseReverseDomain(final String address); @Override final AttributeType getAttributeType(); BigInteger begin(); BigInteger end(); static int compare(final long aMsb, final long aLsb, final long bMsb, final long bLsb); @Override int compareTo(final Ipv6Resource that); @Override boolean contains(final Ipv6Resource that); @Override boolean intersects(final Ipv6Resource that); @Override Ipv6Resource singletonIntervalAtLowerBound(); @Override int compareUpperBound(final Ipv6Resource that); @Override InetAddress beginAsInetAddress(); @Override InetAddress endAsInetAddress(); @Override int getPrefixLength(); @Override String toString(); @Override int hashCode(); @Override boolean equals(final Object obj); static Ipv6Resource parseIPv6Resource(final String resource); static final String IPV6_REVERSE_DOMAIN; static final Ipv6Resource MAX_RANGE; } | @Test public void singletonIntervalAtLowerBound() { assertEquals(Ipv6Resource.parse("2001::/128"), Ipv6Resource.parse("2001::/77").singletonIntervalAtLowerBound()); } |
Ipv6Resource extends IpInterval<Ipv6Resource> implements Comparable<Ipv6Resource> { @Override public int compareTo(final Ipv6Resource that) { int comp = compare(beginMsb, beginLsb, that.beginMsb, that.beginLsb); if (comp == 0) { comp = compare(that.endMsb, that.endLsb, endMsb, endLsb); } return comp; } private Ipv6Resource(final long msb, final long lsb, final int prefixLength); Ipv6Resource(final BigInteger begin, final BigInteger end); static long lsb(final BigInteger begin); static long msb(final BigInteger begin); static Ipv6Resource parseFromStrings(final String msb, final String lsb, final int len); static Ipv6Resource parse(final InetAddress ipv6Address); static Ipv6Resource parse(final CIString prefixOrAddress); static Ipv6Resource parse(final String prefixOrAddress); static Ipv6Resource parseReverseDomain(final String address); @Override final AttributeType getAttributeType(); BigInteger begin(); BigInteger end(); static int compare(final long aMsb, final long aLsb, final long bMsb, final long bLsb); @Override int compareTo(final Ipv6Resource that); @Override boolean contains(final Ipv6Resource that); @Override boolean intersects(final Ipv6Resource that); @Override Ipv6Resource singletonIntervalAtLowerBound(); @Override int compareUpperBound(final Ipv6Resource that); @Override InetAddress beginAsInetAddress(); @Override InetAddress endAsInetAddress(); @Override int getPrefixLength(); @Override String toString(); @Override int hashCode(); @Override boolean equals(final Object obj); static Ipv6Resource parseIPv6Resource(final String resource); static final String IPV6_REVERSE_DOMAIN; static final Ipv6Resource MAX_RANGE; } | @Test public void compareWorks() { subject = resource(10, 20); assertThat(0, is(subject.compareTo(subject))); assertThat(1, is(subject.compareTo(resource(0, 9)))); assertThat(-1, is(subject.compareTo(resource(21, 30)))); assertThat(1, is(subject.compareTo(resource(0, 15)))); assertThat(-1, is(subject.compareTo(resource(15, 30)))); assertThat(1, is(subject.compareTo(resource(0, 20)))); assertThat(1, is(subject.compareTo(resource(10, 30)))); assertThat(-1, is(subject.compareTo(resource(11, 30)))); assertThat(-1, is(subject.compareTo(resource(10, 19)))); assertThat(-1, is(subject.compareTo(resource(11, 20)))); } |
GrsSource implements InitializingBean { void handleLines(final BufferedReader reader, final LineHandler lineHandler) throws IOException { List<String> lines = Lists.newArrayList(); StringBuilder lineBuilder = new StringBuilder(); for (String line = reader.readLine(); line != null; line = reader.readLine()) { if (line.length() == 0) { lineBuilder = addLine(lines, lineBuilder); handleLines(lineHandler, lines); lines = Lists.newArrayList(); continue; } final char firstChar = line.charAt(0); if (firstChar == '#' || firstChar == '%') { continue; } if (firstChar != ' ' && firstChar != '+') { lineBuilder = addLine(lines, lineBuilder); } lineBuilder.append(line).append('\n'); } addLine(lines, lineBuilder); handleLines(lineHandler, lines); } GrsSource(final String name, final SourceContext sourceContext, final DateTimeProvider dateTimeProvider, final AuthoritativeResourceData authoritativeResourceData, final Downloader downloader); @Override void afterPropertiesSet(); Logger getLogger(); @Override String toString(); } | @Test public void handleLines_empty() throws IOException { final BufferedReader reader = new BufferedReader(new StringReader("")); final GrsSource.LineHandler lineHandler = mock(GrsSource.LineHandler.class); subject.handleLines(reader, lineHandler); verifyZeroInteractions(lineHandler); }
@Test public void handleLines_throws_exception() throws IOException { final BufferedReader reader = new BufferedReader(new StringReader("line1\n\nline2")); final GrsSource.LineHandler lineHandler = mock(GrsSource.LineHandler.class); doThrow(NullPointerException.class).when(lineHandler).handleLines(anyListOf(String.class)); subject.handleLines(reader, lineHandler); verify(lineHandler).handleLines(Lists.newArrayList("line1\n")); verify(lineHandler).handleLines(Lists.newArrayList("line2\n")); }
@Test public void handleLines_start_of_line_comment() throws IOException { final BufferedReader reader = new BufferedReader(new StringReader("line1\n#line2\nline3\n%line4\nline5")); final GrsSource.LineHandler lineHandler = mock(GrsSource.LineHandler.class); subject.handleLines(reader, lineHandler); verify(lineHandler).handleLines(Lists.newArrayList("line1\n", "line3\n", "line5\n")); verifyNoMoreInteractions(lineHandler); }
@Test public void handleLines_multiple_newlines() throws IOException { final BufferedReader reader = new BufferedReader(new StringReader("line1\n\n\n\n\n\nline2\n\n\n\n\n")); final GrsSource.LineHandler lineHandler = mock(GrsSource.LineHandler.class); subject.handleLines(reader, lineHandler); verify(lineHandler).handleLines(Lists.newArrayList("line1\n")); verify(lineHandler).handleLines(Lists.newArrayList("line2\n")); verifyNoMoreInteractions(lineHandler); }
@Test public void handleLines_rpsl_object() throws IOException { final BufferedReader reader = new BufferedReader(new StringReader("" + "person: John Smith\n" + "address: Example LTD\n" + " High street 12\n" + " St.Mery Mead\n" + " Essex, UK\n" + "phone: +44 1737 892 004\n" + "e-mail: [email protected]\n" + "nic-hdl: JS1-TEST\n" + "remarks: *******************************\n" + "remarks: This object is only an example!\n" + "remarks: *******************************\n" + "mnt-by: EXAMPLE-MNT\n" + "abuse-mailbox: [email protected]\n" + "changed: [email protected] 20051104\n" + "changed: [email protected] 20051105\n" + "source: TEST\n" + "\n" + "mntner: TEST-ROOT-MNT\n")); final List<List<String>> handledLines = Lists.newArrayList(); subject.handleLines(reader, new GrsSource.LineHandler() { @Override public void handleLines(final List<String> lines) { handledLines.add(lines); } }); assertThat(handledLines, hasSize(2)); assertThat(handledLines.get(0), is((List<String>) Lists.newArrayList( "person: John Smith\n", "" + "address: Example LTD\n" + " High street 12\n" + " St.Mery Mead\n" + " Essex, UK\n", "phone: +44 1737 892 004\n", "e-mail: [email protected]\n", "nic-hdl: JS1-TEST\n", "remarks: *******************************\n", "remarks: This object is only an example!\n", "remarks: *******************************\n", "mnt-by: EXAMPLE-MNT\n", "abuse-mailbox: [email protected]\n", "changed: [email protected] 20051104\n", "changed: [email protected] 20051105\n", "source: TEST\n"))); assertThat(handledLines.get(1), is((List<String>) Lists.newArrayList( "mntner: TEST-ROOT-MNT\n"))); } |
Ipv6Resource extends IpInterval<Ipv6Resource> implements Comparable<Ipv6Resource> { @Override public boolean intersects(final Ipv6Resource that) { return (compare(beginMsb, beginLsb, that.beginMsb, that.beginLsb) >= 0 && compare(beginMsb, beginLsb, that.endMsb, that.endLsb) <= 0) || (compare(endMsb, endLsb, that.beginMsb, that.beginLsb) >= 0 && compare(endMsb, endLsb, that.endMsb, that.endLsb) <= 0) || contains(that); } private Ipv6Resource(final long msb, final long lsb, final int prefixLength); Ipv6Resource(final BigInteger begin, final BigInteger end); static long lsb(final BigInteger begin); static long msb(final BigInteger begin); static Ipv6Resource parseFromStrings(final String msb, final String lsb, final int len); static Ipv6Resource parse(final InetAddress ipv6Address); static Ipv6Resource parse(final CIString prefixOrAddress); static Ipv6Resource parse(final String prefixOrAddress); static Ipv6Resource parseReverseDomain(final String address); @Override final AttributeType getAttributeType(); BigInteger begin(); BigInteger end(); static int compare(final long aMsb, final long aLsb, final long bMsb, final long bLsb); @Override int compareTo(final Ipv6Resource that); @Override boolean contains(final Ipv6Resource that); @Override boolean intersects(final Ipv6Resource that); @Override Ipv6Resource singletonIntervalAtLowerBound(); @Override int compareUpperBound(final Ipv6Resource that); @Override InetAddress beginAsInetAddress(); @Override InetAddress endAsInetAddress(); @Override int getPrefixLength(); @Override String toString(); @Override int hashCode(); @Override boolean equals(final Object obj); static Ipv6Resource parseIPv6Resource(final String resource); static final String IPV6_REVERSE_DOMAIN; static final Ipv6Resource MAX_RANGE; } | @Test public void verifyIntersects() { subject = resource(10, 20); assertTrue(subject.intersects(subject)); assertTrue(subject.intersects(Ipv6Resource.MAX_RANGE)); assertFalse(subject.intersects(resource(9, 9))); assertTrue(subject.intersects(resource(9, 10))); assertTrue(subject.intersects(resource(9, 15))); assertTrue(subject.intersects(resource(9, 20))); assertTrue(subject.intersects(resource(9, 21))); assertTrue(subject.intersects(resource(10, 10))); assertTrue(subject.intersects(resource(10, 15))); assertTrue(subject.intersects(resource(10, 20))); assertTrue(subject.intersects(resource(10, 21))); assertTrue(subject.intersects(resource(15, 15))); assertTrue(subject.intersects(resource(15, 20))); assertTrue(subject.intersects(resource(15, 21))); assertTrue(subject.intersects(resource(20, 20))); assertTrue(subject.intersects(resource(20, 21))); assertFalse(subject.intersects(resource(21, 21))); } |
Ipv6Resource extends IpInterval<Ipv6Resource> implements Comparable<Ipv6Resource> { public static int compare(final long aMsb, final long aLsb, final long bMsb, final long bLsb) { if (aMsb == bMsb) { if (aLsb == bLsb) { return 0; } if ((aLsb < bLsb) ^ (aLsb < 0) ^ (bLsb < 0)) { return -1; } } else if ((aMsb < bMsb) ^ (aMsb < 0) ^ (bMsb < 0)) { return -1; } return 1; } private Ipv6Resource(final long msb, final long lsb, final int prefixLength); Ipv6Resource(final BigInteger begin, final BigInteger end); static long lsb(final BigInteger begin); static long msb(final BigInteger begin); static Ipv6Resource parseFromStrings(final String msb, final String lsb, final int len); static Ipv6Resource parse(final InetAddress ipv6Address); static Ipv6Resource parse(final CIString prefixOrAddress); static Ipv6Resource parse(final String prefixOrAddress); static Ipv6Resource parseReverseDomain(final String address); @Override final AttributeType getAttributeType(); BigInteger begin(); BigInteger end(); static int compare(final long aMsb, final long aLsb, final long bMsb, final long bLsb); @Override int compareTo(final Ipv6Resource that); @Override boolean contains(final Ipv6Resource that); @Override boolean intersects(final Ipv6Resource that); @Override Ipv6Resource singletonIntervalAtLowerBound(); @Override int compareUpperBound(final Ipv6Resource that); @Override InetAddress beginAsInetAddress(); @Override InetAddress endAsInetAddress(); @Override int getPrefixLength(); @Override String toString(); @Override int hashCode(); @Override boolean equals(final Object obj); static Ipv6Resource parseIPv6Resource(final String resource); static final String IPV6_REVERSE_DOMAIN; static final Ipv6Resource MAX_RANGE; } | @Test public void doubleLongUnsignedComparison() { assertThat(compare( 0, 0, 0, 0), is(0)); assertThat(compare( 0, 0, 0, -1), is(-1)); assertThat(compare( 0, 0, 0, 1), is(-1)); assertThat(compare( 0, 0, -1, 0), is(-1)); assertThat(compare( 0, 0, -1, -1), is(-1)); assertThat(compare( 0, 0, -1, 1), is(-1)); assertThat(compare( 0, 0, 1, 0), is(-1)); assertThat(compare( 0, 0, 1, -1), is(-1)); assertThat(compare( 0, 0, 1, 1), is(-1)); assertThat(compare( 0, -1, 0, 0), is(1)); assertThat(compare( 0, -1, 0, -1), is(0)); assertThat(compare( 0, -1, 0, 1), is(1)); assertThat(compare( 0, -1, -1, 0), is(-1)); assertThat(compare( 0, -1, -1, -1), is(-1)); assertThat(compare( 0, -1, -1, 1), is(-1)); assertThat(compare( 0, -1, 1, 0), is(-1)); assertThat(compare( 0, -1, 1, -1), is(-1)); assertThat(compare( 0, -1, 1, 1), is(-1)); assertThat(compare( 0, 1, 0, 0), is(1)); assertThat(compare( 0, 1, 0, -1), is(-1)); assertThat(compare( 0, 1, 0, 1), is(0)); assertThat(compare( 0, 1, -1, 0), is(-1)); assertThat(compare( 0, 1, -1, -1), is(-1)); assertThat(compare( 0, 1, -1, 1), is(-1)); assertThat(compare( 0, 1, 1, 0), is(-1)); assertThat(compare( 0, 1, 1, -1), is(-1)); assertThat(compare( 0, 1, 1, 1), is(-1)); assertThat(compare(-1, 0, 0, 0), is(1)); assertThat(compare(-1, 0, 0, -1), is(1)); assertThat(compare(-1, 0, 0, 1), is(1)); assertThat(compare(-1, 0, -1, 0), is(0)); assertThat(compare(-1, 0, -1, -1), is(-1)); assertThat(compare(-1, 0, -1, 1), is(-1)); assertThat(compare(-1, 0, 1, 0), is(1)); assertThat(compare(-1, 0, 1, -1), is(1)); assertThat(compare(-1, 0, 1, 1), is(1)); assertThat(compare(-1, -1, 0, 0), is(1)); assertThat(compare(-1, -1, 0, -1), is(1)); assertThat(compare(-1, -1, 0, 1), is(1)); assertThat(compare(-1, -1, -1, 0), is(1)); assertThat(compare(-1, -1, -1, -1), is(0)); assertThat(compare(-1, -1, -1, 1), is(1)); assertThat(compare(-1, -1, 1, 0), is(1)); assertThat(compare(-1, -1, 1, -1), is(1)); assertThat(compare(-1, -1, 1, 1), is(1)); assertThat(compare(-1, 1, 0, 0), is(1)); assertThat(compare(-1, 1, 0, -1), is(1)); assertThat(compare(-1, 1, 0, 1), is(1)); assertThat(compare(-1, 1, -1, 0), is(1)); assertThat(compare(-1, 1, -1, -1), is(-1)); assertThat(compare(-1, 1, -1, 1), is(0)); assertThat(compare(-1, 1, 1, 0), is(1)); assertThat(compare(-1, 1, 1, -1), is(1)); assertThat(compare(-1, 1, 1, 1), is(1)); assertThat(compare( 1, 0, 0, 0), is(1)); assertThat(compare( 1, 0, 0, -1), is(1)); assertThat(compare( 1, 0, 0, 1), is(1)); assertThat(compare( 1, 0, -1, 0), is(-1)); assertThat(compare( 1, 0, -1, -1), is(-1)); assertThat(compare( 1, 0, -1, 1), is(-1)); assertThat(compare( 1, 0, 1, 0), is(0)); assertThat(compare( 1, 0, 1, -1), is(-1)); assertThat(compare( 1, 0, 1, 1), is(-1)); assertThat(compare( 1, -1, 0, 0), is(1)); assertThat(compare( 1, -1, 0, -1), is(1)); assertThat(compare( 1, -1, 0, 1), is(1)); assertThat(compare( 1, -1, -1, 0), is(-1)); assertThat(compare( 1, -1, -1, -1), is(-1)); assertThat(compare( 1, -1, -1, 1), is(-1)); assertThat(compare( 1, -1, 1, 0), is(1)); assertThat(compare( 1, -1, 1, -1), is(0)); assertThat(compare( 1, -1, 1, 1), is(1)); assertThat(compare( 1, 1, 0, 0), is(1)); assertThat(compare( 1, 1, 0, -1), is(1)); assertThat(compare( 1, 1, 0, 1), is(1)); assertThat(compare( 1, 1, -1, 0), is(-1)); assertThat(compare( 1, 1, -1, -1), is(-1)); assertThat(compare( 1, 1, -1, 1), is(-1)); assertThat(compare( 1, 1, 1, 0), is(1)); assertThat(compare( 1, 1, 1, -1), is(-1)); assertThat(compare( 1, 1, 1, 1), is(0)); } |
Ipv6Resource extends IpInterval<Ipv6Resource> implements Comparable<Ipv6Resource> { public static Ipv6Resource parseReverseDomain(final String address) { Validate.notEmpty(address, "Address cannot be empty"); String cleanAddress = removeTrailingDot(address.trim()).toLowerCase(); Validate.isTrue(cleanAddress.endsWith(IPV6_REVERSE_DOMAIN), "Invalid reverse domain: ", address); cleanAddress = cleanAddress.substring(0, cleanAddress.length() - IPV6_REVERSE_DOMAIN.length()); Validate.isTrue(REVERSE_PATTERN.matcher(cleanAddress).matches(), "Invalid reverse domain: ", address); final StringBuilder builder = new StringBuilder(); int netmask = 0; for (int index = cleanAddress.length() - 1; index >= 0; index -= 2) { builder.append(cleanAddress.charAt(index)); netmask += 4; if (netmask % 16 == 0 && index > 0) { builder.append(':'); } } if (netmask % 16 != 0) { for (int i = 4 - ((netmask / 4) % 4); i > 0; i--) { builder.append('0'); } } if (netmask <= 112) { builder.append("::"); } builder.append('/'); builder.append(netmask); return parse(builder.toString()); } private Ipv6Resource(final long msb, final long lsb, final int prefixLength); Ipv6Resource(final BigInteger begin, final BigInteger end); static long lsb(final BigInteger begin); static long msb(final BigInteger begin); static Ipv6Resource parseFromStrings(final String msb, final String lsb, final int len); static Ipv6Resource parse(final InetAddress ipv6Address); static Ipv6Resource parse(final CIString prefixOrAddress); static Ipv6Resource parse(final String prefixOrAddress); static Ipv6Resource parseReverseDomain(final String address); @Override final AttributeType getAttributeType(); BigInteger begin(); BigInteger end(); static int compare(final long aMsb, final long aLsb, final long bMsb, final long bLsb); @Override int compareTo(final Ipv6Resource that); @Override boolean contains(final Ipv6Resource that); @Override boolean intersects(final Ipv6Resource that); @Override Ipv6Resource singletonIntervalAtLowerBound(); @Override int compareUpperBound(final Ipv6Resource that); @Override InetAddress beginAsInetAddress(); @Override InetAddress endAsInetAddress(); @Override int getPrefixLength(); @Override String toString(); @Override int hashCode(); @Override boolean equals(final Object obj); static Ipv6Resource parseIPv6Resource(final String resource); static final String IPV6_REVERSE_DOMAIN; static final Ipv6Resource MAX_RANGE; } | @Test(expected = IllegalArgumentException.class) public void reverse_empty() { Ipv6Resource.parseReverseDomain(""); }
@Test(expected = IllegalArgumentException.class) public void reverse_null() { Ipv6Resource.parseReverseDomain(null); }
@Test(expected = IllegalArgumentException.class) public void reverse_no_ip6arpa() { Ipv6Resource.parseReverseDomain("1.2.3.4"); }
@Test(expected = IllegalArgumentException.class) public void reverse_no_octets() { Ipv6Resource.parseReverseDomain(".ip6.arpa"); }
@Test(expected = IllegalArgumentException.class) public void reverse_more_than_four_octets() { Ipv6Resource.parseReverseDomain("8.7.6.5.4.3.2.1.in-addr.arpa"); }
@Test(expected = IllegalArgumentException.class) public void reverse_invalid_nibbles_dash() { Ipv6Resource.parseReverseDomain("1-1.1.a.ip6.arpa"); }
@Test(expected = IllegalArgumentException.class) public void reverse_invalid_nibbles_non_hex() { Ipv6Resource.parseReverseDomain("g.ip6.arpa"); } |
PunycodeConversion { public static String convert(final String value) { final Matcher matcher = EMAIL_ADDRESS_PATTERN.matcher(value); while (matcher.find()) { final String key = matcher.group(1); final String space = matcher.group(2); final String address = matcher.group(3); final String newline = matcher.group(4); final String convertedAddress = toAscii(address); if (!convertedAddress.equals(address)) { final String originalMatch = matcher.group(0); final String convertedMatch = String.format("%s:%s%s%s", key, space, convertedAddress, newline); return convert(value.replace(originalMatch, convertedMatch)); } } return value; } private PunycodeConversion(); static String convert(final String value); } | @Test public void convert_email() { final String value = "role: Test Role\n" + "nic-hdl: TR1-TEST\n" + "e-mail: no-reply@zürich.example\n" + "source: TEST\n"; final String result = PunycodeConversion.convert(value); assertThat(result, is( "role: Test Role\n" + "nic-hdl: TR1-TEST\n" + "e-mail: [email protected]\n" + "source: TEST\n")); }
@Test public void convert_email_local_part_only() { final String value = "role: Test Role\n" + "nic-hdl: TR1-TEST\n" + "e-mail: no-reply\n" + "source: TEST\n"; final String result = PunycodeConversion.convert(value); assertThat(result, is( "role: Test Role\n" + "nic-hdl: TR1-TEST\n" + "e-mail: no-reply\n" + "source: TEST\n")); }
@Test public void convert_email_double_at_address() { final String value = "role: Test Role\n" + "nic-hdl: TR1-TEST\n" + "e-mail: no-reply@@zürich.example\n" + "source: TEST\n"; final String result = PunycodeConversion.convert(value); assertThat(result, is( "role: Test Role\n" + "nic-hdl: TR1-TEST\n" + "e-mail: no-reply@[email protected]\n" + "source: TEST\n")); }
@Test public void convert_email_dots() { final String value = "role: Test Role\n" + "nic-hdl: TR1-TEST\n" + "e-mail: [email protected]ürich..example...\n" + "source: TEST\n"; final String result = PunycodeConversion.convert(value); assertThat(result, is( "role: Test Role\n" + "nic-hdl: TR1-TEST\n" + "e-mail: [email protected]ürich..example...\n" + "source: TEST\n")); }
@Test public void convert_email_name_and_address() { final String value = "role: Test Role\n" + "nic-hdl: TR1-TEST\n" + "e-mail: Example Usër <example@zürich.example>\n" + "source: TEST\n"; final String result = PunycodeConversion.convert(value); assertThat(result, is( "role: Test Role\n" + "nic-hdl: TR1-TEST\n" + "e-mail: Example Usër <[email protected]>\n" + "source: TEST\n")); }
@Test public void convert_email_domain_only_not_local_part() { final String value = "role: Test Role\n" + "nic-hdl: TR1-TEST\n" + "e-mail: no-rëply@zürich.example\n" + "source: TEST\n"; final String result = PunycodeConversion.convert(value); assertThat(result, is( "role: Test Role\n" + "nic-hdl: TR1-TEST\n" + "e-mail: no-rë[email protected]\n" + "source: TEST\n")); }
@Test public void convert_email_cyrillic() { final String value = "role: Test Role\n" + "nic-hdl: TR1-TEST\n" + "e-mail: no-reply@москва.ru\n" + "source: TEST\n"; final String result = PunycodeConversion.convert(value); assertThat(result, is( "role: Test Role\n" + "nic-hdl: TR1-TEST\n" + "e-mail: [email protected]\n" + "source: TEST\n")); }
@Test public void convert_email_with_tabs() { final String value = "role: Test Role\n" + "nic-hdl: TR1-TEST\n" + "e-mail:\t\tno-reply@zürich.example\n" + "source: TEST\n"; final String result = PunycodeConversion.convert(value); assertThat(result, is( "role: Test Role\n" + "nic-hdl: TR1-TEST\n" + "e-mail:\t\[email protected]\n" + "source: TEST\n")); }
@Test public void convert_email_with_tabs_and_spaces() { final String value = "role: Test Role\n" + "nic-hdl: TR1-TEST\n" + "e-mail:\t \t no-reply@zürich.example\n" + "source: TEST\n"; final String result = PunycodeConversion.convert(value); assertThat(result, is( "role: Test Role\n" + "nic-hdl: TR1-TEST\n" + "e-mail:\t \t [email protected]\n" + "source: TEST\n")); }
@Test public void convert_multiple_email() { final String value = "role: Test Role\n" + "nic-hdl: AR1-TEST\n" + "e-mail: user@zürich.example\n" + "e-mail: no-reply@zürich.example\n" + "source: TEST\n"; final String result = PunycodeConversion.convert(value); assertThat(result, is( "role: Test Role\n" + "nic-hdl: AR1-TEST\n" + "e-mail: [email protected]\n" + "e-mail: [email protected]\n" + "source: TEST\n")); }
@Test public void convert_multiple_trailing_email() { final String value = "role: Test Role\n" + "nic-hdl: AR1-TEST\n" + "source: TEST\n" + "e-mail: user@zürich.example\n" + "e-mail: no-reply@zürich.example"; final String result = PunycodeConversion.convert(value); assertThat(result, is( "role: Test Role\n" + "nic-hdl: AR1-TEST\n" + "source: TEST\n" + "e-mail: [email protected]\n" + "e-mail: [email protected]")); }
@Test public void convert_multiple_email_with_separator_remark() { final String value = "role: Test Role\n" + "nic-hdl: AR1-TEST\n" + "e-mail: user@zürich.example\n" + "remarks: separator\n" + "e-mail: no-reply@zürich.example\n" + "source: TEST\n"; final String result = PunycodeConversion.convert(value); assertThat(result, is( "role: Test Role\n" + "nic-hdl: AR1-TEST\n" + "e-mail: [email protected]\n" + "remarks: separator\n" + "e-mail: [email protected]\n" + "source: TEST\n")); }
@Test public void convert_abuse_mailbox() { final String value = "role: Abuse Role\n" + "nic-hdl: AR1-TEST\n" + "abuse-mailbox: abuse@zürich.example\n" + "source: TEST\n"; final String result = PunycodeConversion.convert(value); assertThat(result, is( "role: Abuse Role\n" + "nic-hdl: AR1-TEST\n" + "abuse-mailbox: [email protected]\n" + "source: TEST\n")); }
@Test public void convert_irt_nfy() { final String value = "irt: IRT-EXAMPLE\n" + "irt-nfy: irt@zürich.example\n" + "source: TEST\n"; final String result = PunycodeConversion.convert(value); assertThat(result, is( "irt: IRT-EXAMPLE\n" + "irt-nfy: [email protected]\n" + "source: TEST\n")); }
@Test public void convert_mnt_nfy() { final String value = "mntner: EXAMPLE-MNT\n" + "mnt-nfy: notify@zürich.example\n" + "source: TEST\n"; final String result = PunycodeConversion.convert(value); assertThat(result, is( "mntner: EXAMPLE-MNT\n" + "mnt-nfy: [email protected]\n" + "source: TEST\n")); }
@Test public void convert_notify() { final String value = "mntner: EXAMPLE-MNT\n" + "notify: notify@zürich.example\n" + "source: TEST\n"; final String result = PunycodeConversion.convert(value); assertThat(result, is( "mntner: EXAMPLE-MNT\n" + "notify: [email protected]\n" + "source: TEST\n")); }
@Test public void convert_ref_nfy() { final String value = "organisation: ORG-EX1-TEST\n" + "ref-nfy: notify@zürich.example\n" + "source: TEST\n"; final String result = PunycodeConversion.convert(value); assertThat(result, is( "organisation: ORG-EX1-TEST\n" + "ref-nfy: [email protected]\n" + "source: TEST\n")); }
@Test public void convert_upd_to() { final String value = "mntner: EXAMPLE-MNT\n" + "upd-to: notify@zürich.example\n" + "source: TEST\n"; final String result = PunycodeConversion.convert(value); assertThat(result, is( "mntner: EXAMPLE-MNT\n" + "upd-to: [email protected]\n" + "source: TEST\n")); } |
CIString implements Comparable<CIString>, CharSequence { @Nullable public static CIString ciString(final String value) { if (value == null) { return null; } return new CIString(value); } private CIString(final String value); @Nullable static CIString ciString(final String value); static Set<CIString> ciSet(final String... values); static Set<CIString> ciImmutableSet(final String... values); static Set<CIString> ciSet(final Iterable<String> values); static Set<CIString> ciImmutableSet(final Iterable<String> values); static boolean isBlank(final CIString ciString); @Override boolean equals(@Nullable final Object o); @Override int hashCode(); @Override int compareTo(@Nonnull final CIString o); @Override @Nonnull String toString(); String toLowerCase(); String toUpperCase(); int toInt(); @Override int length(); @Override char charAt(final int index); @Override CharSequence subSequence(final int start, final int end); boolean startsWith(final CIString value); boolean startsWith(final String value); boolean contains(final CIString value); boolean contains(final String value); boolean endsWith(final CIString value); boolean endsWith(final String value); CIString append(final CIString other); } | @Test public void create_null() { assertNull(ciString(null)); } |
CIString implements Comparable<CIString>, CharSequence { @Override public boolean equals(@Nullable final Object o) { if (this == o) { return true; } if (o == null) { return false; } if (o instanceof String) { return value.equalsIgnoreCase((String) o); } return getClass() == o.getClass() && lcValue.equals(((CIString) o).lcValue); } private CIString(final String value); @Nullable static CIString ciString(final String value); static Set<CIString> ciSet(final String... values); static Set<CIString> ciImmutableSet(final String... values); static Set<CIString> ciSet(final Iterable<String> values); static Set<CIString> ciImmutableSet(final Iterable<String> values); static boolean isBlank(final CIString ciString); @Override boolean equals(@Nullable final Object o); @Override int hashCode(); @Override int compareTo(@Nonnull final CIString o); @Override @Nonnull String toString(); String toLowerCase(); String toUpperCase(); int toInt(); @Override int length(); @Override char charAt(final int index); @Override CharSequence subSequence(final int start, final int end); boolean startsWith(final CIString value); boolean startsWith(final String value); boolean contains(final CIString value); boolean contains(final String value); boolean endsWith(final CIString value); boolean endsWith(final String value); CIString append(final CIString other); } | @Test public void equals() { assertThat(ciString("ABC"), is(ciString("ABC"))); assertThat(ciString("ABC"), is(ciString("abc"))); assertThat(ciString("ABC"), is(ciString("aBc"))); final CIString ripe = CIString.ciString("RIPE"); assertFalse(ripe.equals(null)); assertTrue(ripe.equals(ripe)); assertTrue(ripe.equals(CIString.ciString("RIPE"))); assertTrue(ripe.equals("ripe")); assertTrue(ripe.equals("RIPE")); } |
CIString implements Comparable<CIString>, CharSequence { public static Set<CIString> ciSet(final String... values) { final Set<CIString> result = Sets.newLinkedHashSetWithExpectedSize(values.length); for (final String value : values) { result.add(ciString(value)); } return result; } private CIString(final String value); @Nullable static CIString ciString(final String value); static Set<CIString> ciSet(final String... values); static Set<CIString> ciImmutableSet(final String... values); static Set<CIString> ciSet(final Iterable<String> values); static Set<CIString> ciImmutableSet(final Iterable<String> values); static boolean isBlank(final CIString ciString); @Override boolean equals(@Nullable final Object o); @Override int hashCode(); @Override int compareTo(@Nonnull final CIString o); @Override @Nonnull String toString(); String toLowerCase(); String toUpperCase(); int toInt(); @Override int length(); @Override char charAt(final int index); @Override CharSequence subSequence(final int start, final int end); boolean startsWith(final CIString value); boolean startsWith(final String value); boolean contains(final CIString value); boolean contains(final String value); boolean endsWith(final CIString value); boolean endsWith(final String value); CIString append(final CIString other); } | @Test public void ciset() { assertThat(ciSet("a", "b"), is(ciSet("A", "b"))); assertThat(ciSet("a", "b").contains(ciString("A")), is(true)); assertThat(ciSet("a", "b").contains(ciString("c")), is(false)); } |
CIString implements Comparable<CIString>, CharSequence { @Override @Nonnull public String toString() { return value; } private CIString(final String value); @Nullable static CIString ciString(final String value); static Set<CIString> ciSet(final String... values); static Set<CIString> ciImmutableSet(final String... values); static Set<CIString> ciSet(final Iterable<String> values); static Set<CIString> ciImmutableSet(final Iterable<String> values); static boolean isBlank(final CIString ciString); @Override boolean equals(@Nullable final Object o); @Override int hashCode(); @Override int compareTo(@Nonnull final CIString o); @Override @Nonnull String toString(); String toLowerCase(); String toUpperCase(); int toInt(); @Override int length(); @Override char charAt(final int index); @Override CharSequence subSequence(final int start, final int end); boolean startsWith(final CIString value); boolean startsWith(final String value); boolean contains(final CIString value); boolean contains(final String value); boolean endsWith(final CIString value); boolean endsWith(final String value); CIString append(final CIString other); } | @Test public void tostring() { assertThat(ciString("SoMe WeIrd CasIng").toString(), is("SoMe WeIrd CasIng")); } |
CIString implements Comparable<CIString>, CharSequence { @Override public CharSequence subSequence(final int start, final int end) { return value.subSequence(start, end); } private CIString(final String value); @Nullable static CIString ciString(final String value); static Set<CIString> ciSet(final String... values); static Set<CIString> ciImmutableSet(final String... values); static Set<CIString> ciSet(final Iterable<String> values); static Set<CIString> ciImmutableSet(final Iterable<String> values); static boolean isBlank(final CIString ciString); @Override boolean equals(@Nullable final Object o); @Override int hashCode(); @Override int compareTo(@Nonnull final CIString o); @Override @Nonnull String toString(); String toLowerCase(); String toUpperCase(); int toInt(); @Override int length(); @Override char charAt(final int index); @Override CharSequence subSequence(final int start, final int end); boolean startsWith(final CIString value); boolean startsWith(final String value); boolean contains(final CIString value); boolean contains(final String value); boolean endsWith(final CIString value); boolean endsWith(final String value); CIString append(final CIString other); } | @Test public void subsequence() { assertThat(ciString("abcdef").subSequence(1, 3), is((CharSequence) "bc")); assertThat(ciString("ABCDEF").subSequence(1, 3), is((CharSequence) "BC")); } |
CIString implements Comparable<CIString>, CharSequence { @Override public char charAt(final int index) { return value.charAt(index); } private CIString(final String value); @Nullable static CIString ciString(final String value); static Set<CIString> ciSet(final String... values); static Set<CIString> ciImmutableSet(final String... values); static Set<CIString> ciSet(final Iterable<String> values); static Set<CIString> ciImmutableSet(final Iterable<String> values); static boolean isBlank(final CIString ciString); @Override boolean equals(@Nullable final Object o); @Override int hashCode(); @Override int compareTo(@Nonnull final CIString o); @Override @Nonnull String toString(); String toLowerCase(); String toUpperCase(); int toInt(); @Override int length(); @Override char charAt(final int index); @Override CharSequence subSequence(final int start, final int end); boolean startsWith(final CIString value); boolean startsWith(final String value); boolean contains(final CIString value); boolean contains(final String value); boolean endsWith(final CIString value); boolean endsWith(final String value); CIString append(final CIString other); } | @Test public void charAt() { assertThat(ciString("abcdef").charAt(1), is('b')); assertThat(ciString("ABCDEF").charAt(1), is('B')); } |
CIString implements Comparable<CIString>, CharSequence { @Override public int length() { return value.length(); } private CIString(final String value); @Nullable static CIString ciString(final String value); static Set<CIString> ciSet(final String... values); static Set<CIString> ciImmutableSet(final String... values); static Set<CIString> ciSet(final Iterable<String> values); static Set<CIString> ciImmutableSet(final Iterable<String> values); static boolean isBlank(final CIString ciString); @Override boolean equals(@Nullable final Object o); @Override int hashCode(); @Override int compareTo(@Nonnull final CIString o); @Override @Nonnull String toString(); String toLowerCase(); String toUpperCase(); int toInt(); @Override int length(); @Override char charAt(final int index); @Override CharSequence subSequence(final int start, final int end); boolean startsWith(final CIString value); boolean startsWith(final String value); boolean contains(final CIString value); boolean contains(final String value); boolean endsWith(final CIString value); boolean endsWith(final String value); CIString append(final CIString other); } | @Test public void length() { assertThat(ciString("").length(), is(0)); assertThat(ciString("abcdef").length(), is(6)); } |
CIString implements Comparable<CIString>, CharSequence { public boolean startsWith(final CIString value) { return lcValue.startsWith(value.lcValue); } private CIString(final String value); @Nullable static CIString ciString(final String value); static Set<CIString> ciSet(final String... values); static Set<CIString> ciImmutableSet(final String... values); static Set<CIString> ciSet(final Iterable<String> values); static Set<CIString> ciImmutableSet(final Iterable<String> values); static boolean isBlank(final CIString ciString); @Override boolean equals(@Nullable final Object o); @Override int hashCode(); @Override int compareTo(@Nonnull final CIString o); @Override @Nonnull String toString(); String toLowerCase(); String toUpperCase(); int toInt(); @Override int length(); @Override char charAt(final int index); @Override CharSequence subSequence(final int start, final int end); boolean startsWith(final CIString value); boolean startsWith(final String value); boolean contains(final CIString value); boolean contains(final String value); boolean endsWith(final CIString value); boolean endsWith(final String value); CIString append(final CIString other); } | @Test public void startsWith() { assertThat(ciString("").startsWith(ciString("")), is(true)); assertThat(ciString("ab").startsWith(ciString("AB")), is(true)); assertThat(ciString("ab").startsWith(ciString("ab")), is(true)); assertThat(ciString("abcdef").startsWith(ciString("AB")), is(true)); assertThat(ciString("ABCDEF").startsWith(ciString("aB")), is(true)); assertThat(ciString("ABCDEF").startsWith(ciString("def")), is(false)); assertThat(ciString("").startsWith(""), is(true)); assertThat(ciString("ab").startsWith("AB"), is(true)); assertThat(ciString("ab").startsWith("ab"), is(true)); assertThat(ciString("abcdef").startsWith("AB"), is(true)); assertThat(ciString("ABCDEF").startsWith("aB"), is(true)); assertThat(ciString("ABCDEF").startsWith("def"), is(false)); } |
CIString implements Comparable<CIString>, CharSequence { public boolean contains(final CIString value) { return lcValue.contains(value.lcValue); } private CIString(final String value); @Nullable static CIString ciString(final String value); static Set<CIString> ciSet(final String... values); static Set<CIString> ciImmutableSet(final String... values); static Set<CIString> ciSet(final Iterable<String> values); static Set<CIString> ciImmutableSet(final Iterable<String> values); static boolean isBlank(final CIString ciString); @Override boolean equals(@Nullable final Object o); @Override int hashCode(); @Override int compareTo(@Nonnull final CIString o); @Override @Nonnull String toString(); String toLowerCase(); String toUpperCase(); int toInt(); @Override int length(); @Override char charAt(final int index); @Override CharSequence subSequence(final int start, final int end); boolean startsWith(final CIString value); boolean startsWith(final String value); boolean contains(final CIString value); boolean contains(final String value); boolean endsWith(final CIString value); boolean endsWith(final String value); CIString append(final CIString other); } | @Test public void contains() { assertThat(ciString("ABCDEF").contains(ciString("abcdef")), is(true)); assertThat(ciString("ABCDEF").contains(ciString("cd")), is(true)); assertThat(ciString("ABCDEF").contains(ciString("CD")), is(true)); assertThat(ciString("ABCDEF").contains("abcdef"), is(true)); assertThat(ciString("ABCDEF").contains("cd"), is(true)); assertThat(ciString("ABCDEF").contains("CD"), is(true)); } |
CIString implements Comparable<CIString>, CharSequence { public boolean endsWith(final CIString value) { return lcValue.endsWith(value.lcValue); } private CIString(final String value); @Nullable static CIString ciString(final String value); static Set<CIString> ciSet(final String... values); static Set<CIString> ciImmutableSet(final String... values); static Set<CIString> ciSet(final Iterable<String> values); static Set<CIString> ciImmutableSet(final Iterable<String> values); static boolean isBlank(final CIString ciString); @Override boolean equals(@Nullable final Object o); @Override int hashCode(); @Override int compareTo(@Nonnull final CIString o); @Override @Nonnull String toString(); String toLowerCase(); String toUpperCase(); int toInt(); @Override int length(); @Override char charAt(final int index); @Override CharSequence subSequence(final int start, final int end); boolean startsWith(final CIString value); boolean startsWith(final String value); boolean contains(final CIString value); boolean contains(final String value); boolean endsWith(final CIString value); boolean endsWith(final String value); CIString append(final CIString other); } | @Test public void endsWith() { assertThat(ciString("ABCDEF").endsWith(ciString("def")), is(true)); assertThat(ciString("ABCDEF").endsWith(ciString("DEF")), is(true)); assertThat(ciString("ABCDEF").endsWith(ciString("ABC")), is(false)); assertThat(ciString("ABCDEF").endsWith("def"), is(true)); assertThat(ciString("ABCDEF").endsWith("DEF"), is(true)); assertThat(ciString("ABCDEF").endsWith("ABC"), is(false)); } |
CIString implements Comparable<CIString>, CharSequence { public CIString append(final CIString other) { return ciString(value + other.value); } private CIString(final String value); @Nullable static CIString ciString(final String value); static Set<CIString> ciSet(final String... values); static Set<CIString> ciImmutableSet(final String... values); static Set<CIString> ciSet(final Iterable<String> values); static Set<CIString> ciImmutableSet(final Iterable<String> values); static boolean isBlank(final CIString ciString); @Override boolean equals(@Nullable final Object o); @Override int hashCode(); @Override int compareTo(@Nonnull final CIString o); @Override @Nonnull String toString(); String toLowerCase(); String toUpperCase(); int toInt(); @Override int length(); @Override char charAt(final int index); @Override CharSequence subSequence(final int start, final int end); boolean startsWith(final CIString value); boolean startsWith(final String value); boolean contains(final CIString value); boolean contains(final String value); boolean endsWith(final CIString value); boolean endsWith(final String value); CIString append(final CIString other); } | @Test public void append() { assertThat(ciString("").append(ciString("")), is(ciString(""))); assertThat(ciString("a").append(ciString("b")), is(ciString("ab"))); assertThat(ciString("a").append(ciString("b")), is(ciString("AB"))); } |
CIString implements Comparable<CIString>, CharSequence { public int toInt() { return Integer.parseInt(value); } private CIString(final String value); @Nullable static CIString ciString(final String value); static Set<CIString> ciSet(final String... values); static Set<CIString> ciImmutableSet(final String... values); static Set<CIString> ciSet(final Iterable<String> values); static Set<CIString> ciImmutableSet(final Iterable<String> values); static boolean isBlank(final CIString ciString); @Override boolean equals(@Nullable final Object o); @Override int hashCode(); @Override int compareTo(@Nonnull final CIString o); @Override @Nonnull String toString(); String toLowerCase(); String toUpperCase(); int toInt(); @Override int length(); @Override char charAt(final int index); @Override CharSequence subSequence(final int start, final int end); boolean startsWith(final CIString value); boolean startsWith(final String value); boolean contains(final CIString value); boolean contains(final String value); boolean endsWith(final CIString value); boolean endsWith(final String value); CIString append(final CIString other); } | @Test public void toInt() { assertThat(ciString("1").toInt(), is(1)); assertThat(ciString("312").toInt(), is(312)); } |
QueryMessages { public static Message termsAndConditions() { return new Message(Type.INFO, "" + "% This is the RIPE Database query service.\n" + "% The objects are in RPSL format.\n" + "%\n" + "% The RIPE Database is subject to Terms and Conditions.\n" + "% See http: } 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(); } | @Test public void headerShouldContainLinkToTermsAndConditions() { assertThat(QueryMessages.termsAndConditions().toString(), containsString("http: } |
QueryMessages { public static Message duplicateIpFlagsPassed() { return new QueryMessage(Type.ERROR, "" + "ERROR:901: duplicate IP flags passed\n" + "\n" + "More than one IP flag (-l, -L, -m, -M or -x) passed to the server."); } 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(); } | @Test public void duplicateIpFlagsPassedShouldContainError() { assertThat(QueryMessages.duplicateIpFlagsPassed().toString(), containsString("%ERROR:901:")); } |
QueryMessages { public static Message abuseCShown(final CharSequence key, final CharSequence value) { return new QueryMessage(Type.INFO, "Abuse contact for '%s' is '%s'", key, value); } 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(); } | @Test public void restApiExpectsAbuseContactsInSpecificFormat() { assertThat(QueryMessages.abuseCShown("193.0.0.0 - 193.0.7.255", "[email protected]").toString(), is("% Abuse contact for '193.0.0.0 - 193.0.7.255' is '[email protected]'\n")); } |
QueryMessages { public static Message internalErroroccurred() { return new QueryMessage(Type.ERROR, "" + "ERROR:100: internal software error\n" + "\n" + "Please contact [email protected] 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(); } | @Test public void internalErrorMessageShouldContainErrorCode() { assertThat(QueryMessages.internalErroroccurred().toString(), containsString("%ERROR:100:")); } |
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(); } | @Test public void noSearchKeySpecifiedShouldContainError() { assertThat(QueryMessages.noSearchKeySpecified().toString(), containsString("%ERROR:106:")); } |
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(); } | @Test public void noResultsMessageShouldContainErrorCode() { assertThat(QueryMessages.noResults("RIPE").toString(), containsString("%ERROR:101:")); } |
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(); } | @Test public void accessDeniedPermanentlyShouldContainErrorCode() throws UnknownHostException { assertThat(QueryMessages.accessDeniedPermanently(InetAddress.getLocalHost()).toString(), containsString("%ERROR:201:")); } |
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(); } | @Test public void accessDeniedTemporarilyMessageShouldContainErrorCode() throws UnknownHostException { assertThat(QueryMessages.accessDeniedTemporarily(InetAddress.getLocalHost()).toString(), containsString("%ERROR:201:")); } |
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(); } | @Test public void tooLongInputStringShouldContainErrorCode() { assertThat(QueryMessages.inputTooLong().toString(), containsString("%ERROR:107:")); } |
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(); } | @Test public void invalidObjectTypeShouldContainErrorCode() { assertThat(QueryMessages.invalidObjectType("").toString(), containsString("%ERROR:103:")); } |
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); } | @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: [email protected] 20061016\n", "changed: [email protected] 20070402\n", "changed: [email protected] 20070718\n", "source: JPIRR\n"), Lists.newArrayList("" + "as-set: AS-BOGUS\n", "descr: Description\n", "members: AS74\n", "notify: [email protected]\n", "mnt-by: MNT-AS18\n", "changed: [email protected] 20130109\n", "source: JPIRR\n") )); } |
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(); } | @Test public void invalidInetnumMessageShouldContainErrorCode() { assertThat(QueryMessages.uselessIpFlagPassed().toString(), containsString("%WARNING:902:")); } |
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(); } | @Test public void malformedQueryShouldContainError() { assertThat(QueryMessages.malformedQuery().toString(), containsString("%ERROR:111:")); } |
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(); } | @Test public void notAllowedToProxyShouldContainError() { assertThat(QueryMessages.notAllowedToProxy().toString(), containsString("%ERROR:203:")); } |
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; } | @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"))); } } |
WhoisObjectMapper { public RpslObject map(final WhoisObject whoisObject, final Class<?> mapFunction) { final List<RpslAttribute> rpslAttributes = Lists.newArrayList(); final AttributeMapper attributeMapper = objectMapperFunctions.get(mapFunction); for (final Attribute attribute : whoisObject.getAttributes()) { rpslAttributes.addAll(attributeMapper.map(attribute)); } return new RpslObject(rpslAttributes); } @Autowired WhoisObjectMapper(@Value("${api.rest.baseurl}") final String baseUrl,
final AttributeMapper[] objectMapperFunctions); RpslObject map(final WhoisObject whoisObject, final Class<?> mapFunction); List<RpslObject> mapWhoisObjects(final Iterable<WhoisObject> whoisObjects, final Class<?> mapFunction); WhoisResources mapRpslObjects(final Class<?> mapFunction, final RpslObject... rpslObjects); WhoisResources mapRpslObjects(final Iterable<RpslObject> rpslObjects, final Class<?> mapFunction); WhoisResources mapRpslObjects(final Class<? extends AttributeMapper> mapFunction, final ActionRequest ... requests); WhoisObject map(final RpslObject rpslObject, final Class<?> mapFunction); } | @Test public void map_rpsl_mntner() throws Exception { final RpslObject rpslObject = RpslObject.parse( "mntner: TST-MNT\n" + "descr: MNTNER for test\n" + "admin-c: TP1-TEST\n" + "upd-to: [email protected]\n" + "auth: MD5-PW $1$d9fKeTr2$Si7YudNf4rUGmR71n/cqk/ # test\n" + "auth: PGPKEY-28F6CD6C\n" + "mnt-by: TST-MNT\n" + "source: TEST\n"); final WhoisObject whoisObject = mapper.map(rpslObject, FormattedClientAttributeMapper.class); assertThat(whoisObject.getType(), is("mntner")); assertThat(whoisObject.getSource().getId(), is("test")); assertThat(whoisObject.getLink().getType(), is("locator")); assertThat(whoisObject.getLink().getHref(), is("http: assertThat(whoisObject.getPrimaryKey(), hasSize(1)); final Attribute primaryKeyAttribute = whoisObject.getPrimaryKey().get(0); assertThat(primaryKeyAttribute.getName(), is("mntner")); assertThat(primaryKeyAttribute.getValue(), is("TST-MNT")); assertThat(whoisObject.getAttributes(), contains( new Attribute("mntner", "TST-MNT", null, null, null, null), new Attribute("descr", "MNTNER for test", null, null, null, null), new Attribute("admin-c", "TP1-TEST", null, null, null, null), new Attribute("upd-to", "[email protected]", null, null, null, null), new Attribute("auth", "MD5-PW $1$d9fKeTr2$Si7YudNf4rUGmR71n/cqk/", "test", null, null, null), new Attribute("auth", "PGPKEY-28F6CD6C", null, null, null, null), new Attribute("mnt-by", "TST-MNT", null, null, null, null), new Attribute("source", "TEST", null, null, null, null) )); }
@Test public void map_rpsl_as_set_members_multiple_values() throws Exception { final RpslObject rpslObject = RpslObject.parse("" + "as-set: AS-set-attendees\n" + "descr: AS-set containing all attendees' ASNs.\n" + "tech-c: TS1-TEST\n" + "admin-c: TS1-TEST\n" + "members: as1,as2,as3,\n" + "mnt-by: TS1-MNT\n" + "source: TEST"); final WhoisObject whoisObject = mapper.map(rpslObject, FormattedClientAttributeMapper.class); assertThat(whoisObject.getType(), is("as-set")); assertThat(whoisObject.getSource().getId(), is("test")); assertThat(whoisObject.getLink().getType(), is("locator")); assertThat(whoisObject.getLink().getHref(), is("http: assertThat(whoisObject.getPrimaryKey(), hasSize(1)); final Attribute primaryKeyAttribute = whoisObject.getPrimaryKey().get(0); assertThat(primaryKeyAttribute.getName(), is("as-set")); assertThat(primaryKeyAttribute.getValue(), is("AS-set-attendees")); assertThat(whoisObject.getAttributes(), containsInAnyOrder( new Attribute("as-set", "AS-set-attendees", null, null, null, null), new Attribute("descr", "AS-set containing all attendees' ASNs.", null, null, null, null), new Attribute("tech-c", "TS1-TEST", null, null, null, null), new Attribute("admin-c", "TS1-TEST", null, null, null, null), new Attribute("members", "as1", null, null, null, null), new Attribute("members", "as2", null, null, null, null), new Attribute("members", "as3", null, null, null, null), new Attribute("members", "", null, null, null, null), new Attribute("mnt-by", "TS1-MNT", null, null, null, null), new Attribute("source", "TEST", null, null, null, null) )); } |
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); } | @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")); } |
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); } | @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())); } |
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); } | @Test public void getGrsDefaultSources() { final String defaultSources = subject.getGrsDefaultSources(); assertThat(defaultSources, is("ARIN-GRS,APNIC-GRS")); } |
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); } | @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)); } |
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); } | @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")); } |
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); } | @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("[email protected]", "Test User", true), token, "2033-01-30T16:38:27.369+11:00") ); assertThat(subject.login("[email protected]", "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("[email protected]", "password"); fail(); } catch (CrowdClientException expected) { assertThat(expected.getMessage(), is("message")); } } |
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); } | @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")); } } |
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); } | @Test public void get_username_success() { when(builder.get(CrowdClient.CrowdUsers.class)) .then(invocation -> new CrowdClient.CrowdUsers( Arrays.asList(new CrowdClient.CrowdUser("[email protected]", "Test User", true))) ); assertThat(subject.getUsername("uuid"), is("[email protected]")); }
@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")); } } |
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); } | @Test public void get_display_name_success() { when(builder.get(CrowdClient.CrowdUsers.class)) .then(invocation -> new CrowdClient.CrowdUsers( Arrays.asList(new CrowdClient.CrowdUser("[email protected]", "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")); } } |
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); } | @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); } |
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); } | @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); } |
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); } | @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("[email protected]"), 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("[email protected]"); fail(); } catch (CrowdClientException expected) { assertThat(expected.getMessage(), is("Unknown RIPE NCC Access user: [email protected]")); } }
@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("[email protected]"); fail(); } catch (CrowdClientException expected) { assertThat(expected.getMessage(), is("Cannot find UUID for: [email protected]")); } } |
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); } | @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); } |
SsoHelper { public static RpslObject translateAuth(final RpslObject rpslObject, final AuthTranslator authTranslator) { if (!rpslObject.containsAttribute(AttributeType.AUTH)) { return rpslObject; } final Map<RpslAttribute, RpslAttribute> replace = Maps.newHashMap(); for (RpslAttribute authAttribute : rpslObject.findAttributes(AttributeType.AUTH)) { final Iterator<String> authIterator = SPACE_SPLITTER.split(authAttribute.getCleanValue()).iterator(); final String authType = authIterator.next().toUpperCase(); if (authIterator.hasNext()) { final String authToken = authIterator.next(); final RpslAttribute result = authTranslator.translate(authType, authToken, authAttribute); if (result != null) { replace.put(authAttribute, result); } } } if (replace.isEmpty()) { return rpslObject; } else { return new RpslObjectBuilder(rpslObject).replaceAttributes(replace).get(); } } static RpslObject translateAuth(final RpslObject rpslObject, final AuthTranslator authTranslator); } | @Test public void translate_no_auth_attribute() { final RpslObject object = RpslObject.parse("" + "person: Test Person\n" + "nic-hdl: TP1.TEST\n" + "mnt-by: TEST-MNT\n" + "source: TEST"); final RpslObject result = SsoHelper.translateAuth( object, authTranslator); assertThat(result, is(object)); }
@Test public void translate_no_sso_auth_attribute() { final RpslObject object = RpslObject.parse("" + "mntner: TEST-MNT\n" + "mnt-by: TEST-MNT\n" + "auth: MD5-PW aadf\n"); final RpslObject result = SsoHelper.translateAuth(object, authTranslator); assertThat(result, is(object)); }
@Test public void translate_sso_auth_attribute() { final RpslAttribute attribute = new RpslAttribute(AttributeType.AUTH, "SSO [email protected]"); final RpslAttribute translated = new RpslAttribute(AttributeType.AUTH, "SSO bbbb-aaaa-cccc-dddd"); when(authTranslator.translate("SSO", "[email protected]", attribute)).thenReturn(translated); final RpslObject object = RpslObject.parse("" + "mntner: TEST-MNT\n" + "mnt-by: TEST-MNT\n" + "auth: SSO [email protected]\n"); final RpslObject result = SsoHelper.translateAuth(object, authTranslator); assertThat(result.toString(), is("" + "mntner: TEST-MNT\n" + "mnt-by: TEST-MNT\n" + "auth: SSO bbbb-aaaa-cccc-dddd\n")); }
@Test public void translate_many_sso_attributes() { final RpslAttribute attribute = new RpslAttribute(AttributeType.AUTH, "SSO [email protected]"); final RpslAttribute attribute2 = new RpslAttribute(AttributeType.AUTH, "SSO [email protected]"); final RpslAttribute translated1 = new RpslAttribute(AttributeType.AUTH, "SSO bbbb-aaaa-cccc-dddd"); final RpslAttribute translated2 = new RpslAttribute(AttributeType.AUTH, "SSO eeee-ffff-eeee-ffff"); when(authTranslator.translate("SSO", "[email protected]", attribute)).thenReturn(translated1); when(authTranslator.translate("SSO", "[email protected]", attribute2)).thenReturn(translated2); final RpslObject object = RpslObject.parse("" + "mntner: TEST-MNT\n" + "mnt-by: TEST-MNT\n" + "auth: SSO [email protected]\n" + "auth: SSO [email protected]\n"); final RpslObject result = SsoHelper.translateAuth(object, authTranslator); assertThat(result.toString(), is("" + "mntner: TEST-MNT\n" + "mnt-by: TEST-MNT\n" + "auth: SSO bbbb-aaaa-cccc-dddd\n" + "auth: SSO eeee-ffff-eeee-ffff\n")); } |
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(); } | @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)); } |
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); } | @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); } |
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); } | @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: [email protected]" ); 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 '[email protected]'\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())); } |
BriefAbuseCFunction implements Function<ResponseObject, ResponseObject> { @Override public ResponseObject apply(final @Nullable ResponseObject input) { if (!(input instanceof RpslObject)) { return input; } final RpslObject rpslObject = (RpslObject) input; if (Query.ABUSE_CONTACT_OBJECT_TYPES.contains(rpslObject.getType())) { final Optional<AbuseContact> abuseContact = abuseCFinder.getAbuseContact(rpslObject); if (abuseContact.isPresent()) { final List<RpslAttribute> abuseCAttributes = new ArrayList<>(2); abuseCAttributes.add(rpslObject.getTypeAttribute()); abuseCAttributes.add(new RpslAttribute(AttributeType.ABUSE_MAILBOX, abuseContact.get().getAbuseMailbox())); return new RpslAttributes(abuseCAttributes); } } final List<RpslAttribute> newAttributes = new ArrayList<>(2); for (final RpslAttribute attribute : rpslObject.getAttributes()) { if (BRIEF_ATTRIBUTES.contains(attribute.getType())) { newAttributes.add(attribute); } } if (newAttributes.isEmpty()) { return null; } return new RpslAttributes(newAttributes); } BriefAbuseCFunction(final AbuseCFinder abuseCFinder); @Override ResponseObject apply(final @Nullable ResponseObject input); } | @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: [email protected]"); when(abuseCFinder.getAbuseContact(rpslObject)).thenReturn(Optional.empty()); final ResponseObject response = subject.apply(rpslObject); assertThat(response.toString(), is("" + "inetnum: 10.0.0.0\n" + "abuse-mailbox: [email protected]\n")); }
@Test public void apply_inet6num() { RpslObject rpslObject = RpslObject.parse("" + "inet6num: ::0\n" + "mnt-by: BAR\n" + "source: QUX\n" + "abuse-mailbox: [email protected]"); when(abuseCFinder.getAbuseContact(rpslObject)).thenReturn(Optional.empty()); final ResponseObject response = subject.apply(rpslObject); assertThat(response.toString(), is("" + "inet6num: ::0\n" + "abuse-mailbox: [email protected]\n")); }
@Test public void apply_person() { RpslObject rpslObject = RpslObject.parse("" + "person: FOO\n" + "mnt-by: BAR\n" + "nic-hdl: FOO-QUX\n" + "source: QUX\n" + "abuse-mailbox: [email protected]"); final ResponseObject response = subject.apply(rpslObject); assertThat(response.toString(), is("" + "abuse-mailbox: [email protected]\n")); }
@Test public void apply_person_nothing_remains() { RpslObject rpslObject = RpslObject.parse("" + "person: FOO\n" + "nic-hdl: FOO-QUX\n" + "source: QUX"); final ResponseObject response = subject.apply(rpslObject); assertNull(response); }
@Test public void apply_inet6num_abusec() { RpslObject rpslObject = RpslObject.parse("" + "inet6num: ::0\n" + "mnt-by: BAR\n" + "source: RIPE\n" + "abuse-mailbox: [email protected]"); final RpslObject abuseRole = RpslObject.parse("role: Abuse Role\n" + "nic-hdl: AA1-TEST\n" + "abuse-mailbox: [email protected]" ); when(abuseCFinder.getAbuseContact(rpslObject)).thenReturn(Optional.of(new AbuseContact(abuseRole, false, ciString("")))); final ResponseObject response = subject.apply(rpslObject); assertThat(response.toString(), is("" + "inet6num: ::0\n" + "abuse-mailbox: [email protected]\n")); }
@Test public void apply_inetnum_abusec() { RpslObject rpslObject = RpslObject.parse("" + "inetnum: 10.0.0.0\n" + "mnt-by: BAR\n" + "source: RIPE\n" + "abuse-mailbox: [email protected]"); final RpslObject abuseRole = RpslObject.parse("role: Abuse Role\n" + "nic-hdl: AA1-TEST\n" + "abuse-mailbox: [email protected]" ); when(abuseCFinder.getAbuseContact(rpslObject)).thenReturn(Optional.of(new AbuseContact(abuseRole, false, ciString("")))); final ResponseObject response = subject.apply(rpslObject); assertThat(response.toString(), is("" + "inetnum: 10.0.0.0\n" + "abuse-mailbox: [email protected]\n")); }
@Test public void apply_rootobject_abusec() { RpslObject rpslObject = RpslObject.parse("" + "inetnum: 0.0.0.0\n" + "mnt-by: BAR\n" + "source: QUX\n" + "abuse-mailbox: [email protected]"); when(abuseCFinder.getAbuseContact(rpslObject)).thenReturn(Optional.empty()); final ResponseObject response = subject.apply(rpslObject); assertThat(response.toString(), is("" + "inetnum: 0.0.0.0\n" + "abuse-mailbox: [email protected]\n")); } |
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); } | @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")); } |
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); } | @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)); } |
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); } | @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)); } |
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); } | @Test public void getSupportedType() { assertThat(subject.getSupportedType(), is(ObjectType.INET6NUM)); } |
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); } | @Test public void createResource() { final String resource = "::0"; assertThat(subject.createResource(resource), is(Ipv6Resource.parse(resource))); } |
HierarchyLookup { public Collection<RpslObjectInfo> getReferencedIrtsInHierarchy(final RpslObject rpslObject) { final Collection<RpslObjectInfo> irts = getReferencedIrts(rpslObject); if (!irts.isEmpty()) { return irts; } final K resource = createResource(rpslObject.getKey()); final List<V> entries = ipTree.findAllLessSpecific(resource); for (final V entry : entries) { final RpslObject object = rpslObjectDao.getById(entry.getObjectId()); final Collection<RpslObjectInfo> referencedIrts = getReferencedIrts(object); if (!referencedIrts.isEmpty()) { return referencedIrts; } } return Collections.emptyList(); } protected HierarchyLookup(final IpTree<K, V> ipTree, final RpslObjectDao rpslObjectDao); boolean supports(final RpslObject rpslObject); Collection<RpslObjectInfo> getReferencedIrtsInHierarchy(final RpslObject rpslObject); } | @Test public void getAttributeKeysInHierarchyMostSpecific_noMatch() { final RpslObject rpslObject = RpslObject.parse("inetnum: 10.0.0.0"); when(ipv4Tree.findAllLessSpecific(any(Ipv4Resource.class))).thenReturn(Collections.<Ipv4Entry>emptyList()); final Collection<RpslObjectInfo> result = subject.getReferencedIrtsInHierarchy(rpslObject); assertThat(result, hasSize(0)); }
@Test public void getAttributeKeysInHierarchyMostSpecific_match_in_object() { final RpslObject rpslObject = RpslObject.parse("inetnum: 10.0.0.0\nmnt-irt: IRT"); final RpslObjectInfo rpslObjectInfo = new RpslObjectInfo(1, ObjectType.IRT, "IRT"); when(rpslObjectDao.findByKey(ObjectType.IRT, "IRT")).thenReturn(rpslObjectInfo); final Collection<RpslObjectInfo> result = subject.getReferencedIrtsInHierarchy(rpslObject); assertThat(result, contains(rpslObjectInfo)); verifyZeroInteractions(ipv4Tree); }
@Test public void getAttributeKeysInHierarchyMostSpecific_match_in_hierarchy() { final Ipv4Entry ipv4Entry2 = new Ipv4Entry(Ipv4Resource.parse("193.0.0/24"), 2); final RpslObjectInfo rpslObjectInfo = new RpslObjectInfo(2, ObjectType.IRT, "IRT"); final Ipv4Entry ipv4Entry3 = new Ipv4Entry(Ipv4Resource.parse("193.0/16"), 3); when(ipv4Tree.findAllLessSpecific(Ipv4Resource.parse("193.0.0.10"))).thenReturn(Lists.newArrayList(ipv4Entry2, ipv4Entry3)); when(rpslObjectDao.getById(ipv4Entry2.getObjectId())).thenReturn(RpslObject.parse("inetnum: 193.0.0.0-193.0.0.255\nmnt-irt: IRT")); when(rpslObjectDao.findByKey(ObjectType.IRT, "IRT")).thenReturn(rpslObjectInfo); final Collection<RpslObjectInfo> result = subject.getReferencedIrtsInHierarchy(RpslObject.parse("inetnum: 193.0.0.10")); assertThat(result, contains(rpslObjectInfo)); verify(rpslObjectDao, never()).getById(ipv4Entry3.getObjectId()); }
@Test public void getAttributeKeysInHierarchyMostSpecific_none_in_hierarchy() { final Ipv4Entry ipv4Entry2 = new Ipv4Entry(Ipv4Resource.parse("193.0.0/24"), 2); final Ipv4Entry ipv4Entry3 = new Ipv4Entry(Ipv4Resource.parse("193.0/16"), 3); when(ipv4Tree.findAllLessSpecific(Ipv4Resource.parse("193.0.0.10"))).thenReturn(Lists.newArrayList(ipv4Entry2, ipv4Entry3)); when(rpslObjectDao.getById(ipv4Entry2.getObjectId())).thenReturn(RpslObject.parse("inetnum: 193.0.0.0-193.0.0.255")); when(rpslObjectDao.getById(ipv4Entry3.getObjectId())).thenReturn(RpslObject.parse("inetnum: 193.0.0.0-193.0.255.255")); final Collection<RpslObjectInfo> result = subject.getReferencedIrtsInHierarchy(RpslObject.parse("inetnum: 193.0.0.10")); assertThat(result, hasSize(0)); } |
Subsets and Splits