target
stringlengths 20
113k
| src_fm
stringlengths 11
86.3k
| src_fm_fc
stringlengths 21
86.4k
| src_fm_fc_co
stringlengths 30
86.4k
| src_fm_fc_ms
stringlengths 42
86.8k
| src_fm_fc_ms_ff
stringlengths 43
86.8k
|
---|---|---|---|---|---|
@Test public void help() { final RdapObject result = mapper.mapHelp("http: assertThat(result.getLinks(), hasSize(2)); assertThat(result.getLinks().get(0).getRel(), is("self")); assertThat(result.getLinks().get(1).getRel(), is("copyright")); assertThat(result.getEvents(), is(emptyIterable())); assertThat(result.getStatus(), is(emptyIterable())); assertThat(result.getPort43(), is("whois.ripe.net")); } | public RdapObject mapHelp(final String requestUrl) { return mapCommons(new RdapObject(), requestUrl); } | RdapObjectMapper { public RdapObject mapHelp(final String requestUrl) { return mapCommons(new RdapObject(), requestUrl); } } | RdapObjectMapper { public RdapObject mapHelp(final String requestUrl) { return mapCommons(new RdapObject(), requestUrl); } @Autowired RdapObjectMapper(
final NoticeFactory noticeFactory,
@Qualifier("jdbcRpslObjectSlaveDao") final RpslObjectDao rpslObjectDao,
final Ipv4Tree ipv4Tree,
final Ipv6Tree ipv6Tree,
@Value("${rdap.port43:}") final String port43); } | RdapObjectMapper { public RdapObject mapHelp(final String requestUrl) { return mapCommons(new RdapObject(), requestUrl); } @Autowired RdapObjectMapper(
final NoticeFactory noticeFactory,
@Qualifier("jdbcRpslObjectSlaveDao") final RpslObjectDao rpslObjectDao,
final Ipv4Tree ipv4Tree,
final Ipv6Tree ipv6Tree,
@Value("${rdap.port43:}") final String port43); Object map(final String requestUrl,
final RpslObject rpslObject,
final LocalDateTime lastChangedTimestamp,
final Optional<AbuseContact> abuseContact); Object mapSearch(final String requestUrl, final List<RpslObject> objects, final Iterable<LocalDateTime> localDateTimes, final int maxResultSize); RdapObject mapError(final int errorCode, final String errorTitle, final List<String> errorDescriptions); RdapObject mapHelp(final String requestUrl); } | RdapObjectMapper { public RdapObject mapHelp(final String requestUrl) { return mapCommons(new RdapObject(), requestUrl); } @Autowired RdapObjectMapper(
final NoticeFactory noticeFactory,
@Qualifier("jdbcRpslObjectSlaveDao") final RpslObjectDao rpslObjectDao,
final Ipv4Tree ipv4Tree,
final Ipv6Tree ipv6Tree,
@Value("${rdap.port43:}") final String port43); Object map(final String requestUrl,
final RpslObject rpslObject,
final LocalDateTime lastChangedTimestamp,
final Optional<AbuseContact> abuseContact); Object mapSearch(final String requestUrl, final List<RpslObject> objects, final Iterable<LocalDateTime> localDateTimes, final int maxResultSize); RdapObject mapError(final int errorCode, final String errorTitle, final List<String> errorDescriptions); RdapObject mapHelp(final String requestUrl); } |
@Test public void abuse_validation_failed() { final AbuseContact abuseContact = new AbuseContact( RpslObject.parse( "role: Abuse Contact\n" + "nic-hdl: AB-TEST\n" + "mnt-by: TEST-MNT\n" + "abuse-mailbox: [email protected]\n" + "admin-c: TP1-TEST\n" + "tech-c: TP2-TEST\n" + "phone: +31 12345678\n" + "source: TEST" ), true, ciString("ORG-NCC1-RIPE") ); final Autnum result = (Autnum) map( RpslObject.parse("" + "aut-num: AS102\n" + "as-name: End-User-2\n" + "org: ORG-NCC1-RIPE\n" + "admin-c: AP1-TEST\n" + "tech-c: AP1-TEST\n" + "abuse-c: AB-TEST\n" + "notify: [email protected]\n" + "mnt-by: UPD-MNT\n" + "source: TEST\n" ), Optional.of(abuseContact) ); assertThat( result.getRemarks().get(0).getDescription().get(0), is("Abuse contact for 'AS102' is '[email protected]'\nAbuse-mailbox validation failed. Please refer to ORG-NCC1-RIPE for further information.\n") ); } | public Object map(final String requestUrl, final RpslObject rpslObject, final LocalDateTime lastChangedTimestamp, final Optional<AbuseContact> abuseContact) { return mapCommons(getRdapObject(requestUrl, rpslObject, lastChangedTimestamp, abuseContact), requestUrl); } | RdapObjectMapper { public Object map(final String requestUrl, final RpslObject rpslObject, final LocalDateTime lastChangedTimestamp, final Optional<AbuseContact> abuseContact) { return mapCommons(getRdapObject(requestUrl, rpslObject, lastChangedTimestamp, abuseContact), requestUrl); } } | RdapObjectMapper { public Object map(final String requestUrl, final RpslObject rpslObject, final LocalDateTime lastChangedTimestamp, final Optional<AbuseContact> abuseContact) { return mapCommons(getRdapObject(requestUrl, rpslObject, lastChangedTimestamp, abuseContact), requestUrl); } @Autowired RdapObjectMapper(
final NoticeFactory noticeFactory,
@Qualifier("jdbcRpslObjectSlaveDao") final RpslObjectDao rpslObjectDao,
final Ipv4Tree ipv4Tree,
final Ipv6Tree ipv6Tree,
@Value("${rdap.port43:}") final String port43); } | RdapObjectMapper { public Object map(final String requestUrl, final RpslObject rpslObject, final LocalDateTime lastChangedTimestamp, final Optional<AbuseContact> abuseContact) { return mapCommons(getRdapObject(requestUrl, rpslObject, lastChangedTimestamp, abuseContact), requestUrl); } @Autowired RdapObjectMapper(
final NoticeFactory noticeFactory,
@Qualifier("jdbcRpslObjectSlaveDao") final RpslObjectDao rpslObjectDao,
final Ipv4Tree ipv4Tree,
final Ipv6Tree ipv6Tree,
@Value("${rdap.port43:}") final String port43); Object map(final String requestUrl,
final RpslObject rpslObject,
final LocalDateTime lastChangedTimestamp,
final Optional<AbuseContact> abuseContact); Object mapSearch(final String requestUrl, final List<RpslObject> objects, final Iterable<LocalDateTime> localDateTimes, final int maxResultSize); RdapObject mapError(final int errorCode, final String errorTitle, final List<String> errorDescriptions); RdapObject mapHelp(final String requestUrl); } | RdapObjectMapper { public Object map(final String requestUrl, final RpslObject rpslObject, final LocalDateTime lastChangedTimestamp, final Optional<AbuseContact> abuseContact) { return mapCommons(getRdapObject(requestUrl, rpslObject, lastChangedTimestamp, abuseContact), requestUrl); } @Autowired RdapObjectMapper(
final NoticeFactory noticeFactory,
@Qualifier("jdbcRpslObjectSlaveDao") final RpslObjectDao rpslObjectDao,
final Ipv4Tree ipv4Tree,
final Ipv6Tree ipv6Tree,
@Value("${rdap.port43:}") final String port43); Object map(final String requestUrl,
final RpslObject rpslObject,
final LocalDateTime lastChangedTimestamp,
final Optional<AbuseContact> abuseContact); Object mapSearch(final String requestUrl, final List<RpslObject> objects, final Iterable<LocalDateTime> localDateTimes, final int maxResultSize); RdapObject mapError(final int errorCode, final String errorTitle, final List<String> errorDescriptions); RdapObject mapHelp(final String requestUrl); } |
@Test public void abuse_validation_passed() { final AbuseContact abuseContact = new AbuseContact( RpslObject.parse( "role: Abuse Contact\n" + "nic-hdl: AB-TEST\n" + "mnt-by: TEST-MNT\n" + "abuse-mailbox: [email protected]\n" + "admin-c: TP1-TEST\n" + "tech-c: TP2-TEST\n" + "phone: +31 12345678\n" + "source: TEST" ), false, ciString("ORG-NCC1-RIPE") ); final Autnum result = (Autnum) map( RpslObject.parse("" + "aut-num: AS102\n" + "as-name: End-User-2\n" + "org: ORG-NCC1-RIPE\n" + "admin-c: AP1-TEST\n" + "tech-c: AP1-TEST\n" + "abuse-c: AB-TEST\n" + "notify: [email protected]\n" + "mnt-by: UPD-MNT\n" + "source: TEST\n" ), Optional.of(abuseContact) ); assertThat(result.getRemarks(), hasSize(0)); } | public Object map(final String requestUrl, final RpslObject rpslObject, final LocalDateTime lastChangedTimestamp, final Optional<AbuseContact> abuseContact) { return mapCommons(getRdapObject(requestUrl, rpslObject, lastChangedTimestamp, abuseContact), requestUrl); } | RdapObjectMapper { public Object map(final String requestUrl, final RpslObject rpslObject, final LocalDateTime lastChangedTimestamp, final Optional<AbuseContact> abuseContact) { return mapCommons(getRdapObject(requestUrl, rpslObject, lastChangedTimestamp, abuseContact), requestUrl); } } | RdapObjectMapper { public Object map(final String requestUrl, final RpslObject rpslObject, final LocalDateTime lastChangedTimestamp, final Optional<AbuseContact> abuseContact) { return mapCommons(getRdapObject(requestUrl, rpslObject, lastChangedTimestamp, abuseContact), requestUrl); } @Autowired RdapObjectMapper(
final NoticeFactory noticeFactory,
@Qualifier("jdbcRpslObjectSlaveDao") final RpslObjectDao rpslObjectDao,
final Ipv4Tree ipv4Tree,
final Ipv6Tree ipv6Tree,
@Value("${rdap.port43:}") final String port43); } | RdapObjectMapper { public Object map(final String requestUrl, final RpslObject rpslObject, final LocalDateTime lastChangedTimestamp, final Optional<AbuseContact> abuseContact) { return mapCommons(getRdapObject(requestUrl, rpslObject, lastChangedTimestamp, abuseContact), requestUrl); } @Autowired RdapObjectMapper(
final NoticeFactory noticeFactory,
@Qualifier("jdbcRpslObjectSlaveDao") final RpslObjectDao rpslObjectDao,
final Ipv4Tree ipv4Tree,
final Ipv6Tree ipv6Tree,
@Value("${rdap.port43:}") final String port43); Object map(final String requestUrl,
final RpslObject rpslObject,
final LocalDateTime lastChangedTimestamp,
final Optional<AbuseContact> abuseContact); Object mapSearch(final String requestUrl, final List<RpslObject> objects, final Iterable<LocalDateTime> localDateTimes, final int maxResultSize); RdapObject mapError(final int errorCode, final String errorTitle, final List<String> errorDescriptions); RdapObject mapHelp(final String requestUrl); } | RdapObjectMapper { public Object map(final String requestUrl, final RpslObject rpslObject, final LocalDateTime lastChangedTimestamp, final Optional<AbuseContact> abuseContact) { return mapCommons(getRdapObject(requestUrl, rpslObject, lastChangedTimestamp, abuseContact), requestUrl); } @Autowired RdapObjectMapper(
final NoticeFactory noticeFactory,
@Qualifier("jdbcRpslObjectSlaveDao") final RpslObjectDao rpslObjectDao,
final Ipv4Tree ipv4Tree,
final Ipv6Tree ipv6Tree,
@Value("${rdap.port43:}") final String port43); Object map(final String requestUrl,
final RpslObject rpslObject,
final LocalDateTime lastChangedTimestamp,
final Optional<AbuseContact> abuseContact); Object mapSearch(final String requestUrl, final List<RpslObject> objects, final Iterable<LocalDateTime> localDateTimes, final int maxResultSize); RdapObject mapError(final int errorCode, final String errorTitle, final List<String> errorDescriptions); RdapObject mapHelp(final String requestUrl); } |
@Test public void abuse_validation_failed_no_responsible_org() { final AbuseContact abuseContact = new AbuseContact( RpslObject.parse( "role: Abuse Contact\n" + "nic-hdl: AB-TEST\n" + "mnt-by: TEST-MNT\n" + "abuse-mailbox: [email protected]\n" + "admin-c: TP1-TEST\n" + "tech-c: TP2-TEST\n" + "phone: +31 12345678\n" + "source: TEST" ), true, null ); final Autnum result = (Autnum) map( RpslObject.parse("" + "aut-num: AS102\n" + "as-name: End-User-2\n" + "org: ORG-NCC1-RIPE\n" + "admin-c: AP1-TEST\n" + "tech-c: AP1-TEST\n" + "abuse-c: AB-TEST\n" + "notify: [email protected]\n" + "mnt-by: UPD-MNT\n" + "source: TEST\n" ), Optional.of(abuseContact) ); assertThat(result.getRemarks(), hasSize(0)); } | public Object map(final String requestUrl, final RpslObject rpslObject, final LocalDateTime lastChangedTimestamp, final Optional<AbuseContact> abuseContact) { return mapCommons(getRdapObject(requestUrl, rpslObject, lastChangedTimestamp, abuseContact), requestUrl); } | RdapObjectMapper { public Object map(final String requestUrl, final RpslObject rpslObject, final LocalDateTime lastChangedTimestamp, final Optional<AbuseContact> abuseContact) { return mapCommons(getRdapObject(requestUrl, rpslObject, lastChangedTimestamp, abuseContact), requestUrl); } } | RdapObjectMapper { public Object map(final String requestUrl, final RpslObject rpslObject, final LocalDateTime lastChangedTimestamp, final Optional<AbuseContact> abuseContact) { return mapCommons(getRdapObject(requestUrl, rpslObject, lastChangedTimestamp, abuseContact), requestUrl); } @Autowired RdapObjectMapper(
final NoticeFactory noticeFactory,
@Qualifier("jdbcRpslObjectSlaveDao") final RpslObjectDao rpslObjectDao,
final Ipv4Tree ipv4Tree,
final Ipv6Tree ipv6Tree,
@Value("${rdap.port43:}") final String port43); } | RdapObjectMapper { public Object map(final String requestUrl, final RpslObject rpslObject, final LocalDateTime lastChangedTimestamp, final Optional<AbuseContact> abuseContact) { return mapCommons(getRdapObject(requestUrl, rpslObject, lastChangedTimestamp, abuseContact), requestUrl); } @Autowired RdapObjectMapper(
final NoticeFactory noticeFactory,
@Qualifier("jdbcRpslObjectSlaveDao") final RpslObjectDao rpslObjectDao,
final Ipv4Tree ipv4Tree,
final Ipv6Tree ipv6Tree,
@Value("${rdap.port43:}") final String port43); Object map(final String requestUrl,
final RpslObject rpslObject,
final LocalDateTime lastChangedTimestamp,
final Optional<AbuseContact> abuseContact); Object mapSearch(final String requestUrl, final List<RpslObject> objects, final Iterable<LocalDateTime> localDateTimes, final int maxResultSize); RdapObject mapError(final int errorCode, final String errorTitle, final List<String> errorDescriptions); RdapObject mapHelp(final String requestUrl); } | RdapObjectMapper { public Object map(final String requestUrl, final RpslObject rpslObject, final LocalDateTime lastChangedTimestamp, final Optional<AbuseContact> abuseContact) { return mapCommons(getRdapObject(requestUrl, rpslObject, lastChangedTimestamp, abuseContact), requestUrl); } @Autowired RdapObjectMapper(
final NoticeFactory noticeFactory,
@Qualifier("jdbcRpslObjectSlaveDao") final RpslObjectDao rpslObjectDao,
final Ipv4Tree ipv4Tree,
final Ipv6Tree ipv6Tree,
@Value("${rdap.port43:}") final String port43); Object map(final String requestUrl,
final RpslObject rpslObject,
final LocalDateTime lastChangedTimestamp,
final Optional<AbuseContact> abuseContact); Object mapSearch(final String requestUrl, final List<RpslObject> objects, final Iterable<LocalDateTime> localDateTimes, final int maxResultSize); RdapObject mapError(final int errorCode, final String errorTitle, final List<String> errorDescriptions); RdapObject mapHelp(final String requestUrl); } |
@Test public void shouldThrowExceptionForInvalidOrganisation() { expectedEx.expect(NotFoundException.class); expectedEx.expectMessage("Invalid syntax"); validator.validateEntity("ORG-Test"); } | public void validateEntity(final String key) { if (key.toUpperCase().startsWith("ORG-")) { if (!AttributeType.ORGANISATION.isValidValue(ORGANISATION, key)) { throw new NotFoundException("Invalid syntax."); } } else { if (!AttributeType.MNTNER.isValidValue(MNTNER, key)) { throw new NotFoundException("Invalid syntax."); } } } | RdapRequestValidator { public void validateEntity(final String key) { if (key.toUpperCase().startsWith("ORG-")) { if (!AttributeType.ORGANISATION.isValidValue(ORGANISATION, key)) { throw new NotFoundException("Invalid syntax."); } } else { if (!AttributeType.MNTNER.isValidValue(MNTNER, key)) { throw new NotFoundException("Invalid syntax."); } } } } | RdapRequestValidator { public void validateEntity(final String key) { if (key.toUpperCase().startsWith("ORG-")) { if (!AttributeType.ORGANISATION.isValidValue(ORGANISATION, key)) { throw new NotFoundException("Invalid syntax."); } } else { if (!AttributeType.MNTNER.isValidValue(MNTNER, key)) { throw new NotFoundException("Invalid syntax."); } } } @Autowired RdapRequestValidator(final ReservedAutnum reservedAutnum); } | RdapRequestValidator { public void validateEntity(final String key) { if (key.toUpperCase().startsWith("ORG-")) { if (!AttributeType.ORGANISATION.isValidValue(ORGANISATION, key)) { throw new NotFoundException("Invalid syntax."); } } else { if (!AttributeType.MNTNER.isValidValue(MNTNER, key)) { throw new NotFoundException("Invalid syntax."); } } } @Autowired RdapRequestValidator(final ReservedAutnum reservedAutnum); void validateDomain(final String key); void validateIp(final String rawUri, final String key); void validateAutnum(final String key); void validateEntity(final String key); boolean isReservedAsNumber(String key); } | RdapRequestValidator { public void validateEntity(final String key) { if (key.toUpperCase().startsWith("ORG-")) { if (!AttributeType.ORGANISATION.isValidValue(ORGANISATION, key)) { throw new NotFoundException("Invalid syntax."); } } else { if (!AttributeType.MNTNER.isValidValue(MNTNER, key)) { throw new NotFoundException("Invalid syntax."); } } } @Autowired RdapRequestValidator(final ReservedAutnum reservedAutnum); void validateDomain(final String key); void validateIp(final String rawUri, final String key); void validateAutnum(final String key); void validateEntity(final String key); boolean isReservedAsNumber(String key); } |
@Test public void shouldNotThrowAnyExceptionForValidEntity() { validator.validateEntity("ORG-BAD1-TEST"); } | public void validateEntity(final String key) { if (key.toUpperCase().startsWith("ORG-")) { if (!AttributeType.ORGANISATION.isValidValue(ORGANISATION, key)) { throw new NotFoundException("Invalid syntax."); } } else { if (!AttributeType.MNTNER.isValidValue(MNTNER, key)) { throw new NotFoundException("Invalid syntax."); } } } | RdapRequestValidator { public void validateEntity(final String key) { if (key.toUpperCase().startsWith("ORG-")) { if (!AttributeType.ORGANISATION.isValidValue(ORGANISATION, key)) { throw new NotFoundException("Invalid syntax."); } } else { if (!AttributeType.MNTNER.isValidValue(MNTNER, key)) { throw new NotFoundException("Invalid syntax."); } } } } | RdapRequestValidator { public void validateEntity(final String key) { if (key.toUpperCase().startsWith("ORG-")) { if (!AttributeType.ORGANISATION.isValidValue(ORGANISATION, key)) { throw new NotFoundException("Invalid syntax."); } } else { if (!AttributeType.MNTNER.isValidValue(MNTNER, key)) { throw new NotFoundException("Invalid syntax."); } } } @Autowired RdapRequestValidator(final ReservedAutnum reservedAutnum); } | RdapRequestValidator { public void validateEntity(final String key) { if (key.toUpperCase().startsWith("ORG-")) { if (!AttributeType.ORGANISATION.isValidValue(ORGANISATION, key)) { throw new NotFoundException("Invalid syntax."); } } else { if (!AttributeType.MNTNER.isValidValue(MNTNER, key)) { throw new NotFoundException("Invalid syntax."); } } } @Autowired RdapRequestValidator(final ReservedAutnum reservedAutnum); void validateDomain(final String key); void validateIp(final String rawUri, final String key); void validateAutnum(final String key); void validateEntity(final String key); boolean isReservedAsNumber(String key); } | RdapRequestValidator { public void validateEntity(final String key) { if (key.toUpperCase().startsWith("ORG-")) { if (!AttributeType.ORGANISATION.isValidValue(ORGANISATION, key)) { throw new NotFoundException("Invalid syntax."); } } else { if (!AttributeType.MNTNER.isValidValue(MNTNER, key)) { throw new NotFoundException("Invalid syntax."); } } } @Autowired RdapRequestValidator(final ReservedAutnum reservedAutnum); void validateDomain(final String key); void validateIp(final String rawUri, final String key); void validateAutnum(final String key); void validateEntity(final String key); boolean isReservedAsNumber(String key); } |
@Test public void person() { final RpslObject person = RpslObject.parse(15, "" + "person: Fred Blogs\n" + "address: RIPE Network Coordination Centre (NCC)\n" + "address: Singel 258\n" + "address: 1016 AB Amsterdam\n" + "address: The Netherlands\n" + "phone: +31 20 535 4444\n" + "fax-no: +31 20 535 4445\n" + "e-mail: [email protected]\n" + "nic-hdl: FB99999-RIPE\n" + "mnt-by: AARDVARK-MNT\n" + "notify: [email protected]\n" + "source: RIPE"); final RpslObject dummified = subject.dummify(4, person); assertThat(dummified.getAttributes(), contains( new RpslAttribute("person", "Name Removed"), new RpslAttribute("address", "***"), new RpslAttribute("address", "***"), new RpslAttribute("address", "***"), new RpslAttribute("address", "The Netherlands"), new RpslAttribute("phone", "+31 20 ... ...."), new RpslAttribute("fax-no", "+31 20 ... ...."), new RpslAttribute("e-mail", "***@ripe.net"), new RpslAttribute("nic-hdl", "FB99999-RIPE"), new RpslAttribute("mnt-by", "AARDVARK-MNT"), new RpslAttribute("notify", "***@ripe.net"), new RpslAttribute("source", "RIPE"))); } | @Override public RpslObject dummify(final int version, final RpslObject rpslObject) { final ObjectType objectType = rpslObject.getType(); Validate.isTrue(isAllowed(version, rpslObject), "The version is not supported by this dummifier", version); final List<RpslAttribute> attributes = Lists.newArrayList(rpslObject.getAttributes()); RpslAttribute lastAddressLine = null; int lastAddressLineIndex = 0; for (int i = 0; i < attributes.size(); i++) { RpslAttribute replacement = attributes.get(i); final AttributeType attributeType = replacement.getType(); try { if (!(objectType == ObjectType.ROLE && rpslObject.containsAttribute(ABUSE_MAILBOX))) { replacement = replacePerson(attributeType, replacement); replacement = replaceAuth(attributeType, replacement); replacement = replacePhoneFax(attributeType, replacement); if (attributeType == ADDRESS) { lastAddressLine = replacement; lastAddressLineIndex = i; replacement = new RpslAttribute(ADDRESS, "***"); } } replacement = replaceEmail(attributeType, replacement); attributes.set(i, replacement); } catch (RuntimeException e) { LOGGER.debug("Dummifier failed on [" + attributes.get(i).toString().trim() + "]", e); } } if (lastAddressLine != null) { attributes.set(lastAddressLineIndex, lastAddressLine); } return FILTER_CHANGED_FUNCTION.apply(new RpslObject(rpslObject, attributes)); } | DummifierCurrent implements Dummifier { @Override public RpslObject dummify(final int version, final RpslObject rpslObject) { final ObjectType objectType = rpslObject.getType(); Validate.isTrue(isAllowed(version, rpslObject), "The version is not supported by this dummifier", version); final List<RpslAttribute> attributes = Lists.newArrayList(rpslObject.getAttributes()); RpslAttribute lastAddressLine = null; int lastAddressLineIndex = 0; for (int i = 0; i < attributes.size(); i++) { RpslAttribute replacement = attributes.get(i); final AttributeType attributeType = replacement.getType(); try { if (!(objectType == ObjectType.ROLE && rpslObject.containsAttribute(ABUSE_MAILBOX))) { replacement = replacePerson(attributeType, replacement); replacement = replaceAuth(attributeType, replacement); replacement = replacePhoneFax(attributeType, replacement); if (attributeType == ADDRESS) { lastAddressLine = replacement; lastAddressLineIndex = i; replacement = new RpslAttribute(ADDRESS, "***"); } } replacement = replaceEmail(attributeType, replacement); attributes.set(i, replacement); } catch (RuntimeException e) { LOGGER.debug("Dummifier failed on [" + attributes.get(i).toString().trim() + "]", e); } } if (lastAddressLine != null) { attributes.set(lastAddressLineIndex, lastAddressLine); } return FILTER_CHANGED_FUNCTION.apply(new RpslObject(rpslObject, attributes)); } } | DummifierCurrent implements Dummifier { @Override public RpslObject dummify(final int version, final RpslObject rpslObject) { final ObjectType objectType = rpslObject.getType(); Validate.isTrue(isAllowed(version, rpslObject), "The version is not supported by this dummifier", version); final List<RpslAttribute> attributes = Lists.newArrayList(rpslObject.getAttributes()); RpslAttribute lastAddressLine = null; int lastAddressLineIndex = 0; for (int i = 0; i < attributes.size(); i++) { RpslAttribute replacement = attributes.get(i); final AttributeType attributeType = replacement.getType(); try { if (!(objectType == ObjectType.ROLE && rpslObject.containsAttribute(ABUSE_MAILBOX))) { replacement = replacePerson(attributeType, replacement); replacement = replaceAuth(attributeType, replacement); replacement = replacePhoneFax(attributeType, replacement); if (attributeType == ADDRESS) { lastAddressLine = replacement; lastAddressLineIndex = i; replacement = new RpslAttribute(ADDRESS, "***"); } } replacement = replaceEmail(attributeType, replacement); attributes.set(i, replacement); } catch (RuntimeException e) { LOGGER.debug("Dummifier failed on [" + attributes.get(i).toString().trim() + "]", e); } } if (lastAddressLine != null) { attributes.set(lastAddressLineIndex, lastAddressLine); } return FILTER_CHANGED_FUNCTION.apply(new RpslObject(rpslObject, attributes)); } } | DummifierCurrent implements Dummifier { @Override public RpslObject dummify(final int version, final RpslObject rpslObject) { final ObjectType objectType = rpslObject.getType(); Validate.isTrue(isAllowed(version, rpslObject), "The version is not supported by this dummifier", version); final List<RpslAttribute> attributes = Lists.newArrayList(rpslObject.getAttributes()); RpslAttribute lastAddressLine = null; int lastAddressLineIndex = 0; for (int i = 0; i < attributes.size(); i++) { RpslAttribute replacement = attributes.get(i); final AttributeType attributeType = replacement.getType(); try { if (!(objectType == ObjectType.ROLE && rpslObject.containsAttribute(ABUSE_MAILBOX))) { replacement = replacePerson(attributeType, replacement); replacement = replaceAuth(attributeType, replacement); replacement = replacePhoneFax(attributeType, replacement); if (attributeType == ADDRESS) { lastAddressLine = replacement; lastAddressLineIndex = i; replacement = new RpslAttribute(ADDRESS, "***"); } } replacement = replaceEmail(attributeType, replacement); attributes.set(i, replacement); } catch (RuntimeException e) { LOGGER.debug("Dummifier failed on [" + attributes.get(i).toString().trim() + "]", e); } } if (lastAddressLine != null) { attributes.set(lastAddressLineIndex, lastAddressLine); } return FILTER_CHANGED_FUNCTION.apply(new RpslObject(rpslObject, attributes)); } @Override RpslObject dummify(final int version, final RpslObject rpslObject); @Override boolean isAllowed(final int version, final RpslObject object); } | DummifierCurrent implements Dummifier { @Override public RpslObject dummify(final int version, final RpslObject rpslObject) { final ObjectType objectType = rpslObject.getType(); Validate.isTrue(isAllowed(version, rpslObject), "The version is not supported by this dummifier", version); final List<RpslAttribute> attributes = Lists.newArrayList(rpslObject.getAttributes()); RpslAttribute lastAddressLine = null; int lastAddressLineIndex = 0; for (int i = 0; i < attributes.size(); i++) { RpslAttribute replacement = attributes.get(i); final AttributeType attributeType = replacement.getType(); try { if (!(objectType == ObjectType.ROLE && rpslObject.containsAttribute(ABUSE_MAILBOX))) { replacement = replacePerson(attributeType, replacement); replacement = replaceAuth(attributeType, replacement); replacement = replacePhoneFax(attributeType, replacement); if (attributeType == ADDRESS) { lastAddressLine = replacement; lastAddressLineIndex = i; replacement = new RpslAttribute(ADDRESS, "***"); } } replacement = replaceEmail(attributeType, replacement); attributes.set(i, replacement); } catch (RuntimeException e) { LOGGER.debug("Dummifier failed on [" + attributes.get(i).toString().trim() + "]", e); } } if (lastAddressLine != null) { attributes.set(lastAddressLineIndex, lastAddressLine); } return FILTER_CHANGED_FUNCTION.apply(new RpslObject(rpslObject, attributes)); } @Override RpslObject dummify(final int version, final RpslObject rpslObject); @Override boolean isAllowed(final int version, final RpslObject object); } |
@Test(expected = BadRequestException.class) public void shouldThrowExceptionForInvalidAutnum() { validator.validateAutnum("TEST"); } | public void validateAutnum(final String key) { try { AutNum.parse(key); } catch (AttributeParseException e) { throw new BadRequestException("Invalid syntax."); } } | RdapRequestValidator { public void validateAutnum(final String key) { try { AutNum.parse(key); } catch (AttributeParseException e) { throw new BadRequestException("Invalid syntax."); } } } | RdapRequestValidator { public void validateAutnum(final String key) { try { AutNum.parse(key); } catch (AttributeParseException e) { throw new BadRequestException("Invalid syntax."); } } @Autowired RdapRequestValidator(final ReservedAutnum reservedAutnum); } | RdapRequestValidator { public void validateAutnum(final String key) { try { AutNum.parse(key); } catch (AttributeParseException e) { throw new BadRequestException("Invalid syntax."); } } @Autowired RdapRequestValidator(final ReservedAutnum reservedAutnum); void validateDomain(final String key); void validateIp(final String rawUri, final String key); void validateAutnum(final String key); void validateEntity(final String key); boolean isReservedAsNumber(String key); } | RdapRequestValidator { public void validateAutnum(final String key) { try { AutNum.parse(key); } catch (AttributeParseException e) { throw new BadRequestException("Invalid syntax."); } } @Autowired RdapRequestValidator(final ReservedAutnum reservedAutnum); void validateDomain(final String key); void validateIp(final String rawUri, final String key); void validateAutnum(final String key); void validateEntity(final String key); boolean isReservedAsNumber(String key); } |
@Test(expected = BadRequestException.class) public void shouldThrowExceptionForInvalidIP() { validator.validateIp("", "invalid"); } | public void validateIp(final String rawUri, final String key) { try { IpInterval.parse(key); } catch (IllegalArgumentException e) { throw new BadRequestException("Invalid syntax."); } if (rawUri.contains(" throw new BadRequestException("Invalid syntax."); } } | RdapRequestValidator { public void validateIp(final String rawUri, final String key) { try { IpInterval.parse(key); } catch (IllegalArgumentException e) { throw new BadRequestException("Invalid syntax."); } if (rawUri.contains(" throw new BadRequestException("Invalid syntax."); } } } | RdapRequestValidator { public void validateIp(final String rawUri, final String key) { try { IpInterval.parse(key); } catch (IllegalArgumentException e) { throw new BadRequestException("Invalid syntax."); } if (rawUri.contains(" throw new BadRequestException("Invalid syntax."); } } @Autowired RdapRequestValidator(final ReservedAutnum reservedAutnum); } | RdapRequestValidator { public void validateIp(final String rawUri, final String key) { try { IpInterval.parse(key); } catch (IllegalArgumentException e) { throw new BadRequestException("Invalid syntax."); } if (rawUri.contains(" throw new BadRequestException("Invalid syntax."); } } @Autowired RdapRequestValidator(final ReservedAutnum reservedAutnum); void validateDomain(final String key); void validateIp(final String rawUri, final String key); void validateAutnum(final String key); void validateEntity(final String key); boolean isReservedAsNumber(String key); } | RdapRequestValidator { public void validateIp(final String rawUri, final String key) { try { IpInterval.parse(key); } catch (IllegalArgumentException e) { throw new BadRequestException("Invalid syntax."); } if (rawUri.contains(" throw new BadRequestException("Invalid syntax."); } } @Autowired RdapRequestValidator(final ReservedAutnum reservedAutnum); void validateDomain(final String key); void validateIp(final String rawUri, final String key); void validateAutnum(final String key); void validateEntity(final String key); boolean isReservedAsNumber(String key); } |
@Test public void shouldNotThrowExceptionForValidIP() { validator.validateIp("", "192.0.0.0"); } | public void validateIp(final String rawUri, final String key) { try { IpInterval.parse(key); } catch (IllegalArgumentException e) { throw new BadRequestException("Invalid syntax."); } if (rawUri.contains(" throw new BadRequestException("Invalid syntax."); } } | RdapRequestValidator { public void validateIp(final String rawUri, final String key) { try { IpInterval.parse(key); } catch (IllegalArgumentException e) { throw new BadRequestException("Invalid syntax."); } if (rawUri.contains(" throw new BadRequestException("Invalid syntax."); } } } | RdapRequestValidator { public void validateIp(final String rawUri, final String key) { try { IpInterval.parse(key); } catch (IllegalArgumentException e) { throw new BadRequestException("Invalid syntax."); } if (rawUri.contains(" throw new BadRequestException("Invalid syntax."); } } @Autowired RdapRequestValidator(final ReservedAutnum reservedAutnum); } | RdapRequestValidator { public void validateIp(final String rawUri, final String key) { try { IpInterval.parse(key); } catch (IllegalArgumentException e) { throw new BadRequestException("Invalid syntax."); } if (rawUri.contains(" throw new BadRequestException("Invalid syntax."); } } @Autowired RdapRequestValidator(final ReservedAutnum reservedAutnum); void validateDomain(final String key); void validateIp(final String rawUri, final String key); void validateAutnum(final String key); void validateEntity(final String key); boolean isReservedAsNumber(String key); } | RdapRequestValidator { public void validateIp(final String rawUri, final String key) { try { IpInterval.parse(key); } catch (IllegalArgumentException e) { throw new BadRequestException("Invalid syntax."); } if (rawUri.contains(" throw new BadRequestException("Invalid syntax."); } } @Autowired RdapRequestValidator(final ReservedAutnum reservedAutnum); void validateDomain(final String key); void validateIp(final String rawUri, final String key); void validateAutnum(final String key); void validateEntity(final String key); boolean isReservedAsNumber(String key); } |
@Test public void shouldNotThrowAExceptionForValidAutnum() { validator.validateAutnum("AS102"); } | public void validateAutnum(final String key) { try { AutNum.parse(key); } catch (AttributeParseException e) { throw new BadRequestException("Invalid syntax."); } } | RdapRequestValidator { public void validateAutnum(final String key) { try { AutNum.parse(key); } catch (AttributeParseException e) { throw new BadRequestException("Invalid syntax."); } } } | RdapRequestValidator { public void validateAutnum(final String key) { try { AutNum.parse(key); } catch (AttributeParseException e) { throw new BadRequestException("Invalid syntax."); } } @Autowired RdapRequestValidator(final ReservedAutnum reservedAutnum); } | RdapRequestValidator { public void validateAutnum(final String key) { try { AutNum.parse(key); } catch (AttributeParseException e) { throw new BadRequestException("Invalid syntax."); } } @Autowired RdapRequestValidator(final ReservedAutnum reservedAutnum); void validateDomain(final String key); void validateIp(final String rawUri, final String key); void validateAutnum(final String key); void validateEntity(final String key); boolean isReservedAsNumber(String key); } | RdapRequestValidator { public void validateAutnum(final String key) { try { AutNum.parse(key); } catch (AttributeParseException e) { throw new BadRequestException("Invalid syntax."); } } @Autowired RdapRequestValidator(final ReservedAutnum reservedAutnum); void validateDomain(final String key); void validateIp(final String rawUri, final String key); void validateAutnum(final String key); void validateEntity(final String key); boolean isReservedAsNumber(String key); } |
@Test public void xml_extension() throws Exception { final HttpServletRequest request = doFilter("http", "localhost", "/whois/test/inet6num/No%20clue%20what%20the%20range%20is.xml"); assertThat(request.getRequestURI(), is("/whois/test/inet6num/No%20clue%20what%20the%20range%20is")); assertThat(request.getRequestURL().toString(), is("http: assertThat(request.getHeader("Accept"), is("application/xml")); assertThat(toList(request.getHeaders("Accept")), contains("application/xml")); } | @Override public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { if (request instanceof HttpServletRequest) { chain.doFilter(OverrideAcceptHeaderWrapper.wrapRequest((HttpServletRequest) request), response); } else { LOGGER.warn("Unexpected request: {}", request); chain.doFilter(request, response); } } | ExtensionOverridesAcceptHeaderFilter implements Filter { @Override public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { if (request instanceof HttpServletRequest) { chain.doFilter(OverrideAcceptHeaderWrapper.wrapRequest((HttpServletRequest) request), response); } else { LOGGER.warn("Unexpected request: {}", request); chain.doFilter(request, response); } } } | ExtensionOverridesAcceptHeaderFilter implements Filter { @Override public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { if (request instanceof HttpServletRequest) { chain.doFilter(OverrideAcceptHeaderWrapper.wrapRequest((HttpServletRequest) request), response); } else { LOGGER.warn("Unexpected request: {}", request); chain.doFilter(request, response); } } } | ExtensionOverridesAcceptHeaderFilter implements Filter { @Override public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { if (request instanceof HttpServletRequest) { chain.doFilter(OverrideAcceptHeaderWrapper.wrapRequest((HttpServletRequest) request), response); } else { LOGGER.warn("Unexpected request: {}", request); chain.doFilter(request, response); } } @Override void init(final FilterConfig filterConfig); @Override void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain); @Override void destroy(); } | ExtensionOverridesAcceptHeaderFilter implements Filter { @Override public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { if (request instanceof HttpServletRequest) { chain.doFilter(OverrideAcceptHeaderWrapper.wrapRequest((HttpServletRequest) request), response); } else { LOGGER.warn("Unexpected request: {}", request); chain.doFilter(request, response); } } @Override void init(final FilterConfig filterConfig); @Override void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain); @Override void destroy(); } |
@Test public void json_extension() throws Exception { final HttpServletRequest request = doFilter("http", "localhost", "/whois/test/inet6num/No%20clue%20what%20the%20range%20is.json"); assertThat(request.getRequestURI(), is("/whois/test/inet6num/No%20clue%20what%20the%20range%20is")); assertThat(request.getRequestURL().toString(), is("http: assertThat(request.getHeader("Accept"), is("application/json")); assertThat(toList(request.getHeaders("Accept")), contains("application/json")); } | @Override public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { if (request instanceof HttpServletRequest) { chain.doFilter(OverrideAcceptHeaderWrapper.wrapRequest((HttpServletRequest) request), response); } else { LOGGER.warn("Unexpected request: {}", request); chain.doFilter(request, response); } } | ExtensionOverridesAcceptHeaderFilter implements Filter { @Override public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { if (request instanceof HttpServletRequest) { chain.doFilter(OverrideAcceptHeaderWrapper.wrapRequest((HttpServletRequest) request), response); } else { LOGGER.warn("Unexpected request: {}", request); chain.doFilter(request, response); } } } | ExtensionOverridesAcceptHeaderFilter implements Filter { @Override public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { if (request instanceof HttpServletRequest) { chain.doFilter(OverrideAcceptHeaderWrapper.wrapRequest((HttpServletRequest) request), response); } else { LOGGER.warn("Unexpected request: {}", request); chain.doFilter(request, response); } } } | ExtensionOverridesAcceptHeaderFilter implements Filter { @Override public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { if (request instanceof HttpServletRequest) { chain.doFilter(OverrideAcceptHeaderWrapper.wrapRequest((HttpServletRequest) request), response); } else { LOGGER.warn("Unexpected request: {}", request); chain.doFilter(request, response); } } @Override void init(final FilterConfig filterConfig); @Override void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain); @Override void destroy(); } | ExtensionOverridesAcceptHeaderFilter implements Filter { @Override public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { if (request instanceof HttpServletRequest) { chain.doFilter(OverrideAcceptHeaderWrapper.wrapRequest((HttpServletRequest) request), response); } else { LOGGER.warn("Unexpected request: {}", request); chain.doFilter(request, response); } } @Override void init(final FilterConfig filterConfig); @Override void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain); @Override void destroy(); } |
@Test public void unknown_extension() throws Exception { final HttpServletRequest request = doFilter("http", "localhost", "/whois/test/inet6num/No%20clue%20what%20the%20range%20is.unknown"); assertThat(request.getRequestURI(), is("/whois/test/inet6num/No%20clue%20what%20the%20range%20is.unknown")); assertThat(request.getRequestURL().toString(), is("http: assertThat(request.getHeader("Accept"), is(nullValue())); assertThat(request.getHeaders("Accept"), is(nullValue())); } | @Override public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { if (request instanceof HttpServletRequest) { chain.doFilter(OverrideAcceptHeaderWrapper.wrapRequest((HttpServletRequest) request), response); } else { LOGGER.warn("Unexpected request: {}", request); chain.doFilter(request, response); } } | ExtensionOverridesAcceptHeaderFilter implements Filter { @Override public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { if (request instanceof HttpServletRequest) { chain.doFilter(OverrideAcceptHeaderWrapper.wrapRequest((HttpServletRequest) request), response); } else { LOGGER.warn("Unexpected request: {}", request); chain.doFilter(request, response); } } } | ExtensionOverridesAcceptHeaderFilter implements Filter { @Override public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { if (request instanceof HttpServletRequest) { chain.doFilter(OverrideAcceptHeaderWrapper.wrapRequest((HttpServletRequest) request), response); } else { LOGGER.warn("Unexpected request: {}", request); chain.doFilter(request, response); } } } | ExtensionOverridesAcceptHeaderFilter implements Filter { @Override public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { if (request instanceof HttpServletRequest) { chain.doFilter(OverrideAcceptHeaderWrapper.wrapRequest((HttpServletRequest) request), response); } else { LOGGER.warn("Unexpected request: {}", request); chain.doFilter(request, response); } } @Override void init(final FilterConfig filterConfig); @Override void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain); @Override void destroy(); } | ExtensionOverridesAcceptHeaderFilter implements Filter { @Override public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { if (request instanceof HttpServletRequest) { chain.doFilter(OverrideAcceptHeaderWrapper.wrapRequest((HttpServletRequest) request), response); } else { LOGGER.warn("Unexpected request: {}", request); chain.doFilter(request, response); } } @Override void init(final FilterConfig filterConfig); @Override void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain); @Override void destroy(); } |
@Test public void no_extension() throws Exception { final HttpServletRequest request = doFilter("http", "localhost", "/whois/test/inet6num/No%20clue%20what%20the%20range%20is"); assertThat(request.getRequestURI(), is("/whois/test/inet6num/No%20clue%20what%20the%20range%20is")); assertThat(request.getRequestURL().toString(), is("http: assertThat(request.getHeader("Accept"), is(nullValue())); assertThat(request.getHeaders("Accept"), is(nullValue())); } | @Override public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { if (request instanceof HttpServletRequest) { chain.doFilter(OverrideAcceptHeaderWrapper.wrapRequest((HttpServletRequest) request), response); } else { LOGGER.warn("Unexpected request: {}", request); chain.doFilter(request, response); } } | ExtensionOverridesAcceptHeaderFilter implements Filter { @Override public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { if (request instanceof HttpServletRequest) { chain.doFilter(OverrideAcceptHeaderWrapper.wrapRequest((HttpServletRequest) request), response); } else { LOGGER.warn("Unexpected request: {}", request); chain.doFilter(request, response); } } } | ExtensionOverridesAcceptHeaderFilter implements Filter { @Override public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { if (request instanceof HttpServletRequest) { chain.doFilter(OverrideAcceptHeaderWrapper.wrapRequest((HttpServletRequest) request), response); } else { LOGGER.warn("Unexpected request: {}", request); chain.doFilter(request, response); } } } | ExtensionOverridesAcceptHeaderFilter implements Filter { @Override public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { if (request instanceof HttpServletRequest) { chain.doFilter(OverrideAcceptHeaderWrapper.wrapRequest((HttpServletRequest) request), response); } else { LOGGER.warn("Unexpected request: {}", request); chain.doFilter(request, response); } } @Override void init(final FilterConfig filterConfig); @Override void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain); @Override void destroy(); } | ExtensionOverridesAcceptHeaderFilter implements Filter { @Override public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { if (request instanceof HttpServletRequest) { chain.doFilter(OverrideAcceptHeaderWrapper.wrapRequest((HttpServletRequest) request), response); } else { LOGGER.warn("Unexpected request: {}", request); chain.doFilter(request, response); } } @Override void init(final FilterConfig filterConfig); @Override void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain); @Override void destroy(); } |
@Test public void root_slash() throws Exception { final HttpServletRequest request = doFilter("http", "localhost", "/"); assertThat(request.getRequestURI(), is("/")); assertThat(request.getRequestURL().toString(), is("http: assertThat(request.getHeader("Accept"), is(nullValue())); assertThat(request.getHeaders("Accept"), is(nullValue())); } | @Override public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { if (request instanceof HttpServletRequest) { chain.doFilter(OverrideAcceptHeaderWrapper.wrapRequest((HttpServletRequest) request), response); } else { LOGGER.warn("Unexpected request: {}", request); chain.doFilter(request, response); } } | ExtensionOverridesAcceptHeaderFilter implements Filter { @Override public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { if (request instanceof HttpServletRequest) { chain.doFilter(OverrideAcceptHeaderWrapper.wrapRequest((HttpServletRequest) request), response); } else { LOGGER.warn("Unexpected request: {}", request); chain.doFilter(request, response); } } } | ExtensionOverridesAcceptHeaderFilter implements Filter { @Override public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { if (request instanceof HttpServletRequest) { chain.doFilter(OverrideAcceptHeaderWrapper.wrapRequest((HttpServletRequest) request), response); } else { LOGGER.warn("Unexpected request: {}", request); chain.doFilter(request, response); } } } | ExtensionOverridesAcceptHeaderFilter implements Filter { @Override public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { if (request instanceof HttpServletRequest) { chain.doFilter(OverrideAcceptHeaderWrapper.wrapRequest((HttpServletRequest) request), response); } else { LOGGER.warn("Unexpected request: {}", request); chain.doFilter(request, response); } } @Override void init(final FilterConfig filterConfig); @Override void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain); @Override void destroy(); } | ExtensionOverridesAcceptHeaderFilter implements Filter { @Override public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { if (request instanceof HttpServletRequest) { chain.doFilter(OverrideAcceptHeaderWrapper.wrapRequest((HttpServletRequest) request), response); } else { LOGGER.warn("Unexpected request: {}", request); chain.doFilter(request, response); } } @Override void init(final FilterConfig filterConfig); @Override void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain); @Override void destroy(); } |
@Test public void root_no_slash() throws Exception { final HttpServletRequest request = doFilter("http", "localhost", ""); assertThat(request.getRequestURI(), is("")); assertThat(request.getRequestURL().toString(), is("http: assertThat(request.getHeader("Accept"), is(nullValue())); assertThat(request.getHeaders("Accept"), is(nullValue())); } | @Override public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { if (request instanceof HttpServletRequest) { chain.doFilter(OverrideAcceptHeaderWrapper.wrapRequest((HttpServletRequest) request), response); } else { LOGGER.warn("Unexpected request: {}", request); chain.doFilter(request, response); } } | ExtensionOverridesAcceptHeaderFilter implements Filter { @Override public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { if (request instanceof HttpServletRequest) { chain.doFilter(OverrideAcceptHeaderWrapper.wrapRequest((HttpServletRequest) request), response); } else { LOGGER.warn("Unexpected request: {}", request); chain.doFilter(request, response); } } } | ExtensionOverridesAcceptHeaderFilter implements Filter { @Override public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { if (request instanceof HttpServletRequest) { chain.doFilter(OverrideAcceptHeaderWrapper.wrapRequest((HttpServletRequest) request), response); } else { LOGGER.warn("Unexpected request: {}", request); chain.doFilter(request, response); } } } | ExtensionOverridesAcceptHeaderFilter implements Filter { @Override public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { if (request instanceof HttpServletRequest) { chain.doFilter(OverrideAcceptHeaderWrapper.wrapRequest((HttpServletRequest) request), response); } else { LOGGER.warn("Unexpected request: {}", request); chain.doFilter(request, response); } } @Override void init(final FilterConfig filterConfig); @Override void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain); @Override void destroy(); } | ExtensionOverridesAcceptHeaderFilter implements Filter { @Override public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { if (request instanceof HttpServletRequest) { chain.doFilter(OverrideAcceptHeaderWrapper.wrapRequest((HttpServletRequest) request), response); } else { LOGGER.warn("Unexpected request: {}", request); chain.doFilter(request, response); } } @Override void init(final FilterConfig filterConfig); @Override void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain); @Override void destroy(); } |
@Test public void inetnum() { final RpslObject inetnum = RpslObject.parse(13, "" + "inetnum: 193.0.0.0 - 193.0.7.255\n" + "netname: RIPE-NCC\n" + "descr: RIPE Network Coordination Centre\n" + "descr: Amsterdam, Netherlands\n" + "remarks: Used for RIPE NCC infrastructure.\n" + "country: NL\n" + "admin-c: JDR-RIPE\n" + "admin-c: BRD-RIPE\n" + "tech-c: OPS4-RIPE\n" + "notify: [email protected]\n" + "status: ASSIGNED PI\n" + "source: RIPE\n" + "mnt-by: RIPE-NCC-MNT\n" + "mnt-lower: RIPE-NCC-MNT\n" + "source: TEST"); final RpslObject dummified = subject.dummify(4, inetnum); assertThat(dummified.getAttributes(), contains( new RpslAttribute("inetnum", "193.0.0.0 - 193.0.7.255"), new RpslAttribute("netname", "RIPE-NCC"), new RpslAttribute("descr", "RIPE Network Coordination Centre"), new RpslAttribute("descr", "Amsterdam, Netherlands"), new RpslAttribute("remarks", "Used for RIPE NCC infrastructure."), new RpslAttribute("country", "NL"), new RpslAttribute("admin-c", "JDR-RIPE"), new RpslAttribute("admin-c", "BRD-RIPE"), new RpslAttribute("tech-c", "OPS4-RIPE"), new RpslAttribute("notify", "***@ripe.net"), new RpslAttribute("status", "ASSIGNED PI"), new RpslAttribute("source", "RIPE"), new RpslAttribute("mnt-by", "RIPE-NCC-MNT"), new RpslAttribute("mnt-lower", "RIPE-NCC-MNT"), new RpslAttribute("source", "TEST") )); } | @Override public RpslObject dummify(final int version, final RpslObject rpslObject) { final ObjectType objectType = rpslObject.getType(); Validate.isTrue(isAllowed(version, rpslObject), "The version is not supported by this dummifier", version); final List<RpslAttribute> attributes = Lists.newArrayList(rpslObject.getAttributes()); RpslAttribute lastAddressLine = null; int lastAddressLineIndex = 0; for (int i = 0; i < attributes.size(); i++) { RpslAttribute replacement = attributes.get(i); final AttributeType attributeType = replacement.getType(); try { if (!(objectType == ObjectType.ROLE && rpslObject.containsAttribute(ABUSE_MAILBOX))) { replacement = replacePerson(attributeType, replacement); replacement = replaceAuth(attributeType, replacement); replacement = replacePhoneFax(attributeType, replacement); if (attributeType == ADDRESS) { lastAddressLine = replacement; lastAddressLineIndex = i; replacement = new RpslAttribute(ADDRESS, "***"); } } replacement = replaceEmail(attributeType, replacement); attributes.set(i, replacement); } catch (RuntimeException e) { LOGGER.debug("Dummifier failed on [" + attributes.get(i).toString().trim() + "]", e); } } if (lastAddressLine != null) { attributes.set(lastAddressLineIndex, lastAddressLine); } return FILTER_CHANGED_FUNCTION.apply(new RpslObject(rpslObject, attributes)); } | DummifierCurrent implements Dummifier { @Override public RpslObject dummify(final int version, final RpslObject rpslObject) { final ObjectType objectType = rpslObject.getType(); Validate.isTrue(isAllowed(version, rpslObject), "The version is not supported by this dummifier", version); final List<RpslAttribute> attributes = Lists.newArrayList(rpslObject.getAttributes()); RpslAttribute lastAddressLine = null; int lastAddressLineIndex = 0; for (int i = 0; i < attributes.size(); i++) { RpslAttribute replacement = attributes.get(i); final AttributeType attributeType = replacement.getType(); try { if (!(objectType == ObjectType.ROLE && rpslObject.containsAttribute(ABUSE_MAILBOX))) { replacement = replacePerson(attributeType, replacement); replacement = replaceAuth(attributeType, replacement); replacement = replacePhoneFax(attributeType, replacement); if (attributeType == ADDRESS) { lastAddressLine = replacement; lastAddressLineIndex = i; replacement = new RpslAttribute(ADDRESS, "***"); } } replacement = replaceEmail(attributeType, replacement); attributes.set(i, replacement); } catch (RuntimeException e) { LOGGER.debug("Dummifier failed on [" + attributes.get(i).toString().trim() + "]", e); } } if (lastAddressLine != null) { attributes.set(lastAddressLineIndex, lastAddressLine); } return FILTER_CHANGED_FUNCTION.apply(new RpslObject(rpslObject, attributes)); } } | DummifierCurrent implements Dummifier { @Override public RpslObject dummify(final int version, final RpslObject rpslObject) { final ObjectType objectType = rpslObject.getType(); Validate.isTrue(isAllowed(version, rpslObject), "The version is not supported by this dummifier", version); final List<RpslAttribute> attributes = Lists.newArrayList(rpslObject.getAttributes()); RpslAttribute lastAddressLine = null; int lastAddressLineIndex = 0; for (int i = 0; i < attributes.size(); i++) { RpslAttribute replacement = attributes.get(i); final AttributeType attributeType = replacement.getType(); try { if (!(objectType == ObjectType.ROLE && rpslObject.containsAttribute(ABUSE_MAILBOX))) { replacement = replacePerson(attributeType, replacement); replacement = replaceAuth(attributeType, replacement); replacement = replacePhoneFax(attributeType, replacement); if (attributeType == ADDRESS) { lastAddressLine = replacement; lastAddressLineIndex = i; replacement = new RpslAttribute(ADDRESS, "***"); } } replacement = replaceEmail(attributeType, replacement); attributes.set(i, replacement); } catch (RuntimeException e) { LOGGER.debug("Dummifier failed on [" + attributes.get(i).toString().trim() + "]", e); } } if (lastAddressLine != null) { attributes.set(lastAddressLineIndex, lastAddressLine); } return FILTER_CHANGED_FUNCTION.apply(new RpslObject(rpslObject, attributes)); } } | DummifierCurrent implements Dummifier { @Override public RpslObject dummify(final int version, final RpslObject rpslObject) { final ObjectType objectType = rpslObject.getType(); Validate.isTrue(isAllowed(version, rpslObject), "The version is not supported by this dummifier", version); final List<RpslAttribute> attributes = Lists.newArrayList(rpslObject.getAttributes()); RpslAttribute lastAddressLine = null; int lastAddressLineIndex = 0; for (int i = 0; i < attributes.size(); i++) { RpslAttribute replacement = attributes.get(i); final AttributeType attributeType = replacement.getType(); try { if (!(objectType == ObjectType.ROLE && rpslObject.containsAttribute(ABUSE_MAILBOX))) { replacement = replacePerson(attributeType, replacement); replacement = replaceAuth(attributeType, replacement); replacement = replacePhoneFax(attributeType, replacement); if (attributeType == ADDRESS) { lastAddressLine = replacement; lastAddressLineIndex = i; replacement = new RpslAttribute(ADDRESS, "***"); } } replacement = replaceEmail(attributeType, replacement); attributes.set(i, replacement); } catch (RuntimeException e) { LOGGER.debug("Dummifier failed on [" + attributes.get(i).toString().trim() + "]", e); } } if (lastAddressLine != null) { attributes.set(lastAddressLineIndex, lastAddressLine); } return FILTER_CHANGED_FUNCTION.apply(new RpslObject(rpslObject, attributes)); } @Override RpslObject dummify(final int version, final RpslObject rpslObject); @Override boolean isAllowed(final int version, final RpslObject object); } | DummifierCurrent implements Dummifier { @Override public RpslObject dummify(final int version, final RpslObject rpslObject) { final ObjectType objectType = rpslObject.getType(); Validate.isTrue(isAllowed(version, rpslObject), "The version is not supported by this dummifier", version); final List<RpslAttribute> attributes = Lists.newArrayList(rpslObject.getAttributes()); RpslAttribute lastAddressLine = null; int lastAddressLineIndex = 0; for (int i = 0; i < attributes.size(); i++) { RpslAttribute replacement = attributes.get(i); final AttributeType attributeType = replacement.getType(); try { if (!(objectType == ObjectType.ROLE && rpslObject.containsAttribute(ABUSE_MAILBOX))) { replacement = replacePerson(attributeType, replacement); replacement = replaceAuth(attributeType, replacement); replacement = replacePhoneFax(attributeType, replacement); if (attributeType == ADDRESS) { lastAddressLine = replacement; lastAddressLineIndex = i; replacement = new RpslAttribute(ADDRESS, "***"); } } replacement = replaceEmail(attributeType, replacement); attributes.set(i, replacement); } catch (RuntimeException e) { LOGGER.debug("Dummifier failed on [" + attributes.get(i).toString().trim() + "]", e); } } if (lastAddressLine != null) { attributes.set(lastAddressLineIndex, lastAddressLine); } return FILTER_CHANGED_FUNCTION.apply(new RpslObject(rpslObject, attributes)); } @Override RpslObject dummify(final int version, final RpslObject rpslObject); @Override boolean isAllowed(final int version, final RpslObject object); } |
@Test public void init() throws Exception { subject.init(null); } | @Override public void init(final FilterConfig filterConfig) throws ServletException { } | RemoteAddressFilter implements Filter { @Override public void init(final FilterConfig filterConfig) throws ServletException { } } | RemoteAddressFilter implements Filter { @Override public void init(final FilterConfig filterConfig) throws ServletException { } } | RemoteAddressFilter implements Filter { @Override public void init(final FilterConfig filterConfig) throws ServletException { } @Override void init(final FilterConfig filterConfig); @Override void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain); @Override void destroy(); } | RemoteAddressFilter implements Filter { @Override public void init(final FilterConfig filterConfig) throws ServletException { } @Override void init(final FilterConfig filterConfig); @Override void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain); @Override void destroy(); } |
@Test public void destroy() { subject.destroy(); } | @Override public void destroy() { } | RemoteAddressFilter implements Filter { @Override public void destroy() { } } | RemoteAddressFilter implements Filter { @Override public void destroy() { } } | RemoteAddressFilter implements Filter { @Override public void destroy() { } @Override void init(final FilterConfig filterConfig); @Override void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain); @Override void destroy(); } | RemoteAddressFilter implements Filter { @Override public void destroy() { } @Override void init(final FilterConfig filterConfig); @Override void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain); @Override void destroy(); } |
@Test public void no_servletRequest() throws Exception { final ServletRequest servletRequest = mock(ServletRequest.class); final ServletResponse servletResponse = mock(ServletResponse.class); subject.doFilter(servletRequest, servletResponse, filterChain); verify(filterChain).doFilter(servletRequest, servletResponse); } | @Override public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { if (request instanceof HttpServletRequest) { chain.doFilter(new RemoteAddressRequestWrapper((HttpServletRequest) request), response); } else { chain.doFilter(request, response); } } | RemoteAddressFilter implements Filter { @Override public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { if (request instanceof HttpServletRequest) { chain.doFilter(new RemoteAddressRequestWrapper((HttpServletRequest) request), response); } else { chain.doFilter(request, response); } } } | RemoteAddressFilter implements Filter { @Override public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { if (request instanceof HttpServletRequest) { chain.doFilter(new RemoteAddressRequestWrapper((HttpServletRequest) request), response); } else { chain.doFilter(request, response); } } } | RemoteAddressFilter implements Filter { @Override public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { if (request instanceof HttpServletRequest) { chain.doFilter(new RemoteAddressRequestWrapper((HttpServletRequest) request), response); } else { chain.doFilter(request, response); } } @Override void init(final FilterConfig filterConfig); @Override void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain); @Override void destroy(); } | RemoteAddressFilter implements Filter { @Override public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { if (request instanceof HttpServletRequest) { chain.doFilter(new RemoteAddressRequestWrapper((HttpServletRequest) request), response); } else { chain.doFilter(request, response); } } @Override void init(final FilterConfig filterConfig); @Override void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain); @Override void destroy(); } |
@Test public void no_forward_header() throws Exception { when(request.getRemoteAddr()).thenReturn("10.0.0.0"); subject.doFilter(request, response, filterChain); verify(filterChain).doFilter(argThat(new CheckRemoteAddress("10.0.0.0")), any(ServletResponse.class)); } | @Override public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { if (request instanceof HttpServletRequest) { chain.doFilter(new RemoteAddressRequestWrapper((HttpServletRequest) request), response); } else { chain.doFilter(request, response); } } | RemoteAddressFilter implements Filter { @Override public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { if (request instanceof HttpServletRequest) { chain.doFilter(new RemoteAddressRequestWrapper((HttpServletRequest) request), response); } else { chain.doFilter(request, response); } } } | RemoteAddressFilter implements Filter { @Override public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { if (request instanceof HttpServletRequest) { chain.doFilter(new RemoteAddressRequestWrapper((HttpServletRequest) request), response); } else { chain.doFilter(request, response); } } } | RemoteAddressFilter implements Filter { @Override public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { if (request instanceof HttpServletRequest) { chain.doFilter(new RemoteAddressRequestWrapper((HttpServletRequest) request), response); } else { chain.doFilter(request, response); } } @Override void init(final FilterConfig filterConfig); @Override void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain); @Override void destroy(); } | RemoteAddressFilter implements Filter { @Override public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { if (request instanceof HttpServletRequest) { chain.doFilter(new RemoteAddressRequestWrapper((HttpServletRequest) request), response); } else { chain.doFilter(request, response); } } @Override void init(final FilterConfig filterConfig); @Override void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain); @Override void destroy(); } |
@Test public void forward_header() throws Exception { when(request.getHeaders(HttpHeaders.X_FORWARDED_FOR)).thenReturn(Collections.enumeration(Lists.newArrayList("193.0.20.1"))); when(request.getRemoteAddr()).thenReturn("10.0.0.0"); subject.doFilter(request, response, filterChain); verify(filterChain).doFilter(argThat(new CheckRemoteAddress("193.0.20.1")), any(ServletResponse.class)); } | @Override public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { if (request instanceof HttpServletRequest) { chain.doFilter(new RemoteAddressRequestWrapper((HttpServletRequest) request), response); } else { chain.doFilter(request, response); } } | RemoteAddressFilter implements Filter { @Override public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { if (request instanceof HttpServletRequest) { chain.doFilter(new RemoteAddressRequestWrapper((HttpServletRequest) request), response); } else { chain.doFilter(request, response); } } } | RemoteAddressFilter implements Filter { @Override public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { if (request instanceof HttpServletRequest) { chain.doFilter(new RemoteAddressRequestWrapper((HttpServletRequest) request), response); } else { chain.doFilter(request, response); } } } | RemoteAddressFilter implements Filter { @Override public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { if (request instanceof HttpServletRequest) { chain.doFilter(new RemoteAddressRequestWrapper((HttpServletRequest) request), response); } else { chain.doFilter(request, response); } } @Override void init(final FilterConfig filterConfig); @Override void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain); @Override void destroy(); } | RemoteAddressFilter implements Filter { @Override public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { if (request instanceof HttpServletRequest) { chain.doFilter(new RemoteAddressRequestWrapper((HttpServletRequest) request), response); } else { chain.doFilter(request, response); } } @Override void init(final FilterConfig filterConfig); @Override void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain); @Override void destroy(); } |
@Test public void forward_headers_ripe_range() throws Exception { when(request.getHeaders(HttpHeaders.X_FORWARDED_FOR)).thenReturn(Collections.enumeration(Lists.newArrayList("74.125.136.99", "193.0.20.1"))); when(request.getRemoteAddr()).thenReturn("10.0.0.0"); subject.doFilter(request, response, filterChain); verify(filterChain).doFilter(argThat(new CheckRemoteAddress("74.125.136.99")), any(ServletResponse.class)); } | @Override public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { if (request instanceof HttpServletRequest) { chain.doFilter(new RemoteAddressRequestWrapper((HttpServletRequest) request), response); } else { chain.doFilter(request, response); } } | RemoteAddressFilter implements Filter { @Override public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { if (request instanceof HttpServletRequest) { chain.doFilter(new RemoteAddressRequestWrapper((HttpServletRequest) request), response); } else { chain.doFilter(request, response); } } } | RemoteAddressFilter implements Filter { @Override public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { if (request instanceof HttpServletRequest) { chain.doFilter(new RemoteAddressRequestWrapper((HttpServletRequest) request), response); } else { chain.doFilter(request, response); } } } | RemoteAddressFilter implements Filter { @Override public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { if (request instanceof HttpServletRequest) { chain.doFilter(new RemoteAddressRequestWrapper((HttpServletRequest) request), response); } else { chain.doFilter(request, response); } } @Override void init(final FilterConfig filterConfig); @Override void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain); @Override void destroy(); } | RemoteAddressFilter implements Filter { @Override public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { if (request instanceof HttpServletRequest) { chain.doFilter(new RemoteAddressRequestWrapper((HttpServletRequest) request), response); } else { chain.doFilter(request, response); } } @Override void init(final FilterConfig filterConfig); @Override void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain); @Override void destroy(); } |
@Test public void forward_header_comma_separated_values() throws Exception { when(request.getHeaders(HttpHeaders.X_FORWARDED_FOR)).thenReturn(Collections.enumeration(Lists.newArrayList("74.125.136.99, 193.0.20.1"))); when(request.getRemoteAddr()).thenReturn("10.0.0.0"); subject.doFilter(request, response, filterChain); verify(filterChain).doFilter(argThat(new CheckRemoteAddress("193.0.20.1")), any(ServletResponse.class)); } | @Override public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { if (request instanceof HttpServletRequest) { chain.doFilter(new RemoteAddressRequestWrapper((HttpServletRequest) request), response); } else { chain.doFilter(request, response); } } | RemoteAddressFilter implements Filter { @Override public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { if (request instanceof HttpServletRequest) { chain.doFilter(new RemoteAddressRequestWrapper((HttpServletRequest) request), response); } else { chain.doFilter(request, response); } } } | RemoteAddressFilter implements Filter { @Override public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { if (request instanceof HttpServletRequest) { chain.doFilter(new RemoteAddressRequestWrapper((HttpServletRequest) request), response); } else { chain.doFilter(request, response); } } } | RemoteAddressFilter implements Filter { @Override public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { if (request instanceof HttpServletRequest) { chain.doFilter(new RemoteAddressRequestWrapper((HttpServletRequest) request), response); } else { chain.doFilter(request, response); } } @Override void init(final FilterConfig filterConfig); @Override void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain); @Override void destroy(); } | RemoteAddressFilter implements Filter { @Override public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { if (request instanceof HttpServletRequest) { chain.doFilter(new RemoteAddressRequestWrapper((HttpServletRequest) request), response); } else { chain.doFilter(request, response); } } @Override void init(final FilterConfig filterConfig); @Override void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain); @Override void destroy(); } |
@Test public void getUpdateMessage() { List<ContentWithCredentials> contentWithCredentialsList = Lists.newArrayList(); contentWithCredentialsList.add(new ContentWithCredentials("password: some password\nmntner: TST-MNT")); contentWithCredentialsList.add(new ContentWithCredentials("password: another password\nmntner: TST2-MNT")); final MailMessage subject = new MailMessage("id", "from", "subject", "date", "replyTo", "replyToEmail", Keyword.NONE, contentWithCredentialsList); assertThat(subject.getUpdateMessage(), is("" + "password: some password\n" + "mntner: TST-MNT\n" + "\n" + "password: another password\n" + "mntner: TST2-MNT")); } | public String getUpdateMessage() { StringBuilder builder = new StringBuilder(); Iterator<ContentWithCredentials> iterator = contentWithCredentials.iterator(); while (iterator.hasNext()) { builder.append(iterator.next().getContent()); if (iterator.hasNext()) { builder.append("\n\n"); } } return builder.toString(); } | MailMessage implements Origin { public String getUpdateMessage() { StringBuilder builder = new StringBuilder(); Iterator<ContentWithCredentials> iterator = contentWithCredentials.iterator(); while (iterator.hasNext()) { builder.append(iterator.next().getContent()); if (iterator.hasNext()) { builder.append("\n\n"); } } return builder.toString(); } } | MailMessage implements Origin { public String getUpdateMessage() { StringBuilder builder = new StringBuilder(); Iterator<ContentWithCredentials> iterator = contentWithCredentials.iterator(); while (iterator.hasNext()) { builder.append(iterator.next().getContent()); if (iterator.hasNext()) { builder.append("\n\n"); } } return builder.toString(); } MailMessage(final String id, final String from, final String subject, final String date, final String replyTo, String replyToEmail, final Keyword keyword, List<ContentWithCredentials> contentWithCredentials); } | MailMessage implements Origin { public String getUpdateMessage() { StringBuilder builder = new StringBuilder(); Iterator<ContentWithCredentials> iterator = contentWithCredentials.iterator(); while (iterator.hasNext()) { builder.append(iterator.next().getContent()); if (iterator.hasNext()) { builder.append("\n\n"); } } return builder.toString(); } MailMessage(final String id, final String from, final String subject, final String date, final String replyTo, String replyToEmail, final Keyword keyword, List<ContentWithCredentials> contentWithCredentials); @Override boolean isDefaultOverride(); @Override boolean allowAdminOperations(); String getId(); String getSubject(); String getDate(); String getReplyTo(); String getReplyToEmail(); String getUpdateMessage(); List<ContentWithCredentials> getContentWithCredentials(); @Override String getFrom(); Keyword getKeyword(); @Override String getResponseHeader(); @Override String getNotificationHeader(); @Override String getName(); @Override String toString(); } | MailMessage implements Origin { public String getUpdateMessage() { StringBuilder builder = new StringBuilder(); Iterator<ContentWithCredentials> iterator = contentWithCredentials.iterator(); while (iterator.hasNext()) { builder.append(iterator.next().getContent()); if (iterator.hasNext()) { builder.append("\n\n"); } } return builder.toString(); } MailMessage(final String id, final String from, final String subject, final String date, final String replyTo, String replyToEmail, final Keyword keyword, List<ContentWithCredentials> contentWithCredentials); @Override boolean isDefaultOverride(); @Override boolean allowAdminOperations(); String getId(); String getSubject(); String getDate(); String getReplyTo(); String getReplyToEmail(); String getUpdateMessage(); List<ContentWithCredentials> getContentWithCredentials(); @Override String getFrom(); Keyword getKeyword(); @Override String getResponseHeader(); @Override String getNotificationHeader(); @Override String getName(); @Override String toString(); } |
@Test public void shouldProcess() throws Exception { when(message.getReplyTo()).thenReturn("[email protected]"); when(message.getReplyToEmail()).thenReturn("[email protected]"); assertThat(subject.shouldProcess(message), is(true)); } | public boolean shouldProcess(final MailMessage message) { String replyToEmail = message.getReplyToEmail(); if (replyToEmail == null) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, missing reply address")); return false; } try { new InternetAddress(replyToEmail, true); } catch (final AddressException e) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply address invalid: %s", replyToEmail)); return false; } if (!EmailValidator.getInstance().isValid(replyToEmail)) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply address invalid: %s", replyToEmail)); return false; } replyToEmail = replyToEmail.toLowerCase(); if (replyToEmail.endsWith("localhost") || replyToEmail.endsWith("127.0.0.1")) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply to localhost: %s", replyToEmail)); return false; } return true; } | MessageFilter { public boolean shouldProcess(final MailMessage message) { String replyToEmail = message.getReplyToEmail(); if (replyToEmail == null) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, missing reply address")); return false; } try { new InternetAddress(replyToEmail, true); } catch (final AddressException e) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply address invalid: %s", replyToEmail)); return false; } if (!EmailValidator.getInstance().isValid(replyToEmail)) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply address invalid: %s", replyToEmail)); return false; } replyToEmail = replyToEmail.toLowerCase(); if (replyToEmail.endsWith("localhost") || replyToEmail.endsWith("127.0.0.1")) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply to localhost: %s", replyToEmail)); return false; } return true; } } | MessageFilter { public boolean shouldProcess(final MailMessage message) { String replyToEmail = message.getReplyToEmail(); if (replyToEmail == null) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, missing reply address")); return false; } try { new InternetAddress(replyToEmail, true); } catch (final AddressException e) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply address invalid: %s", replyToEmail)); return false; } if (!EmailValidator.getInstance().isValid(replyToEmail)) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply address invalid: %s", replyToEmail)); return false; } replyToEmail = replyToEmail.toLowerCase(); if (replyToEmail.endsWith("localhost") || replyToEmail.endsWith("127.0.0.1")) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply to localhost: %s", replyToEmail)); return false; } return true; } @Autowired MessageFilter(final LoggerContext loggerContext); } | MessageFilter { public boolean shouldProcess(final MailMessage message) { String replyToEmail = message.getReplyToEmail(); if (replyToEmail == null) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, missing reply address")); return false; } try { new InternetAddress(replyToEmail, true); } catch (final AddressException e) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply address invalid: %s", replyToEmail)); return false; } if (!EmailValidator.getInstance().isValid(replyToEmail)) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply address invalid: %s", replyToEmail)); return false; } replyToEmail = replyToEmail.toLowerCase(); if (replyToEmail.endsWith("localhost") || replyToEmail.endsWith("127.0.0.1")) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply to localhost: %s", replyToEmail)); return false; } return true; } @Autowired MessageFilter(final LoggerContext loggerContext); boolean shouldProcess(final MailMessage message); } | MessageFilter { public boolean shouldProcess(final MailMessage message) { String replyToEmail = message.getReplyToEmail(); if (replyToEmail == null) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, missing reply address")); return false; } try { new InternetAddress(replyToEmail, true); } catch (final AddressException e) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply address invalid: %s", replyToEmail)); return false; } if (!EmailValidator.getInstance().isValid(replyToEmail)) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply address invalid: %s", replyToEmail)); return false; } replyToEmail = replyToEmail.toLowerCase(); if (replyToEmail.endsWith("localhost") || replyToEmail.endsWith("127.0.0.1")) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply to localhost: %s", replyToEmail)); return false; } return true; } @Autowired MessageFilter(final LoggerContext loggerContext); boolean shouldProcess(final MailMessage message); } |
@Test public void shouldProcessFull() throws Exception { when(message.getReplyTo()).thenReturn("Maximus Maxus <[email protected]>"); when(message.getReplyToEmail()).thenReturn("[email protected]"); assertThat(subject.shouldProcess(message), is(true)); } | public boolean shouldProcess(final MailMessage message) { String replyToEmail = message.getReplyToEmail(); if (replyToEmail == null) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, missing reply address")); return false; } try { new InternetAddress(replyToEmail, true); } catch (final AddressException e) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply address invalid: %s", replyToEmail)); return false; } if (!EmailValidator.getInstance().isValid(replyToEmail)) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply address invalid: %s", replyToEmail)); return false; } replyToEmail = replyToEmail.toLowerCase(); if (replyToEmail.endsWith("localhost") || replyToEmail.endsWith("127.0.0.1")) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply to localhost: %s", replyToEmail)); return false; } return true; } | MessageFilter { public boolean shouldProcess(final MailMessage message) { String replyToEmail = message.getReplyToEmail(); if (replyToEmail == null) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, missing reply address")); return false; } try { new InternetAddress(replyToEmail, true); } catch (final AddressException e) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply address invalid: %s", replyToEmail)); return false; } if (!EmailValidator.getInstance().isValid(replyToEmail)) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply address invalid: %s", replyToEmail)); return false; } replyToEmail = replyToEmail.toLowerCase(); if (replyToEmail.endsWith("localhost") || replyToEmail.endsWith("127.0.0.1")) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply to localhost: %s", replyToEmail)); return false; } return true; } } | MessageFilter { public boolean shouldProcess(final MailMessage message) { String replyToEmail = message.getReplyToEmail(); if (replyToEmail == null) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, missing reply address")); return false; } try { new InternetAddress(replyToEmail, true); } catch (final AddressException e) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply address invalid: %s", replyToEmail)); return false; } if (!EmailValidator.getInstance().isValid(replyToEmail)) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply address invalid: %s", replyToEmail)); return false; } replyToEmail = replyToEmail.toLowerCase(); if (replyToEmail.endsWith("localhost") || replyToEmail.endsWith("127.0.0.1")) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply to localhost: %s", replyToEmail)); return false; } return true; } @Autowired MessageFilter(final LoggerContext loggerContext); } | MessageFilter { public boolean shouldProcess(final MailMessage message) { String replyToEmail = message.getReplyToEmail(); if (replyToEmail == null) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, missing reply address")); return false; } try { new InternetAddress(replyToEmail, true); } catch (final AddressException e) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply address invalid: %s", replyToEmail)); return false; } if (!EmailValidator.getInstance().isValid(replyToEmail)) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply address invalid: %s", replyToEmail)); return false; } replyToEmail = replyToEmail.toLowerCase(); if (replyToEmail.endsWith("localhost") || replyToEmail.endsWith("127.0.0.1")) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply to localhost: %s", replyToEmail)); return false; } return true; } @Autowired MessageFilter(final LoggerContext loggerContext); boolean shouldProcess(final MailMessage message); } | MessageFilter { public boolean shouldProcess(final MailMessage message) { String replyToEmail = message.getReplyToEmail(); if (replyToEmail == null) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, missing reply address")); return false; } try { new InternetAddress(replyToEmail, true); } catch (final AddressException e) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply address invalid: %s", replyToEmail)); return false; } if (!EmailValidator.getInstance().isValid(replyToEmail)) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply address invalid: %s", replyToEmail)); return false; } replyToEmail = replyToEmail.toLowerCase(); if (replyToEmail.endsWith("localhost") || replyToEmail.endsWith("127.0.0.1")) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply to localhost: %s", replyToEmail)); return false; } return true; } @Autowired MessageFilter(final LoggerContext loggerContext); boolean shouldProcess(final MailMessage message); } |
@Test public void organisation() { final RpslObject organisation = RpslObject.parse(12, "" + "organisation: ORG-NCC1-RIPE\n" + "org-name: RIPE Network Coordination Centre\n" + "org-type: RIR\n" + "address: RIPE NCC\n" + " Singel 258\n" + " 1016 AB Amsterdam\n" + " Netherlands\n" + "phone: +31 20 535 4444\n" + "fax-no: +31 20 535 4445\n" + "e-mail: [email protected]\n" + "admin-c: AP110-RIPE\n" + "admin-c: CREW-RIPE\n" + "tech-c: CREW-RIPE\n" + "ref-nfy: [email protected]\n" + "mnt-ref: RIPE-NCC-RIS-MNT\n" + "mnt-ref: RIPE-NCC-HM-MNT\n" + "notify: [email protected]\n" + "mnt-by: RIPE-NCC-HM-MNT\n" + "source: RIPE"); final RpslObject dummified = subject.dummify(4, organisation); assertThat(dummified.getAttributes(), containsInAnyOrder( new RpslAttribute("organisation", "ORG-NCC1-RIPE"), new RpslAttribute("org-name", "RIPE Network Coordination Centre"), new RpslAttribute("org-type", "RIR"), new RpslAttribute("address", "RIPE NCC\n" + " Singel 258\n" + " 1016 AB Amsterdam\n" + " Netherlands"), new RpslAttribute("e-mail", "***@ripe.net"), new RpslAttribute("mnt-ref", "RIPE-NCC-RIS-MNT"), new RpslAttribute("mnt-ref", "RIPE-NCC-HM-MNT"), new RpslAttribute("mnt-by", "RIPE-NCC-HM-MNT"), new RpslAttribute("phone", "+31 20 ... ...."), new RpslAttribute("fax-no", "+31 20 ... ...."), new RpslAttribute("admin-c", "AP110-RIPE"), new RpslAttribute("admin-c", "CREW-RIPE"), new RpslAttribute("tech-c", "CREW-RIPE"), new RpslAttribute("ref-nfy", "***@ripe.net"), new RpslAttribute("notify", "***@ripe.net"), new RpslAttribute("source", "RIPE") )); } | @Override public RpslObject dummify(final int version, final RpslObject rpslObject) { final ObjectType objectType = rpslObject.getType(); Validate.isTrue(isAllowed(version, rpslObject), "The version is not supported by this dummifier", version); final List<RpslAttribute> attributes = Lists.newArrayList(rpslObject.getAttributes()); RpslAttribute lastAddressLine = null; int lastAddressLineIndex = 0; for (int i = 0; i < attributes.size(); i++) { RpslAttribute replacement = attributes.get(i); final AttributeType attributeType = replacement.getType(); try { if (!(objectType == ObjectType.ROLE && rpslObject.containsAttribute(ABUSE_MAILBOX))) { replacement = replacePerson(attributeType, replacement); replacement = replaceAuth(attributeType, replacement); replacement = replacePhoneFax(attributeType, replacement); if (attributeType == ADDRESS) { lastAddressLine = replacement; lastAddressLineIndex = i; replacement = new RpslAttribute(ADDRESS, "***"); } } replacement = replaceEmail(attributeType, replacement); attributes.set(i, replacement); } catch (RuntimeException e) { LOGGER.debug("Dummifier failed on [" + attributes.get(i).toString().trim() + "]", e); } } if (lastAddressLine != null) { attributes.set(lastAddressLineIndex, lastAddressLine); } return FILTER_CHANGED_FUNCTION.apply(new RpslObject(rpslObject, attributes)); } | DummifierCurrent implements Dummifier { @Override public RpslObject dummify(final int version, final RpslObject rpslObject) { final ObjectType objectType = rpslObject.getType(); Validate.isTrue(isAllowed(version, rpslObject), "The version is not supported by this dummifier", version); final List<RpslAttribute> attributes = Lists.newArrayList(rpslObject.getAttributes()); RpslAttribute lastAddressLine = null; int lastAddressLineIndex = 0; for (int i = 0; i < attributes.size(); i++) { RpslAttribute replacement = attributes.get(i); final AttributeType attributeType = replacement.getType(); try { if (!(objectType == ObjectType.ROLE && rpslObject.containsAttribute(ABUSE_MAILBOX))) { replacement = replacePerson(attributeType, replacement); replacement = replaceAuth(attributeType, replacement); replacement = replacePhoneFax(attributeType, replacement); if (attributeType == ADDRESS) { lastAddressLine = replacement; lastAddressLineIndex = i; replacement = new RpslAttribute(ADDRESS, "***"); } } replacement = replaceEmail(attributeType, replacement); attributes.set(i, replacement); } catch (RuntimeException e) { LOGGER.debug("Dummifier failed on [" + attributes.get(i).toString().trim() + "]", e); } } if (lastAddressLine != null) { attributes.set(lastAddressLineIndex, lastAddressLine); } return FILTER_CHANGED_FUNCTION.apply(new RpslObject(rpslObject, attributes)); } } | DummifierCurrent implements Dummifier { @Override public RpslObject dummify(final int version, final RpslObject rpslObject) { final ObjectType objectType = rpslObject.getType(); Validate.isTrue(isAllowed(version, rpslObject), "The version is not supported by this dummifier", version); final List<RpslAttribute> attributes = Lists.newArrayList(rpslObject.getAttributes()); RpslAttribute lastAddressLine = null; int lastAddressLineIndex = 0; for (int i = 0; i < attributes.size(); i++) { RpslAttribute replacement = attributes.get(i); final AttributeType attributeType = replacement.getType(); try { if (!(objectType == ObjectType.ROLE && rpslObject.containsAttribute(ABUSE_MAILBOX))) { replacement = replacePerson(attributeType, replacement); replacement = replaceAuth(attributeType, replacement); replacement = replacePhoneFax(attributeType, replacement); if (attributeType == ADDRESS) { lastAddressLine = replacement; lastAddressLineIndex = i; replacement = new RpslAttribute(ADDRESS, "***"); } } replacement = replaceEmail(attributeType, replacement); attributes.set(i, replacement); } catch (RuntimeException e) { LOGGER.debug("Dummifier failed on [" + attributes.get(i).toString().trim() + "]", e); } } if (lastAddressLine != null) { attributes.set(lastAddressLineIndex, lastAddressLine); } return FILTER_CHANGED_FUNCTION.apply(new RpslObject(rpslObject, attributes)); } } | DummifierCurrent implements Dummifier { @Override public RpslObject dummify(final int version, final RpslObject rpslObject) { final ObjectType objectType = rpslObject.getType(); Validate.isTrue(isAllowed(version, rpslObject), "The version is not supported by this dummifier", version); final List<RpslAttribute> attributes = Lists.newArrayList(rpslObject.getAttributes()); RpslAttribute lastAddressLine = null; int lastAddressLineIndex = 0; for (int i = 0; i < attributes.size(); i++) { RpslAttribute replacement = attributes.get(i); final AttributeType attributeType = replacement.getType(); try { if (!(objectType == ObjectType.ROLE && rpslObject.containsAttribute(ABUSE_MAILBOX))) { replacement = replacePerson(attributeType, replacement); replacement = replaceAuth(attributeType, replacement); replacement = replacePhoneFax(attributeType, replacement); if (attributeType == ADDRESS) { lastAddressLine = replacement; lastAddressLineIndex = i; replacement = new RpslAttribute(ADDRESS, "***"); } } replacement = replaceEmail(attributeType, replacement); attributes.set(i, replacement); } catch (RuntimeException e) { LOGGER.debug("Dummifier failed on [" + attributes.get(i).toString().trim() + "]", e); } } if (lastAddressLine != null) { attributes.set(lastAddressLineIndex, lastAddressLine); } return FILTER_CHANGED_FUNCTION.apply(new RpslObject(rpslObject, attributes)); } @Override RpslObject dummify(final int version, final RpslObject rpslObject); @Override boolean isAllowed(final int version, final RpslObject object); } | DummifierCurrent implements Dummifier { @Override public RpslObject dummify(final int version, final RpslObject rpslObject) { final ObjectType objectType = rpslObject.getType(); Validate.isTrue(isAllowed(version, rpslObject), "The version is not supported by this dummifier", version); final List<RpslAttribute> attributes = Lists.newArrayList(rpslObject.getAttributes()); RpslAttribute lastAddressLine = null; int lastAddressLineIndex = 0; for (int i = 0; i < attributes.size(); i++) { RpslAttribute replacement = attributes.get(i); final AttributeType attributeType = replacement.getType(); try { if (!(objectType == ObjectType.ROLE && rpslObject.containsAttribute(ABUSE_MAILBOX))) { replacement = replacePerson(attributeType, replacement); replacement = replaceAuth(attributeType, replacement); replacement = replacePhoneFax(attributeType, replacement); if (attributeType == ADDRESS) { lastAddressLine = replacement; lastAddressLineIndex = i; replacement = new RpslAttribute(ADDRESS, "***"); } } replacement = replaceEmail(attributeType, replacement); attributes.set(i, replacement); } catch (RuntimeException e) { LOGGER.debug("Dummifier failed on [" + attributes.get(i).toString().trim() + "]", e); } } if (lastAddressLine != null) { attributes.set(lastAddressLineIndex, lastAddressLine); } return FILTER_CHANGED_FUNCTION.apply(new RpslObject(rpslObject, attributes)); } @Override RpslObject dummify(final int version, final RpslObject rpslObject); @Override boolean isAllowed(final int version, final RpslObject object); } |
@Test public void shouldProcess_localhost() throws Exception { when(message.getReplyTo()).thenReturn("something@localhost"); when(message.getReplyToEmail()).thenReturn("something@localhost"); assertThat(subject.shouldProcess(message), is(false)); } | public boolean shouldProcess(final MailMessage message) { String replyToEmail = message.getReplyToEmail(); if (replyToEmail == null) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, missing reply address")); return false; } try { new InternetAddress(replyToEmail, true); } catch (final AddressException e) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply address invalid: %s", replyToEmail)); return false; } if (!EmailValidator.getInstance().isValid(replyToEmail)) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply address invalid: %s", replyToEmail)); return false; } replyToEmail = replyToEmail.toLowerCase(); if (replyToEmail.endsWith("localhost") || replyToEmail.endsWith("127.0.0.1")) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply to localhost: %s", replyToEmail)); return false; } return true; } | MessageFilter { public boolean shouldProcess(final MailMessage message) { String replyToEmail = message.getReplyToEmail(); if (replyToEmail == null) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, missing reply address")); return false; } try { new InternetAddress(replyToEmail, true); } catch (final AddressException e) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply address invalid: %s", replyToEmail)); return false; } if (!EmailValidator.getInstance().isValid(replyToEmail)) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply address invalid: %s", replyToEmail)); return false; } replyToEmail = replyToEmail.toLowerCase(); if (replyToEmail.endsWith("localhost") || replyToEmail.endsWith("127.0.0.1")) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply to localhost: %s", replyToEmail)); return false; } return true; } } | MessageFilter { public boolean shouldProcess(final MailMessage message) { String replyToEmail = message.getReplyToEmail(); if (replyToEmail == null) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, missing reply address")); return false; } try { new InternetAddress(replyToEmail, true); } catch (final AddressException e) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply address invalid: %s", replyToEmail)); return false; } if (!EmailValidator.getInstance().isValid(replyToEmail)) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply address invalid: %s", replyToEmail)); return false; } replyToEmail = replyToEmail.toLowerCase(); if (replyToEmail.endsWith("localhost") || replyToEmail.endsWith("127.0.0.1")) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply to localhost: %s", replyToEmail)); return false; } return true; } @Autowired MessageFilter(final LoggerContext loggerContext); } | MessageFilter { public boolean shouldProcess(final MailMessage message) { String replyToEmail = message.getReplyToEmail(); if (replyToEmail == null) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, missing reply address")); return false; } try { new InternetAddress(replyToEmail, true); } catch (final AddressException e) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply address invalid: %s", replyToEmail)); return false; } if (!EmailValidator.getInstance().isValid(replyToEmail)) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply address invalid: %s", replyToEmail)); return false; } replyToEmail = replyToEmail.toLowerCase(); if (replyToEmail.endsWith("localhost") || replyToEmail.endsWith("127.0.0.1")) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply to localhost: %s", replyToEmail)); return false; } return true; } @Autowired MessageFilter(final LoggerContext loggerContext); boolean shouldProcess(final MailMessage message); } | MessageFilter { public boolean shouldProcess(final MailMessage message) { String replyToEmail = message.getReplyToEmail(); if (replyToEmail == null) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, missing reply address")); return false; } try { new InternetAddress(replyToEmail, true); } catch (final AddressException e) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply address invalid: %s", replyToEmail)); return false; } if (!EmailValidator.getInstance().isValid(replyToEmail)) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply address invalid: %s", replyToEmail)); return false; } replyToEmail = replyToEmail.toLowerCase(); if (replyToEmail.endsWith("localhost") || replyToEmail.endsWith("127.0.0.1")) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply to localhost: %s", replyToEmail)); return false; } return true; } @Autowired MessageFilter(final LoggerContext loggerContext); boolean shouldProcess(final MailMessage message); } |
@Test public void shouldProcess_127_0_0_1() throws Exception { when(message.getReplyTo()).thenReturn("[email protected]"); when(message.getReplyToEmail()).thenReturn("[email protected]"); assertThat(subject.shouldProcess(message), is(false)); } | public boolean shouldProcess(final MailMessage message) { String replyToEmail = message.getReplyToEmail(); if (replyToEmail == null) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, missing reply address")); return false; } try { new InternetAddress(replyToEmail, true); } catch (final AddressException e) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply address invalid: %s", replyToEmail)); return false; } if (!EmailValidator.getInstance().isValid(replyToEmail)) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply address invalid: %s", replyToEmail)); return false; } replyToEmail = replyToEmail.toLowerCase(); if (replyToEmail.endsWith("localhost") || replyToEmail.endsWith("127.0.0.1")) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply to localhost: %s", replyToEmail)); return false; } return true; } | MessageFilter { public boolean shouldProcess(final MailMessage message) { String replyToEmail = message.getReplyToEmail(); if (replyToEmail == null) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, missing reply address")); return false; } try { new InternetAddress(replyToEmail, true); } catch (final AddressException e) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply address invalid: %s", replyToEmail)); return false; } if (!EmailValidator.getInstance().isValid(replyToEmail)) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply address invalid: %s", replyToEmail)); return false; } replyToEmail = replyToEmail.toLowerCase(); if (replyToEmail.endsWith("localhost") || replyToEmail.endsWith("127.0.0.1")) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply to localhost: %s", replyToEmail)); return false; } return true; } } | MessageFilter { public boolean shouldProcess(final MailMessage message) { String replyToEmail = message.getReplyToEmail(); if (replyToEmail == null) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, missing reply address")); return false; } try { new InternetAddress(replyToEmail, true); } catch (final AddressException e) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply address invalid: %s", replyToEmail)); return false; } if (!EmailValidator.getInstance().isValid(replyToEmail)) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply address invalid: %s", replyToEmail)); return false; } replyToEmail = replyToEmail.toLowerCase(); if (replyToEmail.endsWith("localhost") || replyToEmail.endsWith("127.0.0.1")) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply to localhost: %s", replyToEmail)); return false; } return true; } @Autowired MessageFilter(final LoggerContext loggerContext); } | MessageFilter { public boolean shouldProcess(final MailMessage message) { String replyToEmail = message.getReplyToEmail(); if (replyToEmail == null) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, missing reply address")); return false; } try { new InternetAddress(replyToEmail, true); } catch (final AddressException e) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply address invalid: %s", replyToEmail)); return false; } if (!EmailValidator.getInstance().isValid(replyToEmail)) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply address invalid: %s", replyToEmail)); return false; } replyToEmail = replyToEmail.toLowerCase(); if (replyToEmail.endsWith("localhost") || replyToEmail.endsWith("127.0.0.1")) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply to localhost: %s", replyToEmail)); return false; } return true; } @Autowired MessageFilter(final LoggerContext loggerContext); boolean shouldProcess(final MailMessage message); } | MessageFilter { public boolean shouldProcess(final MailMessage message) { String replyToEmail = message.getReplyToEmail(); if (replyToEmail == null) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, missing reply address")); return false; } try { new InternetAddress(replyToEmail, true); } catch (final AddressException e) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply address invalid: %s", replyToEmail)); return false; } if (!EmailValidator.getInstance().isValid(replyToEmail)) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply address invalid: %s", replyToEmail)); return false; } replyToEmail = replyToEmail.toLowerCase(); if (replyToEmail.endsWith("localhost") || replyToEmail.endsWith("127.0.0.1")) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply to localhost: %s", replyToEmail)); return false; } return true; } @Autowired MessageFilter(final LoggerContext loggerContext); boolean shouldProcess(final MailMessage message); } |
@Test public void noReplytoFails() throws Exception { when(message.getReplyTo()).thenReturn(null); when(message.getReplyToEmail()).thenReturn(null); assertThat(subject.shouldProcess(message), is(false)); } | public boolean shouldProcess(final MailMessage message) { String replyToEmail = message.getReplyToEmail(); if (replyToEmail == null) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, missing reply address")); return false; } try { new InternetAddress(replyToEmail, true); } catch (final AddressException e) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply address invalid: %s", replyToEmail)); return false; } if (!EmailValidator.getInstance().isValid(replyToEmail)) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply address invalid: %s", replyToEmail)); return false; } replyToEmail = replyToEmail.toLowerCase(); if (replyToEmail.endsWith("localhost") || replyToEmail.endsWith("127.0.0.1")) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply to localhost: %s", replyToEmail)); return false; } return true; } | MessageFilter { public boolean shouldProcess(final MailMessage message) { String replyToEmail = message.getReplyToEmail(); if (replyToEmail == null) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, missing reply address")); return false; } try { new InternetAddress(replyToEmail, true); } catch (final AddressException e) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply address invalid: %s", replyToEmail)); return false; } if (!EmailValidator.getInstance().isValid(replyToEmail)) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply address invalid: %s", replyToEmail)); return false; } replyToEmail = replyToEmail.toLowerCase(); if (replyToEmail.endsWith("localhost") || replyToEmail.endsWith("127.0.0.1")) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply to localhost: %s", replyToEmail)); return false; } return true; } } | MessageFilter { public boolean shouldProcess(final MailMessage message) { String replyToEmail = message.getReplyToEmail(); if (replyToEmail == null) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, missing reply address")); return false; } try { new InternetAddress(replyToEmail, true); } catch (final AddressException e) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply address invalid: %s", replyToEmail)); return false; } if (!EmailValidator.getInstance().isValid(replyToEmail)) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply address invalid: %s", replyToEmail)); return false; } replyToEmail = replyToEmail.toLowerCase(); if (replyToEmail.endsWith("localhost") || replyToEmail.endsWith("127.0.0.1")) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply to localhost: %s", replyToEmail)); return false; } return true; } @Autowired MessageFilter(final LoggerContext loggerContext); } | MessageFilter { public boolean shouldProcess(final MailMessage message) { String replyToEmail = message.getReplyToEmail(); if (replyToEmail == null) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, missing reply address")); return false; } try { new InternetAddress(replyToEmail, true); } catch (final AddressException e) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply address invalid: %s", replyToEmail)); return false; } if (!EmailValidator.getInstance().isValid(replyToEmail)) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply address invalid: %s", replyToEmail)); return false; } replyToEmail = replyToEmail.toLowerCase(); if (replyToEmail.endsWith("localhost") || replyToEmail.endsWith("127.0.0.1")) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply to localhost: %s", replyToEmail)); return false; } return true; } @Autowired MessageFilter(final LoggerContext loggerContext); boolean shouldProcess(final MailMessage message); } | MessageFilter { public boolean shouldProcess(final MailMessage message) { String replyToEmail = message.getReplyToEmail(); if (replyToEmail == null) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, missing reply address")); return false; } try { new InternetAddress(replyToEmail, true); } catch (final AddressException e) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply address invalid: %s", replyToEmail)); return false; } if (!EmailValidator.getInstance().isValid(replyToEmail)) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply address invalid: %s", replyToEmail)); return false; } replyToEmail = replyToEmail.toLowerCase(); if (replyToEmail.endsWith("localhost") || replyToEmail.endsWith("127.0.0.1")) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply to localhost: %s", replyToEmail)); return false; } return true; } @Autowired MessageFilter(final LoggerContext loggerContext); boolean shouldProcess(final MailMessage message); } |
@Test public void noReplytoFailsFull() throws Exception { when(message.getReplyTo()).thenReturn("Maximus Maxus"); when(message.getReplyToEmail()).thenReturn(null); assertThat(subject.shouldProcess(message), is(false)); } | public boolean shouldProcess(final MailMessage message) { String replyToEmail = message.getReplyToEmail(); if (replyToEmail == null) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, missing reply address")); return false; } try { new InternetAddress(replyToEmail, true); } catch (final AddressException e) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply address invalid: %s", replyToEmail)); return false; } if (!EmailValidator.getInstance().isValid(replyToEmail)) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply address invalid: %s", replyToEmail)); return false; } replyToEmail = replyToEmail.toLowerCase(); if (replyToEmail.endsWith("localhost") || replyToEmail.endsWith("127.0.0.1")) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply to localhost: %s", replyToEmail)); return false; } return true; } | MessageFilter { public boolean shouldProcess(final MailMessage message) { String replyToEmail = message.getReplyToEmail(); if (replyToEmail == null) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, missing reply address")); return false; } try { new InternetAddress(replyToEmail, true); } catch (final AddressException e) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply address invalid: %s", replyToEmail)); return false; } if (!EmailValidator.getInstance().isValid(replyToEmail)) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply address invalid: %s", replyToEmail)); return false; } replyToEmail = replyToEmail.toLowerCase(); if (replyToEmail.endsWith("localhost") || replyToEmail.endsWith("127.0.0.1")) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply to localhost: %s", replyToEmail)); return false; } return true; } } | MessageFilter { public boolean shouldProcess(final MailMessage message) { String replyToEmail = message.getReplyToEmail(); if (replyToEmail == null) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, missing reply address")); return false; } try { new InternetAddress(replyToEmail, true); } catch (final AddressException e) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply address invalid: %s", replyToEmail)); return false; } if (!EmailValidator.getInstance().isValid(replyToEmail)) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply address invalid: %s", replyToEmail)); return false; } replyToEmail = replyToEmail.toLowerCase(); if (replyToEmail.endsWith("localhost") || replyToEmail.endsWith("127.0.0.1")) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply to localhost: %s", replyToEmail)); return false; } return true; } @Autowired MessageFilter(final LoggerContext loggerContext); } | MessageFilter { public boolean shouldProcess(final MailMessage message) { String replyToEmail = message.getReplyToEmail(); if (replyToEmail == null) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, missing reply address")); return false; } try { new InternetAddress(replyToEmail, true); } catch (final AddressException e) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply address invalid: %s", replyToEmail)); return false; } if (!EmailValidator.getInstance().isValid(replyToEmail)) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply address invalid: %s", replyToEmail)); return false; } replyToEmail = replyToEmail.toLowerCase(); if (replyToEmail.endsWith("localhost") || replyToEmail.endsWith("127.0.0.1")) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply to localhost: %s", replyToEmail)); return false; } return true; } @Autowired MessageFilter(final LoggerContext loggerContext); boolean shouldProcess(final MailMessage message); } | MessageFilter { public boolean shouldProcess(final MailMessage message) { String replyToEmail = message.getReplyToEmail(); if (replyToEmail == null) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, missing reply address")); return false; } try { new InternetAddress(replyToEmail, true); } catch (final AddressException e) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply address invalid: %s", replyToEmail)); return false; } if (!EmailValidator.getInstance().isValid(replyToEmail)) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply address invalid: %s", replyToEmail)); return false; } replyToEmail = replyToEmail.toLowerCase(); if (replyToEmail.endsWith("localhost") || replyToEmail.endsWith("127.0.0.1")) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply to localhost: %s", replyToEmail)); return false; } return true; } @Autowired MessageFilter(final LoggerContext loggerContext); boolean shouldProcess(final MailMessage message); } |
@Test public void invalidReplytoFails() throws Exception { when(message.getReplyTo()).thenReturn("email_with_no_domain_or_at_sign"); when(message.getReplyToEmail()).thenReturn("email_with_no_domain_or_at_sign"); assertThat(subject.shouldProcess(message), is(false)); } | public boolean shouldProcess(final MailMessage message) { String replyToEmail = message.getReplyToEmail(); if (replyToEmail == null) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, missing reply address")); return false; } try { new InternetAddress(replyToEmail, true); } catch (final AddressException e) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply address invalid: %s", replyToEmail)); return false; } if (!EmailValidator.getInstance().isValid(replyToEmail)) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply address invalid: %s", replyToEmail)); return false; } replyToEmail = replyToEmail.toLowerCase(); if (replyToEmail.endsWith("localhost") || replyToEmail.endsWith("127.0.0.1")) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply to localhost: %s", replyToEmail)); return false; } return true; } | MessageFilter { public boolean shouldProcess(final MailMessage message) { String replyToEmail = message.getReplyToEmail(); if (replyToEmail == null) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, missing reply address")); return false; } try { new InternetAddress(replyToEmail, true); } catch (final AddressException e) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply address invalid: %s", replyToEmail)); return false; } if (!EmailValidator.getInstance().isValid(replyToEmail)) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply address invalid: %s", replyToEmail)); return false; } replyToEmail = replyToEmail.toLowerCase(); if (replyToEmail.endsWith("localhost") || replyToEmail.endsWith("127.0.0.1")) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply to localhost: %s", replyToEmail)); return false; } return true; } } | MessageFilter { public boolean shouldProcess(final MailMessage message) { String replyToEmail = message.getReplyToEmail(); if (replyToEmail == null) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, missing reply address")); return false; } try { new InternetAddress(replyToEmail, true); } catch (final AddressException e) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply address invalid: %s", replyToEmail)); return false; } if (!EmailValidator.getInstance().isValid(replyToEmail)) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply address invalid: %s", replyToEmail)); return false; } replyToEmail = replyToEmail.toLowerCase(); if (replyToEmail.endsWith("localhost") || replyToEmail.endsWith("127.0.0.1")) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply to localhost: %s", replyToEmail)); return false; } return true; } @Autowired MessageFilter(final LoggerContext loggerContext); } | MessageFilter { public boolean shouldProcess(final MailMessage message) { String replyToEmail = message.getReplyToEmail(); if (replyToEmail == null) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, missing reply address")); return false; } try { new InternetAddress(replyToEmail, true); } catch (final AddressException e) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply address invalid: %s", replyToEmail)); return false; } if (!EmailValidator.getInstance().isValid(replyToEmail)) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply address invalid: %s", replyToEmail)); return false; } replyToEmail = replyToEmail.toLowerCase(); if (replyToEmail.endsWith("localhost") || replyToEmail.endsWith("127.0.0.1")) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply to localhost: %s", replyToEmail)); return false; } return true; } @Autowired MessageFilter(final LoggerContext loggerContext); boolean shouldProcess(final MailMessage message); } | MessageFilter { public boolean shouldProcess(final MailMessage message) { String replyToEmail = message.getReplyToEmail(); if (replyToEmail == null) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, missing reply address")); return false; } try { new InternetAddress(replyToEmail, true); } catch (final AddressException e) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply address invalid: %s", replyToEmail)); return false; } if (!EmailValidator.getInstance().isValid(replyToEmail)) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply address invalid: %s", replyToEmail)); return false; } replyToEmail = replyToEmail.toLowerCase(); if (replyToEmail.endsWith("localhost") || replyToEmail.endsWith("127.0.0.1")) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply to localhost: %s", replyToEmail)); return false; } return true; } @Autowired MessageFilter(final LoggerContext loggerContext); boolean shouldProcess(final MailMessage message); } |
@Test public void invalidReplytoFailsFull() throws Exception { when(message.getReplyTo()).thenReturn("Minima Mina <email_with_no_domain_or_at_sign>"); when(message.getReplyToEmail()).thenReturn("email_with_no_domain_or_at_sign"); assertThat(subject.shouldProcess(message), is(false)); } | public boolean shouldProcess(final MailMessage message) { String replyToEmail = message.getReplyToEmail(); if (replyToEmail == null) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, missing reply address")); return false; } try { new InternetAddress(replyToEmail, true); } catch (final AddressException e) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply address invalid: %s", replyToEmail)); return false; } if (!EmailValidator.getInstance().isValid(replyToEmail)) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply address invalid: %s", replyToEmail)); return false; } replyToEmail = replyToEmail.toLowerCase(); if (replyToEmail.endsWith("localhost") || replyToEmail.endsWith("127.0.0.1")) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply to localhost: %s", replyToEmail)); return false; } return true; } | MessageFilter { public boolean shouldProcess(final MailMessage message) { String replyToEmail = message.getReplyToEmail(); if (replyToEmail == null) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, missing reply address")); return false; } try { new InternetAddress(replyToEmail, true); } catch (final AddressException e) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply address invalid: %s", replyToEmail)); return false; } if (!EmailValidator.getInstance().isValid(replyToEmail)) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply address invalid: %s", replyToEmail)); return false; } replyToEmail = replyToEmail.toLowerCase(); if (replyToEmail.endsWith("localhost") || replyToEmail.endsWith("127.0.0.1")) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply to localhost: %s", replyToEmail)); return false; } return true; } } | MessageFilter { public boolean shouldProcess(final MailMessage message) { String replyToEmail = message.getReplyToEmail(); if (replyToEmail == null) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, missing reply address")); return false; } try { new InternetAddress(replyToEmail, true); } catch (final AddressException e) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply address invalid: %s", replyToEmail)); return false; } if (!EmailValidator.getInstance().isValid(replyToEmail)) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply address invalid: %s", replyToEmail)); return false; } replyToEmail = replyToEmail.toLowerCase(); if (replyToEmail.endsWith("localhost") || replyToEmail.endsWith("127.0.0.1")) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply to localhost: %s", replyToEmail)); return false; } return true; } @Autowired MessageFilter(final LoggerContext loggerContext); } | MessageFilter { public boolean shouldProcess(final MailMessage message) { String replyToEmail = message.getReplyToEmail(); if (replyToEmail == null) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, missing reply address")); return false; } try { new InternetAddress(replyToEmail, true); } catch (final AddressException e) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply address invalid: %s", replyToEmail)); return false; } if (!EmailValidator.getInstance().isValid(replyToEmail)) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply address invalid: %s", replyToEmail)); return false; } replyToEmail = replyToEmail.toLowerCase(); if (replyToEmail.endsWith("localhost") || replyToEmail.endsWith("127.0.0.1")) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply to localhost: %s", replyToEmail)); return false; } return true; } @Autowired MessageFilter(final LoggerContext loggerContext); boolean shouldProcess(final MailMessage message); } | MessageFilter { public boolean shouldProcess(final MailMessage message) { String replyToEmail = message.getReplyToEmail(); if (replyToEmail == null) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, missing reply address")); return false; } try { new InternetAddress(replyToEmail, true); } catch (final AddressException e) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply address invalid: %s", replyToEmail)); return false; } if (!EmailValidator.getInstance().isValid(replyToEmail)) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply address invalid: %s", replyToEmail)); return false; } replyToEmail = replyToEmail.toLowerCase(); if (replyToEmail.endsWith("localhost") || replyToEmail.endsWith("127.0.0.1")) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply to localhost: %s", replyToEmail)); return false; } return true; } @Autowired MessageFilter(final LoggerContext loggerContext); boolean shouldProcess(final MailMessage message); } |
@Test(expected = IllegalStateException.class) public void start_twice() { when(mailMessageDao.claimMessage()).thenReturn(null); subject.start(); subject.start(); } | @Override public void start() { if (handlerExecutor != null || pollerExecutor != null) { throw new IllegalStateException("Already started"); } if (nrThreads > 0) { freeThreads.set(nrThreads); handlerExecutor = Executors.newFixedThreadPool(nrThreads); pollerExecutor = Executors.newSingleThreadScheduledExecutor(); pollerExecutor.scheduleWithFixedDelay(new MessagePoller(), intervalMs, intervalMs, TimeUnit.MILLISECONDS); LOGGER.info("Message dequeue started"); } } | MessageDequeue implements ApplicationService { @Override public void start() { if (handlerExecutor != null || pollerExecutor != null) { throw new IllegalStateException("Already started"); } if (nrThreads > 0) { freeThreads.set(nrThreads); handlerExecutor = Executors.newFixedThreadPool(nrThreads); pollerExecutor = Executors.newSingleThreadScheduledExecutor(); pollerExecutor.scheduleWithFixedDelay(new MessagePoller(), intervalMs, intervalMs, TimeUnit.MILLISECONDS); LOGGER.info("Message dequeue started"); } } } | MessageDequeue implements ApplicationService { @Override public void start() { if (handlerExecutor != null || pollerExecutor != null) { throw new IllegalStateException("Already started"); } if (nrThreads > 0) { freeThreads.set(nrThreads); handlerExecutor = Executors.newFixedThreadPool(nrThreads); pollerExecutor = Executors.newSingleThreadScheduledExecutor(); pollerExecutor.scheduleWithFixedDelay(new MessagePoller(), intervalMs, intervalMs, TimeUnit.MILLISECONDS); LOGGER.info("Message dequeue started"); } } @Autowired MessageDequeue(final MaintenanceMode maintenanceMode,
final MailGateway mailGateway,
final MailMessageDao mailMessageDao,
final MessageFilter messageFilter,
final MessageParser messageParser,
final UpdatesParser updatesParser,
final UpdateRequestHandler messageHandler,
final LoggerContext loggerContext,
final DateTimeProvider dateTimeProvider); } | MessageDequeue implements ApplicationService { @Override public void start() { if (handlerExecutor != null || pollerExecutor != null) { throw new IllegalStateException("Already started"); } if (nrThreads > 0) { freeThreads.set(nrThreads); handlerExecutor = Executors.newFixedThreadPool(nrThreads); pollerExecutor = Executors.newSingleThreadScheduledExecutor(); pollerExecutor.scheduleWithFixedDelay(new MessagePoller(), intervalMs, intervalMs, TimeUnit.MILLISECONDS); LOGGER.info("Message dequeue started"); } } @Autowired MessageDequeue(final MaintenanceMode maintenanceMode,
final MailGateway mailGateway,
final MailMessageDao mailMessageDao,
final MessageFilter messageFilter,
final MessageParser messageParser,
final UpdatesParser updatesParser,
final UpdateRequestHandler messageHandler,
final LoggerContext loggerContext,
final DateTimeProvider dateTimeProvider); @Override void start(); @Override void stop(final boolean force); } | MessageDequeue implements ApplicationService { @Override public void start() { if (handlerExecutor != null || pollerExecutor != null) { throw new IllegalStateException("Already started"); } if (nrThreads > 0) { freeThreads.set(nrThreads); handlerExecutor = Executors.newFixedThreadPool(nrThreads); pollerExecutor = Executors.newSingleThreadScheduledExecutor(); pollerExecutor.scheduleWithFixedDelay(new MessagePoller(), intervalMs, intervalMs, TimeUnit.MILLISECONDS); LOGGER.info("Message dequeue started"); } } @Autowired MessageDequeue(final MaintenanceMode maintenanceMode,
final MailGateway mailGateway,
final MailMessageDao mailMessageDao,
final MessageFilter messageFilter,
final MessageParser messageParser,
final UpdatesParser updatesParser,
final UpdateRequestHandler messageHandler,
final LoggerContext loggerContext,
final DateTimeProvider dateTimeProvider); @Override void start(); @Override void stop(final boolean force); } |
@Test public void stop_not_running() throws InterruptedException { subject.stop(true); } | @Override public void stop(final boolean force) { LOGGER.info("Message dequeue stopping"); if (stopExecutor(pollerExecutor)) { pollerExecutor = null; } if (stopExecutor(handlerExecutor)) { handlerExecutor = null; } LOGGER.info("Message dequeue stopped"); } | MessageDequeue implements ApplicationService { @Override public void stop(final boolean force) { LOGGER.info("Message dequeue stopping"); if (stopExecutor(pollerExecutor)) { pollerExecutor = null; } if (stopExecutor(handlerExecutor)) { handlerExecutor = null; } LOGGER.info("Message dequeue stopped"); } } | MessageDequeue implements ApplicationService { @Override public void stop(final boolean force) { LOGGER.info("Message dequeue stopping"); if (stopExecutor(pollerExecutor)) { pollerExecutor = null; } if (stopExecutor(handlerExecutor)) { handlerExecutor = null; } LOGGER.info("Message dequeue stopped"); } @Autowired MessageDequeue(final MaintenanceMode maintenanceMode,
final MailGateway mailGateway,
final MailMessageDao mailMessageDao,
final MessageFilter messageFilter,
final MessageParser messageParser,
final UpdatesParser updatesParser,
final UpdateRequestHandler messageHandler,
final LoggerContext loggerContext,
final DateTimeProvider dateTimeProvider); } | MessageDequeue implements ApplicationService { @Override public void stop(final boolean force) { LOGGER.info("Message dequeue stopping"); if (stopExecutor(pollerExecutor)) { pollerExecutor = null; } if (stopExecutor(handlerExecutor)) { handlerExecutor = null; } LOGGER.info("Message dequeue stopped"); } @Autowired MessageDequeue(final MaintenanceMode maintenanceMode,
final MailGateway mailGateway,
final MailMessageDao mailMessageDao,
final MessageFilter messageFilter,
final MessageParser messageParser,
final UpdatesParser updatesParser,
final UpdateRequestHandler messageHandler,
final LoggerContext loggerContext,
final DateTimeProvider dateTimeProvider); @Override void start(); @Override void stop(final boolean force); } | MessageDequeue implements ApplicationService { @Override public void stop(final boolean force) { LOGGER.info("Message dequeue stopping"); if (stopExecutor(pollerExecutor)) { pollerExecutor = null; } if (stopExecutor(handlerExecutor)) { handlerExecutor = null; } LOGGER.info("Message dequeue stopped"); } @Autowired MessageDequeue(final MaintenanceMode maintenanceMode,
final MailGateway mailGateway,
final MailMessageDao mailMessageDao,
final MessageFilter messageFilter,
final MessageParser messageParser,
final UpdatesParser updatesParser,
final UpdateRequestHandler messageHandler,
final LoggerContext loggerContext,
final DateTimeProvider dateTimeProvider); @Override void start(); @Override void stop(final boolean force); } |
@Test public void noMessages() { when(mailMessageDao.claimMessage()).thenReturn(null); subject.start(); verifyZeroInteractions(messageHandler); } | @Override public void start() { if (handlerExecutor != null || pollerExecutor != null) { throw new IllegalStateException("Already started"); } if (nrThreads > 0) { freeThreads.set(nrThreads); handlerExecutor = Executors.newFixedThreadPool(nrThreads); pollerExecutor = Executors.newSingleThreadScheduledExecutor(); pollerExecutor.scheduleWithFixedDelay(new MessagePoller(), intervalMs, intervalMs, TimeUnit.MILLISECONDS); LOGGER.info("Message dequeue started"); } } | MessageDequeue implements ApplicationService { @Override public void start() { if (handlerExecutor != null || pollerExecutor != null) { throw new IllegalStateException("Already started"); } if (nrThreads > 0) { freeThreads.set(nrThreads); handlerExecutor = Executors.newFixedThreadPool(nrThreads); pollerExecutor = Executors.newSingleThreadScheduledExecutor(); pollerExecutor.scheduleWithFixedDelay(new MessagePoller(), intervalMs, intervalMs, TimeUnit.MILLISECONDS); LOGGER.info("Message dequeue started"); } } } | MessageDequeue implements ApplicationService { @Override public void start() { if (handlerExecutor != null || pollerExecutor != null) { throw new IllegalStateException("Already started"); } if (nrThreads > 0) { freeThreads.set(nrThreads); handlerExecutor = Executors.newFixedThreadPool(nrThreads); pollerExecutor = Executors.newSingleThreadScheduledExecutor(); pollerExecutor.scheduleWithFixedDelay(new MessagePoller(), intervalMs, intervalMs, TimeUnit.MILLISECONDS); LOGGER.info("Message dequeue started"); } } @Autowired MessageDequeue(final MaintenanceMode maintenanceMode,
final MailGateway mailGateway,
final MailMessageDao mailMessageDao,
final MessageFilter messageFilter,
final MessageParser messageParser,
final UpdatesParser updatesParser,
final UpdateRequestHandler messageHandler,
final LoggerContext loggerContext,
final DateTimeProvider dateTimeProvider); } | MessageDequeue implements ApplicationService { @Override public void start() { if (handlerExecutor != null || pollerExecutor != null) { throw new IllegalStateException("Already started"); } if (nrThreads > 0) { freeThreads.set(nrThreads); handlerExecutor = Executors.newFixedThreadPool(nrThreads); pollerExecutor = Executors.newSingleThreadScheduledExecutor(); pollerExecutor.scheduleWithFixedDelay(new MessagePoller(), intervalMs, intervalMs, TimeUnit.MILLISECONDS); LOGGER.info("Message dequeue started"); } } @Autowired MessageDequeue(final MaintenanceMode maintenanceMode,
final MailGateway mailGateway,
final MailMessageDao mailMessageDao,
final MessageFilter messageFilter,
final MessageParser messageParser,
final UpdatesParser updatesParser,
final UpdateRequestHandler messageHandler,
final LoggerContext loggerContext,
final DateTimeProvider dateTimeProvider); @Override void start(); @Override void stop(final boolean force); } | MessageDequeue implements ApplicationService { @Override public void start() { if (handlerExecutor != null || pollerExecutor != null) { throw new IllegalStateException("Already started"); } if (nrThreads > 0) { freeThreads.set(nrThreads); handlerExecutor = Executors.newFixedThreadPool(nrThreads); pollerExecutor = Executors.newSingleThreadScheduledExecutor(); pollerExecutor.scheduleWithFixedDelay(new MessagePoller(), intervalMs, intervalMs, TimeUnit.MILLISECONDS); LOGGER.info("Message dequeue started"); } } @Autowired MessageDequeue(final MaintenanceMode maintenanceMode,
final MailGateway mailGateway,
final MailMessageDao mailMessageDao,
final MessageFilter messageFilter,
final MessageParser messageParser,
final UpdatesParser updatesParser,
final UpdateRequestHandler messageHandler,
final LoggerContext loggerContext,
final DateTimeProvider dateTimeProvider); @Override void start(); @Override void stop(final boolean force); } |
@Test public void handleMessage_filtered() throws Exception { final MimeMessage message = MimeMessageProvider.getMessageSimpleTextUnsigned(); when(messageFilter.shouldProcess(any(MailMessage.class))).thenReturn(false); when(mailMessageDao.getMessage("1")).thenReturn(message); when(mailMessageDao.claimMessage()).thenReturn("1").thenReturn(null); subject.start(); verify(mailMessageDao, timeout(TIMEOUT)).deleteMessage("1"); verify(loggerContext, timeout(TIMEOUT)).init("20120527220444.GA6565"); verify(loggerContext, timeout(TIMEOUT)).log(eq("msg-in.txt"), any(MailMessageLogCallback.class)); verify(mailMessageDao, timeout(TIMEOUT)).setStatus("1", DequeueStatus.LOGGED); verify(mailMessageDao, timeout(TIMEOUT)).setStatus("1", DequeueStatus.PARSED); verifyZeroInteractions(messageHandler); } | @Override public void start() { if (handlerExecutor != null || pollerExecutor != null) { throw new IllegalStateException("Already started"); } if (nrThreads > 0) { freeThreads.set(nrThreads); handlerExecutor = Executors.newFixedThreadPool(nrThreads); pollerExecutor = Executors.newSingleThreadScheduledExecutor(); pollerExecutor.scheduleWithFixedDelay(new MessagePoller(), intervalMs, intervalMs, TimeUnit.MILLISECONDS); LOGGER.info("Message dequeue started"); } } | MessageDequeue implements ApplicationService { @Override public void start() { if (handlerExecutor != null || pollerExecutor != null) { throw new IllegalStateException("Already started"); } if (nrThreads > 0) { freeThreads.set(nrThreads); handlerExecutor = Executors.newFixedThreadPool(nrThreads); pollerExecutor = Executors.newSingleThreadScheduledExecutor(); pollerExecutor.scheduleWithFixedDelay(new MessagePoller(), intervalMs, intervalMs, TimeUnit.MILLISECONDS); LOGGER.info("Message dequeue started"); } } } | MessageDequeue implements ApplicationService { @Override public void start() { if (handlerExecutor != null || pollerExecutor != null) { throw new IllegalStateException("Already started"); } if (nrThreads > 0) { freeThreads.set(nrThreads); handlerExecutor = Executors.newFixedThreadPool(nrThreads); pollerExecutor = Executors.newSingleThreadScheduledExecutor(); pollerExecutor.scheduleWithFixedDelay(new MessagePoller(), intervalMs, intervalMs, TimeUnit.MILLISECONDS); LOGGER.info("Message dequeue started"); } } @Autowired MessageDequeue(final MaintenanceMode maintenanceMode,
final MailGateway mailGateway,
final MailMessageDao mailMessageDao,
final MessageFilter messageFilter,
final MessageParser messageParser,
final UpdatesParser updatesParser,
final UpdateRequestHandler messageHandler,
final LoggerContext loggerContext,
final DateTimeProvider dateTimeProvider); } | MessageDequeue implements ApplicationService { @Override public void start() { if (handlerExecutor != null || pollerExecutor != null) { throw new IllegalStateException("Already started"); } if (nrThreads > 0) { freeThreads.set(nrThreads); handlerExecutor = Executors.newFixedThreadPool(nrThreads); pollerExecutor = Executors.newSingleThreadScheduledExecutor(); pollerExecutor.scheduleWithFixedDelay(new MessagePoller(), intervalMs, intervalMs, TimeUnit.MILLISECONDS); LOGGER.info("Message dequeue started"); } } @Autowired MessageDequeue(final MaintenanceMode maintenanceMode,
final MailGateway mailGateway,
final MailMessageDao mailMessageDao,
final MessageFilter messageFilter,
final MessageParser messageParser,
final UpdatesParser updatesParser,
final UpdateRequestHandler messageHandler,
final LoggerContext loggerContext,
final DateTimeProvider dateTimeProvider); @Override void start(); @Override void stop(final boolean force); } | MessageDequeue implements ApplicationService { @Override public void start() { if (handlerExecutor != null || pollerExecutor != null) { throw new IllegalStateException("Already started"); } if (nrThreads > 0) { freeThreads.set(nrThreads); handlerExecutor = Executors.newFixedThreadPool(nrThreads); pollerExecutor = Executors.newSingleThreadScheduledExecutor(); pollerExecutor.scheduleWithFixedDelay(new MessagePoller(), intervalMs, intervalMs, TimeUnit.MILLISECONDS); LOGGER.info("Message dequeue started"); } } @Autowired MessageDequeue(final MaintenanceMode maintenanceMode,
final MailGateway mailGateway,
final MailMessageDao mailMessageDao,
final MessageFilter messageFilter,
final MessageParser messageParser,
final UpdatesParser updatesParser,
final UpdateRequestHandler messageHandler,
final LoggerContext loggerContext,
final DateTimeProvider dateTimeProvider); @Override void start(); @Override void stop(final boolean force); } |
@Test public void mntner() { final RpslObject mntner = RpslObject.parse(11, "" + "mntner: AARDVARK-MNT\n" + "descr: Mntner for guy's objects\n" + "admin-c: FB99999-RIPE\n" + "tech-c: FB99999-RIPE\n" + "upd-to: [email protected]\n" + "auth: X509-1\n" + "auth: X509-1689\n" + "auth: MD5-PW $1$SaltSalt$ThisIsABrokenMd5Hash.\n" + "auth: SSO 1234-5678-9abc-dead-beef\n" + "notify: [email protected]\n" + "mnt-by: AARDVARK-MNT\n" + "source: RIPE # Filtered"); final RpslObject dummified = subject.dummify(4, mntner); assertThat(dummified.getAttributes(), containsInAnyOrder( new RpslAttribute("mntner", "AARDVARK-MNT"), new RpslAttribute("descr", "Mntner for guy's objects"), new RpslAttribute("admin-c", "FB99999-RIPE"), new RpslAttribute("tech-c", "FB99999-RIPE"), new RpslAttribute("upd-to", "***@ripe.net"), new RpslAttribute("auth", "X509-1"), new RpslAttribute("auth", "X509-1689"), new RpslAttribute("auth", "MD5-PW # Filtered"), new RpslAttribute("auth", "SSO # Filtered"), new RpslAttribute("notify", "***@ripe.net"), new RpslAttribute("mnt-by", "AARDVARK-MNT"), new RpslAttribute("source", "RIPE") )); } | @Override public RpslObject dummify(final int version, final RpslObject rpslObject) { final ObjectType objectType = rpslObject.getType(); Validate.isTrue(isAllowed(version, rpslObject), "The version is not supported by this dummifier", version); final List<RpslAttribute> attributes = Lists.newArrayList(rpslObject.getAttributes()); RpslAttribute lastAddressLine = null; int lastAddressLineIndex = 0; for (int i = 0; i < attributes.size(); i++) { RpslAttribute replacement = attributes.get(i); final AttributeType attributeType = replacement.getType(); try { if (!(objectType == ObjectType.ROLE && rpslObject.containsAttribute(ABUSE_MAILBOX))) { replacement = replacePerson(attributeType, replacement); replacement = replaceAuth(attributeType, replacement); replacement = replacePhoneFax(attributeType, replacement); if (attributeType == ADDRESS) { lastAddressLine = replacement; lastAddressLineIndex = i; replacement = new RpslAttribute(ADDRESS, "***"); } } replacement = replaceEmail(attributeType, replacement); attributes.set(i, replacement); } catch (RuntimeException e) { LOGGER.debug("Dummifier failed on [" + attributes.get(i).toString().trim() + "]", e); } } if (lastAddressLine != null) { attributes.set(lastAddressLineIndex, lastAddressLine); } return FILTER_CHANGED_FUNCTION.apply(new RpslObject(rpslObject, attributes)); } | DummifierCurrent implements Dummifier { @Override public RpslObject dummify(final int version, final RpslObject rpslObject) { final ObjectType objectType = rpslObject.getType(); Validate.isTrue(isAllowed(version, rpslObject), "The version is not supported by this dummifier", version); final List<RpslAttribute> attributes = Lists.newArrayList(rpslObject.getAttributes()); RpslAttribute lastAddressLine = null; int lastAddressLineIndex = 0; for (int i = 0; i < attributes.size(); i++) { RpslAttribute replacement = attributes.get(i); final AttributeType attributeType = replacement.getType(); try { if (!(objectType == ObjectType.ROLE && rpslObject.containsAttribute(ABUSE_MAILBOX))) { replacement = replacePerson(attributeType, replacement); replacement = replaceAuth(attributeType, replacement); replacement = replacePhoneFax(attributeType, replacement); if (attributeType == ADDRESS) { lastAddressLine = replacement; lastAddressLineIndex = i; replacement = new RpslAttribute(ADDRESS, "***"); } } replacement = replaceEmail(attributeType, replacement); attributes.set(i, replacement); } catch (RuntimeException e) { LOGGER.debug("Dummifier failed on [" + attributes.get(i).toString().trim() + "]", e); } } if (lastAddressLine != null) { attributes.set(lastAddressLineIndex, lastAddressLine); } return FILTER_CHANGED_FUNCTION.apply(new RpslObject(rpslObject, attributes)); } } | DummifierCurrent implements Dummifier { @Override public RpslObject dummify(final int version, final RpslObject rpslObject) { final ObjectType objectType = rpslObject.getType(); Validate.isTrue(isAllowed(version, rpslObject), "The version is not supported by this dummifier", version); final List<RpslAttribute> attributes = Lists.newArrayList(rpslObject.getAttributes()); RpslAttribute lastAddressLine = null; int lastAddressLineIndex = 0; for (int i = 0; i < attributes.size(); i++) { RpslAttribute replacement = attributes.get(i); final AttributeType attributeType = replacement.getType(); try { if (!(objectType == ObjectType.ROLE && rpslObject.containsAttribute(ABUSE_MAILBOX))) { replacement = replacePerson(attributeType, replacement); replacement = replaceAuth(attributeType, replacement); replacement = replacePhoneFax(attributeType, replacement); if (attributeType == ADDRESS) { lastAddressLine = replacement; lastAddressLineIndex = i; replacement = new RpslAttribute(ADDRESS, "***"); } } replacement = replaceEmail(attributeType, replacement); attributes.set(i, replacement); } catch (RuntimeException e) { LOGGER.debug("Dummifier failed on [" + attributes.get(i).toString().trim() + "]", e); } } if (lastAddressLine != null) { attributes.set(lastAddressLineIndex, lastAddressLine); } return FILTER_CHANGED_FUNCTION.apply(new RpslObject(rpslObject, attributes)); } } | DummifierCurrent implements Dummifier { @Override public RpslObject dummify(final int version, final RpslObject rpslObject) { final ObjectType objectType = rpslObject.getType(); Validate.isTrue(isAllowed(version, rpslObject), "The version is not supported by this dummifier", version); final List<RpslAttribute> attributes = Lists.newArrayList(rpslObject.getAttributes()); RpslAttribute lastAddressLine = null; int lastAddressLineIndex = 0; for (int i = 0; i < attributes.size(); i++) { RpslAttribute replacement = attributes.get(i); final AttributeType attributeType = replacement.getType(); try { if (!(objectType == ObjectType.ROLE && rpslObject.containsAttribute(ABUSE_MAILBOX))) { replacement = replacePerson(attributeType, replacement); replacement = replaceAuth(attributeType, replacement); replacement = replacePhoneFax(attributeType, replacement); if (attributeType == ADDRESS) { lastAddressLine = replacement; lastAddressLineIndex = i; replacement = new RpslAttribute(ADDRESS, "***"); } } replacement = replaceEmail(attributeType, replacement); attributes.set(i, replacement); } catch (RuntimeException e) { LOGGER.debug("Dummifier failed on [" + attributes.get(i).toString().trim() + "]", e); } } if (lastAddressLine != null) { attributes.set(lastAddressLineIndex, lastAddressLine); } return FILTER_CHANGED_FUNCTION.apply(new RpslObject(rpslObject, attributes)); } @Override RpslObject dummify(final int version, final RpslObject rpslObject); @Override boolean isAllowed(final int version, final RpslObject object); } | DummifierCurrent implements Dummifier { @Override public RpslObject dummify(final int version, final RpslObject rpslObject) { final ObjectType objectType = rpslObject.getType(); Validate.isTrue(isAllowed(version, rpslObject), "The version is not supported by this dummifier", version); final List<RpslAttribute> attributes = Lists.newArrayList(rpslObject.getAttributes()); RpslAttribute lastAddressLine = null; int lastAddressLineIndex = 0; for (int i = 0; i < attributes.size(); i++) { RpslAttribute replacement = attributes.get(i); final AttributeType attributeType = replacement.getType(); try { if (!(objectType == ObjectType.ROLE && rpslObject.containsAttribute(ABUSE_MAILBOX))) { replacement = replacePerson(attributeType, replacement); replacement = replaceAuth(attributeType, replacement); replacement = replacePhoneFax(attributeType, replacement); if (attributeType == ADDRESS) { lastAddressLine = replacement; lastAddressLineIndex = i; replacement = new RpslAttribute(ADDRESS, "***"); } } replacement = replaceEmail(attributeType, replacement); attributes.set(i, replacement); } catch (RuntimeException e) { LOGGER.debug("Dummifier failed on [" + attributes.get(i).toString().trim() + "]", e); } } if (lastAddressLine != null) { attributes.set(lastAddressLineIndex, lastAddressLine); } return FILTER_CHANGED_FUNCTION.apply(new RpslObject(rpslObject, attributes)); } @Override RpslObject dummify(final int version, final RpslObject rpslObject); @Override boolean isAllowed(final int version, final RpslObject object); } |
@Test public void handleMessage() throws Exception { final MimeMessage message = MimeMessageProvider.getMessageSimpleTextUnsigned(); when(messageFilter.shouldProcess(any(MailMessage.class))).thenReturn(true); when(messageParser.parse(eq(message), any(UpdateContext.class))).thenReturn( new MailMessage("", "", "", "", "", "", Keyword.NONE, Lists.<ContentWithCredentials>newArrayList())); when(updatesParser.parse(any(UpdateContext.class), anyListOf(ContentWithCredentials.class))).thenReturn(Lists.<Update>newArrayList()); when(messageHandler.handle(any(UpdateRequest.class), any(UpdateContext.class))).thenReturn(new UpdateResponse(UpdateStatus.SUCCESS, "")); when(mailMessageDao.getMessage("1")).thenReturn(message); when(mailMessageDao.claimMessage()).thenReturn("1").thenReturn(null); subject.start(); verify(mailMessageDao, timeout(TIMEOUT)).deleteMessage("1"); verify(loggerContext, timeout(TIMEOUT)).init("20120527220444.GA6565"); verify(loggerContext, timeout(TIMEOUT)).log(eq("msg-in.txt"), any(MailMessageLogCallback.class)); verify(mailMessageDao, timeout(TIMEOUT)).setStatus("1", DequeueStatus.LOGGED); verify(mailMessageDao, timeout(TIMEOUT)).setStatus("1", DequeueStatus.PARSED); verify(messageHandler, timeout(TIMEOUT)).handle(any(UpdateRequest.class), any(UpdateContext.class)); verify(mailGateway, timeout(TIMEOUT)).sendEmail(anyString(), anyString(), anyString(), any()); } | private void handleMessage(final String messageId) { final MimeMessage message = mailMessageDao.getMessage(messageId); try { loggerContext.init(getMessageIdLocalPart(message)); try { handleMessageInContext(messageId, message); } finally { loggerContext.remove(); } } catch (MessagingException e) { LOGGER.error("Handle message", e); } catch (IOException e) { LOGGER.error("Handle message", e); } } | MessageDequeue implements ApplicationService { private void handleMessage(final String messageId) { final MimeMessage message = mailMessageDao.getMessage(messageId); try { loggerContext.init(getMessageIdLocalPart(message)); try { handleMessageInContext(messageId, message); } finally { loggerContext.remove(); } } catch (MessagingException e) { LOGGER.error("Handle message", e); } catch (IOException e) { LOGGER.error("Handle message", e); } } } | MessageDequeue implements ApplicationService { private void handleMessage(final String messageId) { final MimeMessage message = mailMessageDao.getMessage(messageId); try { loggerContext.init(getMessageIdLocalPart(message)); try { handleMessageInContext(messageId, message); } finally { loggerContext.remove(); } } catch (MessagingException e) { LOGGER.error("Handle message", e); } catch (IOException e) { LOGGER.error("Handle message", e); } } @Autowired MessageDequeue(final MaintenanceMode maintenanceMode,
final MailGateway mailGateway,
final MailMessageDao mailMessageDao,
final MessageFilter messageFilter,
final MessageParser messageParser,
final UpdatesParser updatesParser,
final UpdateRequestHandler messageHandler,
final LoggerContext loggerContext,
final DateTimeProvider dateTimeProvider); } | MessageDequeue implements ApplicationService { private void handleMessage(final String messageId) { final MimeMessage message = mailMessageDao.getMessage(messageId); try { loggerContext.init(getMessageIdLocalPart(message)); try { handleMessageInContext(messageId, message); } finally { loggerContext.remove(); } } catch (MessagingException e) { LOGGER.error("Handle message", e); } catch (IOException e) { LOGGER.error("Handle message", e); } } @Autowired MessageDequeue(final MaintenanceMode maintenanceMode,
final MailGateway mailGateway,
final MailMessageDao mailMessageDao,
final MessageFilter messageFilter,
final MessageParser messageParser,
final UpdatesParser updatesParser,
final UpdateRequestHandler messageHandler,
final LoggerContext loggerContext,
final DateTimeProvider dateTimeProvider); @Override void start(); @Override void stop(final boolean force); } | MessageDequeue implements ApplicationService { private void handleMessage(final String messageId) { final MimeMessage message = mailMessageDao.getMessage(messageId); try { loggerContext.init(getMessageIdLocalPart(message)); try { handleMessageInContext(messageId, message); } finally { loggerContext.remove(); } } catch (MessagingException e) { LOGGER.error("Handle message", e); } catch (IOException e) { LOGGER.error("Handle message", e); } } @Autowired MessageDequeue(final MaintenanceMode maintenanceMode,
final MailGateway mailGateway,
final MailMessageDao mailMessageDao,
final MessageFilter messageFilter,
final MessageParser messageParser,
final UpdatesParser updatesParser,
final UpdateRequestHandler messageHandler,
final LoggerContext loggerContext,
final DateTimeProvider dateTimeProvider); @Override void start(); @Override void stop(final boolean force); } |
@Test public void handleMessage_exception() throws Exception { final MimeMessage message = MimeMessageProvider.getMessageSimpleTextUnsigned(); when(messageFilter.shouldProcess(any(MailMessage.class))).thenReturn(true); when(messageParser.parse(eq(message), any(UpdateContext.class))).thenReturn( new MailMessage("", "", "", "", "", "", Keyword.NONE, Lists.<ContentWithCredentials>newArrayList())); when(updatesParser.parse(any(UpdateContext.class), anyListOf(ContentWithCredentials.class))).thenReturn(Lists.<Update>newArrayList()); when(messageHandler.handle(any(UpdateRequest.class), any(UpdateContext.class))).thenThrow(RuntimeException.class); when(mailMessageDao.getMessage("1")).thenReturn(message); when(mailMessageDao.claimMessage()).thenReturn("1").thenReturn(null); subject.start(); verify(mailMessageDao, timeout(TIMEOUT)).setStatus("1", DequeueStatus.LOGGED); verify(mailMessageDao, timeout(TIMEOUT)).setStatus("1", DequeueStatus.PARSED); verify(mailMessageDao, timeout(TIMEOUT)).setStatus("1", DequeueStatus.FAILED); verify(loggerContext, timeout(TIMEOUT)).init("20120527220444.GA6565"); verify(loggerContext, timeout(TIMEOUT)).log(eq("msg-in.txt"), any(MailMessageLogCallback.class)); verifyZeroInteractions(mailGateway); verify(mailMessageDao, never()).deleteMessage("1"); } | @Override public void start() { if (handlerExecutor != null || pollerExecutor != null) { throw new IllegalStateException("Already started"); } if (nrThreads > 0) { freeThreads.set(nrThreads); handlerExecutor = Executors.newFixedThreadPool(nrThreads); pollerExecutor = Executors.newSingleThreadScheduledExecutor(); pollerExecutor.scheduleWithFixedDelay(new MessagePoller(), intervalMs, intervalMs, TimeUnit.MILLISECONDS); LOGGER.info("Message dequeue started"); } } | MessageDequeue implements ApplicationService { @Override public void start() { if (handlerExecutor != null || pollerExecutor != null) { throw new IllegalStateException("Already started"); } if (nrThreads > 0) { freeThreads.set(nrThreads); handlerExecutor = Executors.newFixedThreadPool(nrThreads); pollerExecutor = Executors.newSingleThreadScheduledExecutor(); pollerExecutor.scheduleWithFixedDelay(new MessagePoller(), intervalMs, intervalMs, TimeUnit.MILLISECONDS); LOGGER.info("Message dequeue started"); } } } | MessageDequeue implements ApplicationService { @Override public void start() { if (handlerExecutor != null || pollerExecutor != null) { throw new IllegalStateException("Already started"); } if (nrThreads > 0) { freeThreads.set(nrThreads); handlerExecutor = Executors.newFixedThreadPool(nrThreads); pollerExecutor = Executors.newSingleThreadScheduledExecutor(); pollerExecutor.scheduleWithFixedDelay(new MessagePoller(), intervalMs, intervalMs, TimeUnit.MILLISECONDS); LOGGER.info("Message dequeue started"); } } @Autowired MessageDequeue(final MaintenanceMode maintenanceMode,
final MailGateway mailGateway,
final MailMessageDao mailMessageDao,
final MessageFilter messageFilter,
final MessageParser messageParser,
final UpdatesParser updatesParser,
final UpdateRequestHandler messageHandler,
final LoggerContext loggerContext,
final DateTimeProvider dateTimeProvider); } | MessageDequeue implements ApplicationService { @Override public void start() { if (handlerExecutor != null || pollerExecutor != null) { throw new IllegalStateException("Already started"); } if (nrThreads > 0) { freeThreads.set(nrThreads); handlerExecutor = Executors.newFixedThreadPool(nrThreads); pollerExecutor = Executors.newSingleThreadScheduledExecutor(); pollerExecutor.scheduleWithFixedDelay(new MessagePoller(), intervalMs, intervalMs, TimeUnit.MILLISECONDS); LOGGER.info("Message dequeue started"); } } @Autowired MessageDequeue(final MaintenanceMode maintenanceMode,
final MailGateway mailGateway,
final MailMessageDao mailMessageDao,
final MessageFilter messageFilter,
final MessageParser messageParser,
final UpdatesParser updatesParser,
final UpdateRequestHandler messageHandler,
final LoggerContext loggerContext,
final DateTimeProvider dateTimeProvider); @Override void start(); @Override void stop(final boolean force); } | MessageDequeue implements ApplicationService { @Override public void start() { if (handlerExecutor != null || pollerExecutor != null) { throw new IllegalStateException("Already started"); } if (nrThreads > 0) { freeThreads.set(nrThreads); handlerExecutor = Executors.newFixedThreadPool(nrThreads); pollerExecutor = Executors.newSingleThreadScheduledExecutor(); pollerExecutor.scheduleWithFixedDelay(new MessagePoller(), intervalMs, intervalMs, TimeUnit.MILLISECONDS); LOGGER.info("Message dequeue started"); } } @Autowired MessageDequeue(final MaintenanceMode maintenanceMode,
final MailGateway mailGateway,
final MailMessageDao mailMessageDao,
final MessageFilter messageFilter,
final MessageParser messageParser,
final UpdatesParser updatesParser,
final UpdateRequestHandler messageHandler,
final LoggerContext loggerContext,
final DateTimeProvider dateTimeProvider); @Override void start(); @Override void stop(final boolean force); } |
@Test public void handleMessage_invalidReplyTo() throws Exception { final MimeMessage message = new MimeMessage(null, new ByteArrayInputStream("Reply-To: <respondera: [email protected]>".getBytes())); when(messageFilter.shouldProcess(any(MailMessage.class))).thenReturn(false); when(messageParser.parse(eq(message), any(UpdateContext.class))).thenReturn( new MailMessage("", null, "", "", null, "", Keyword.NONE, Lists.<ContentWithCredentials>newArrayList())); when(mailMessageDao.getMessage("1")).thenReturn(message); when(mailMessageDao.claimMessage()).thenReturn("1").thenReturn(null); subject.start(); verify(mailMessageDao, timeout(TIMEOUT)).deleteMessage("1"); } | @Override public void start() { if (handlerExecutor != null || pollerExecutor != null) { throw new IllegalStateException("Already started"); } if (nrThreads > 0) { freeThreads.set(nrThreads); handlerExecutor = Executors.newFixedThreadPool(nrThreads); pollerExecutor = Executors.newSingleThreadScheduledExecutor(); pollerExecutor.scheduleWithFixedDelay(new MessagePoller(), intervalMs, intervalMs, TimeUnit.MILLISECONDS); LOGGER.info("Message dequeue started"); } } | MessageDequeue implements ApplicationService { @Override public void start() { if (handlerExecutor != null || pollerExecutor != null) { throw new IllegalStateException("Already started"); } if (nrThreads > 0) { freeThreads.set(nrThreads); handlerExecutor = Executors.newFixedThreadPool(nrThreads); pollerExecutor = Executors.newSingleThreadScheduledExecutor(); pollerExecutor.scheduleWithFixedDelay(new MessagePoller(), intervalMs, intervalMs, TimeUnit.MILLISECONDS); LOGGER.info("Message dequeue started"); } } } | MessageDequeue implements ApplicationService { @Override public void start() { if (handlerExecutor != null || pollerExecutor != null) { throw new IllegalStateException("Already started"); } if (nrThreads > 0) { freeThreads.set(nrThreads); handlerExecutor = Executors.newFixedThreadPool(nrThreads); pollerExecutor = Executors.newSingleThreadScheduledExecutor(); pollerExecutor.scheduleWithFixedDelay(new MessagePoller(), intervalMs, intervalMs, TimeUnit.MILLISECONDS); LOGGER.info("Message dequeue started"); } } @Autowired MessageDequeue(final MaintenanceMode maintenanceMode,
final MailGateway mailGateway,
final MailMessageDao mailMessageDao,
final MessageFilter messageFilter,
final MessageParser messageParser,
final UpdatesParser updatesParser,
final UpdateRequestHandler messageHandler,
final LoggerContext loggerContext,
final DateTimeProvider dateTimeProvider); } | MessageDequeue implements ApplicationService { @Override public void start() { if (handlerExecutor != null || pollerExecutor != null) { throw new IllegalStateException("Already started"); } if (nrThreads > 0) { freeThreads.set(nrThreads); handlerExecutor = Executors.newFixedThreadPool(nrThreads); pollerExecutor = Executors.newSingleThreadScheduledExecutor(); pollerExecutor.scheduleWithFixedDelay(new MessagePoller(), intervalMs, intervalMs, TimeUnit.MILLISECONDS); LOGGER.info("Message dequeue started"); } } @Autowired MessageDequeue(final MaintenanceMode maintenanceMode,
final MailGateway mailGateway,
final MailMessageDao mailMessageDao,
final MessageFilter messageFilter,
final MessageParser messageParser,
final UpdatesParser updatesParser,
final UpdateRequestHandler messageHandler,
final LoggerContext loggerContext,
final DateTimeProvider dateTimeProvider); @Override void start(); @Override void stop(final boolean force); } | MessageDequeue implements ApplicationService { @Override public void start() { if (handlerExecutor != null || pollerExecutor != null) { throw new IllegalStateException("Already started"); } if (nrThreads > 0) { freeThreads.set(nrThreads); handlerExecutor = Executors.newFixedThreadPool(nrThreads); pollerExecutor = Executors.newSingleThreadScheduledExecutor(); pollerExecutor.scheduleWithFixedDelay(new MessagePoller(), intervalMs, intervalMs, TimeUnit.MILLISECONDS); LOGGER.info("Message dequeue started"); } } @Autowired MessageDequeue(final MaintenanceMode maintenanceMode,
final MailGateway mailGateway,
final MailMessageDao mailMessageDao,
final MessageFilter messageFilter,
final MessageParser messageParser,
final UpdatesParser updatesParser,
final UpdateRequestHandler messageHandler,
final LoggerContext loggerContext,
final DateTimeProvider dateTimeProvider); @Override void start(); @Override void stop(final boolean force); } |
@Test public void getMessageIdLocalPart_local_and_domain_parts() throws Exception { Message message = mock(Message.class); when(message.getHeader("Message-Id")).thenReturn(new String[]{"<[email protected]>"}); final String messageIdLocalPart = subject.getMessageIdLocalPart(message); assertThat(messageIdLocalPart, is("20120527220444.GA6565")); } | String getMessageIdLocalPart(final Message message) throws MessagingException { final String[] headers = message.getHeader("Message-Id"); if (headers != null && headers.length > 0) { Matcher matcher = MESSAGE_ID_PATTERN.matcher(headers[0]); if (matcher.matches()) { return matcher.group(1); } LOGGER.debug("Unable to parse Message-Id: {}", headers[0]); } return "No-Message-Id." + dateTimeProvider.getElapsedTime(); } | MessageDequeue implements ApplicationService { String getMessageIdLocalPart(final Message message) throws MessagingException { final String[] headers = message.getHeader("Message-Id"); if (headers != null && headers.length > 0) { Matcher matcher = MESSAGE_ID_PATTERN.matcher(headers[0]); if (matcher.matches()) { return matcher.group(1); } LOGGER.debug("Unable to parse Message-Id: {}", headers[0]); } return "No-Message-Id." + dateTimeProvider.getElapsedTime(); } } | MessageDequeue implements ApplicationService { String getMessageIdLocalPart(final Message message) throws MessagingException { final String[] headers = message.getHeader("Message-Id"); if (headers != null && headers.length > 0) { Matcher matcher = MESSAGE_ID_PATTERN.matcher(headers[0]); if (matcher.matches()) { return matcher.group(1); } LOGGER.debug("Unable to parse Message-Id: {}", headers[0]); } return "No-Message-Id." + dateTimeProvider.getElapsedTime(); } @Autowired MessageDequeue(final MaintenanceMode maintenanceMode,
final MailGateway mailGateway,
final MailMessageDao mailMessageDao,
final MessageFilter messageFilter,
final MessageParser messageParser,
final UpdatesParser updatesParser,
final UpdateRequestHandler messageHandler,
final LoggerContext loggerContext,
final DateTimeProvider dateTimeProvider); } | MessageDequeue implements ApplicationService { String getMessageIdLocalPart(final Message message) throws MessagingException { final String[] headers = message.getHeader("Message-Id"); if (headers != null && headers.length > 0) { Matcher matcher = MESSAGE_ID_PATTERN.matcher(headers[0]); if (matcher.matches()) { return matcher.group(1); } LOGGER.debug("Unable to parse Message-Id: {}", headers[0]); } return "No-Message-Id." + dateTimeProvider.getElapsedTime(); } @Autowired MessageDequeue(final MaintenanceMode maintenanceMode,
final MailGateway mailGateway,
final MailMessageDao mailMessageDao,
final MessageFilter messageFilter,
final MessageParser messageParser,
final UpdatesParser updatesParser,
final UpdateRequestHandler messageHandler,
final LoggerContext loggerContext,
final DateTimeProvider dateTimeProvider); @Override void start(); @Override void stop(final boolean force); } | MessageDequeue implements ApplicationService { String getMessageIdLocalPart(final Message message) throws MessagingException { final String[] headers = message.getHeader("Message-Id"); if (headers != null && headers.length > 0) { Matcher matcher = MESSAGE_ID_PATTERN.matcher(headers[0]); if (matcher.matches()) { return matcher.group(1); } LOGGER.debug("Unable to parse Message-Id: {}", headers[0]); } return "No-Message-Id." + dateTimeProvider.getElapsedTime(); } @Autowired MessageDequeue(final MaintenanceMode maintenanceMode,
final MailGateway mailGateway,
final MailMessageDao mailMessageDao,
final MessageFilter messageFilter,
final MessageParser messageParser,
final UpdatesParser updatesParser,
final UpdateRequestHandler messageHandler,
final LoggerContext loggerContext,
final DateTimeProvider dateTimeProvider); @Override void start(); @Override void stop(final boolean force); } |
@Test public void getMessageIdLocalPart_local_part_only() throws Exception { Message message = mock(Message.class); when(message.getHeader("Message-Id")).thenReturn(new String[]{"<20120527220444.GA6565>"}); final String messageIdLocalPart = subject.getMessageIdLocalPart(message); assertThat(messageIdLocalPart, is("20120527220444.GA6565")); } | String getMessageIdLocalPart(final Message message) throws MessagingException { final String[] headers = message.getHeader("Message-Id"); if (headers != null && headers.length > 0) { Matcher matcher = MESSAGE_ID_PATTERN.matcher(headers[0]); if (matcher.matches()) { return matcher.group(1); } LOGGER.debug("Unable to parse Message-Id: {}", headers[0]); } return "No-Message-Id." + dateTimeProvider.getElapsedTime(); } | MessageDequeue implements ApplicationService { String getMessageIdLocalPart(final Message message) throws MessagingException { final String[] headers = message.getHeader("Message-Id"); if (headers != null && headers.length > 0) { Matcher matcher = MESSAGE_ID_PATTERN.matcher(headers[0]); if (matcher.matches()) { return matcher.group(1); } LOGGER.debug("Unable to parse Message-Id: {}", headers[0]); } return "No-Message-Id." + dateTimeProvider.getElapsedTime(); } } | MessageDequeue implements ApplicationService { String getMessageIdLocalPart(final Message message) throws MessagingException { final String[] headers = message.getHeader("Message-Id"); if (headers != null && headers.length > 0) { Matcher matcher = MESSAGE_ID_PATTERN.matcher(headers[0]); if (matcher.matches()) { return matcher.group(1); } LOGGER.debug("Unable to parse Message-Id: {}", headers[0]); } return "No-Message-Id." + dateTimeProvider.getElapsedTime(); } @Autowired MessageDequeue(final MaintenanceMode maintenanceMode,
final MailGateway mailGateway,
final MailMessageDao mailMessageDao,
final MessageFilter messageFilter,
final MessageParser messageParser,
final UpdatesParser updatesParser,
final UpdateRequestHandler messageHandler,
final LoggerContext loggerContext,
final DateTimeProvider dateTimeProvider); } | MessageDequeue implements ApplicationService { String getMessageIdLocalPart(final Message message) throws MessagingException { final String[] headers = message.getHeader("Message-Id"); if (headers != null && headers.length > 0) { Matcher matcher = MESSAGE_ID_PATTERN.matcher(headers[0]); if (matcher.matches()) { return matcher.group(1); } LOGGER.debug("Unable to parse Message-Id: {}", headers[0]); } return "No-Message-Id." + dateTimeProvider.getElapsedTime(); } @Autowired MessageDequeue(final MaintenanceMode maintenanceMode,
final MailGateway mailGateway,
final MailMessageDao mailMessageDao,
final MessageFilter messageFilter,
final MessageParser messageParser,
final UpdatesParser updatesParser,
final UpdateRequestHandler messageHandler,
final LoggerContext loggerContext,
final DateTimeProvider dateTimeProvider); @Override void start(); @Override void stop(final boolean force); } | MessageDequeue implements ApplicationService { String getMessageIdLocalPart(final Message message) throws MessagingException { final String[] headers = message.getHeader("Message-Id"); if (headers != null && headers.length > 0) { Matcher matcher = MESSAGE_ID_PATTERN.matcher(headers[0]); if (matcher.matches()) { return matcher.group(1); } LOGGER.debug("Unable to parse Message-Id: {}", headers[0]); } return "No-Message-Id." + dateTimeProvider.getElapsedTime(); } @Autowired MessageDequeue(final MaintenanceMode maintenanceMode,
final MailGateway mailGateway,
final MailMessageDao mailMessageDao,
final MessageFilter messageFilter,
final MessageParser messageParser,
final UpdatesParser updatesParser,
final UpdateRequestHandler messageHandler,
final LoggerContext loggerContext,
final DateTimeProvider dateTimeProvider); @Override void start(); @Override void stop(final boolean force); } |
@Test public void getMessageIdLocalPart_emptyMessageId() throws Exception { Message message = mock(Message.class); final String messageIdLocalPart = subject.getMessageIdLocalPart(message); assertThat(messageIdLocalPart, containsString("No-Message-Id.")); } | String getMessageIdLocalPart(final Message message) throws MessagingException { final String[] headers = message.getHeader("Message-Id"); if (headers != null && headers.length > 0) { Matcher matcher = MESSAGE_ID_PATTERN.matcher(headers[0]); if (matcher.matches()) { return matcher.group(1); } LOGGER.debug("Unable to parse Message-Id: {}", headers[0]); } return "No-Message-Id." + dateTimeProvider.getElapsedTime(); } | MessageDequeue implements ApplicationService { String getMessageIdLocalPart(final Message message) throws MessagingException { final String[] headers = message.getHeader("Message-Id"); if (headers != null && headers.length > 0) { Matcher matcher = MESSAGE_ID_PATTERN.matcher(headers[0]); if (matcher.matches()) { return matcher.group(1); } LOGGER.debug("Unable to parse Message-Id: {}", headers[0]); } return "No-Message-Id." + dateTimeProvider.getElapsedTime(); } } | MessageDequeue implements ApplicationService { String getMessageIdLocalPart(final Message message) throws MessagingException { final String[] headers = message.getHeader("Message-Id"); if (headers != null && headers.length > 0) { Matcher matcher = MESSAGE_ID_PATTERN.matcher(headers[0]); if (matcher.matches()) { return matcher.group(1); } LOGGER.debug("Unable to parse Message-Id: {}", headers[0]); } return "No-Message-Id." + dateTimeProvider.getElapsedTime(); } @Autowired MessageDequeue(final MaintenanceMode maintenanceMode,
final MailGateway mailGateway,
final MailMessageDao mailMessageDao,
final MessageFilter messageFilter,
final MessageParser messageParser,
final UpdatesParser updatesParser,
final UpdateRequestHandler messageHandler,
final LoggerContext loggerContext,
final DateTimeProvider dateTimeProvider); } | MessageDequeue implements ApplicationService { String getMessageIdLocalPart(final Message message) throws MessagingException { final String[] headers = message.getHeader("Message-Id"); if (headers != null && headers.length > 0) { Matcher matcher = MESSAGE_ID_PATTERN.matcher(headers[0]); if (matcher.matches()) { return matcher.group(1); } LOGGER.debug("Unable to parse Message-Id: {}", headers[0]); } return "No-Message-Id." + dateTimeProvider.getElapsedTime(); } @Autowired MessageDequeue(final MaintenanceMode maintenanceMode,
final MailGateway mailGateway,
final MailMessageDao mailMessageDao,
final MessageFilter messageFilter,
final MessageParser messageParser,
final UpdatesParser updatesParser,
final UpdateRequestHandler messageHandler,
final LoggerContext loggerContext,
final DateTimeProvider dateTimeProvider); @Override void start(); @Override void stop(final boolean force); } | MessageDequeue implements ApplicationService { String getMessageIdLocalPart(final Message message) throws MessagingException { final String[] headers = message.getHeader("Message-Id"); if (headers != null && headers.length > 0) { Matcher matcher = MESSAGE_ID_PATTERN.matcher(headers[0]); if (matcher.matches()) { return matcher.group(1); } LOGGER.debug("Unable to parse Message-Id: {}", headers[0]); } return "No-Message-Id." + dateTimeProvider.getElapsedTime(); } @Autowired MessageDequeue(final MaintenanceMode maintenanceMode,
final MailGateway mailGateway,
final MailMessageDao mailMessageDao,
final MessageFilter messageFilter,
final MessageParser messageParser,
final UpdatesParser updatesParser,
final UpdateRequestHandler messageHandler,
final LoggerContext loggerContext,
final DateTimeProvider dateTimeProvider); @Override void start(); @Override void stop(final boolean force); } |
@Test public void getMessageIdLocalPart_messageId_doesnt_match() throws Exception { Message message = mock(Message.class); when(message.getHeader("Message-Id")).thenReturn(new String[]{"<W[20"}); final String messageIdLocalPart = subject.getMessageIdLocalPart(message); assertThat(messageIdLocalPart, containsString("No-Message-Id.")); } | String getMessageIdLocalPart(final Message message) throws MessagingException { final String[] headers = message.getHeader("Message-Id"); if (headers != null && headers.length > 0) { Matcher matcher = MESSAGE_ID_PATTERN.matcher(headers[0]); if (matcher.matches()) { return matcher.group(1); } LOGGER.debug("Unable to parse Message-Id: {}", headers[0]); } return "No-Message-Id." + dateTimeProvider.getElapsedTime(); } | MessageDequeue implements ApplicationService { String getMessageIdLocalPart(final Message message) throws MessagingException { final String[] headers = message.getHeader("Message-Id"); if (headers != null && headers.length > 0) { Matcher matcher = MESSAGE_ID_PATTERN.matcher(headers[0]); if (matcher.matches()) { return matcher.group(1); } LOGGER.debug("Unable to parse Message-Id: {}", headers[0]); } return "No-Message-Id." + dateTimeProvider.getElapsedTime(); } } | MessageDequeue implements ApplicationService { String getMessageIdLocalPart(final Message message) throws MessagingException { final String[] headers = message.getHeader("Message-Id"); if (headers != null && headers.length > 0) { Matcher matcher = MESSAGE_ID_PATTERN.matcher(headers[0]); if (matcher.matches()) { return matcher.group(1); } LOGGER.debug("Unable to parse Message-Id: {}", headers[0]); } return "No-Message-Id." + dateTimeProvider.getElapsedTime(); } @Autowired MessageDequeue(final MaintenanceMode maintenanceMode,
final MailGateway mailGateway,
final MailMessageDao mailMessageDao,
final MessageFilter messageFilter,
final MessageParser messageParser,
final UpdatesParser updatesParser,
final UpdateRequestHandler messageHandler,
final LoggerContext loggerContext,
final DateTimeProvider dateTimeProvider); } | MessageDequeue implements ApplicationService { String getMessageIdLocalPart(final Message message) throws MessagingException { final String[] headers = message.getHeader("Message-Id"); if (headers != null && headers.length > 0) { Matcher matcher = MESSAGE_ID_PATTERN.matcher(headers[0]); if (matcher.matches()) { return matcher.group(1); } LOGGER.debug("Unable to parse Message-Id: {}", headers[0]); } return "No-Message-Id." + dateTimeProvider.getElapsedTime(); } @Autowired MessageDequeue(final MaintenanceMode maintenanceMode,
final MailGateway mailGateway,
final MailMessageDao mailMessageDao,
final MessageFilter messageFilter,
final MessageParser messageParser,
final UpdatesParser updatesParser,
final UpdateRequestHandler messageHandler,
final LoggerContext loggerContext,
final DateTimeProvider dateTimeProvider); @Override void start(); @Override void stop(final boolean force); } | MessageDequeue implements ApplicationService { String getMessageIdLocalPart(final Message message) throws MessagingException { final String[] headers = message.getHeader("Message-Id"); if (headers != null && headers.length > 0) { Matcher matcher = MESSAGE_ID_PATTERN.matcher(headers[0]); if (matcher.matches()) { return matcher.group(1); } LOGGER.debug("Unable to parse Message-Id: {}", headers[0]); } return "No-Message-Id." + dateTimeProvider.getElapsedTime(); } @Autowired MessageDequeue(final MaintenanceMode maintenanceMode,
final MailGateway mailGateway,
final MailMessageDao mailMessageDao,
final MessageFilter messageFilter,
final MessageParser messageParser,
final UpdatesParser updatesParser,
final UpdateRequestHandler messageHandler,
final LoggerContext loggerContext,
final DateTimeProvider dateTimeProvider); @Override void start(); @Override void stop(final boolean force); } |
@Test public void malformed_from_header_is_detected() throws Exception { final MimeMessage message = new MimeMessage(null, new ByteArrayInputStream(("From: <\"[email protected]\">\n" + "Subject: blabla\n" + "To: [email protected]\n" + "\n" + "body\n").getBytes())); when(mailMessageDao.getMessage("1")).thenReturn(message); when(mailMessageDao.claimMessage()).thenReturn("1").thenReturn(null); when(messageParser.parse(eq(message), any(UpdateContext.class))).thenAnswer(new Answer<MailMessage>() { @Override public MailMessage answer(InvocationOnMock invocation) throws Throwable { final Object[] arguments = invocation.getArguments(); return new MessageParser(loggerContext).parse(((MimeMessage) arguments[0]), ((UpdateContext) arguments[1])); } }); when(messageFilter.shouldProcess(any(MailMessage.class))).thenAnswer(new Answer<Boolean>() { @Override public Boolean answer(InvocationOnMock invocation) throws Throwable { final Object[] arguments = invocation.getArguments(); return new MessageFilter(loggerContext).shouldProcess((MailMessage)arguments[0]); } }); subject.start(); verify(mailMessageDao, timeout(TIMEOUT)).deleteMessage("1"); verify(updatesParser, never()).parse(any(UpdateContext.class), anyList()); verify(messageHandler, never()).handle(any(UpdateRequest.class), any(UpdateContext.class)); verify(loggerContext).log(any(net.ripe.db.whois.common.Message.class)); } | @Override public void start() { if (handlerExecutor != null || pollerExecutor != null) { throw new IllegalStateException("Already started"); } if (nrThreads > 0) { freeThreads.set(nrThreads); handlerExecutor = Executors.newFixedThreadPool(nrThreads); pollerExecutor = Executors.newSingleThreadScheduledExecutor(); pollerExecutor.scheduleWithFixedDelay(new MessagePoller(), intervalMs, intervalMs, TimeUnit.MILLISECONDS); LOGGER.info("Message dequeue started"); } } | MessageDequeue implements ApplicationService { @Override public void start() { if (handlerExecutor != null || pollerExecutor != null) { throw new IllegalStateException("Already started"); } if (nrThreads > 0) { freeThreads.set(nrThreads); handlerExecutor = Executors.newFixedThreadPool(nrThreads); pollerExecutor = Executors.newSingleThreadScheduledExecutor(); pollerExecutor.scheduleWithFixedDelay(new MessagePoller(), intervalMs, intervalMs, TimeUnit.MILLISECONDS); LOGGER.info("Message dequeue started"); } } } | MessageDequeue implements ApplicationService { @Override public void start() { if (handlerExecutor != null || pollerExecutor != null) { throw new IllegalStateException("Already started"); } if (nrThreads > 0) { freeThreads.set(nrThreads); handlerExecutor = Executors.newFixedThreadPool(nrThreads); pollerExecutor = Executors.newSingleThreadScheduledExecutor(); pollerExecutor.scheduleWithFixedDelay(new MessagePoller(), intervalMs, intervalMs, TimeUnit.MILLISECONDS); LOGGER.info("Message dequeue started"); } } @Autowired MessageDequeue(final MaintenanceMode maintenanceMode,
final MailGateway mailGateway,
final MailMessageDao mailMessageDao,
final MessageFilter messageFilter,
final MessageParser messageParser,
final UpdatesParser updatesParser,
final UpdateRequestHandler messageHandler,
final LoggerContext loggerContext,
final DateTimeProvider dateTimeProvider); } | MessageDequeue implements ApplicationService { @Override public void start() { if (handlerExecutor != null || pollerExecutor != null) { throw new IllegalStateException("Already started"); } if (nrThreads > 0) { freeThreads.set(nrThreads); handlerExecutor = Executors.newFixedThreadPool(nrThreads); pollerExecutor = Executors.newSingleThreadScheduledExecutor(); pollerExecutor.scheduleWithFixedDelay(new MessagePoller(), intervalMs, intervalMs, TimeUnit.MILLISECONDS); LOGGER.info("Message dequeue started"); } } @Autowired MessageDequeue(final MaintenanceMode maintenanceMode,
final MailGateway mailGateway,
final MailMessageDao mailMessageDao,
final MessageFilter messageFilter,
final MessageParser messageParser,
final UpdatesParser updatesParser,
final UpdateRequestHandler messageHandler,
final LoggerContext loggerContext,
final DateTimeProvider dateTimeProvider); @Override void start(); @Override void stop(final boolean force); } | MessageDequeue implements ApplicationService { @Override public void start() { if (handlerExecutor != null || pollerExecutor != null) { throw new IllegalStateException("Already started"); } if (nrThreads > 0) { freeThreads.set(nrThreads); handlerExecutor = Executors.newFixedThreadPool(nrThreads); pollerExecutor = Executors.newSingleThreadScheduledExecutor(); pollerExecutor.scheduleWithFixedDelay(new MessagePoller(), intervalMs, intervalMs, TimeUnit.MILLISECONDS); LOGGER.info("Message dequeue started"); } } @Autowired MessageDequeue(final MaintenanceMode maintenanceMode,
final MailGateway mailGateway,
final MailMessageDao mailMessageDao,
final MessageFilter messageFilter,
final MessageParser messageParser,
final UpdatesParser updatesParser,
final UpdateRequestHandler messageHandler,
final LoggerContext loggerContext,
final DateTimeProvider dateTimeProvider); @Override void start(); @Override void stop(final boolean force); } |
@Test public void parseKeywords_validOnes() throws Exception { final Keyword[] validKeywords = new Keyword[]{Keyword.HELP, Keyword.HOWTO, Keyword.NEW, Keyword.NONE}; for (Keyword keyword : validKeywords) { final String keywordKeyword = keyword.getKeyword(); if (keywordKeyword == null) { continue; } when(mimeMessage.getSubject()).thenReturn(keywordKeyword); final MailMessage message = subject.parse(mimeMessage, updateContext); assertThat(keyword.toString(), message.getKeyword(), is(keyword)); verify(updateContext, never()).addGlobalMessage(any(Message.class)); } } | public MailMessage parse(final MimeMessage message, final UpdateContext updateContext) throws MessagingException { final MailMessageBuilder messageBuilder = new MailMessageBuilder(); messageBuilder.id(message.getMessageID()); parseSubject(messageBuilder, message, updateContext); String[] deliveryDate = message.getHeader("Delivery-date"); if (deliveryDate != null && deliveryDate.length > 0 && deliveryDate[0].length() > 0) { messageBuilder.date(deliveryDate[0]); } else { messageBuilder.date(DATE_FORMAT.format(ZonedDateTime.now())); } parseReplyTo(messageBuilder, message); try { parseContents(messageBuilder, message); final MailMessage mailMessage = messageBuilder.build(); if (!mailMessage.getKeyword().isContentExpected() || !mailMessage.getContentWithCredentials().isEmpty()) { return mailMessage; } } catch (ParseException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message"), e); } catch (MessagingException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message using java mail"), e); } catch (IOException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Exception parsing message"), e); } catch (RuntimeException e) { LOGGER.error("Unexpected error parsing message: {}", message.getMessageID(), e); } updateContext.addGlobalMessage(UpdateMessages.noValidUpdateFound()); return messageBuilder.build(); } | MessageParser { public MailMessage parse(final MimeMessage message, final UpdateContext updateContext) throws MessagingException { final MailMessageBuilder messageBuilder = new MailMessageBuilder(); messageBuilder.id(message.getMessageID()); parseSubject(messageBuilder, message, updateContext); String[] deliveryDate = message.getHeader("Delivery-date"); if (deliveryDate != null && deliveryDate.length > 0 && deliveryDate[0].length() > 0) { messageBuilder.date(deliveryDate[0]); } else { messageBuilder.date(DATE_FORMAT.format(ZonedDateTime.now())); } parseReplyTo(messageBuilder, message); try { parseContents(messageBuilder, message); final MailMessage mailMessage = messageBuilder.build(); if (!mailMessage.getKeyword().isContentExpected() || !mailMessage.getContentWithCredentials().isEmpty()) { return mailMessage; } } catch (ParseException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message"), e); } catch (MessagingException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message using java mail"), e); } catch (IOException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Exception parsing message"), e); } catch (RuntimeException e) { LOGGER.error("Unexpected error parsing message: {}", message.getMessageID(), e); } updateContext.addGlobalMessage(UpdateMessages.noValidUpdateFound()); return messageBuilder.build(); } } | MessageParser { public MailMessage parse(final MimeMessage message, final UpdateContext updateContext) throws MessagingException { final MailMessageBuilder messageBuilder = new MailMessageBuilder(); messageBuilder.id(message.getMessageID()); parseSubject(messageBuilder, message, updateContext); String[] deliveryDate = message.getHeader("Delivery-date"); if (deliveryDate != null && deliveryDate.length > 0 && deliveryDate[0].length() > 0) { messageBuilder.date(deliveryDate[0]); } else { messageBuilder.date(DATE_FORMAT.format(ZonedDateTime.now())); } parseReplyTo(messageBuilder, message); try { parseContents(messageBuilder, message); final MailMessage mailMessage = messageBuilder.build(); if (!mailMessage.getKeyword().isContentExpected() || !mailMessage.getContentWithCredentials().isEmpty()) { return mailMessage; } } catch (ParseException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message"), e); } catch (MessagingException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message using java mail"), e); } catch (IOException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Exception parsing message"), e); } catch (RuntimeException e) { LOGGER.error("Unexpected error parsing message: {}", message.getMessageID(), e); } updateContext.addGlobalMessage(UpdateMessages.noValidUpdateFound()); return messageBuilder.build(); } @Autowired MessageParser(final LoggerContext loggerContext); } | MessageParser { public MailMessage parse(final MimeMessage message, final UpdateContext updateContext) throws MessagingException { final MailMessageBuilder messageBuilder = new MailMessageBuilder(); messageBuilder.id(message.getMessageID()); parseSubject(messageBuilder, message, updateContext); String[] deliveryDate = message.getHeader("Delivery-date"); if (deliveryDate != null && deliveryDate.length > 0 && deliveryDate[0].length() > 0) { messageBuilder.date(deliveryDate[0]); } else { messageBuilder.date(DATE_FORMAT.format(ZonedDateTime.now())); } parseReplyTo(messageBuilder, message); try { parseContents(messageBuilder, message); final MailMessage mailMessage = messageBuilder.build(); if (!mailMessage.getKeyword().isContentExpected() || !mailMessage.getContentWithCredentials().isEmpty()) { return mailMessage; } } catch (ParseException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message"), e); } catch (MessagingException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message using java mail"), e); } catch (IOException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Exception parsing message"), e); } catch (RuntimeException e) { LOGGER.error("Unexpected error parsing message: {}", message.getMessageID(), e); } updateContext.addGlobalMessage(UpdateMessages.noValidUpdateFound()); return messageBuilder.build(); } @Autowired MessageParser(final LoggerContext loggerContext); MailMessage parse(final MimeMessage message, final UpdateContext updateContext); } | MessageParser { public MailMessage parse(final MimeMessage message, final UpdateContext updateContext) throws MessagingException { final MailMessageBuilder messageBuilder = new MailMessageBuilder(); messageBuilder.id(message.getMessageID()); parseSubject(messageBuilder, message, updateContext); String[] deliveryDate = message.getHeader("Delivery-date"); if (deliveryDate != null && deliveryDate.length > 0 && deliveryDate[0].length() > 0) { messageBuilder.date(deliveryDate[0]); } else { messageBuilder.date(DATE_FORMAT.format(ZonedDateTime.now())); } parseReplyTo(messageBuilder, message); try { parseContents(messageBuilder, message); final MailMessage mailMessage = messageBuilder.build(); if (!mailMessage.getKeyword().isContentExpected() || !mailMessage.getContentWithCredentials().isEmpty()) { return mailMessage; } } catch (ParseException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message"), e); } catch (MessagingException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message using java mail"), e); } catch (IOException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Exception parsing message"), e); } catch (RuntimeException e) { LOGGER.error("Unexpected error parsing message: {}", message.getMessageID(), e); } updateContext.addGlobalMessage(UpdateMessages.noValidUpdateFound()); return messageBuilder.build(); } @Autowired MessageParser(final LoggerContext loggerContext); MailMessage parse(final MimeMessage message, final UpdateContext updateContext); } |
@Test public void parseKeywords_diff() throws Exception { final Keyword keyword = Keyword.DIFF; when(mimeMessage.getSubject()).thenReturn(keyword.getKeyword()); final MailMessage message = subject.parse(mimeMessage, updateContext); assertThat(keyword.toString(), message.getKeyword(), is(keyword)); verify(updateContext, times(1)).addGlobalMessage(UpdateMessages.diffNotSupported()); } | public MailMessage parse(final MimeMessage message, final UpdateContext updateContext) throws MessagingException { final MailMessageBuilder messageBuilder = new MailMessageBuilder(); messageBuilder.id(message.getMessageID()); parseSubject(messageBuilder, message, updateContext); String[] deliveryDate = message.getHeader("Delivery-date"); if (deliveryDate != null && deliveryDate.length > 0 && deliveryDate[0].length() > 0) { messageBuilder.date(deliveryDate[0]); } else { messageBuilder.date(DATE_FORMAT.format(ZonedDateTime.now())); } parseReplyTo(messageBuilder, message); try { parseContents(messageBuilder, message); final MailMessage mailMessage = messageBuilder.build(); if (!mailMessage.getKeyword().isContentExpected() || !mailMessage.getContentWithCredentials().isEmpty()) { return mailMessage; } } catch (ParseException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message"), e); } catch (MessagingException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message using java mail"), e); } catch (IOException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Exception parsing message"), e); } catch (RuntimeException e) { LOGGER.error("Unexpected error parsing message: {}", message.getMessageID(), e); } updateContext.addGlobalMessage(UpdateMessages.noValidUpdateFound()); return messageBuilder.build(); } | MessageParser { public MailMessage parse(final MimeMessage message, final UpdateContext updateContext) throws MessagingException { final MailMessageBuilder messageBuilder = new MailMessageBuilder(); messageBuilder.id(message.getMessageID()); parseSubject(messageBuilder, message, updateContext); String[] deliveryDate = message.getHeader("Delivery-date"); if (deliveryDate != null && deliveryDate.length > 0 && deliveryDate[0].length() > 0) { messageBuilder.date(deliveryDate[0]); } else { messageBuilder.date(DATE_FORMAT.format(ZonedDateTime.now())); } parseReplyTo(messageBuilder, message); try { parseContents(messageBuilder, message); final MailMessage mailMessage = messageBuilder.build(); if (!mailMessage.getKeyword().isContentExpected() || !mailMessage.getContentWithCredentials().isEmpty()) { return mailMessage; } } catch (ParseException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message"), e); } catch (MessagingException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message using java mail"), e); } catch (IOException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Exception parsing message"), e); } catch (RuntimeException e) { LOGGER.error("Unexpected error parsing message: {}", message.getMessageID(), e); } updateContext.addGlobalMessage(UpdateMessages.noValidUpdateFound()); return messageBuilder.build(); } } | MessageParser { public MailMessage parse(final MimeMessage message, final UpdateContext updateContext) throws MessagingException { final MailMessageBuilder messageBuilder = new MailMessageBuilder(); messageBuilder.id(message.getMessageID()); parseSubject(messageBuilder, message, updateContext); String[] deliveryDate = message.getHeader("Delivery-date"); if (deliveryDate != null && deliveryDate.length > 0 && deliveryDate[0].length() > 0) { messageBuilder.date(deliveryDate[0]); } else { messageBuilder.date(DATE_FORMAT.format(ZonedDateTime.now())); } parseReplyTo(messageBuilder, message); try { parseContents(messageBuilder, message); final MailMessage mailMessage = messageBuilder.build(); if (!mailMessage.getKeyword().isContentExpected() || !mailMessage.getContentWithCredentials().isEmpty()) { return mailMessage; } } catch (ParseException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message"), e); } catch (MessagingException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message using java mail"), e); } catch (IOException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Exception parsing message"), e); } catch (RuntimeException e) { LOGGER.error("Unexpected error parsing message: {}", message.getMessageID(), e); } updateContext.addGlobalMessage(UpdateMessages.noValidUpdateFound()); return messageBuilder.build(); } @Autowired MessageParser(final LoggerContext loggerContext); } | MessageParser { public MailMessage parse(final MimeMessage message, final UpdateContext updateContext) throws MessagingException { final MailMessageBuilder messageBuilder = new MailMessageBuilder(); messageBuilder.id(message.getMessageID()); parseSubject(messageBuilder, message, updateContext); String[] deliveryDate = message.getHeader("Delivery-date"); if (deliveryDate != null && deliveryDate.length > 0 && deliveryDate[0].length() > 0) { messageBuilder.date(deliveryDate[0]); } else { messageBuilder.date(DATE_FORMAT.format(ZonedDateTime.now())); } parseReplyTo(messageBuilder, message); try { parseContents(messageBuilder, message); final MailMessage mailMessage = messageBuilder.build(); if (!mailMessage.getKeyword().isContentExpected() || !mailMessage.getContentWithCredentials().isEmpty()) { return mailMessage; } } catch (ParseException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message"), e); } catch (MessagingException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message using java mail"), e); } catch (IOException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Exception parsing message"), e); } catch (RuntimeException e) { LOGGER.error("Unexpected error parsing message: {}", message.getMessageID(), e); } updateContext.addGlobalMessage(UpdateMessages.noValidUpdateFound()); return messageBuilder.build(); } @Autowired MessageParser(final LoggerContext loggerContext); MailMessage parse(final MimeMessage message, final UpdateContext updateContext); } | MessageParser { public MailMessage parse(final MimeMessage message, final UpdateContext updateContext) throws MessagingException { final MailMessageBuilder messageBuilder = new MailMessageBuilder(); messageBuilder.id(message.getMessageID()); parseSubject(messageBuilder, message, updateContext); String[] deliveryDate = message.getHeader("Delivery-date"); if (deliveryDate != null && deliveryDate.length > 0 && deliveryDate[0].length() > 0) { messageBuilder.date(deliveryDate[0]); } else { messageBuilder.date(DATE_FORMAT.format(ZonedDateTime.now())); } parseReplyTo(messageBuilder, message); try { parseContents(messageBuilder, message); final MailMessage mailMessage = messageBuilder.build(); if (!mailMessage.getKeyword().isContentExpected() || !mailMessage.getContentWithCredentials().isEmpty()) { return mailMessage; } } catch (ParseException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message"), e); } catch (MessagingException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message using java mail"), e); } catch (IOException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Exception parsing message"), e); } catch (RuntimeException e) { LOGGER.error("Unexpected error parsing message: {}", message.getMessageID(), e); } updateContext.addGlobalMessage(UpdateMessages.noValidUpdateFound()); return messageBuilder.build(); } @Autowired MessageParser(final LoggerContext loggerContext); MailMessage parse(final MimeMessage message, final UpdateContext updateContext); } |
@Test public void role_without_abuse_mailbox() { final RpslObject role = RpslObject.parse(10, "" + "role: RIPE NCC tech contact\n" + "address: RIPE Network Coordination Centre (NCC)\n" + "address: Singel 258\n" + "address: 1016 AB Amsterdam\n" + "address: The Netherlands\n" + "phone: +31 20 535 4444\n" + "fax-no: +31 20 535 4445\n" + "e-mail: [email protected]\n" + "nic-hdl: RNTC-RIPE\n" + "mnt-by: RIPE-DBM-MNT\n" + "notify: [email protected]\n" + "source: RIPE"); final RpslObject dummified = subject.dummify(4, role); assertThat(dummified.getAttributes(), contains( new RpslAttribute("role", "RIPE NCC tech contact"), new RpslAttribute("address", "***"), new RpslAttribute("address", "***"), new RpslAttribute("address", "***"), new RpslAttribute("address", "The Netherlands"), new RpslAttribute("phone", "+31 20 ... ...."), new RpslAttribute("fax-no", "+31 20 ... ...."), new RpslAttribute("e-mail", "***@ripe.net"), new RpslAttribute("nic-hdl", "RNTC-RIPE"), new RpslAttribute("mnt-by", "RIPE-DBM-MNT"), new RpslAttribute("notify", "***@ripe.net"), new RpslAttribute("source", "RIPE") )); } | @Override public RpslObject dummify(final int version, final RpslObject rpslObject) { final ObjectType objectType = rpslObject.getType(); Validate.isTrue(isAllowed(version, rpslObject), "The version is not supported by this dummifier", version); final List<RpslAttribute> attributes = Lists.newArrayList(rpslObject.getAttributes()); RpslAttribute lastAddressLine = null; int lastAddressLineIndex = 0; for (int i = 0; i < attributes.size(); i++) { RpslAttribute replacement = attributes.get(i); final AttributeType attributeType = replacement.getType(); try { if (!(objectType == ObjectType.ROLE && rpslObject.containsAttribute(ABUSE_MAILBOX))) { replacement = replacePerson(attributeType, replacement); replacement = replaceAuth(attributeType, replacement); replacement = replacePhoneFax(attributeType, replacement); if (attributeType == ADDRESS) { lastAddressLine = replacement; lastAddressLineIndex = i; replacement = new RpslAttribute(ADDRESS, "***"); } } replacement = replaceEmail(attributeType, replacement); attributes.set(i, replacement); } catch (RuntimeException e) { LOGGER.debug("Dummifier failed on [" + attributes.get(i).toString().trim() + "]", e); } } if (lastAddressLine != null) { attributes.set(lastAddressLineIndex, lastAddressLine); } return FILTER_CHANGED_FUNCTION.apply(new RpslObject(rpslObject, attributes)); } | DummifierCurrent implements Dummifier { @Override public RpslObject dummify(final int version, final RpslObject rpslObject) { final ObjectType objectType = rpslObject.getType(); Validate.isTrue(isAllowed(version, rpslObject), "The version is not supported by this dummifier", version); final List<RpslAttribute> attributes = Lists.newArrayList(rpslObject.getAttributes()); RpslAttribute lastAddressLine = null; int lastAddressLineIndex = 0; for (int i = 0; i < attributes.size(); i++) { RpslAttribute replacement = attributes.get(i); final AttributeType attributeType = replacement.getType(); try { if (!(objectType == ObjectType.ROLE && rpslObject.containsAttribute(ABUSE_MAILBOX))) { replacement = replacePerson(attributeType, replacement); replacement = replaceAuth(attributeType, replacement); replacement = replacePhoneFax(attributeType, replacement); if (attributeType == ADDRESS) { lastAddressLine = replacement; lastAddressLineIndex = i; replacement = new RpslAttribute(ADDRESS, "***"); } } replacement = replaceEmail(attributeType, replacement); attributes.set(i, replacement); } catch (RuntimeException e) { LOGGER.debug("Dummifier failed on [" + attributes.get(i).toString().trim() + "]", e); } } if (lastAddressLine != null) { attributes.set(lastAddressLineIndex, lastAddressLine); } return FILTER_CHANGED_FUNCTION.apply(new RpslObject(rpslObject, attributes)); } } | DummifierCurrent implements Dummifier { @Override public RpslObject dummify(final int version, final RpslObject rpslObject) { final ObjectType objectType = rpslObject.getType(); Validate.isTrue(isAllowed(version, rpslObject), "The version is not supported by this dummifier", version); final List<RpslAttribute> attributes = Lists.newArrayList(rpslObject.getAttributes()); RpslAttribute lastAddressLine = null; int lastAddressLineIndex = 0; for (int i = 0; i < attributes.size(); i++) { RpslAttribute replacement = attributes.get(i); final AttributeType attributeType = replacement.getType(); try { if (!(objectType == ObjectType.ROLE && rpslObject.containsAttribute(ABUSE_MAILBOX))) { replacement = replacePerson(attributeType, replacement); replacement = replaceAuth(attributeType, replacement); replacement = replacePhoneFax(attributeType, replacement); if (attributeType == ADDRESS) { lastAddressLine = replacement; lastAddressLineIndex = i; replacement = new RpslAttribute(ADDRESS, "***"); } } replacement = replaceEmail(attributeType, replacement); attributes.set(i, replacement); } catch (RuntimeException e) { LOGGER.debug("Dummifier failed on [" + attributes.get(i).toString().trim() + "]", e); } } if (lastAddressLine != null) { attributes.set(lastAddressLineIndex, lastAddressLine); } return FILTER_CHANGED_FUNCTION.apply(new RpslObject(rpslObject, attributes)); } } | DummifierCurrent implements Dummifier { @Override public RpslObject dummify(final int version, final RpslObject rpslObject) { final ObjectType objectType = rpslObject.getType(); Validate.isTrue(isAllowed(version, rpslObject), "The version is not supported by this dummifier", version); final List<RpslAttribute> attributes = Lists.newArrayList(rpslObject.getAttributes()); RpslAttribute lastAddressLine = null; int lastAddressLineIndex = 0; for (int i = 0; i < attributes.size(); i++) { RpslAttribute replacement = attributes.get(i); final AttributeType attributeType = replacement.getType(); try { if (!(objectType == ObjectType.ROLE && rpslObject.containsAttribute(ABUSE_MAILBOX))) { replacement = replacePerson(attributeType, replacement); replacement = replaceAuth(attributeType, replacement); replacement = replacePhoneFax(attributeType, replacement); if (attributeType == ADDRESS) { lastAddressLine = replacement; lastAddressLineIndex = i; replacement = new RpslAttribute(ADDRESS, "***"); } } replacement = replaceEmail(attributeType, replacement); attributes.set(i, replacement); } catch (RuntimeException e) { LOGGER.debug("Dummifier failed on [" + attributes.get(i).toString().trim() + "]", e); } } if (lastAddressLine != null) { attributes.set(lastAddressLineIndex, lastAddressLine); } return FILTER_CHANGED_FUNCTION.apply(new RpslObject(rpslObject, attributes)); } @Override RpslObject dummify(final int version, final RpslObject rpslObject); @Override boolean isAllowed(final int version, final RpslObject object); } | DummifierCurrent implements Dummifier { @Override public RpslObject dummify(final int version, final RpslObject rpslObject) { final ObjectType objectType = rpslObject.getType(); Validate.isTrue(isAllowed(version, rpslObject), "The version is not supported by this dummifier", version); final List<RpslAttribute> attributes = Lists.newArrayList(rpslObject.getAttributes()); RpslAttribute lastAddressLine = null; int lastAddressLineIndex = 0; for (int i = 0; i < attributes.size(); i++) { RpslAttribute replacement = attributes.get(i); final AttributeType attributeType = replacement.getType(); try { if (!(objectType == ObjectType.ROLE && rpslObject.containsAttribute(ABUSE_MAILBOX))) { replacement = replacePerson(attributeType, replacement); replacement = replaceAuth(attributeType, replacement); replacement = replacePhoneFax(attributeType, replacement); if (attributeType == ADDRESS) { lastAddressLine = replacement; lastAddressLineIndex = i; replacement = new RpslAttribute(ADDRESS, "***"); } } replacement = replaceEmail(attributeType, replacement); attributes.set(i, replacement); } catch (RuntimeException e) { LOGGER.debug("Dummifier failed on [" + attributes.get(i).toString().trim() + "]", e); } } if (lastAddressLine != null) { attributes.set(lastAddressLineIndex, lastAddressLine); } return FILTER_CHANGED_FUNCTION.apply(new RpslObject(rpslObject, attributes)); } @Override RpslObject dummify(final int version, final RpslObject rpslObject); @Override boolean isAllowed(final int version, final RpslObject object); } |
@Test public void parse_set_delivery_date() throws Exception { MimeMessage simpleTextUnsignedMessage = MimeMessageProvider.getMessageSimpleTextUnsigned(); final MailMessage result = subject.parse(simpleTextUnsignedMessage, updateContext); assertThat(result.getDate(), is("Mon, 28 May 2012 00:04:45 +0200")); } | public MailMessage parse(final MimeMessage message, final UpdateContext updateContext) throws MessagingException { final MailMessageBuilder messageBuilder = new MailMessageBuilder(); messageBuilder.id(message.getMessageID()); parseSubject(messageBuilder, message, updateContext); String[] deliveryDate = message.getHeader("Delivery-date"); if (deliveryDate != null && deliveryDate.length > 0 && deliveryDate[0].length() > 0) { messageBuilder.date(deliveryDate[0]); } else { messageBuilder.date(DATE_FORMAT.format(ZonedDateTime.now())); } parseReplyTo(messageBuilder, message); try { parseContents(messageBuilder, message); final MailMessage mailMessage = messageBuilder.build(); if (!mailMessage.getKeyword().isContentExpected() || !mailMessage.getContentWithCredentials().isEmpty()) { return mailMessage; } } catch (ParseException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message"), e); } catch (MessagingException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message using java mail"), e); } catch (IOException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Exception parsing message"), e); } catch (RuntimeException e) { LOGGER.error("Unexpected error parsing message: {}", message.getMessageID(), e); } updateContext.addGlobalMessage(UpdateMessages.noValidUpdateFound()); return messageBuilder.build(); } | MessageParser { public MailMessage parse(final MimeMessage message, final UpdateContext updateContext) throws MessagingException { final MailMessageBuilder messageBuilder = new MailMessageBuilder(); messageBuilder.id(message.getMessageID()); parseSubject(messageBuilder, message, updateContext); String[] deliveryDate = message.getHeader("Delivery-date"); if (deliveryDate != null && deliveryDate.length > 0 && deliveryDate[0].length() > 0) { messageBuilder.date(deliveryDate[0]); } else { messageBuilder.date(DATE_FORMAT.format(ZonedDateTime.now())); } parseReplyTo(messageBuilder, message); try { parseContents(messageBuilder, message); final MailMessage mailMessage = messageBuilder.build(); if (!mailMessage.getKeyword().isContentExpected() || !mailMessage.getContentWithCredentials().isEmpty()) { return mailMessage; } } catch (ParseException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message"), e); } catch (MessagingException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message using java mail"), e); } catch (IOException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Exception parsing message"), e); } catch (RuntimeException e) { LOGGER.error("Unexpected error parsing message: {}", message.getMessageID(), e); } updateContext.addGlobalMessage(UpdateMessages.noValidUpdateFound()); return messageBuilder.build(); } } | MessageParser { public MailMessage parse(final MimeMessage message, final UpdateContext updateContext) throws MessagingException { final MailMessageBuilder messageBuilder = new MailMessageBuilder(); messageBuilder.id(message.getMessageID()); parseSubject(messageBuilder, message, updateContext); String[] deliveryDate = message.getHeader("Delivery-date"); if (deliveryDate != null && deliveryDate.length > 0 && deliveryDate[0].length() > 0) { messageBuilder.date(deliveryDate[0]); } else { messageBuilder.date(DATE_FORMAT.format(ZonedDateTime.now())); } parseReplyTo(messageBuilder, message); try { parseContents(messageBuilder, message); final MailMessage mailMessage = messageBuilder.build(); if (!mailMessage.getKeyword().isContentExpected() || !mailMessage.getContentWithCredentials().isEmpty()) { return mailMessage; } } catch (ParseException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message"), e); } catch (MessagingException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message using java mail"), e); } catch (IOException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Exception parsing message"), e); } catch (RuntimeException e) { LOGGER.error("Unexpected error parsing message: {}", message.getMessageID(), e); } updateContext.addGlobalMessage(UpdateMessages.noValidUpdateFound()); return messageBuilder.build(); } @Autowired MessageParser(final LoggerContext loggerContext); } | MessageParser { public MailMessage parse(final MimeMessage message, final UpdateContext updateContext) throws MessagingException { final MailMessageBuilder messageBuilder = new MailMessageBuilder(); messageBuilder.id(message.getMessageID()); parseSubject(messageBuilder, message, updateContext); String[] deliveryDate = message.getHeader("Delivery-date"); if (deliveryDate != null && deliveryDate.length > 0 && deliveryDate[0].length() > 0) { messageBuilder.date(deliveryDate[0]); } else { messageBuilder.date(DATE_FORMAT.format(ZonedDateTime.now())); } parseReplyTo(messageBuilder, message); try { parseContents(messageBuilder, message); final MailMessage mailMessage = messageBuilder.build(); if (!mailMessage.getKeyword().isContentExpected() || !mailMessage.getContentWithCredentials().isEmpty()) { return mailMessage; } } catch (ParseException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message"), e); } catch (MessagingException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message using java mail"), e); } catch (IOException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Exception parsing message"), e); } catch (RuntimeException e) { LOGGER.error("Unexpected error parsing message: {}", message.getMessageID(), e); } updateContext.addGlobalMessage(UpdateMessages.noValidUpdateFound()); return messageBuilder.build(); } @Autowired MessageParser(final LoggerContext loggerContext); MailMessage parse(final MimeMessage message, final UpdateContext updateContext); } | MessageParser { public MailMessage parse(final MimeMessage message, final UpdateContext updateContext) throws MessagingException { final MailMessageBuilder messageBuilder = new MailMessageBuilder(); messageBuilder.id(message.getMessageID()); parseSubject(messageBuilder, message, updateContext); String[] deliveryDate = message.getHeader("Delivery-date"); if (deliveryDate != null && deliveryDate.length > 0 && deliveryDate[0].length() > 0) { messageBuilder.date(deliveryDate[0]); } else { messageBuilder.date(DATE_FORMAT.format(ZonedDateTime.now())); } parseReplyTo(messageBuilder, message); try { parseContents(messageBuilder, message); final MailMessage mailMessage = messageBuilder.build(); if (!mailMessage.getKeyword().isContentExpected() || !mailMessage.getContentWithCredentials().isEmpty()) { return mailMessage; } } catch (ParseException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message"), e); } catch (MessagingException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message using java mail"), e); } catch (IOException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Exception parsing message"), e); } catch (RuntimeException e) { LOGGER.error("Unexpected error parsing message: {}", message.getMessageID(), e); } updateContext.addGlobalMessage(UpdateMessages.noValidUpdateFound()); return messageBuilder.build(); } @Autowired MessageParser(final LoggerContext loggerContext); MailMessage parse(final MimeMessage message, final UpdateContext updateContext); } |
@Test public void parse_set_default_date() throws Exception { when(mimeMessage.getSubject()).thenReturn("NEW"); final MailMessage message = subject.parse(mimeMessage, updateContext); assertThat(message.getDate().length(), not(is(0))); final String timezone = DateTimeFormatter.ofPattern("zzz").format(ZonedDateTime.now()); assertThat(message.getDate(), containsString(timezone)); final String year = DateTimeFormatter.ofPattern("yyyy").format(ZonedDateTime.now()); assertThat(message.getDate(), containsString(year)); } | public MailMessage parse(final MimeMessage message, final UpdateContext updateContext) throws MessagingException { final MailMessageBuilder messageBuilder = new MailMessageBuilder(); messageBuilder.id(message.getMessageID()); parseSubject(messageBuilder, message, updateContext); String[] deliveryDate = message.getHeader("Delivery-date"); if (deliveryDate != null && deliveryDate.length > 0 && deliveryDate[0].length() > 0) { messageBuilder.date(deliveryDate[0]); } else { messageBuilder.date(DATE_FORMAT.format(ZonedDateTime.now())); } parseReplyTo(messageBuilder, message); try { parseContents(messageBuilder, message); final MailMessage mailMessage = messageBuilder.build(); if (!mailMessage.getKeyword().isContentExpected() || !mailMessage.getContentWithCredentials().isEmpty()) { return mailMessage; } } catch (ParseException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message"), e); } catch (MessagingException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message using java mail"), e); } catch (IOException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Exception parsing message"), e); } catch (RuntimeException e) { LOGGER.error("Unexpected error parsing message: {}", message.getMessageID(), e); } updateContext.addGlobalMessage(UpdateMessages.noValidUpdateFound()); return messageBuilder.build(); } | MessageParser { public MailMessage parse(final MimeMessage message, final UpdateContext updateContext) throws MessagingException { final MailMessageBuilder messageBuilder = new MailMessageBuilder(); messageBuilder.id(message.getMessageID()); parseSubject(messageBuilder, message, updateContext); String[] deliveryDate = message.getHeader("Delivery-date"); if (deliveryDate != null && deliveryDate.length > 0 && deliveryDate[0].length() > 0) { messageBuilder.date(deliveryDate[0]); } else { messageBuilder.date(DATE_FORMAT.format(ZonedDateTime.now())); } parseReplyTo(messageBuilder, message); try { parseContents(messageBuilder, message); final MailMessage mailMessage = messageBuilder.build(); if (!mailMessage.getKeyword().isContentExpected() || !mailMessage.getContentWithCredentials().isEmpty()) { return mailMessage; } } catch (ParseException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message"), e); } catch (MessagingException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message using java mail"), e); } catch (IOException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Exception parsing message"), e); } catch (RuntimeException e) { LOGGER.error("Unexpected error parsing message: {}", message.getMessageID(), e); } updateContext.addGlobalMessage(UpdateMessages.noValidUpdateFound()); return messageBuilder.build(); } } | MessageParser { public MailMessage parse(final MimeMessage message, final UpdateContext updateContext) throws MessagingException { final MailMessageBuilder messageBuilder = new MailMessageBuilder(); messageBuilder.id(message.getMessageID()); parseSubject(messageBuilder, message, updateContext); String[] deliveryDate = message.getHeader("Delivery-date"); if (deliveryDate != null && deliveryDate.length > 0 && deliveryDate[0].length() > 0) { messageBuilder.date(deliveryDate[0]); } else { messageBuilder.date(DATE_FORMAT.format(ZonedDateTime.now())); } parseReplyTo(messageBuilder, message); try { parseContents(messageBuilder, message); final MailMessage mailMessage = messageBuilder.build(); if (!mailMessage.getKeyword().isContentExpected() || !mailMessage.getContentWithCredentials().isEmpty()) { return mailMessage; } } catch (ParseException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message"), e); } catch (MessagingException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message using java mail"), e); } catch (IOException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Exception parsing message"), e); } catch (RuntimeException e) { LOGGER.error("Unexpected error parsing message: {}", message.getMessageID(), e); } updateContext.addGlobalMessage(UpdateMessages.noValidUpdateFound()); return messageBuilder.build(); } @Autowired MessageParser(final LoggerContext loggerContext); } | MessageParser { public MailMessage parse(final MimeMessage message, final UpdateContext updateContext) throws MessagingException { final MailMessageBuilder messageBuilder = new MailMessageBuilder(); messageBuilder.id(message.getMessageID()); parseSubject(messageBuilder, message, updateContext); String[] deliveryDate = message.getHeader("Delivery-date"); if (deliveryDate != null && deliveryDate.length > 0 && deliveryDate[0].length() > 0) { messageBuilder.date(deliveryDate[0]); } else { messageBuilder.date(DATE_FORMAT.format(ZonedDateTime.now())); } parseReplyTo(messageBuilder, message); try { parseContents(messageBuilder, message); final MailMessage mailMessage = messageBuilder.build(); if (!mailMessage.getKeyword().isContentExpected() || !mailMessage.getContentWithCredentials().isEmpty()) { return mailMessage; } } catch (ParseException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message"), e); } catch (MessagingException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message using java mail"), e); } catch (IOException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Exception parsing message"), e); } catch (RuntimeException e) { LOGGER.error("Unexpected error parsing message: {}", message.getMessageID(), e); } updateContext.addGlobalMessage(UpdateMessages.noValidUpdateFound()); return messageBuilder.build(); } @Autowired MessageParser(final LoggerContext loggerContext); MailMessage parse(final MimeMessage message, final UpdateContext updateContext); } | MessageParser { public MailMessage parse(final MimeMessage message, final UpdateContext updateContext) throws MessagingException { final MailMessageBuilder messageBuilder = new MailMessageBuilder(); messageBuilder.id(message.getMessageID()); parseSubject(messageBuilder, message, updateContext); String[] deliveryDate = message.getHeader("Delivery-date"); if (deliveryDate != null && deliveryDate.length > 0 && deliveryDate[0].length() > 0) { messageBuilder.date(deliveryDate[0]); } else { messageBuilder.date(DATE_FORMAT.format(ZonedDateTime.now())); } parseReplyTo(messageBuilder, message); try { parseContents(messageBuilder, message); final MailMessage mailMessage = messageBuilder.build(); if (!mailMessage.getKeyword().isContentExpected() || !mailMessage.getContentWithCredentials().isEmpty()) { return mailMessage; } } catch (ParseException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message"), e); } catch (MessagingException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message using java mail"), e); } catch (IOException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Exception parsing message"), e); } catch (RuntimeException e) { LOGGER.error("Unexpected error parsing message: {}", message.getMessageID(), e); } updateContext.addGlobalMessage(UpdateMessages.noValidUpdateFound()); return messageBuilder.build(); } @Autowired MessageParser(final LoggerContext loggerContext); MailMessage parse(final MimeMessage message, final UpdateContext updateContext); } |
@Test public void parseKeywords_mixedCaps() throws Exception { when(mimeMessage.getSubject()).thenReturn("nEw"); final MailMessage message = subject.parse(mimeMessage, updateContext); assertThat(message.getKeyword(), is(Keyword.NEW)); verify(updateContext, never()).addGlobalMessage(any(Message.class)); } | public MailMessage parse(final MimeMessage message, final UpdateContext updateContext) throws MessagingException { final MailMessageBuilder messageBuilder = new MailMessageBuilder(); messageBuilder.id(message.getMessageID()); parseSubject(messageBuilder, message, updateContext); String[] deliveryDate = message.getHeader("Delivery-date"); if (deliveryDate != null && deliveryDate.length > 0 && deliveryDate[0].length() > 0) { messageBuilder.date(deliveryDate[0]); } else { messageBuilder.date(DATE_FORMAT.format(ZonedDateTime.now())); } parseReplyTo(messageBuilder, message); try { parseContents(messageBuilder, message); final MailMessage mailMessage = messageBuilder.build(); if (!mailMessage.getKeyword().isContentExpected() || !mailMessage.getContentWithCredentials().isEmpty()) { return mailMessage; } } catch (ParseException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message"), e); } catch (MessagingException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message using java mail"), e); } catch (IOException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Exception parsing message"), e); } catch (RuntimeException e) { LOGGER.error("Unexpected error parsing message: {}", message.getMessageID(), e); } updateContext.addGlobalMessage(UpdateMessages.noValidUpdateFound()); return messageBuilder.build(); } | MessageParser { public MailMessage parse(final MimeMessage message, final UpdateContext updateContext) throws MessagingException { final MailMessageBuilder messageBuilder = new MailMessageBuilder(); messageBuilder.id(message.getMessageID()); parseSubject(messageBuilder, message, updateContext); String[] deliveryDate = message.getHeader("Delivery-date"); if (deliveryDate != null && deliveryDate.length > 0 && deliveryDate[0].length() > 0) { messageBuilder.date(deliveryDate[0]); } else { messageBuilder.date(DATE_FORMAT.format(ZonedDateTime.now())); } parseReplyTo(messageBuilder, message); try { parseContents(messageBuilder, message); final MailMessage mailMessage = messageBuilder.build(); if (!mailMessage.getKeyword().isContentExpected() || !mailMessage.getContentWithCredentials().isEmpty()) { return mailMessage; } } catch (ParseException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message"), e); } catch (MessagingException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message using java mail"), e); } catch (IOException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Exception parsing message"), e); } catch (RuntimeException e) { LOGGER.error("Unexpected error parsing message: {}", message.getMessageID(), e); } updateContext.addGlobalMessage(UpdateMessages.noValidUpdateFound()); return messageBuilder.build(); } } | MessageParser { public MailMessage parse(final MimeMessage message, final UpdateContext updateContext) throws MessagingException { final MailMessageBuilder messageBuilder = new MailMessageBuilder(); messageBuilder.id(message.getMessageID()); parseSubject(messageBuilder, message, updateContext); String[] deliveryDate = message.getHeader("Delivery-date"); if (deliveryDate != null && deliveryDate.length > 0 && deliveryDate[0].length() > 0) { messageBuilder.date(deliveryDate[0]); } else { messageBuilder.date(DATE_FORMAT.format(ZonedDateTime.now())); } parseReplyTo(messageBuilder, message); try { parseContents(messageBuilder, message); final MailMessage mailMessage = messageBuilder.build(); if (!mailMessage.getKeyword().isContentExpected() || !mailMessage.getContentWithCredentials().isEmpty()) { return mailMessage; } } catch (ParseException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message"), e); } catch (MessagingException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message using java mail"), e); } catch (IOException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Exception parsing message"), e); } catch (RuntimeException e) { LOGGER.error("Unexpected error parsing message: {}", message.getMessageID(), e); } updateContext.addGlobalMessage(UpdateMessages.noValidUpdateFound()); return messageBuilder.build(); } @Autowired MessageParser(final LoggerContext loggerContext); } | MessageParser { public MailMessage parse(final MimeMessage message, final UpdateContext updateContext) throws MessagingException { final MailMessageBuilder messageBuilder = new MailMessageBuilder(); messageBuilder.id(message.getMessageID()); parseSubject(messageBuilder, message, updateContext); String[] deliveryDate = message.getHeader("Delivery-date"); if (deliveryDate != null && deliveryDate.length > 0 && deliveryDate[0].length() > 0) { messageBuilder.date(deliveryDate[0]); } else { messageBuilder.date(DATE_FORMAT.format(ZonedDateTime.now())); } parseReplyTo(messageBuilder, message); try { parseContents(messageBuilder, message); final MailMessage mailMessage = messageBuilder.build(); if (!mailMessage.getKeyword().isContentExpected() || !mailMessage.getContentWithCredentials().isEmpty()) { return mailMessage; } } catch (ParseException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message"), e); } catch (MessagingException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message using java mail"), e); } catch (IOException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Exception parsing message"), e); } catch (RuntimeException e) { LOGGER.error("Unexpected error parsing message: {}", message.getMessageID(), e); } updateContext.addGlobalMessage(UpdateMessages.noValidUpdateFound()); return messageBuilder.build(); } @Autowired MessageParser(final LoggerContext loggerContext); MailMessage parse(final MimeMessage message, final UpdateContext updateContext); } | MessageParser { public MailMessage parse(final MimeMessage message, final UpdateContext updateContext) throws MessagingException { final MailMessageBuilder messageBuilder = new MailMessageBuilder(); messageBuilder.id(message.getMessageID()); parseSubject(messageBuilder, message, updateContext); String[] deliveryDate = message.getHeader("Delivery-date"); if (deliveryDate != null && deliveryDate.length > 0 && deliveryDate[0].length() > 0) { messageBuilder.date(deliveryDate[0]); } else { messageBuilder.date(DATE_FORMAT.format(ZonedDateTime.now())); } parseReplyTo(messageBuilder, message); try { parseContents(messageBuilder, message); final MailMessage mailMessage = messageBuilder.build(); if (!mailMessage.getKeyword().isContentExpected() || !mailMessage.getContentWithCredentials().isEmpty()) { return mailMessage; } } catch (ParseException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message"), e); } catch (MessagingException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message using java mail"), e); } catch (IOException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Exception parsing message"), e); } catch (RuntimeException e) { LOGGER.error("Unexpected error parsing message: {}", message.getMessageID(), e); } updateContext.addGlobalMessage(UpdateMessages.noValidUpdateFound()); return messageBuilder.build(); } @Autowired MessageParser(final LoggerContext loggerContext); MailMessage parse(final MimeMessage message, final UpdateContext updateContext); } |
@Test public void parseSending_stringWithKeyword() throws Exception { final String keywordString = "sending my new objects"; when(mimeMessage.getSubject()).thenReturn(keywordString); final MailMessage message = subject.parse(mimeMessage, updateContext); assertThat(message.getKeyword(), is(Keyword.NONE)); verify(updateContext, times(1)).addGlobalMessage(UpdateMessages.invalidKeywordsFound(keywordString)); verify(updateContext, times(1)).addGlobalMessage(UpdateMessages.allKeywordsIgnored()); } | public MailMessage parse(final MimeMessage message, final UpdateContext updateContext) throws MessagingException { final MailMessageBuilder messageBuilder = new MailMessageBuilder(); messageBuilder.id(message.getMessageID()); parseSubject(messageBuilder, message, updateContext); String[] deliveryDate = message.getHeader("Delivery-date"); if (deliveryDate != null && deliveryDate.length > 0 && deliveryDate[0].length() > 0) { messageBuilder.date(deliveryDate[0]); } else { messageBuilder.date(DATE_FORMAT.format(ZonedDateTime.now())); } parseReplyTo(messageBuilder, message); try { parseContents(messageBuilder, message); final MailMessage mailMessage = messageBuilder.build(); if (!mailMessage.getKeyword().isContentExpected() || !mailMessage.getContentWithCredentials().isEmpty()) { return mailMessage; } } catch (ParseException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message"), e); } catch (MessagingException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message using java mail"), e); } catch (IOException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Exception parsing message"), e); } catch (RuntimeException e) { LOGGER.error("Unexpected error parsing message: {}", message.getMessageID(), e); } updateContext.addGlobalMessage(UpdateMessages.noValidUpdateFound()); return messageBuilder.build(); } | MessageParser { public MailMessage parse(final MimeMessage message, final UpdateContext updateContext) throws MessagingException { final MailMessageBuilder messageBuilder = new MailMessageBuilder(); messageBuilder.id(message.getMessageID()); parseSubject(messageBuilder, message, updateContext); String[] deliveryDate = message.getHeader("Delivery-date"); if (deliveryDate != null && deliveryDate.length > 0 && deliveryDate[0].length() > 0) { messageBuilder.date(deliveryDate[0]); } else { messageBuilder.date(DATE_FORMAT.format(ZonedDateTime.now())); } parseReplyTo(messageBuilder, message); try { parseContents(messageBuilder, message); final MailMessage mailMessage = messageBuilder.build(); if (!mailMessage.getKeyword().isContentExpected() || !mailMessage.getContentWithCredentials().isEmpty()) { return mailMessage; } } catch (ParseException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message"), e); } catch (MessagingException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message using java mail"), e); } catch (IOException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Exception parsing message"), e); } catch (RuntimeException e) { LOGGER.error("Unexpected error parsing message: {}", message.getMessageID(), e); } updateContext.addGlobalMessage(UpdateMessages.noValidUpdateFound()); return messageBuilder.build(); } } | MessageParser { public MailMessage parse(final MimeMessage message, final UpdateContext updateContext) throws MessagingException { final MailMessageBuilder messageBuilder = new MailMessageBuilder(); messageBuilder.id(message.getMessageID()); parseSubject(messageBuilder, message, updateContext); String[] deliveryDate = message.getHeader("Delivery-date"); if (deliveryDate != null && deliveryDate.length > 0 && deliveryDate[0].length() > 0) { messageBuilder.date(deliveryDate[0]); } else { messageBuilder.date(DATE_FORMAT.format(ZonedDateTime.now())); } parseReplyTo(messageBuilder, message); try { parseContents(messageBuilder, message); final MailMessage mailMessage = messageBuilder.build(); if (!mailMessage.getKeyword().isContentExpected() || !mailMessage.getContentWithCredentials().isEmpty()) { return mailMessage; } } catch (ParseException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message"), e); } catch (MessagingException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message using java mail"), e); } catch (IOException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Exception parsing message"), e); } catch (RuntimeException e) { LOGGER.error("Unexpected error parsing message: {}", message.getMessageID(), e); } updateContext.addGlobalMessage(UpdateMessages.noValidUpdateFound()); return messageBuilder.build(); } @Autowired MessageParser(final LoggerContext loggerContext); } | MessageParser { public MailMessage parse(final MimeMessage message, final UpdateContext updateContext) throws MessagingException { final MailMessageBuilder messageBuilder = new MailMessageBuilder(); messageBuilder.id(message.getMessageID()); parseSubject(messageBuilder, message, updateContext); String[] deliveryDate = message.getHeader("Delivery-date"); if (deliveryDate != null && deliveryDate.length > 0 && deliveryDate[0].length() > 0) { messageBuilder.date(deliveryDate[0]); } else { messageBuilder.date(DATE_FORMAT.format(ZonedDateTime.now())); } parseReplyTo(messageBuilder, message); try { parseContents(messageBuilder, message); final MailMessage mailMessage = messageBuilder.build(); if (!mailMessage.getKeyword().isContentExpected() || !mailMessage.getContentWithCredentials().isEmpty()) { return mailMessage; } } catch (ParseException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message"), e); } catch (MessagingException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message using java mail"), e); } catch (IOException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Exception parsing message"), e); } catch (RuntimeException e) { LOGGER.error("Unexpected error parsing message: {}", message.getMessageID(), e); } updateContext.addGlobalMessage(UpdateMessages.noValidUpdateFound()); return messageBuilder.build(); } @Autowired MessageParser(final LoggerContext loggerContext); MailMessage parse(final MimeMessage message, final UpdateContext updateContext); } | MessageParser { public MailMessage parse(final MimeMessage message, final UpdateContext updateContext) throws MessagingException { final MailMessageBuilder messageBuilder = new MailMessageBuilder(); messageBuilder.id(message.getMessageID()); parseSubject(messageBuilder, message, updateContext); String[] deliveryDate = message.getHeader("Delivery-date"); if (deliveryDate != null && deliveryDate.length > 0 && deliveryDate[0].length() > 0) { messageBuilder.date(deliveryDate[0]); } else { messageBuilder.date(DATE_FORMAT.format(ZonedDateTime.now())); } parseReplyTo(messageBuilder, message); try { parseContents(messageBuilder, message); final MailMessage mailMessage = messageBuilder.build(); if (!mailMessage.getKeyword().isContentExpected() || !mailMessage.getContentWithCredentials().isEmpty()) { return mailMessage; } } catch (ParseException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message"), e); } catch (MessagingException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message using java mail"), e); } catch (IOException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Exception parsing message"), e); } catch (RuntimeException e) { LOGGER.error("Unexpected error parsing message: {}", message.getMessageID(), e); } updateContext.addGlobalMessage(UpdateMessages.noValidUpdateFound()); return messageBuilder.build(); } @Autowired MessageParser(final LoggerContext loggerContext); MailMessage parse(final MimeMessage message, final UpdateContext updateContext); } |
@Test public void parseKeywords_keyWords() throws Exception { final String keywordString = "KEYWORDS:"; when(mimeMessage.getSubject()).thenReturn(keywordString); final MailMessage message = subject.parse(mimeMessage, updateContext); assertThat(message.getKeyword(), is(Keyword.NONE)); verify(updateContext, times(1)).addGlobalMessage(UpdateMessages.invalidKeywordsFound(keywordString)); verify(updateContext, times(1)).addGlobalMessage(UpdateMessages.allKeywordsIgnored()); } | public MailMessage parse(final MimeMessage message, final UpdateContext updateContext) throws MessagingException { final MailMessageBuilder messageBuilder = new MailMessageBuilder(); messageBuilder.id(message.getMessageID()); parseSubject(messageBuilder, message, updateContext); String[] deliveryDate = message.getHeader("Delivery-date"); if (deliveryDate != null && deliveryDate.length > 0 && deliveryDate[0].length() > 0) { messageBuilder.date(deliveryDate[0]); } else { messageBuilder.date(DATE_FORMAT.format(ZonedDateTime.now())); } parseReplyTo(messageBuilder, message); try { parseContents(messageBuilder, message); final MailMessage mailMessage = messageBuilder.build(); if (!mailMessage.getKeyword().isContentExpected() || !mailMessage.getContentWithCredentials().isEmpty()) { return mailMessage; } } catch (ParseException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message"), e); } catch (MessagingException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message using java mail"), e); } catch (IOException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Exception parsing message"), e); } catch (RuntimeException e) { LOGGER.error("Unexpected error parsing message: {}", message.getMessageID(), e); } updateContext.addGlobalMessage(UpdateMessages.noValidUpdateFound()); return messageBuilder.build(); } | MessageParser { public MailMessage parse(final MimeMessage message, final UpdateContext updateContext) throws MessagingException { final MailMessageBuilder messageBuilder = new MailMessageBuilder(); messageBuilder.id(message.getMessageID()); parseSubject(messageBuilder, message, updateContext); String[] deliveryDate = message.getHeader("Delivery-date"); if (deliveryDate != null && deliveryDate.length > 0 && deliveryDate[0].length() > 0) { messageBuilder.date(deliveryDate[0]); } else { messageBuilder.date(DATE_FORMAT.format(ZonedDateTime.now())); } parseReplyTo(messageBuilder, message); try { parseContents(messageBuilder, message); final MailMessage mailMessage = messageBuilder.build(); if (!mailMessage.getKeyword().isContentExpected() || !mailMessage.getContentWithCredentials().isEmpty()) { return mailMessage; } } catch (ParseException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message"), e); } catch (MessagingException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message using java mail"), e); } catch (IOException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Exception parsing message"), e); } catch (RuntimeException e) { LOGGER.error("Unexpected error parsing message: {}", message.getMessageID(), e); } updateContext.addGlobalMessage(UpdateMessages.noValidUpdateFound()); return messageBuilder.build(); } } | MessageParser { public MailMessage parse(final MimeMessage message, final UpdateContext updateContext) throws MessagingException { final MailMessageBuilder messageBuilder = new MailMessageBuilder(); messageBuilder.id(message.getMessageID()); parseSubject(messageBuilder, message, updateContext); String[] deliveryDate = message.getHeader("Delivery-date"); if (deliveryDate != null && deliveryDate.length > 0 && deliveryDate[0].length() > 0) { messageBuilder.date(deliveryDate[0]); } else { messageBuilder.date(DATE_FORMAT.format(ZonedDateTime.now())); } parseReplyTo(messageBuilder, message); try { parseContents(messageBuilder, message); final MailMessage mailMessage = messageBuilder.build(); if (!mailMessage.getKeyword().isContentExpected() || !mailMessage.getContentWithCredentials().isEmpty()) { return mailMessage; } } catch (ParseException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message"), e); } catch (MessagingException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message using java mail"), e); } catch (IOException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Exception parsing message"), e); } catch (RuntimeException e) { LOGGER.error("Unexpected error parsing message: {}", message.getMessageID(), e); } updateContext.addGlobalMessage(UpdateMessages.noValidUpdateFound()); return messageBuilder.build(); } @Autowired MessageParser(final LoggerContext loggerContext); } | MessageParser { public MailMessage parse(final MimeMessage message, final UpdateContext updateContext) throws MessagingException { final MailMessageBuilder messageBuilder = new MailMessageBuilder(); messageBuilder.id(message.getMessageID()); parseSubject(messageBuilder, message, updateContext); String[] deliveryDate = message.getHeader("Delivery-date"); if (deliveryDate != null && deliveryDate.length > 0 && deliveryDate[0].length() > 0) { messageBuilder.date(deliveryDate[0]); } else { messageBuilder.date(DATE_FORMAT.format(ZonedDateTime.now())); } parseReplyTo(messageBuilder, message); try { parseContents(messageBuilder, message); final MailMessage mailMessage = messageBuilder.build(); if (!mailMessage.getKeyword().isContentExpected() || !mailMessage.getContentWithCredentials().isEmpty()) { return mailMessage; } } catch (ParseException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message"), e); } catch (MessagingException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message using java mail"), e); } catch (IOException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Exception parsing message"), e); } catch (RuntimeException e) { LOGGER.error("Unexpected error parsing message: {}", message.getMessageID(), e); } updateContext.addGlobalMessage(UpdateMessages.noValidUpdateFound()); return messageBuilder.build(); } @Autowired MessageParser(final LoggerContext loggerContext); MailMessage parse(final MimeMessage message, final UpdateContext updateContext); } | MessageParser { public MailMessage parse(final MimeMessage message, final UpdateContext updateContext) throws MessagingException { final MailMessageBuilder messageBuilder = new MailMessageBuilder(); messageBuilder.id(message.getMessageID()); parseSubject(messageBuilder, message, updateContext); String[] deliveryDate = message.getHeader("Delivery-date"); if (deliveryDate != null && deliveryDate.length > 0 && deliveryDate[0].length() > 0) { messageBuilder.date(deliveryDate[0]); } else { messageBuilder.date(DATE_FORMAT.format(ZonedDateTime.now())); } parseReplyTo(messageBuilder, message); try { parseContents(messageBuilder, message); final MailMessage mailMessage = messageBuilder.build(); if (!mailMessage.getKeyword().isContentExpected() || !mailMessage.getContentWithCredentials().isEmpty()) { return mailMessage; } } catch (ParseException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message"), e); } catch (MessagingException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message using java mail"), e); } catch (IOException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Exception parsing message"), e); } catch (RuntimeException e) { LOGGER.error("Unexpected error parsing message: {}", message.getMessageID(), e); } updateContext.addGlobalMessage(UpdateMessages.noValidUpdateFound()); return messageBuilder.build(); } @Autowired MessageParser(final LoggerContext loggerContext); MailMessage parse(final MimeMessage message, final UpdateContext updateContext); } |
@Test public void parseKeywords_keyWordsAndNew() throws Exception { final String keywordString = "KEYWORDS: new"; when(mimeMessage.getSubject()).thenReturn(keywordString); final MailMessage message = subject.parse(mimeMessage, updateContext); assertThat(message.getKeyword(), is(Keyword.NONE)); verify(updateContext, times(1)).addGlobalMessage(UpdateMessages.invalidKeywordsFound(keywordString)); verify(updateContext, times(1)).addGlobalMessage(UpdateMessages.allKeywordsIgnored()); } | public MailMessage parse(final MimeMessage message, final UpdateContext updateContext) throws MessagingException { final MailMessageBuilder messageBuilder = new MailMessageBuilder(); messageBuilder.id(message.getMessageID()); parseSubject(messageBuilder, message, updateContext); String[] deliveryDate = message.getHeader("Delivery-date"); if (deliveryDate != null && deliveryDate.length > 0 && deliveryDate[0].length() > 0) { messageBuilder.date(deliveryDate[0]); } else { messageBuilder.date(DATE_FORMAT.format(ZonedDateTime.now())); } parseReplyTo(messageBuilder, message); try { parseContents(messageBuilder, message); final MailMessage mailMessage = messageBuilder.build(); if (!mailMessage.getKeyword().isContentExpected() || !mailMessage.getContentWithCredentials().isEmpty()) { return mailMessage; } } catch (ParseException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message"), e); } catch (MessagingException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message using java mail"), e); } catch (IOException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Exception parsing message"), e); } catch (RuntimeException e) { LOGGER.error("Unexpected error parsing message: {}", message.getMessageID(), e); } updateContext.addGlobalMessage(UpdateMessages.noValidUpdateFound()); return messageBuilder.build(); } | MessageParser { public MailMessage parse(final MimeMessage message, final UpdateContext updateContext) throws MessagingException { final MailMessageBuilder messageBuilder = new MailMessageBuilder(); messageBuilder.id(message.getMessageID()); parseSubject(messageBuilder, message, updateContext); String[] deliveryDate = message.getHeader("Delivery-date"); if (deliveryDate != null && deliveryDate.length > 0 && deliveryDate[0].length() > 0) { messageBuilder.date(deliveryDate[0]); } else { messageBuilder.date(DATE_FORMAT.format(ZonedDateTime.now())); } parseReplyTo(messageBuilder, message); try { parseContents(messageBuilder, message); final MailMessage mailMessage = messageBuilder.build(); if (!mailMessage.getKeyword().isContentExpected() || !mailMessage.getContentWithCredentials().isEmpty()) { return mailMessage; } } catch (ParseException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message"), e); } catch (MessagingException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message using java mail"), e); } catch (IOException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Exception parsing message"), e); } catch (RuntimeException e) { LOGGER.error("Unexpected error parsing message: {}", message.getMessageID(), e); } updateContext.addGlobalMessage(UpdateMessages.noValidUpdateFound()); return messageBuilder.build(); } } | MessageParser { public MailMessage parse(final MimeMessage message, final UpdateContext updateContext) throws MessagingException { final MailMessageBuilder messageBuilder = new MailMessageBuilder(); messageBuilder.id(message.getMessageID()); parseSubject(messageBuilder, message, updateContext); String[] deliveryDate = message.getHeader("Delivery-date"); if (deliveryDate != null && deliveryDate.length > 0 && deliveryDate[0].length() > 0) { messageBuilder.date(deliveryDate[0]); } else { messageBuilder.date(DATE_FORMAT.format(ZonedDateTime.now())); } parseReplyTo(messageBuilder, message); try { parseContents(messageBuilder, message); final MailMessage mailMessage = messageBuilder.build(); if (!mailMessage.getKeyword().isContentExpected() || !mailMessage.getContentWithCredentials().isEmpty()) { return mailMessage; } } catch (ParseException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message"), e); } catch (MessagingException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message using java mail"), e); } catch (IOException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Exception parsing message"), e); } catch (RuntimeException e) { LOGGER.error("Unexpected error parsing message: {}", message.getMessageID(), e); } updateContext.addGlobalMessage(UpdateMessages.noValidUpdateFound()); return messageBuilder.build(); } @Autowired MessageParser(final LoggerContext loggerContext); } | MessageParser { public MailMessage parse(final MimeMessage message, final UpdateContext updateContext) throws MessagingException { final MailMessageBuilder messageBuilder = new MailMessageBuilder(); messageBuilder.id(message.getMessageID()); parseSubject(messageBuilder, message, updateContext); String[] deliveryDate = message.getHeader("Delivery-date"); if (deliveryDate != null && deliveryDate.length > 0 && deliveryDate[0].length() > 0) { messageBuilder.date(deliveryDate[0]); } else { messageBuilder.date(DATE_FORMAT.format(ZonedDateTime.now())); } parseReplyTo(messageBuilder, message); try { parseContents(messageBuilder, message); final MailMessage mailMessage = messageBuilder.build(); if (!mailMessage.getKeyword().isContentExpected() || !mailMessage.getContentWithCredentials().isEmpty()) { return mailMessage; } } catch (ParseException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message"), e); } catch (MessagingException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message using java mail"), e); } catch (IOException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Exception parsing message"), e); } catch (RuntimeException e) { LOGGER.error("Unexpected error parsing message: {}", message.getMessageID(), e); } updateContext.addGlobalMessage(UpdateMessages.noValidUpdateFound()); return messageBuilder.build(); } @Autowired MessageParser(final LoggerContext loggerContext); MailMessage parse(final MimeMessage message, final UpdateContext updateContext); } | MessageParser { public MailMessage parse(final MimeMessage message, final UpdateContext updateContext) throws MessagingException { final MailMessageBuilder messageBuilder = new MailMessageBuilder(); messageBuilder.id(message.getMessageID()); parseSubject(messageBuilder, message, updateContext); String[] deliveryDate = message.getHeader("Delivery-date"); if (deliveryDate != null && deliveryDate.length > 0 && deliveryDate[0].length() > 0) { messageBuilder.date(deliveryDate[0]); } else { messageBuilder.date(DATE_FORMAT.format(ZonedDateTime.now())); } parseReplyTo(messageBuilder, message); try { parseContents(messageBuilder, message); final MailMessage mailMessage = messageBuilder.build(); if (!mailMessage.getKeyword().isContentExpected() || !mailMessage.getContentWithCredentials().isEmpty()) { return mailMessage; } } catch (ParseException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message"), e); } catch (MessagingException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message using java mail"), e); } catch (IOException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Exception parsing message"), e); } catch (RuntimeException e) { LOGGER.error("Unexpected error parsing message: {}", message.getMessageID(), e); } updateContext.addGlobalMessage(UpdateMessages.noValidUpdateFound()); return messageBuilder.build(); } @Autowired MessageParser(final LoggerContext loggerContext); MailMessage parse(final MimeMessage message, final UpdateContext updateContext); } |
@Test public void parse_invalid_reply_to() throws Exception { MimeMessage messageWithInvalidReplyTo = new MimeMessage(null, new ByteArrayInputStream("Reply-To: <respondera: [email protected]>".getBytes())); MailMessage result = subject.parse(messageWithInvalidReplyTo, updateContext); assertThat(result.getReplyTo(), isEmptyString()); } | public MailMessage parse(final MimeMessage message, final UpdateContext updateContext) throws MessagingException { final MailMessageBuilder messageBuilder = new MailMessageBuilder(); messageBuilder.id(message.getMessageID()); parseSubject(messageBuilder, message, updateContext); String[] deliveryDate = message.getHeader("Delivery-date"); if (deliveryDate != null && deliveryDate.length > 0 && deliveryDate[0].length() > 0) { messageBuilder.date(deliveryDate[0]); } else { messageBuilder.date(DATE_FORMAT.format(ZonedDateTime.now())); } parseReplyTo(messageBuilder, message); try { parseContents(messageBuilder, message); final MailMessage mailMessage = messageBuilder.build(); if (!mailMessage.getKeyword().isContentExpected() || !mailMessage.getContentWithCredentials().isEmpty()) { return mailMessage; } } catch (ParseException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message"), e); } catch (MessagingException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message using java mail"), e); } catch (IOException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Exception parsing message"), e); } catch (RuntimeException e) { LOGGER.error("Unexpected error parsing message: {}", message.getMessageID(), e); } updateContext.addGlobalMessage(UpdateMessages.noValidUpdateFound()); return messageBuilder.build(); } | MessageParser { public MailMessage parse(final MimeMessage message, final UpdateContext updateContext) throws MessagingException { final MailMessageBuilder messageBuilder = new MailMessageBuilder(); messageBuilder.id(message.getMessageID()); parseSubject(messageBuilder, message, updateContext); String[] deliveryDate = message.getHeader("Delivery-date"); if (deliveryDate != null && deliveryDate.length > 0 && deliveryDate[0].length() > 0) { messageBuilder.date(deliveryDate[0]); } else { messageBuilder.date(DATE_FORMAT.format(ZonedDateTime.now())); } parseReplyTo(messageBuilder, message); try { parseContents(messageBuilder, message); final MailMessage mailMessage = messageBuilder.build(); if (!mailMessage.getKeyword().isContentExpected() || !mailMessage.getContentWithCredentials().isEmpty()) { return mailMessage; } } catch (ParseException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message"), e); } catch (MessagingException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message using java mail"), e); } catch (IOException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Exception parsing message"), e); } catch (RuntimeException e) { LOGGER.error("Unexpected error parsing message: {}", message.getMessageID(), e); } updateContext.addGlobalMessage(UpdateMessages.noValidUpdateFound()); return messageBuilder.build(); } } | MessageParser { public MailMessage parse(final MimeMessage message, final UpdateContext updateContext) throws MessagingException { final MailMessageBuilder messageBuilder = new MailMessageBuilder(); messageBuilder.id(message.getMessageID()); parseSubject(messageBuilder, message, updateContext); String[] deliveryDate = message.getHeader("Delivery-date"); if (deliveryDate != null && deliveryDate.length > 0 && deliveryDate[0].length() > 0) { messageBuilder.date(deliveryDate[0]); } else { messageBuilder.date(DATE_FORMAT.format(ZonedDateTime.now())); } parseReplyTo(messageBuilder, message); try { parseContents(messageBuilder, message); final MailMessage mailMessage = messageBuilder.build(); if (!mailMessage.getKeyword().isContentExpected() || !mailMessage.getContentWithCredentials().isEmpty()) { return mailMessage; } } catch (ParseException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message"), e); } catch (MessagingException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message using java mail"), e); } catch (IOException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Exception parsing message"), e); } catch (RuntimeException e) { LOGGER.error("Unexpected error parsing message: {}", message.getMessageID(), e); } updateContext.addGlobalMessage(UpdateMessages.noValidUpdateFound()); return messageBuilder.build(); } @Autowired MessageParser(final LoggerContext loggerContext); } | MessageParser { public MailMessage parse(final MimeMessage message, final UpdateContext updateContext) throws MessagingException { final MailMessageBuilder messageBuilder = new MailMessageBuilder(); messageBuilder.id(message.getMessageID()); parseSubject(messageBuilder, message, updateContext); String[] deliveryDate = message.getHeader("Delivery-date"); if (deliveryDate != null && deliveryDate.length > 0 && deliveryDate[0].length() > 0) { messageBuilder.date(deliveryDate[0]); } else { messageBuilder.date(DATE_FORMAT.format(ZonedDateTime.now())); } parseReplyTo(messageBuilder, message); try { parseContents(messageBuilder, message); final MailMessage mailMessage = messageBuilder.build(); if (!mailMessage.getKeyword().isContentExpected() || !mailMessage.getContentWithCredentials().isEmpty()) { return mailMessage; } } catch (ParseException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message"), e); } catch (MessagingException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message using java mail"), e); } catch (IOException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Exception parsing message"), e); } catch (RuntimeException e) { LOGGER.error("Unexpected error parsing message: {}", message.getMessageID(), e); } updateContext.addGlobalMessage(UpdateMessages.noValidUpdateFound()); return messageBuilder.build(); } @Autowired MessageParser(final LoggerContext loggerContext); MailMessage parse(final MimeMessage message, final UpdateContext updateContext); } | MessageParser { public MailMessage parse(final MimeMessage message, final UpdateContext updateContext) throws MessagingException { final MailMessageBuilder messageBuilder = new MailMessageBuilder(); messageBuilder.id(message.getMessageID()); parseSubject(messageBuilder, message, updateContext); String[] deliveryDate = message.getHeader("Delivery-date"); if (deliveryDate != null && deliveryDate.length > 0 && deliveryDate[0].length() > 0) { messageBuilder.date(deliveryDate[0]); } else { messageBuilder.date(DATE_FORMAT.format(ZonedDateTime.now())); } parseReplyTo(messageBuilder, message); try { parseContents(messageBuilder, message); final MailMessage mailMessage = messageBuilder.build(); if (!mailMessage.getKeyword().isContentExpected() || !mailMessage.getContentWithCredentials().isEmpty()) { return mailMessage; } } catch (ParseException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message"), e); } catch (MessagingException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message using java mail"), e); } catch (IOException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Exception parsing message"), e); } catch (RuntimeException e) { LOGGER.error("Unexpected error parsing message: {}", message.getMessageID(), e); } updateContext.addGlobalMessage(UpdateMessages.noValidUpdateFound()); return messageBuilder.build(); } @Autowired MessageParser(final LoggerContext loggerContext); MailMessage parse(final MimeMessage message, final UpdateContext updateContext); } |
@Test public void parse_missing_reply_to() throws Exception { MimeMessage messageWithoutReplyTo = new MimeMessage(null, new ByteArrayInputStream("From: [email protected]".getBytes())); MailMessage result = subject.parse(messageWithoutReplyTo, updateContext); assertThat(result.getReplyTo(), is("[email protected]")); assertThat(result.getFrom(), is("[email protected]")); } | public MailMessage parse(final MimeMessage message, final UpdateContext updateContext) throws MessagingException { final MailMessageBuilder messageBuilder = new MailMessageBuilder(); messageBuilder.id(message.getMessageID()); parseSubject(messageBuilder, message, updateContext); String[] deliveryDate = message.getHeader("Delivery-date"); if (deliveryDate != null && deliveryDate.length > 0 && deliveryDate[0].length() > 0) { messageBuilder.date(deliveryDate[0]); } else { messageBuilder.date(DATE_FORMAT.format(ZonedDateTime.now())); } parseReplyTo(messageBuilder, message); try { parseContents(messageBuilder, message); final MailMessage mailMessage = messageBuilder.build(); if (!mailMessage.getKeyword().isContentExpected() || !mailMessage.getContentWithCredentials().isEmpty()) { return mailMessage; } } catch (ParseException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message"), e); } catch (MessagingException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message using java mail"), e); } catch (IOException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Exception parsing message"), e); } catch (RuntimeException e) { LOGGER.error("Unexpected error parsing message: {}", message.getMessageID(), e); } updateContext.addGlobalMessage(UpdateMessages.noValidUpdateFound()); return messageBuilder.build(); } | MessageParser { public MailMessage parse(final MimeMessage message, final UpdateContext updateContext) throws MessagingException { final MailMessageBuilder messageBuilder = new MailMessageBuilder(); messageBuilder.id(message.getMessageID()); parseSubject(messageBuilder, message, updateContext); String[] deliveryDate = message.getHeader("Delivery-date"); if (deliveryDate != null && deliveryDate.length > 0 && deliveryDate[0].length() > 0) { messageBuilder.date(deliveryDate[0]); } else { messageBuilder.date(DATE_FORMAT.format(ZonedDateTime.now())); } parseReplyTo(messageBuilder, message); try { parseContents(messageBuilder, message); final MailMessage mailMessage = messageBuilder.build(); if (!mailMessage.getKeyword().isContentExpected() || !mailMessage.getContentWithCredentials().isEmpty()) { return mailMessage; } } catch (ParseException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message"), e); } catch (MessagingException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message using java mail"), e); } catch (IOException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Exception parsing message"), e); } catch (RuntimeException e) { LOGGER.error("Unexpected error parsing message: {}", message.getMessageID(), e); } updateContext.addGlobalMessage(UpdateMessages.noValidUpdateFound()); return messageBuilder.build(); } } | MessageParser { public MailMessage parse(final MimeMessage message, final UpdateContext updateContext) throws MessagingException { final MailMessageBuilder messageBuilder = new MailMessageBuilder(); messageBuilder.id(message.getMessageID()); parseSubject(messageBuilder, message, updateContext); String[] deliveryDate = message.getHeader("Delivery-date"); if (deliveryDate != null && deliveryDate.length > 0 && deliveryDate[0].length() > 0) { messageBuilder.date(deliveryDate[0]); } else { messageBuilder.date(DATE_FORMAT.format(ZonedDateTime.now())); } parseReplyTo(messageBuilder, message); try { parseContents(messageBuilder, message); final MailMessage mailMessage = messageBuilder.build(); if (!mailMessage.getKeyword().isContentExpected() || !mailMessage.getContentWithCredentials().isEmpty()) { return mailMessage; } } catch (ParseException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message"), e); } catch (MessagingException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message using java mail"), e); } catch (IOException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Exception parsing message"), e); } catch (RuntimeException e) { LOGGER.error("Unexpected error parsing message: {}", message.getMessageID(), e); } updateContext.addGlobalMessage(UpdateMessages.noValidUpdateFound()); return messageBuilder.build(); } @Autowired MessageParser(final LoggerContext loggerContext); } | MessageParser { public MailMessage parse(final MimeMessage message, final UpdateContext updateContext) throws MessagingException { final MailMessageBuilder messageBuilder = new MailMessageBuilder(); messageBuilder.id(message.getMessageID()); parseSubject(messageBuilder, message, updateContext); String[] deliveryDate = message.getHeader("Delivery-date"); if (deliveryDate != null && deliveryDate.length > 0 && deliveryDate[0].length() > 0) { messageBuilder.date(deliveryDate[0]); } else { messageBuilder.date(DATE_FORMAT.format(ZonedDateTime.now())); } parseReplyTo(messageBuilder, message); try { parseContents(messageBuilder, message); final MailMessage mailMessage = messageBuilder.build(); if (!mailMessage.getKeyword().isContentExpected() || !mailMessage.getContentWithCredentials().isEmpty()) { return mailMessage; } } catch (ParseException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message"), e); } catch (MessagingException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message using java mail"), e); } catch (IOException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Exception parsing message"), e); } catch (RuntimeException e) { LOGGER.error("Unexpected error parsing message: {}", message.getMessageID(), e); } updateContext.addGlobalMessage(UpdateMessages.noValidUpdateFound()); return messageBuilder.build(); } @Autowired MessageParser(final LoggerContext loggerContext); MailMessage parse(final MimeMessage message, final UpdateContext updateContext); } | MessageParser { public MailMessage parse(final MimeMessage message, final UpdateContext updateContext) throws MessagingException { final MailMessageBuilder messageBuilder = new MailMessageBuilder(); messageBuilder.id(message.getMessageID()); parseSubject(messageBuilder, message, updateContext); String[] deliveryDate = message.getHeader("Delivery-date"); if (deliveryDate != null && deliveryDate.length > 0 && deliveryDate[0].length() > 0) { messageBuilder.date(deliveryDate[0]); } else { messageBuilder.date(DATE_FORMAT.format(ZonedDateTime.now())); } parseReplyTo(messageBuilder, message); try { parseContents(messageBuilder, message); final MailMessage mailMessage = messageBuilder.build(); if (!mailMessage.getKeyword().isContentExpected() || !mailMessage.getContentWithCredentials().isEmpty()) { return mailMessage; } } catch (ParseException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message"), e); } catch (MessagingException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message using java mail"), e); } catch (IOException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Exception parsing message"), e); } catch (RuntimeException e) { LOGGER.error("Unexpected error parsing message: {}", message.getMessageID(), e); } updateContext.addGlobalMessage(UpdateMessages.noValidUpdateFound()); return messageBuilder.build(); } @Autowired MessageParser(final LoggerContext loggerContext); MailMessage parse(final MimeMessage message, final UpdateContext updateContext); } |
@Test public void parse_text_html_message() throws Exception { final MailMessage message = subject.parse(MimeMessageProvider.getUpdateMessage("simpleHtmlTextUnsigned.mail"), updateContext); assertThat(message.getId(), is("<[email protected]>")); assertThat(message.getReplyTo(), is("[email protected]")); assertThat(message.getKeyword(), is(Keyword.NONE)); assertThat(message.getContentWithCredentials(), hasSize(0)); } | public MailMessage parse(final MimeMessage message, final UpdateContext updateContext) throws MessagingException { final MailMessageBuilder messageBuilder = new MailMessageBuilder(); messageBuilder.id(message.getMessageID()); parseSubject(messageBuilder, message, updateContext); String[] deliveryDate = message.getHeader("Delivery-date"); if (deliveryDate != null && deliveryDate.length > 0 && deliveryDate[0].length() > 0) { messageBuilder.date(deliveryDate[0]); } else { messageBuilder.date(DATE_FORMAT.format(ZonedDateTime.now())); } parseReplyTo(messageBuilder, message); try { parseContents(messageBuilder, message); final MailMessage mailMessage = messageBuilder.build(); if (!mailMessage.getKeyword().isContentExpected() || !mailMessage.getContentWithCredentials().isEmpty()) { return mailMessage; } } catch (ParseException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message"), e); } catch (MessagingException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message using java mail"), e); } catch (IOException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Exception parsing message"), e); } catch (RuntimeException e) { LOGGER.error("Unexpected error parsing message: {}", message.getMessageID(), e); } updateContext.addGlobalMessage(UpdateMessages.noValidUpdateFound()); return messageBuilder.build(); } | MessageParser { public MailMessage parse(final MimeMessage message, final UpdateContext updateContext) throws MessagingException { final MailMessageBuilder messageBuilder = new MailMessageBuilder(); messageBuilder.id(message.getMessageID()); parseSubject(messageBuilder, message, updateContext); String[] deliveryDate = message.getHeader("Delivery-date"); if (deliveryDate != null && deliveryDate.length > 0 && deliveryDate[0].length() > 0) { messageBuilder.date(deliveryDate[0]); } else { messageBuilder.date(DATE_FORMAT.format(ZonedDateTime.now())); } parseReplyTo(messageBuilder, message); try { parseContents(messageBuilder, message); final MailMessage mailMessage = messageBuilder.build(); if (!mailMessage.getKeyword().isContentExpected() || !mailMessage.getContentWithCredentials().isEmpty()) { return mailMessage; } } catch (ParseException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message"), e); } catch (MessagingException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message using java mail"), e); } catch (IOException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Exception parsing message"), e); } catch (RuntimeException e) { LOGGER.error("Unexpected error parsing message: {}", message.getMessageID(), e); } updateContext.addGlobalMessage(UpdateMessages.noValidUpdateFound()); return messageBuilder.build(); } } | MessageParser { public MailMessage parse(final MimeMessage message, final UpdateContext updateContext) throws MessagingException { final MailMessageBuilder messageBuilder = new MailMessageBuilder(); messageBuilder.id(message.getMessageID()); parseSubject(messageBuilder, message, updateContext); String[] deliveryDate = message.getHeader("Delivery-date"); if (deliveryDate != null && deliveryDate.length > 0 && deliveryDate[0].length() > 0) { messageBuilder.date(deliveryDate[0]); } else { messageBuilder.date(DATE_FORMAT.format(ZonedDateTime.now())); } parseReplyTo(messageBuilder, message); try { parseContents(messageBuilder, message); final MailMessage mailMessage = messageBuilder.build(); if (!mailMessage.getKeyword().isContentExpected() || !mailMessage.getContentWithCredentials().isEmpty()) { return mailMessage; } } catch (ParseException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message"), e); } catch (MessagingException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message using java mail"), e); } catch (IOException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Exception parsing message"), e); } catch (RuntimeException e) { LOGGER.error("Unexpected error parsing message: {}", message.getMessageID(), e); } updateContext.addGlobalMessage(UpdateMessages.noValidUpdateFound()); return messageBuilder.build(); } @Autowired MessageParser(final LoggerContext loggerContext); } | MessageParser { public MailMessage parse(final MimeMessage message, final UpdateContext updateContext) throws MessagingException { final MailMessageBuilder messageBuilder = new MailMessageBuilder(); messageBuilder.id(message.getMessageID()); parseSubject(messageBuilder, message, updateContext); String[] deliveryDate = message.getHeader("Delivery-date"); if (deliveryDate != null && deliveryDate.length > 0 && deliveryDate[0].length() > 0) { messageBuilder.date(deliveryDate[0]); } else { messageBuilder.date(DATE_FORMAT.format(ZonedDateTime.now())); } parseReplyTo(messageBuilder, message); try { parseContents(messageBuilder, message); final MailMessage mailMessage = messageBuilder.build(); if (!mailMessage.getKeyword().isContentExpected() || !mailMessage.getContentWithCredentials().isEmpty()) { return mailMessage; } } catch (ParseException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message"), e); } catch (MessagingException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message using java mail"), e); } catch (IOException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Exception parsing message"), e); } catch (RuntimeException e) { LOGGER.error("Unexpected error parsing message: {}", message.getMessageID(), e); } updateContext.addGlobalMessage(UpdateMessages.noValidUpdateFound()); return messageBuilder.build(); } @Autowired MessageParser(final LoggerContext loggerContext); MailMessage parse(final MimeMessage message, final UpdateContext updateContext); } | MessageParser { public MailMessage parse(final MimeMessage message, final UpdateContext updateContext) throws MessagingException { final MailMessageBuilder messageBuilder = new MailMessageBuilder(); messageBuilder.id(message.getMessageID()); parseSubject(messageBuilder, message, updateContext); String[] deliveryDate = message.getHeader("Delivery-date"); if (deliveryDate != null && deliveryDate.length > 0 && deliveryDate[0].length() > 0) { messageBuilder.date(deliveryDate[0]); } else { messageBuilder.date(DATE_FORMAT.format(ZonedDateTime.now())); } parseReplyTo(messageBuilder, message); try { parseContents(messageBuilder, message); final MailMessage mailMessage = messageBuilder.build(); if (!mailMessage.getKeyword().isContentExpected() || !mailMessage.getContentWithCredentials().isEmpty()) { return mailMessage; } } catch (ParseException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message"), e); } catch (MessagingException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message using java mail"), e); } catch (IOException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Exception parsing message"), e); } catch (RuntimeException e) { LOGGER.error("Unexpected error parsing message: {}", message.getMessageID(), e); } updateContext.addGlobalMessage(UpdateMessages.noValidUpdateFound()); return messageBuilder.build(); } @Autowired MessageParser(final LoggerContext loggerContext); MailMessage parse(final MimeMessage message, final UpdateContext updateContext); } |
@Test public void illegal_charset() throws Exception { assertThat(subject.getCharset(new ContentType("text/plain;\n\tcharset=\"_iso-2022-jp$ESC\"")), is(StandardCharsets.ISO_8859_1)); } | Charset getCharset(final ContentType contentType) { final String charset = contentType.getParameter("charset"); if (charset != null) { try { return Charset.forName(MimeUtility.javaCharset(charset)); } catch (UnsupportedCharsetException e) { loggerContext.log(new Message(Messages.Type.WARNING, "Unsupported charset: %s in contentType: %s", charset, contentType)); } catch (IllegalCharsetNameException e) { loggerContext.log(new Message(Messages.Type.WARNING, "Illegal charset: %s in contentType: %s", charset, contentType)); } } return StandardCharsets.ISO_8859_1; } | MessageParser { Charset getCharset(final ContentType contentType) { final String charset = contentType.getParameter("charset"); if (charset != null) { try { return Charset.forName(MimeUtility.javaCharset(charset)); } catch (UnsupportedCharsetException e) { loggerContext.log(new Message(Messages.Type.WARNING, "Unsupported charset: %s in contentType: %s", charset, contentType)); } catch (IllegalCharsetNameException e) { loggerContext.log(new Message(Messages.Type.WARNING, "Illegal charset: %s in contentType: %s", charset, contentType)); } } return StandardCharsets.ISO_8859_1; } } | MessageParser { Charset getCharset(final ContentType contentType) { final String charset = contentType.getParameter("charset"); if (charset != null) { try { return Charset.forName(MimeUtility.javaCharset(charset)); } catch (UnsupportedCharsetException e) { loggerContext.log(new Message(Messages.Type.WARNING, "Unsupported charset: %s in contentType: %s", charset, contentType)); } catch (IllegalCharsetNameException e) { loggerContext.log(new Message(Messages.Type.WARNING, "Illegal charset: %s in contentType: %s", charset, contentType)); } } return StandardCharsets.ISO_8859_1; } @Autowired MessageParser(final LoggerContext loggerContext); } | MessageParser { Charset getCharset(final ContentType contentType) { final String charset = contentType.getParameter("charset"); if (charset != null) { try { return Charset.forName(MimeUtility.javaCharset(charset)); } catch (UnsupportedCharsetException e) { loggerContext.log(new Message(Messages.Type.WARNING, "Unsupported charset: %s in contentType: %s", charset, contentType)); } catch (IllegalCharsetNameException e) { loggerContext.log(new Message(Messages.Type.WARNING, "Illegal charset: %s in contentType: %s", charset, contentType)); } } return StandardCharsets.ISO_8859_1; } @Autowired MessageParser(final LoggerContext loggerContext); MailMessage parse(final MimeMessage message, final UpdateContext updateContext); } | MessageParser { Charset getCharset(final ContentType contentType) { final String charset = contentType.getParameter("charset"); if (charset != null) { try { return Charset.forName(MimeUtility.javaCharset(charset)); } catch (UnsupportedCharsetException e) { loggerContext.log(new Message(Messages.Type.WARNING, "Unsupported charset: %s in contentType: %s", charset, contentType)); } catch (IllegalCharsetNameException e) { loggerContext.log(new Message(Messages.Type.WARNING, "Illegal charset: %s in contentType: %s", charset, contentType)); } } return StandardCharsets.ISO_8859_1; } @Autowired MessageParser(final LoggerContext loggerContext); MailMessage parse(final MimeMessage message, final UpdateContext updateContext); } |
@Test public void role_with_abuse_mailbox() { final RpslObject role = RpslObject.parse(10, "" + "role: RIPE NCC tech contact\n" + "address: RIPE Network Coordination Centre (NCC)\n" + "address: Singel 258\n" + "address: 1016 AB Amsterdam\n" + "address: The Netherlands\n" + "phone: +31 20 535 4444\n" + "fax-no: +31 20 535 4445\n" + "e-mail: [email protected]\n" + "abuse-mailbox: [email protected]\n" + "nic-hdl: RNTC-RIPE\n" + "mnt-by: RIPE-DBM-MNT\n" + "notify: [email protected]\n" + "source: RIPE"); final RpslObject dummified = subject.dummify(4, role); assertThat(dummified.getAttributes(), contains( new RpslAttribute("role", "RIPE NCC tech contact"), new RpslAttribute("address", "RIPE Network Coordination Centre (NCC)"), new RpslAttribute("address", "Singel 258"), new RpslAttribute("address", "1016 AB Amsterdam"), new RpslAttribute("address", "The Netherlands"), new RpslAttribute("phone", "+31 20 535 4444"), new RpslAttribute("fax-no", "+31 20 535 4445"), new RpslAttribute("e-mail", "***@ripe.net"), new RpslAttribute("abuse-mailbox", "[email protected]"), new RpslAttribute("nic-hdl", "RNTC-RIPE"), new RpslAttribute("mnt-by", "RIPE-DBM-MNT"), new RpslAttribute("notify", "***@ripe.net"), new RpslAttribute("source", "RIPE") )); } | @Override public RpslObject dummify(final int version, final RpslObject rpslObject) { final ObjectType objectType = rpslObject.getType(); Validate.isTrue(isAllowed(version, rpslObject), "The version is not supported by this dummifier", version); final List<RpslAttribute> attributes = Lists.newArrayList(rpslObject.getAttributes()); RpslAttribute lastAddressLine = null; int lastAddressLineIndex = 0; for (int i = 0; i < attributes.size(); i++) { RpslAttribute replacement = attributes.get(i); final AttributeType attributeType = replacement.getType(); try { if (!(objectType == ObjectType.ROLE && rpslObject.containsAttribute(ABUSE_MAILBOX))) { replacement = replacePerson(attributeType, replacement); replacement = replaceAuth(attributeType, replacement); replacement = replacePhoneFax(attributeType, replacement); if (attributeType == ADDRESS) { lastAddressLine = replacement; lastAddressLineIndex = i; replacement = new RpslAttribute(ADDRESS, "***"); } } replacement = replaceEmail(attributeType, replacement); attributes.set(i, replacement); } catch (RuntimeException e) { LOGGER.debug("Dummifier failed on [" + attributes.get(i).toString().trim() + "]", e); } } if (lastAddressLine != null) { attributes.set(lastAddressLineIndex, lastAddressLine); } return FILTER_CHANGED_FUNCTION.apply(new RpslObject(rpslObject, attributes)); } | DummifierCurrent implements Dummifier { @Override public RpslObject dummify(final int version, final RpslObject rpslObject) { final ObjectType objectType = rpslObject.getType(); Validate.isTrue(isAllowed(version, rpslObject), "The version is not supported by this dummifier", version); final List<RpslAttribute> attributes = Lists.newArrayList(rpslObject.getAttributes()); RpslAttribute lastAddressLine = null; int lastAddressLineIndex = 0; for (int i = 0; i < attributes.size(); i++) { RpslAttribute replacement = attributes.get(i); final AttributeType attributeType = replacement.getType(); try { if (!(objectType == ObjectType.ROLE && rpslObject.containsAttribute(ABUSE_MAILBOX))) { replacement = replacePerson(attributeType, replacement); replacement = replaceAuth(attributeType, replacement); replacement = replacePhoneFax(attributeType, replacement); if (attributeType == ADDRESS) { lastAddressLine = replacement; lastAddressLineIndex = i; replacement = new RpslAttribute(ADDRESS, "***"); } } replacement = replaceEmail(attributeType, replacement); attributes.set(i, replacement); } catch (RuntimeException e) { LOGGER.debug("Dummifier failed on [" + attributes.get(i).toString().trim() + "]", e); } } if (lastAddressLine != null) { attributes.set(lastAddressLineIndex, lastAddressLine); } return FILTER_CHANGED_FUNCTION.apply(new RpslObject(rpslObject, attributes)); } } | DummifierCurrent implements Dummifier { @Override public RpslObject dummify(final int version, final RpslObject rpslObject) { final ObjectType objectType = rpslObject.getType(); Validate.isTrue(isAllowed(version, rpslObject), "The version is not supported by this dummifier", version); final List<RpslAttribute> attributes = Lists.newArrayList(rpslObject.getAttributes()); RpslAttribute lastAddressLine = null; int lastAddressLineIndex = 0; for (int i = 0; i < attributes.size(); i++) { RpslAttribute replacement = attributes.get(i); final AttributeType attributeType = replacement.getType(); try { if (!(objectType == ObjectType.ROLE && rpslObject.containsAttribute(ABUSE_MAILBOX))) { replacement = replacePerson(attributeType, replacement); replacement = replaceAuth(attributeType, replacement); replacement = replacePhoneFax(attributeType, replacement); if (attributeType == ADDRESS) { lastAddressLine = replacement; lastAddressLineIndex = i; replacement = new RpslAttribute(ADDRESS, "***"); } } replacement = replaceEmail(attributeType, replacement); attributes.set(i, replacement); } catch (RuntimeException e) { LOGGER.debug("Dummifier failed on [" + attributes.get(i).toString().trim() + "]", e); } } if (lastAddressLine != null) { attributes.set(lastAddressLineIndex, lastAddressLine); } return FILTER_CHANGED_FUNCTION.apply(new RpslObject(rpslObject, attributes)); } } | DummifierCurrent implements Dummifier { @Override public RpslObject dummify(final int version, final RpslObject rpslObject) { final ObjectType objectType = rpslObject.getType(); Validate.isTrue(isAllowed(version, rpslObject), "The version is not supported by this dummifier", version); final List<RpslAttribute> attributes = Lists.newArrayList(rpslObject.getAttributes()); RpslAttribute lastAddressLine = null; int lastAddressLineIndex = 0; for (int i = 0; i < attributes.size(); i++) { RpslAttribute replacement = attributes.get(i); final AttributeType attributeType = replacement.getType(); try { if (!(objectType == ObjectType.ROLE && rpslObject.containsAttribute(ABUSE_MAILBOX))) { replacement = replacePerson(attributeType, replacement); replacement = replaceAuth(attributeType, replacement); replacement = replacePhoneFax(attributeType, replacement); if (attributeType == ADDRESS) { lastAddressLine = replacement; lastAddressLineIndex = i; replacement = new RpslAttribute(ADDRESS, "***"); } } replacement = replaceEmail(attributeType, replacement); attributes.set(i, replacement); } catch (RuntimeException e) { LOGGER.debug("Dummifier failed on [" + attributes.get(i).toString().trim() + "]", e); } } if (lastAddressLine != null) { attributes.set(lastAddressLineIndex, lastAddressLine); } return FILTER_CHANGED_FUNCTION.apply(new RpslObject(rpslObject, attributes)); } @Override RpslObject dummify(final int version, final RpslObject rpslObject); @Override boolean isAllowed(final int version, final RpslObject object); } | DummifierCurrent implements Dummifier { @Override public RpslObject dummify(final int version, final RpslObject rpslObject) { final ObjectType objectType = rpslObject.getType(); Validate.isTrue(isAllowed(version, rpslObject), "The version is not supported by this dummifier", version); final List<RpslAttribute> attributes = Lists.newArrayList(rpslObject.getAttributes()); RpslAttribute lastAddressLine = null; int lastAddressLineIndex = 0; for (int i = 0; i < attributes.size(); i++) { RpslAttribute replacement = attributes.get(i); final AttributeType attributeType = replacement.getType(); try { if (!(objectType == ObjectType.ROLE && rpslObject.containsAttribute(ABUSE_MAILBOX))) { replacement = replacePerson(attributeType, replacement); replacement = replaceAuth(attributeType, replacement); replacement = replacePhoneFax(attributeType, replacement); if (attributeType == ADDRESS) { lastAddressLine = replacement; lastAddressLineIndex = i; replacement = new RpslAttribute(ADDRESS, "***"); } } replacement = replaceEmail(attributeType, replacement); attributes.set(i, replacement); } catch (RuntimeException e) { LOGGER.debug("Dummifier failed on [" + attributes.get(i).toString().trim() + "]", e); } } if (lastAddressLine != null) { attributes.set(lastAddressLineIndex, lastAddressLine); } return FILTER_CHANGED_FUNCTION.apply(new RpslObject(rpslObject, attributes)); } @Override RpslObject dummify(final int version, final RpslObject rpslObject); @Override boolean isAllowed(final int version, final RpslObject object); } |
@Test public void parse_signed_message_missing_crc_check() throws Exception { final MailMessage message = subject.parse( getMessage( "To: [email protected]\n" + "From: No Reply <[email protected]>\n" + "Date: Thu, 30 Mar 2017 09:00:00 +0100\n" + "MIME-Version: 1.0\n" + "Content-Type: text/plain; charset=windows-1252\n" + "Content-Transfer-Encoding: 7bit\n" + "\n" + "\n" + "-----BEGIN PGP SIGNED MESSAGE-----\n" + "Hash: SHA1\n" + "\n" + "aut-num: AS3333\n" + "remarks: +---------------------\n" + "----------------------+\n" + "mnt-by: TEST-MNT\n" + "source: TEST\n" + "\n" + "\n" + "-----BEGIN PGP SIGNATURE-----\n" + "Version: GnuPG v2\n" + " \n" + "iEYEARECAAYFAljcrkEACgkQYAnVsDBumXz9bwCfZQAm+4e7bbXztKzgwjGpjBQs\n" + "cYEAn3pN9uN9zhFrph7Co4tZ00aw/7TG\n" + "=NjUf\n" + "-----END PGP SIGNATURE-----\n" + "\n" + "\n" + "\n"), updateContext); assertThat(message.getContentWithCredentials(), hasSize(1)); final ContentWithCredentials contentWithCredentials = message.getContentWithCredentials().get(0); assertThat(contentWithCredentials.getCredentials(), hasSize(0)); } | public MailMessage parse(final MimeMessage message, final UpdateContext updateContext) throws MessagingException { final MailMessageBuilder messageBuilder = new MailMessageBuilder(); messageBuilder.id(message.getMessageID()); parseSubject(messageBuilder, message, updateContext); String[] deliveryDate = message.getHeader("Delivery-date"); if (deliveryDate != null && deliveryDate.length > 0 && deliveryDate[0].length() > 0) { messageBuilder.date(deliveryDate[0]); } else { messageBuilder.date(DATE_FORMAT.format(ZonedDateTime.now())); } parseReplyTo(messageBuilder, message); try { parseContents(messageBuilder, message); final MailMessage mailMessage = messageBuilder.build(); if (!mailMessage.getKeyword().isContentExpected() || !mailMessage.getContentWithCredentials().isEmpty()) { return mailMessage; } } catch (ParseException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message"), e); } catch (MessagingException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message using java mail"), e); } catch (IOException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Exception parsing message"), e); } catch (RuntimeException e) { LOGGER.error("Unexpected error parsing message: {}", message.getMessageID(), e); } updateContext.addGlobalMessage(UpdateMessages.noValidUpdateFound()); return messageBuilder.build(); } | MessageParser { public MailMessage parse(final MimeMessage message, final UpdateContext updateContext) throws MessagingException { final MailMessageBuilder messageBuilder = new MailMessageBuilder(); messageBuilder.id(message.getMessageID()); parseSubject(messageBuilder, message, updateContext); String[] deliveryDate = message.getHeader("Delivery-date"); if (deliveryDate != null && deliveryDate.length > 0 && deliveryDate[0].length() > 0) { messageBuilder.date(deliveryDate[0]); } else { messageBuilder.date(DATE_FORMAT.format(ZonedDateTime.now())); } parseReplyTo(messageBuilder, message); try { parseContents(messageBuilder, message); final MailMessage mailMessage = messageBuilder.build(); if (!mailMessage.getKeyword().isContentExpected() || !mailMessage.getContentWithCredentials().isEmpty()) { return mailMessage; } } catch (ParseException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message"), e); } catch (MessagingException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message using java mail"), e); } catch (IOException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Exception parsing message"), e); } catch (RuntimeException e) { LOGGER.error("Unexpected error parsing message: {}", message.getMessageID(), e); } updateContext.addGlobalMessage(UpdateMessages.noValidUpdateFound()); return messageBuilder.build(); } } | MessageParser { public MailMessage parse(final MimeMessage message, final UpdateContext updateContext) throws MessagingException { final MailMessageBuilder messageBuilder = new MailMessageBuilder(); messageBuilder.id(message.getMessageID()); parseSubject(messageBuilder, message, updateContext); String[] deliveryDate = message.getHeader("Delivery-date"); if (deliveryDate != null && deliveryDate.length > 0 && deliveryDate[0].length() > 0) { messageBuilder.date(deliveryDate[0]); } else { messageBuilder.date(DATE_FORMAT.format(ZonedDateTime.now())); } parseReplyTo(messageBuilder, message); try { parseContents(messageBuilder, message); final MailMessage mailMessage = messageBuilder.build(); if (!mailMessage.getKeyword().isContentExpected() || !mailMessage.getContentWithCredentials().isEmpty()) { return mailMessage; } } catch (ParseException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message"), e); } catch (MessagingException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message using java mail"), e); } catch (IOException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Exception parsing message"), e); } catch (RuntimeException e) { LOGGER.error("Unexpected error parsing message: {}", message.getMessageID(), e); } updateContext.addGlobalMessage(UpdateMessages.noValidUpdateFound()); return messageBuilder.build(); } @Autowired MessageParser(final LoggerContext loggerContext); } | MessageParser { public MailMessage parse(final MimeMessage message, final UpdateContext updateContext) throws MessagingException { final MailMessageBuilder messageBuilder = new MailMessageBuilder(); messageBuilder.id(message.getMessageID()); parseSubject(messageBuilder, message, updateContext); String[] deliveryDate = message.getHeader("Delivery-date"); if (deliveryDate != null && deliveryDate.length > 0 && deliveryDate[0].length() > 0) { messageBuilder.date(deliveryDate[0]); } else { messageBuilder.date(DATE_FORMAT.format(ZonedDateTime.now())); } parseReplyTo(messageBuilder, message); try { parseContents(messageBuilder, message); final MailMessage mailMessage = messageBuilder.build(); if (!mailMessage.getKeyword().isContentExpected() || !mailMessage.getContentWithCredentials().isEmpty()) { return mailMessage; } } catch (ParseException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message"), e); } catch (MessagingException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message using java mail"), e); } catch (IOException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Exception parsing message"), e); } catch (RuntimeException e) { LOGGER.error("Unexpected error parsing message: {}", message.getMessageID(), e); } updateContext.addGlobalMessage(UpdateMessages.noValidUpdateFound()); return messageBuilder.build(); } @Autowired MessageParser(final LoggerContext loggerContext); MailMessage parse(final MimeMessage message, final UpdateContext updateContext); } | MessageParser { public MailMessage parse(final MimeMessage message, final UpdateContext updateContext) throws MessagingException { final MailMessageBuilder messageBuilder = new MailMessageBuilder(); messageBuilder.id(message.getMessageID()); parseSubject(messageBuilder, message, updateContext); String[] deliveryDate = message.getHeader("Delivery-date"); if (deliveryDate != null && deliveryDate.length > 0 && deliveryDate[0].length() > 0) { messageBuilder.date(deliveryDate[0]); } else { messageBuilder.date(DATE_FORMAT.format(ZonedDateTime.now())); } parseReplyTo(messageBuilder, message); try { parseContents(messageBuilder, message); final MailMessage mailMessage = messageBuilder.build(); if (!mailMessage.getKeyword().isContentExpected() || !mailMessage.getContentWithCredentials().isEmpty()) { return mailMessage; } } catch (ParseException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message"), e); } catch (MessagingException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message using java mail"), e); } catch (IOException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Exception parsing message"), e); } catch (RuntimeException e) { LOGGER.error("Unexpected error parsing message: {}", message.getMessageID(), e); } updateContext.addGlobalMessage(UpdateMessages.noValidUpdateFound()); return messageBuilder.build(); } @Autowired MessageParser(final LoggerContext loggerContext); MailMessage parse(final MimeMessage message, final UpdateContext updateContext); } |
@Test public void equals_null() { assertThat(new DnsCheckRequest(update, "domain", "glue").equals(null), is(false)); } | @Override public boolean equals(final Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; final DnsCheckRequest that = (DnsCheckRequest) o; return Objects.equals(domain, that.domain) && Objects.equals(glue, that.glue); } | DnsCheckRequest { @Override public boolean equals(final Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; final DnsCheckRequest that = (DnsCheckRequest) o; return Objects.equals(domain, that.domain) && Objects.equals(glue, that.glue); } } | DnsCheckRequest { @Override public boolean equals(final Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; final DnsCheckRequest that = (DnsCheckRequest) o; return Objects.equals(domain, that.domain) && Objects.equals(glue, that.glue); } DnsCheckRequest(final Update update, final String domain, final String glue); } | DnsCheckRequest { @Override public boolean equals(final Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; final DnsCheckRequest that = (DnsCheckRequest) o; return Objects.equals(domain, that.domain) && Objects.equals(glue, that.glue); } DnsCheckRequest(final Update update, final String domain, final String glue); Update getUpdate(); String getDomain(); String getGlue(); @Override boolean equals(final Object o); @Override int hashCode(); @Override String toString(); } | DnsCheckRequest { @Override public boolean equals(final Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; final DnsCheckRequest that = (DnsCheckRequest) o; return Objects.equals(domain, that.domain) && Objects.equals(glue, that.glue); } DnsCheckRequest(final Update update, final String domain, final String glue); Update getUpdate(); String getDomain(); String getGlue(); @Override boolean equals(final Object o); @Override int hashCode(); @Override String toString(); } |
@Test public void equals_other_class() { assertThat(new DnsCheckRequest(update, "domain", "glue").equals(""), is(false)); } | @Override public boolean equals(final Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; final DnsCheckRequest that = (DnsCheckRequest) o; return Objects.equals(domain, that.domain) && Objects.equals(glue, that.glue); } | DnsCheckRequest { @Override public boolean equals(final Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; final DnsCheckRequest that = (DnsCheckRequest) o; return Objects.equals(domain, that.domain) && Objects.equals(glue, that.glue); } } | DnsCheckRequest { @Override public boolean equals(final Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; final DnsCheckRequest that = (DnsCheckRequest) o; return Objects.equals(domain, that.domain) && Objects.equals(glue, that.glue); } DnsCheckRequest(final Update update, final String domain, final String glue); } | DnsCheckRequest { @Override public boolean equals(final Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; final DnsCheckRequest that = (DnsCheckRequest) o; return Objects.equals(domain, that.domain) && Objects.equals(glue, that.glue); } DnsCheckRequest(final Update update, final String domain, final String glue); Update getUpdate(); String getDomain(); String getGlue(); @Override boolean equals(final Object o); @Override int hashCode(); @Override String toString(); } | DnsCheckRequest { @Override public boolean equals(final Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; final DnsCheckRequest that = (DnsCheckRequest) o; return Objects.equals(domain, that.domain) && Objects.equals(glue, that.glue); } DnsCheckRequest(final Update update, final String domain, final String glue); Update getUpdate(); String getDomain(); String getGlue(); @Override boolean equals(final Object o); @Override int hashCode(); @Override String toString(); } |
@Test public void equals_same_instance() { final DnsCheckRequest dnsCheckRequest = new DnsCheckRequest(update, "domain", "glue"); assertThat(dnsCheckRequest.equals(dnsCheckRequest), is(true)); } | @Override public boolean equals(final Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; final DnsCheckRequest that = (DnsCheckRequest) o; return Objects.equals(domain, that.domain) && Objects.equals(glue, that.glue); } | DnsCheckRequest { @Override public boolean equals(final Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; final DnsCheckRequest that = (DnsCheckRequest) o; return Objects.equals(domain, that.domain) && Objects.equals(glue, that.glue); } } | DnsCheckRequest { @Override public boolean equals(final Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; final DnsCheckRequest that = (DnsCheckRequest) o; return Objects.equals(domain, that.domain) && Objects.equals(glue, that.glue); } DnsCheckRequest(final Update update, final String domain, final String glue); } | DnsCheckRequest { @Override public boolean equals(final Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; final DnsCheckRequest that = (DnsCheckRequest) o; return Objects.equals(domain, that.domain) && Objects.equals(glue, that.glue); } DnsCheckRequest(final Update update, final String domain, final String glue); Update getUpdate(); String getDomain(); String getGlue(); @Override boolean equals(final Object o); @Override int hashCode(); @Override String toString(); } | DnsCheckRequest { @Override public boolean equals(final Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; final DnsCheckRequest that = (DnsCheckRequest) o; return Objects.equals(domain, that.domain) && Objects.equals(glue, that.glue); } DnsCheckRequest(final Update update, final String domain, final String glue); Update getUpdate(); String getDomain(); String getGlue(); @Override boolean equals(final Object o); @Override int hashCode(); @Override String toString(); } |
@Test public void equals_not_equal_domain() { final DnsCheckRequest dnsCheckRequest1 = new DnsCheckRequest(update, "domain", "glue"); final DnsCheckRequest dnsCheckRequest2 = new DnsCheckRequest(update, "DOMAIN", "glue"); assertThat(dnsCheckRequest1.equals(dnsCheckRequest2), is(false)); } | @Override public boolean equals(final Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; final DnsCheckRequest that = (DnsCheckRequest) o; return Objects.equals(domain, that.domain) && Objects.equals(glue, that.glue); } | DnsCheckRequest { @Override public boolean equals(final Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; final DnsCheckRequest that = (DnsCheckRequest) o; return Objects.equals(domain, that.domain) && Objects.equals(glue, that.glue); } } | DnsCheckRequest { @Override public boolean equals(final Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; final DnsCheckRequest that = (DnsCheckRequest) o; return Objects.equals(domain, that.domain) && Objects.equals(glue, that.glue); } DnsCheckRequest(final Update update, final String domain, final String glue); } | DnsCheckRequest { @Override public boolean equals(final Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; final DnsCheckRequest that = (DnsCheckRequest) o; return Objects.equals(domain, that.domain) && Objects.equals(glue, that.glue); } DnsCheckRequest(final Update update, final String domain, final String glue); Update getUpdate(); String getDomain(); String getGlue(); @Override boolean equals(final Object o); @Override int hashCode(); @Override String toString(); } | DnsCheckRequest { @Override public boolean equals(final Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; final DnsCheckRequest that = (DnsCheckRequest) o; return Objects.equals(domain, that.domain) && Objects.equals(glue, that.glue); } DnsCheckRequest(final Update update, final String domain, final String glue); Update getUpdate(); String getDomain(); String getGlue(); @Override boolean equals(final Object o); @Override int hashCode(); @Override String toString(); } |
@Test public void equals_not_equal_glue() { final DnsCheckRequest dnsCheckRequest1 = new DnsCheckRequest(update, "domain", "glue"); final DnsCheckRequest dnsCheckRequest2 = new DnsCheckRequest(update, "domain", "GLUE"); assertThat(dnsCheckRequest1.equals(dnsCheckRequest2), is(false)); } | @Override public boolean equals(final Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; final DnsCheckRequest that = (DnsCheckRequest) o; return Objects.equals(domain, that.domain) && Objects.equals(glue, that.glue); } | DnsCheckRequest { @Override public boolean equals(final Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; final DnsCheckRequest that = (DnsCheckRequest) o; return Objects.equals(domain, that.domain) && Objects.equals(glue, that.glue); } } | DnsCheckRequest { @Override public boolean equals(final Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; final DnsCheckRequest that = (DnsCheckRequest) o; return Objects.equals(domain, that.domain) && Objects.equals(glue, that.glue); } DnsCheckRequest(final Update update, final String domain, final String glue); } | DnsCheckRequest { @Override public boolean equals(final Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; final DnsCheckRequest that = (DnsCheckRequest) o; return Objects.equals(domain, that.domain) && Objects.equals(glue, that.glue); } DnsCheckRequest(final Update update, final String domain, final String glue); Update getUpdate(); String getDomain(); String getGlue(); @Override boolean equals(final Object o); @Override int hashCode(); @Override String toString(); } | DnsCheckRequest { @Override public boolean equals(final Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; final DnsCheckRequest that = (DnsCheckRequest) o; return Objects.equals(domain, that.domain) && Objects.equals(glue, that.glue); } DnsCheckRequest(final Update update, final String domain, final String glue); Update getUpdate(); String getDomain(); String getGlue(); @Override boolean equals(final Object o); @Override int hashCode(); @Override String toString(); } |
@Test public void single_record_with_error_message() { mock(RpslObject.parse("domain: 22.0.193.in-addr.arpa")); when(startDomainTestResponse.getResult()).thenReturn("1"); when(testProgressResponse.getResult()).thenReturn("50").thenReturn("100"); when(result.getResults()).thenReturn(Lists.newArrayList(message)); when(message.getMessage()).thenReturn("check failed"); when(message.getLevel()).thenReturn("ERROR"); final Map<DnsCheckRequest, DnsCheckResponse> response = subject.performDnsChecks( Sets.newHashSet(new DnsCheckRequest(update, "1.ripe.net", null)) ); assertThat(response.size(), is(1)); assertThat(response.values(), hasSize(1)); final List<Message> messages = response.values().iterator().next().getMessages(); assertThat(messages, contains(new Message(Messages.Type.ERROR, "check failed"))); } | @Override public Map<DnsCheckRequest, DnsCheckResponse> performDnsChecks(final Set<DnsCheckRequest> dnsCheckRequests) { return dnsCheckRequests .parallelStream() .collect(Collectors.toMap( dnsCheckRequest -> dnsCheckRequest, new ZonemasterFunction())); } | ZonemasterDnsGateway implements DnsGateway { @Override public Map<DnsCheckRequest, DnsCheckResponse> performDnsChecks(final Set<DnsCheckRequest> dnsCheckRequests) { return dnsCheckRequests .parallelStream() .collect(Collectors.toMap( dnsCheckRequest -> dnsCheckRequest, new ZonemasterFunction())); } } | ZonemasterDnsGateway implements DnsGateway { @Override public Map<DnsCheckRequest, DnsCheckResponse> performDnsChecks(final Set<DnsCheckRequest> dnsCheckRequests) { return dnsCheckRequests .parallelStream() .collect(Collectors.toMap( dnsCheckRequest -> dnsCheckRequest, new ZonemasterFunction())); } ZonemasterDnsGateway(final ZonemasterRestClient zonemasterRestClient); } | ZonemasterDnsGateway implements DnsGateway { @Override public Map<DnsCheckRequest, DnsCheckResponse> performDnsChecks(final Set<DnsCheckRequest> dnsCheckRequests) { return dnsCheckRequests .parallelStream() .collect(Collectors.toMap( dnsCheckRequest -> dnsCheckRequest, new ZonemasterFunction())); } ZonemasterDnsGateway(final ZonemasterRestClient zonemasterRestClient); @Override Map<DnsCheckRequest, DnsCheckResponse> performDnsChecks(final Set<DnsCheckRequest> dnsCheckRequests); } | ZonemasterDnsGateway implements DnsGateway { @Override public Map<DnsCheckRequest, DnsCheckResponse> performDnsChecks(final Set<DnsCheckRequest> dnsCheckRequests) { return dnsCheckRequests .parallelStream() .collect(Collectors.toMap( dnsCheckRequest -> dnsCheckRequest, new ZonemasterFunction())); } ZonemasterDnsGateway(final ZonemasterRestClient zonemasterRestClient); @Override Map<DnsCheckRequest, DnsCheckResponse> performDnsChecks(final Set<DnsCheckRequest> dnsCheckRequests); } |
@Test public void odd_number_of_domain_objects_above_threshold() { mock(RpslObject.parse("domain: 22.0.193.in-addr.arpa")); when(startDomainTestResponse.getResult()).thenReturn("1"); when(testProgressResponse.getResult()).thenReturn("100"); final Map<DnsCheckRequest, DnsCheckResponse> response = subject.performDnsChecks(Sets.newHashSet( new DnsCheckRequest(update, "1.ripe.net", null), new DnsCheckRequest(update, "2.ripe.net", null), new DnsCheckRequest(update, "3.ripe.net", null), new DnsCheckRequest(update, "4.ripe.net", null), new DnsCheckRequest(update, "5.ripe.net", null), new DnsCheckRequest(update, "6.ripe.net", null), new DnsCheckRequest(update, "7.ripe.net", null), new DnsCheckRequest(update, "8.ripe.net", null), new DnsCheckRequest(update, "9.ripe.net", null), new DnsCheckRequest(update, "10.ripe.net", null), new DnsCheckRequest(update, "11.ripe.net", null) )); assertThat(response.values(), hasSize(11)); } | @Override public Map<DnsCheckRequest, DnsCheckResponse> performDnsChecks(final Set<DnsCheckRequest> dnsCheckRequests) { return dnsCheckRequests .parallelStream() .collect(Collectors.toMap( dnsCheckRequest -> dnsCheckRequest, new ZonemasterFunction())); } | ZonemasterDnsGateway implements DnsGateway { @Override public Map<DnsCheckRequest, DnsCheckResponse> performDnsChecks(final Set<DnsCheckRequest> dnsCheckRequests) { return dnsCheckRequests .parallelStream() .collect(Collectors.toMap( dnsCheckRequest -> dnsCheckRequest, new ZonemasterFunction())); } } | ZonemasterDnsGateway implements DnsGateway { @Override public Map<DnsCheckRequest, DnsCheckResponse> performDnsChecks(final Set<DnsCheckRequest> dnsCheckRequests) { return dnsCheckRequests .parallelStream() .collect(Collectors.toMap( dnsCheckRequest -> dnsCheckRequest, new ZonemasterFunction())); } ZonemasterDnsGateway(final ZonemasterRestClient zonemasterRestClient); } | ZonemasterDnsGateway implements DnsGateway { @Override public Map<DnsCheckRequest, DnsCheckResponse> performDnsChecks(final Set<DnsCheckRequest> dnsCheckRequests) { return dnsCheckRequests .parallelStream() .collect(Collectors.toMap( dnsCheckRequest -> dnsCheckRequest, new ZonemasterFunction())); } ZonemasterDnsGateway(final ZonemasterRestClient zonemasterRestClient); @Override Map<DnsCheckRequest, DnsCheckResponse> performDnsChecks(final Set<DnsCheckRequest> dnsCheckRequests); } | ZonemasterDnsGateway implements DnsGateway { @Override public Map<DnsCheckRequest, DnsCheckResponse> performDnsChecks(final Set<DnsCheckRequest> dnsCheckRequests) { return dnsCheckRequests .parallelStream() .collect(Collectors.toMap( dnsCheckRequest -> dnsCheckRequest, new ZonemasterFunction())); } ZonemasterDnsGateway(final ZonemasterRestClient zonemasterRestClient); @Override Map<DnsCheckRequest, DnsCheckResponse> performDnsChecks(final Set<DnsCheckRequest> dnsCheckRequests); } |
@Test public void even_number_of_domain_objects_above_threshold() { mock(RpslObject.parse("domain: 22.0.193.in-addr.arpa")); when(startDomainTestResponse.getResult()).thenReturn("1"); when(testProgressResponse.getResult()).thenReturn("100"); final Map<DnsCheckRequest, DnsCheckResponse> response = subject.performDnsChecks(Sets.newHashSet( new DnsCheckRequest(update, "1.ripe.net", null), new DnsCheckRequest(update, "2.ripe.net", null), new DnsCheckRequest(update, "3.ripe.net", null), new DnsCheckRequest(update, "4.ripe.net", null), new DnsCheckRequest(update, "5.ripe.net", null), new DnsCheckRequest(update, "6.ripe.net", null), new DnsCheckRequest(update, "7.ripe.net", null), new DnsCheckRequest(update, "8.ripe.net", null), new DnsCheckRequest(update, "9.ripe.net", null), new DnsCheckRequest(update, "10.ripe.net", null), new DnsCheckRequest(update, "11.ripe.net", null), new DnsCheckRequest(update, "12.ripe.net", null) )); assertThat(response.values(), hasSize(12)); } | @Override public Map<DnsCheckRequest, DnsCheckResponse> performDnsChecks(final Set<DnsCheckRequest> dnsCheckRequests) { return dnsCheckRequests .parallelStream() .collect(Collectors.toMap( dnsCheckRequest -> dnsCheckRequest, new ZonemasterFunction())); } | ZonemasterDnsGateway implements DnsGateway { @Override public Map<DnsCheckRequest, DnsCheckResponse> performDnsChecks(final Set<DnsCheckRequest> dnsCheckRequests) { return dnsCheckRequests .parallelStream() .collect(Collectors.toMap( dnsCheckRequest -> dnsCheckRequest, new ZonemasterFunction())); } } | ZonemasterDnsGateway implements DnsGateway { @Override public Map<DnsCheckRequest, DnsCheckResponse> performDnsChecks(final Set<DnsCheckRequest> dnsCheckRequests) { return dnsCheckRequests .parallelStream() .collect(Collectors.toMap( dnsCheckRequest -> dnsCheckRequest, new ZonemasterFunction())); } ZonemasterDnsGateway(final ZonemasterRestClient zonemasterRestClient); } | ZonemasterDnsGateway implements DnsGateway { @Override public Map<DnsCheckRequest, DnsCheckResponse> performDnsChecks(final Set<DnsCheckRequest> dnsCheckRequests) { return dnsCheckRequests .parallelStream() .collect(Collectors.toMap( dnsCheckRequest -> dnsCheckRequest, new ZonemasterFunction())); } ZonemasterDnsGateway(final ZonemasterRestClient zonemasterRestClient); @Override Map<DnsCheckRequest, DnsCheckResponse> performDnsChecks(final Set<DnsCheckRequest> dnsCheckRequests); } | ZonemasterDnsGateway implements DnsGateway { @Override public Map<DnsCheckRequest, DnsCheckResponse> performDnsChecks(final Set<DnsCheckRequest> dnsCheckRequests) { return dnsCheckRequests .parallelStream() .collect(Collectors.toMap( dnsCheckRequest -> dnsCheckRequest, new ZonemasterFunction())); } ZonemasterDnsGateway(final ZonemasterRestClient zonemasterRestClient); @Override Map<DnsCheckRequest, DnsCheckResponse> performDnsChecks(final Set<DnsCheckRequest> dnsCheckRequests); } |
@Test public void check_delete() { when(update.getOperation()).thenReturn(Operation.DELETE); subject.checkAll(updateRequest, updateContext); verifyZeroInteractions(dnsGateway); } | public void checkAll(final UpdateRequest updateRequest, final UpdateContext updateContext) { if (!dnsCheckEnabled) { return; } Set<DnsCheckRequest> dnsCheckRequestSet = Sets.newLinkedHashSet(); for (Update update : updateRequest.getUpdates()) { if (isDnsCheckRequired(update)) { dnsCheckRequestSet.add(createDnsCheckRequest(update)); } } if (dnsCheckRequestSet.isEmpty()) { return; } final Stopwatch stopwatch = Stopwatch.createStarted(); final Map<DnsCheckRequest, DnsCheckResponse> dnsCheckResponseMap = dnsGateway.performDnsChecks(dnsCheckRequestSet); loggerContext.log(new Message(Messages.Type.INFO, "Called dnsGateway with %d requests and processed in %s", dnsCheckRequestSet.size(), stopwatch.stop().toString())); for (Map.Entry<DnsCheckRequest, DnsCheckResponse> entry : dnsCheckResponseMap.entrySet()) { final DnsCheckRequest dnsCheckRequest = entry.getKey(); final DnsCheckResponse dnsCheckResponse = entry.getValue(); updateContext.addDnsCheckResponse(dnsCheckRequest, dnsCheckResponse); for (final Message message : dnsCheckResponse.getMessages()) { updateContext.addMessage(dnsCheckRequest.getUpdate(), message); } } } | DnsChecker { public void checkAll(final UpdateRequest updateRequest, final UpdateContext updateContext) { if (!dnsCheckEnabled) { return; } Set<DnsCheckRequest> dnsCheckRequestSet = Sets.newLinkedHashSet(); for (Update update : updateRequest.getUpdates()) { if (isDnsCheckRequired(update)) { dnsCheckRequestSet.add(createDnsCheckRequest(update)); } } if (dnsCheckRequestSet.isEmpty()) { return; } final Stopwatch stopwatch = Stopwatch.createStarted(); final Map<DnsCheckRequest, DnsCheckResponse> dnsCheckResponseMap = dnsGateway.performDnsChecks(dnsCheckRequestSet); loggerContext.log(new Message(Messages.Type.INFO, "Called dnsGateway with %d requests and processed in %s", dnsCheckRequestSet.size(), stopwatch.stop().toString())); for (Map.Entry<DnsCheckRequest, DnsCheckResponse> entry : dnsCheckResponseMap.entrySet()) { final DnsCheckRequest dnsCheckRequest = entry.getKey(); final DnsCheckResponse dnsCheckResponse = entry.getValue(); updateContext.addDnsCheckResponse(dnsCheckRequest, dnsCheckResponse); for (final Message message : dnsCheckResponse.getMessages()) { updateContext.addMessage(dnsCheckRequest.getUpdate(), message); } } } } | DnsChecker { public void checkAll(final UpdateRequest updateRequest, final UpdateContext updateContext) { if (!dnsCheckEnabled) { return; } Set<DnsCheckRequest> dnsCheckRequestSet = Sets.newLinkedHashSet(); for (Update update : updateRequest.getUpdates()) { if (isDnsCheckRequired(update)) { dnsCheckRequestSet.add(createDnsCheckRequest(update)); } } if (dnsCheckRequestSet.isEmpty()) { return; } final Stopwatch stopwatch = Stopwatch.createStarted(); final Map<DnsCheckRequest, DnsCheckResponse> dnsCheckResponseMap = dnsGateway.performDnsChecks(dnsCheckRequestSet); loggerContext.log(new Message(Messages.Type.INFO, "Called dnsGateway with %d requests and processed in %s", dnsCheckRequestSet.size(), stopwatch.stop().toString())); for (Map.Entry<DnsCheckRequest, DnsCheckResponse> entry : dnsCheckResponseMap.entrySet()) { final DnsCheckRequest dnsCheckRequest = entry.getKey(); final DnsCheckResponse dnsCheckResponse = entry.getValue(); updateContext.addDnsCheckResponse(dnsCheckRequest, dnsCheckResponse); for (final Message message : dnsCheckResponse.getMessages()) { updateContext.addMessage(dnsCheckRequest.getUpdate(), message); } } } @Autowired DnsChecker(final DnsGateway dnsGateway,
final LoggerContext loggerContext,
@Value("${whois.zonemaster.baseUrl:}") final String baseUrl); } | DnsChecker { public void checkAll(final UpdateRequest updateRequest, final UpdateContext updateContext) { if (!dnsCheckEnabled) { return; } Set<DnsCheckRequest> dnsCheckRequestSet = Sets.newLinkedHashSet(); for (Update update : updateRequest.getUpdates()) { if (isDnsCheckRequired(update)) { dnsCheckRequestSet.add(createDnsCheckRequest(update)); } } if (dnsCheckRequestSet.isEmpty()) { return; } final Stopwatch stopwatch = Stopwatch.createStarted(); final Map<DnsCheckRequest, DnsCheckResponse> dnsCheckResponseMap = dnsGateway.performDnsChecks(dnsCheckRequestSet); loggerContext.log(new Message(Messages.Type.INFO, "Called dnsGateway with %d requests and processed in %s", dnsCheckRequestSet.size(), stopwatch.stop().toString())); for (Map.Entry<DnsCheckRequest, DnsCheckResponse> entry : dnsCheckResponseMap.entrySet()) { final DnsCheckRequest dnsCheckRequest = entry.getKey(); final DnsCheckResponse dnsCheckResponse = entry.getValue(); updateContext.addDnsCheckResponse(dnsCheckRequest, dnsCheckResponse); for (final Message message : dnsCheckResponse.getMessages()) { updateContext.addMessage(dnsCheckRequest.getUpdate(), message); } } } @Autowired DnsChecker(final DnsGateway dnsGateway,
final LoggerContext loggerContext,
@Value("${whois.zonemaster.baseUrl:}") final String baseUrl); void checkAll(final UpdateRequest updateRequest, final UpdateContext updateContext); } | DnsChecker { public void checkAll(final UpdateRequest updateRequest, final UpdateContext updateContext) { if (!dnsCheckEnabled) { return; } Set<DnsCheckRequest> dnsCheckRequestSet = Sets.newLinkedHashSet(); for (Update update : updateRequest.getUpdates()) { if (isDnsCheckRequired(update)) { dnsCheckRequestSet.add(createDnsCheckRequest(update)); } } if (dnsCheckRequestSet.isEmpty()) { return; } final Stopwatch stopwatch = Stopwatch.createStarted(); final Map<DnsCheckRequest, DnsCheckResponse> dnsCheckResponseMap = dnsGateway.performDnsChecks(dnsCheckRequestSet); loggerContext.log(new Message(Messages.Type.INFO, "Called dnsGateway with %d requests and processed in %s", dnsCheckRequestSet.size(), stopwatch.stop().toString())); for (Map.Entry<DnsCheckRequest, DnsCheckResponse> entry : dnsCheckResponseMap.entrySet()) { final DnsCheckRequest dnsCheckRequest = entry.getKey(); final DnsCheckResponse dnsCheckResponse = entry.getValue(); updateContext.addDnsCheckResponse(dnsCheckRequest, dnsCheckResponse); for (final Message message : dnsCheckResponse.getMessages()) { updateContext.addMessage(dnsCheckRequest.getUpdate(), message); } } } @Autowired DnsChecker(final DnsGateway dnsGateway,
final LoggerContext loggerContext,
@Value("${whois.zonemaster.baseUrl:}") final String baseUrl); void checkAll(final UpdateRequest updateRequest, final UpdateContext updateContext); } |
@Test public void transform_domain_no_dot() { final RpslObject rpslObject = RpslObject.parse("domain: 17.45.212.in-addr.arpa"); final RpslObject result = attributeSanitizer.sanitize(rpslObject, objectMessages); assertThat(result.getKey().toString(), is("17.45.212.in-addr.arpa")); assertThat(result.getValueForAttribute(AttributeType.DOMAIN).toString(), is("17.45.212.in-addr.arpa")); verifyZeroInteractions(objectMessages); } | public RpslObject sanitize(final RpslObject object, final ObjectMessages objectMessages) { final Map<RpslAttribute, RpslAttribute> replacements = Maps.newHashMap(); for (final RpslAttribute attribute : object.getAttributes()) { final AttributeType type = attribute.getType(); String newValue = null; final Sanitizer sanitizer = SANITIZER_MAP.get(type); if (sanitizer == null) { continue; } try { newValue = sanitizer.sanitize(attribute); } catch (IllegalArgumentException ignored) { LOGGER.debug("{}: {}", ignored.getClass().getName(), ignored.getMessage()); } if (newValue == null) { continue; } final List<Message> attributeMessages = Lists.newArrayList(); if (!sanitizer.silent() && !attribute.getCleanValue().toString().equals(newValue)) { attributeMessages.add(ValidationMessages.attributeValueConverted(attribute.getCleanValue(), newValue)); } if (keyAttributes.contains(type) && attribute.getValue().indexOf('\n') != -1) { attributeMessages.add(ValidationMessages.continuationLinesRemoved()); } if (keyAttributes.contains(type) && attribute.getValue().indexOf('#') != -1) { attributeMessages.add(ValidationMessages.remarksReformatted()); } final String replacement = newValue + getCommentReplacement(attribute); final RpslAttribute transformed = new RpslAttribute(attribute.getKey(), replacement); replacements.put(attribute, transformed); for (final Message attributeMessage : attributeMessages) { objectMessages.addMessage(transformed, attributeMessage); } } return new RpslObjectBuilder(object).replaceAttributes(replacements).get(); } | AttributeSanitizer { public RpslObject sanitize(final RpslObject object, final ObjectMessages objectMessages) { final Map<RpslAttribute, RpslAttribute> replacements = Maps.newHashMap(); for (final RpslAttribute attribute : object.getAttributes()) { final AttributeType type = attribute.getType(); String newValue = null; final Sanitizer sanitizer = SANITIZER_MAP.get(type); if (sanitizer == null) { continue; } try { newValue = sanitizer.sanitize(attribute); } catch (IllegalArgumentException ignored) { LOGGER.debug("{}: {}", ignored.getClass().getName(), ignored.getMessage()); } if (newValue == null) { continue; } final List<Message> attributeMessages = Lists.newArrayList(); if (!sanitizer.silent() && !attribute.getCleanValue().toString().equals(newValue)) { attributeMessages.add(ValidationMessages.attributeValueConverted(attribute.getCleanValue(), newValue)); } if (keyAttributes.contains(type) && attribute.getValue().indexOf('\n') != -1) { attributeMessages.add(ValidationMessages.continuationLinesRemoved()); } if (keyAttributes.contains(type) && attribute.getValue().indexOf('#') != -1) { attributeMessages.add(ValidationMessages.remarksReformatted()); } final String replacement = newValue + getCommentReplacement(attribute); final RpslAttribute transformed = new RpslAttribute(attribute.getKey(), replacement); replacements.put(attribute, transformed); for (final Message attributeMessage : attributeMessages) { objectMessages.addMessage(transformed, attributeMessage); } } return new RpslObjectBuilder(object).replaceAttributes(replacements).get(); } } | AttributeSanitizer { public RpslObject sanitize(final RpslObject object, final ObjectMessages objectMessages) { final Map<RpslAttribute, RpslAttribute> replacements = Maps.newHashMap(); for (final RpslAttribute attribute : object.getAttributes()) { final AttributeType type = attribute.getType(); String newValue = null; final Sanitizer sanitizer = SANITIZER_MAP.get(type); if (sanitizer == null) { continue; } try { newValue = sanitizer.sanitize(attribute); } catch (IllegalArgumentException ignored) { LOGGER.debug("{}: {}", ignored.getClass().getName(), ignored.getMessage()); } if (newValue == null) { continue; } final List<Message> attributeMessages = Lists.newArrayList(); if (!sanitizer.silent() && !attribute.getCleanValue().toString().equals(newValue)) { attributeMessages.add(ValidationMessages.attributeValueConverted(attribute.getCleanValue(), newValue)); } if (keyAttributes.contains(type) && attribute.getValue().indexOf('\n') != -1) { attributeMessages.add(ValidationMessages.continuationLinesRemoved()); } if (keyAttributes.contains(type) && attribute.getValue().indexOf('#') != -1) { attributeMessages.add(ValidationMessages.remarksReformatted()); } final String replacement = newValue + getCommentReplacement(attribute); final RpslAttribute transformed = new RpslAttribute(attribute.getKey(), replacement); replacements.put(attribute, transformed); for (final Message attributeMessage : attributeMessages) { objectMessages.addMessage(transformed, attributeMessage); } } return new RpslObjectBuilder(object).replaceAttributes(replacements).get(); } @Autowired AttributeSanitizer(DateTimeProvider dateTimeProvider); } | AttributeSanitizer { public RpslObject sanitize(final RpslObject object, final ObjectMessages objectMessages) { final Map<RpslAttribute, RpslAttribute> replacements = Maps.newHashMap(); for (final RpslAttribute attribute : object.getAttributes()) { final AttributeType type = attribute.getType(); String newValue = null; final Sanitizer sanitizer = SANITIZER_MAP.get(type); if (sanitizer == null) { continue; } try { newValue = sanitizer.sanitize(attribute); } catch (IllegalArgumentException ignored) { LOGGER.debug("{}: {}", ignored.getClass().getName(), ignored.getMessage()); } if (newValue == null) { continue; } final List<Message> attributeMessages = Lists.newArrayList(); if (!sanitizer.silent() && !attribute.getCleanValue().toString().equals(newValue)) { attributeMessages.add(ValidationMessages.attributeValueConverted(attribute.getCleanValue(), newValue)); } if (keyAttributes.contains(type) && attribute.getValue().indexOf('\n') != -1) { attributeMessages.add(ValidationMessages.continuationLinesRemoved()); } if (keyAttributes.contains(type) && attribute.getValue().indexOf('#') != -1) { attributeMessages.add(ValidationMessages.remarksReformatted()); } final String replacement = newValue + getCommentReplacement(attribute); final RpslAttribute transformed = new RpslAttribute(attribute.getKey(), replacement); replacements.put(attribute, transformed); for (final Message attributeMessage : attributeMessages) { objectMessages.addMessage(transformed, attributeMessage); } } return new RpslObjectBuilder(object).replaceAttributes(replacements).get(); } @Autowired AttributeSanitizer(DateTimeProvider dateTimeProvider); CIString sanitizeKey(final RpslObject originalObject); RpslObject sanitize(final RpslObject object, final ObjectMessages objectMessages); } | AttributeSanitizer { public RpslObject sanitize(final RpslObject object, final ObjectMessages objectMessages) { final Map<RpslAttribute, RpslAttribute> replacements = Maps.newHashMap(); for (final RpslAttribute attribute : object.getAttributes()) { final AttributeType type = attribute.getType(); String newValue = null; final Sanitizer sanitizer = SANITIZER_MAP.get(type); if (sanitizer == null) { continue; } try { newValue = sanitizer.sanitize(attribute); } catch (IllegalArgumentException ignored) { LOGGER.debug("{}: {}", ignored.getClass().getName(), ignored.getMessage()); } if (newValue == null) { continue; } final List<Message> attributeMessages = Lists.newArrayList(); if (!sanitizer.silent() && !attribute.getCleanValue().toString().equals(newValue)) { attributeMessages.add(ValidationMessages.attributeValueConverted(attribute.getCleanValue(), newValue)); } if (keyAttributes.contains(type) && attribute.getValue().indexOf('\n') != -1) { attributeMessages.add(ValidationMessages.continuationLinesRemoved()); } if (keyAttributes.contains(type) && attribute.getValue().indexOf('#') != -1) { attributeMessages.add(ValidationMessages.remarksReformatted()); } final String replacement = newValue + getCommentReplacement(attribute); final RpslAttribute transformed = new RpslAttribute(attribute.getKey(), replacement); replacements.put(attribute, transformed); for (final Message attributeMessage : attributeMessages) { objectMessages.addMessage(transformed, attributeMessage); } } return new RpslObjectBuilder(object).replaceAttributes(replacements).get(); } @Autowired AttributeSanitizer(DateTimeProvider dateTimeProvider); CIString sanitizeKey(final RpslObject originalObject); RpslObject sanitize(final RpslObject object, final ObjectMessages objectMessages); } |
@Test public void check_not_domain() { when(update.getType()).thenReturn(ObjectType.INETNUM); subject.checkAll(updateRequest, updateContext); verifyZeroInteractions(dnsGateway); } | public void checkAll(final UpdateRequest updateRequest, final UpdateContext updateContext) { if (!dnsCheckEnabled) { return; } Set<DnsCheckRequest> dnsCheckRequestSet = Sets.newLinkedHashSet(); for (Update update : updateRequest.getUpdates()) { if (isDnsCheckRequired(update)) { dnsCheckRequestSet.add(createDnsCheckRequest(update)); } } if (dnsCheckRequestSet.isEmpty()) { return; } final Stopwatch stopwatch = Stopwatch.createStarted(); final Map<DnsCheckRequest, DnsCheckResponse> dnsCheckResponseMap = dnsGateway.performDnsChecks(dnsCheckRequestSet); loggerContext.log(new Message(Messages.Type.INFO, "Called dnsGateway with %d requests and processed in %s", dnsCheckRequestSet.size(), stopwatch.stop().toString())); for (Map.Entry<DnsCheckRequest, DnsCheckResponse> entry : dnsCheckResponseMap.entrySet()) { final DnsCheckRequest dnsCheckRequest = entry.getKey(); final DnsCheckResponse dnsCheckResponse = entry.getValue(); updateContext.addDnsCheckResponse(dnsCheckRequest, dnsCheckResponse); for (final Message message : dnsCheckResponse.getMessages()) { updateContext.addMessage(dnsCheckRequest.getUpdate(), message); } } } | DnsChecker { public void checkAll(final UpdateRequest updateRequest, final UpdateContext updateContext) { if (!dnsCheckEnabled) { return; } Set<DnsCheckRequest> dnsCheckRequestSet = Sets.newLinkedHashSet(); for (Update update : updateRequest.getUpdates()) { if (isDnsCheckRequired(update)) { dnsCheckRequestSet.add(createDnsCheckRequest(update)); } } if (dnsCheckRequestSet.isEmpty()) { return; } final Stopwatch stopwatch = Stopwatch.createStarted(); final Map<DnsCheckRequest, DnsCheckResponse> dnsCheckResponseMap = dnsGateway.performDnsChecks(dnsCheckRequestSet); loggerContext.log(new Message(Messages.Type.INFO, "Called dnsGateway with %d requests and processed in %s", dnsCheckRequestSet.size(), stopwatch.stop().toString())); for (Map.Entry<DnsCheckRequest, DnsCheckResponse> entry : dnsCheckResponseMap.entrySet()) { final DnsCheckRequest dnsCheckRequest = entry.getKey(); final DnsCheckResponse dnsCheckResponse = entry.getValue(); updateContext.addDnsCheckResponse(dnsCheckRequest, dnsCheckResponse); for (final Message message : dnsCheckResponse.getMessages()) { updateContext.addMessage(dnsCheckRequest.getUpdate(), message); } } } } | DnsChecker { public void checkAll(final UpdateRequest updateRequest, final UpdateContext updateContext) { if (!dnsCheckEnabled) { return; } Set<DnsCheckRequest> dnsCheckRequestSet = Sets.newLinkedHashSet(); for (Update update : updateRequest.getUpdates()) { if (isDnsCheckRequired(update)) { dnsCheckRequestSet.add(createDnsCheckRequest(update)); } } if (dnsCheckRequestSet.isEmpty()) { return; } final Stopwatch stopwatch = Stopwatch.createStarted(); final Map<DnsCheckRequest, DnsCheckResponse> dnsCheckResponseMap = dnsGateway.performDnsChecks(dnsCheckRequestSet); loggerContext.log(new Message(Messages.Type.INFO, "Called dnsGateway with %d requests and processed in %s", dnsCheckRequestSet.size(), stopwatch.stop().toString())); for (Map.Entry<DnsCheckRequest, DnsCheckResponse> entry : dnsCheckResponseMap.entrySet()) { final DnsCheckRequest dnsCheckRequest = entry.getKey(); final DnsCheckResponse dnsCheckResponse = entry.getValue(); updateContext.addDnsCheckResponse(dnsCheckRequest, dnsCheckResponse); for (final Message message : dnsCheckResponse.getMessages()) { updateContext.addMessage(dnsCheckRequest.getUpdate(), message); } } } @Autowired DnsChecker(final DnsGateway dnsGateway,
final LoggerContext loggerContext,
@Value("${whois.zonemaster.baseUrl:}") final String baseUrl); } | DnsChecker { public void checkAll(final UpdateRequest updateRequest, final UpdateContext updateContext) { if (!dnsCheckEnabled) { return; } Set<DnsCheckRequest> dnsCheckRequestSet = Sets.newLinkedHashSet(); for (Update update : updateRequest.getUpdates()) { if (isDnsCheckRequired(update)) { dnsCheckRequestSet.add(createDnsCheckRequest(update)); } } if (dnsCheckRequestSet.isEmpty()) { return; } final Stopwatch stopwatch = Stopwatch.createStarted(); final Map<DnsCheckRequest, DnsCheckResponse> dnsCheckResponseMap = dnsGateway.performDnsChecks(dnsCheckRequestSet); loggerContext.log(new Message(Messages.Type.INFO, "Called dnsGateway with %d requests and processed in %s", dnsCheckRequestSet.size(), stopwatch.stop().toString())); for (Map.Entry<DnsCheckRequest, DnsCheckResponse> entry : dnsCheckResponseMap.entrySet()) { final DnsCheckRequest dnsCheckRequest = entry.getKey(); final DnsCheckResponse dnsCheckResponse = entry.getValue(); updateContext.addDnsCheckResponse(dnsCheckRequest, dnsCheckResponse); for (final Message message : dnsCheckResponse.getMessages()) { updateContext.addMessage(dnsCheckRequest.getUpdate(), message); } } } @Autowired DnsChecker(final DnsGateway dnsGateway,
final LoggerContext loggerContext,
@Value("${whois.zonemaster.baseUrl:}") final String baseUrl); void checkAll(final UpdateRequest updateRequest, final UpdateContext updateContext); } | DnsChecker { public void checkAll(final UpdateRequest updateRequest, final UpdateContext updateContext) { if (!dnsCheckEnabled) { return; } Set<DnsCheckRequest> dnsCheckRequestSet = Sets.newLinkedHashSet(); for (Update update : updateRequest.getUpdates()) { if (isDnsCheckRequired(update)) { dnsCheckRequestSet.add(createDnsCheckRequest(update)); } } if (dnsCheckRequestSet.isEmpty()) { return; } final Stopwatch stopwatch = Stopwatch.createStarted(); final Map<DnsCheckRequest, DnsCheckResponse> dnsCheckResponseMap = dnsGateway.performDnsChecks(dnsCheckRequestSet); loggerContext.log(new Message(Messages.Type.INFO, "Called dnsGateway with %d requests and processed in %s", dnsCheckRequestSet.size(), stopwatch.stop().toString())); for (Map.Entry<DnsCheckRequest, DnsCheckResponse> entry : dnsCheckResponseMap.entrySet()) { final DnsCheckRequest dnsCheckRequest = entry.getKey(); final DnsCheckResponse dnsCheckResponse = entry.getValue(); updateContext.addDnsCheckResponse(dnsCheckRequest, dnsCheckResponse); for (final Message message : dnsCheckResponse.getMessages()) { updateContext.addMessage(dnsCheckRequest.getUpdate(), message); } } } @Autowired DnsChecker(final DnsGateway dnsGateway,
final LoggerContext loggerContext,
@Value("${whois.zonemaster.baseUrl:}") final String baseUrl); void checkAll(final UpdateRequest updateRequest, final UpdateContext updateContext); } |
@Test public void check_override() { when(update.isOverride()).thenReturn(true); subject.checkAll(updateRequest, updateContext); verifyZeroInteractions(dnsGateway); } | public void checkAll(final UpdateRequest updateRequest, final UpdateContext updateContext) { if (!dnsCheckEnabled) { return; } Set<DnsCheckRequest> dnsCheckRequestSet = Sets.newLinkedHashSet(); for (Update update : updateRequest.getUpdates()) { if (isDnsCheckRequired(update)) { dnsCheckRequestSet.add(createDnsCheckRequest(update)); } } if (dnsCheckRequestSet.isEmpty()) { return; } final Stopwatch stopwatch = Stopwatch.createStarted(); final Map<DnsCheckRequest, DnsCheckResponse> dnsCheckResponseMap = dnsGateway.performDnsChecks(dnsCheckRequestSet); loggerContext.log(new Message(Messages.Type.INFO, "Called dnsGateway with %d requests and processed in %s", dnsCheckRequestSet.size(), stopwatch.stop().toString())); for (Map.Entry<DnsCheckRequest, DnsCheckResponse> entry : dnsCheckResponseMap.entrySet()) { final DnsCheckRequest dnsCheckRequest = entry.getKey(); final DnsCheckResponse dnsCheckResponse = entry.getValue(); updateContext.addDnsCheckResponse(dnsCheckRequest, dnsCheckResponse); for (final Message message : dnsCheckResponse.getMessages()) { updateContext.addMessage(dnsCheckRequest.getUpdate(), message); } } } | DnsChecker { public void checkAll(final UpdateRequest updateRequest, final UpdateContext updateContext) { if (!dnsCheckEnabled) { return; } Set<DnsCheckRequest> dnsCheckRequestSet = Sets.newLinkedHashSet(); for (Update update : updateRequest.getUpdates()) { if (isDnsCheckRequired(update)) { dnsCheckRequestSet.add(createDnsCheckRequest(update)); } } if (dnsCheckRequestSet.isEmpty()) { return; } final Stopwatch stopwatch = Stopwatch.createStarted(); final Map<DnsCheckRequest, DnsCheckResponse> dnsCheckResponseMap = dnsGateway.performDnsChecks(dnsCheckRequestSet); loggerContext.log(new Message(Messages.Type.INFO, "Called dnsGateway with %d requests and processed in %s", dnsCheckRequestSet.size(), stopwatch.stop().toString())); for (Map.Entry<DnsCheckRequest, DnsCheckResponse> entry : dnsCheckResponseMap.entrySet()) { final DnsCheckRequest dnsCheckRequest = entry.getKey(); final DnsCheckResponse dnsCheckResponse = entry.getValue(); updateContext.addDnsCheckResponse(dnsCheckRequest, dnsCheckResponse); for (final Message message : dnsCheckResponse.getMessages()) { updateContext.addMessage(dnsCheckRequest.getUpdate(), message); } } } } | DnsChecker { public void checkAll(final UpdateRequest updateRequest, final UpdateContext updateContext) { if (!dnsCheckEnabled) { return; } Set<DnsCheckRequest> dnsCheckRequestSet = Sets.newLinkedHashSet(); for (Update update : updateRequest.getUpdates()) { if (isDnsCheckRequired(update)) { dnsCheckRequestSet.add(createDnsCheckRequest(update)); } } if (dnsCheckRequestSet.isEmpty()) { return; } final Stopwatch stopwatch = Stopwatch.createStarted(); final Map<DnsCheckRequest, DnsCheckResponse> dnsCheckResponseMap = dnsGateway.performDnsChecks(dnsCheckRequestSet); loggerContext.log(new Message(Messages.Type.INFO, "Called dnsGateway with %d requests and processed in %s", dnsCheckRequestSet.size(), stopwatch.stop().toString())); for (Map.Entry<DnsCheckRequest, DnsCheckResponse> entry : dnsCheckResponseMap.entrySet()) { final DnsCheckRequest dnsCheckRequest = entry.getKey(); final DnsCheckResponse dnsCheckResponse = entry.getValue(); updateContext.addDnsCheckResponse(dnsCheckRequest, dnsCheckResponse); for (final Message message : dnsCheckResponse.getMessages()) { updateContext.addMessage(dnsCheckRequest.getUpdate(), message); } } } @Autowired DnsChecker(final DnsGateway dnsGateway,
final LoggerContext loggerContext,
@Value("${whois.zonemaster.baseUrl:}") final String baseUrl); } | DnsChecker { public void checkAll(final UpdateRequest updateRequest, final UpdateContext updateContext) { if (!dnsCheckEnabled) { return; } Set<DnsCheckRequest> dnsCheckRequestSet = Sets.newLinkedHashSet(); for (Update update : updateRequest.getUpdates()) { if (isDnsCheckRequired(update)) { dnsCheckRequestSet.add(createDnsCheckRequest(update)); } } if (dnsCheckRequestSet.isEmpty()) { return; } final Stopwatch stopwatch = Stopwatch.createStarted(); final Map<DnsCheckRequest, DnsCheckResponse> dnsCheckResponseMap = dnsGateway.performDnsChecks(dnsCheckRequestSet); loggerContext.log(new Message(Messages.Type.INFO, "Called dnsGateway with %d requests and processed in %s", dnsCheckRequestSet.size(), stopwatch.stop().toString())); for (Map.Entry<DnsCheckRequest, DnsCheckResponse> entry : dnsCheckResponseMap.entrySet()) { final DnsCheckRequest dnsCheckRequest = entry.getKey(); final DnsCheckResponse dnsCheckResponse = entry.getValue(); updateContext.addDnsCheckResponse(dnsCheckRequest, dnsCheckResponse); for (final Message message : dnsCheckResponse.getMessages()) { updateContext.addMessage(dnsCheckRequest.getUpdate(), message); } } } @Autowired DnsChecker(final DnsGateway dnsGateway,
final LoggerContext loggerContext,
@Value("${whois.zonemaster.baseUrl:}") final String baseUrl); void checkAll(final UpdateRequest updateRequest, final UpdateContext updateContext); } | DnsChecker { public void checkAll(final UpdateRequest updateRequest, final UpdateContext updateContext) { if (!dnsCheckEnabled) { return; } Set<DnsCheckRequest> dnsCheckRequestSet = Sets.newLinkedHashSet(); for (Update update : updateRequest.getUpdates()) { if (isDnsCheckRequired(update)) { dnsCheckRequestSet.add(createDnsCheckRequest(update)); } } if (dnsCheckRequestSet.isEmpty()) { return; } final Stopwatch stopwatch = Stopwatch.createStarted(); final Map<DnsCheckRequest, DnsCheckResponse> dnsCheckResponseMap = dnsGateway.performDnsChecks(dnsCheckRequestSet); loggerContext.log(new Message(Messages.Type.INFO, "Called dnsGateway with %d requests and processed in %s", dnsCheckRequestSet.size(), stopwatch.stop().toString())); for (Map.Entry<DnsCheckRequest, DnsCheckResponse> entry : dnsCheckResponseMap.entrySet()) { final DnsCheckRequest dnsCheckRequest = entry.getKey(); final DnsCheckResponse dnsCheckResponse = entry.getValue(); updateContext.addDnsCheckResponse(dnsCheckRequest, dnsCheckResponse); for (final Message message : dnsCheckResponse.getMessages()) { updateContext.addMessage(dnsCheckRequest.getUpdate(), message); } } } @Autowired DnsChecker(final DnsGateway dnsGateway,
final LoggerContext loggerContext,
@Value("${whois.zonemaster.baseUrl:}") final String baseUrl); void checkAll(final UpdateRequest updateRequest, final UpdateContext updateContext); } |
@Test public void checkAll() { when(update.getOperation()).thenReturn(Operation.UNSPECIFIED); when(update.getType()).thenReturn(ObjectType.DOMAIN); when(update.isOverride()).thenReturn(false); when(update.getSubmittedObject()).thenReturn(RpslObject.parse("" + "domain: 36.84.80.in-addr.arpa\n" + "descr: Description\n" + "descr: Description\n" + "admin-c: DUMY-RIPE\n" + "tech-c: DUMY-RIPE\n" + "zone-c: DUMY-RIPE\n" + "notify: [email protected]\n" + "nserver: ns1.test.se 80.84.32.12\n" + "nserver: ns2.test.se 80.84.32.10\n" + "source: RIPE\n" + "mnt-by: TEST-MNT" )); List<Update> updateList = Lists.newArrayList(); Set<DnsCheckRequest> dnsCheckRequests = Sets.newLinkedHashSet(); Map<DnsCheckRequest, DnsCheckResponse> dnsResults = Maps.newHashMap(); DnsCheckRequest dnsCheckRequest = new DnsCheckRequest(update, "36.84.80.in-addr.arpa", "ns1.test.se/80.84.32.12 ns2.test.se/80.84.32.10"); dnsCheckRequests.add(dnsCheckRequest); DnsCheckResponse dnsCheckResponse = new DnsCheckResponse(); updateList.add(update); dnsResults.put(dnsCheckRequest, dnsCheckResponse); when(updateRequest.getUpdates()).thenReturn(updateList); when(updateContext.getCachedDnsCheckResponse(any(DnsCheckRequest.class))).thenReturn(null); when(dnsGateway.performDnsChecks(dnsCheckRequests)).thenReturn(dnsResults); subject.checkAll(updateRequest, updateContext); verify(dnsGateway).performDnsChecks(dnsCheckRequests); assertThat(dnsCheckRequest.getDomain(), is("36.84.80.in-addr.arpa")); assertThat(dnsCheckRequest.getGlue(), is("ns1.test.se/80.84.32.12 ns2.test.se/80.84.32.10")); verify(updateContext, never()).addMessage(any(UpdateContainer.class), any(Message.class)); } | public void checkAll(final UpdateRequest updateRequest, final UpdateContext updateContext) { if (!dnsCheckEnabled) { return; } Set<DnsCheckRequest> dnsCheckRequestSet = Sets.newLinkedHashSet(); for (Update update : updateRequest.getUpdates()) { if (isDnsCheckRequired(update)) { dnsCheckRequestSet.add(createDnsCheckRequest(update)); } } if (dnsCheckRequestSet.isEmpty()) { return; } final Stopwatch stopwatch = Stopwatch.createStarted(); final Map<DnsCheckRequest, DnsCheckResponse> dnsCheckResponseMap = dnsGateway.performDnsChecks(dnsCheckRequestSet); loggerContext.log(new Message(Messages.Type.INFO, "Called dnsGateway with %d requests and processed in %s", dnsCheckRequestSet.size(), stopwatch.stop().toString())); for (Map.Entry<DnsCheckRequest, DnsCheckResponse> entry : dnsCheckResponseMap.entrySet()) { final DnsCheckRequest dnsCheckRequest = entry.getKey(); final DnsCheckResponse dnsCheckResponse = entry.getValue(); updateContext.addDnsCheckResponse(dnsCheckRequest, dnsCheckResponse); for (final Message message : dnsCheckResponse.getMessages()) { updateContext.addMessage(dnsCheckRequest.getUpdate(), message); } } } | DnsChecker { public void checkAll(final UpdateRequest updateRequest, final UpdateContext updateContext) { if (!dnsCheckEnabled) { return; } Set<DnsCheckRequest> dnsCheckRequestSet = Sets.newLinkedHashSet(); for (Update update : updateRequest.getUpdates()) { if (isDnsCheckRequired(update)) { dnsCheckRequestSet.add(createDnsCheckRequest(update)); } } if (dnsCheckRequestSet.isEmpty()) { return; } final Stopwatch stopwatch = Stopwatch.createStarted(); final Map<DnsCheckRequest, DnsCheckResponse> dnsCheckResponseMap = dnsGateway.performDnsChecks(dnsCheckRequestSet); loggerContext.log(new Message(Messages.Type.INFO, "Called dnsGateway with %d requests and processed in %s", dnsCheckRequestSet.size(), stopwatch.stop().toString())); for (Map.Entry<DnsCheckRequest, DnsCheckResponse> entry : dnsCheckResponseMap.entrySet()) { final DnsCheckRequest dnsCheckRequest = entry.getKey(); final DnsCheckResponse dnsCheckResponse = entry.getValue(); updateContext.addDnsCheckResponse(dnsCheckRequest, dnsCheckResponse); for (final Message message : dnsCheckResponse.getMessages()) { updateContext.addMessage(dnsCheckRequest.getUpdate(), message); } } } } | DnsChecker { public void checkAll(final UpdateRequest updateRequest, final UpdateContext updateContext) { if (!dnsCheckEnabled) { return; } Set<DnsCheckRequest> dnsCheckRequestSet = Sets.newLinkedHashSet(); for (Update update : updateRequest.getUpdates()) { if (isDnsCheckRequired(update)) { dnsCheckRequestSet.add(createDnsCheckRequest(update)); } } if (dnsCheckRequestSet.isEmpty()) { return; } final Stopwatch stopwatch = Stopwatch.createStarted(); final Map<DnsCheckRequest, DnsCheckResponse> dnsCheckResponseMap = dnsGateway.performDnsChecks(dnsCheckRequestSet); loggerContext.log(new Message(Messages.Type.INFO, "Called dnsGateway with %d requests and processed in %s", dnsCheckRequestSet.size(), stopwatch.stop().toString())); for (Map.Entry<DnsCheckRequest, DnsCheckResponse> entry : dnsCheckResponseMap.entrySet()) { final DnsCheckRequest dnsCheckRequest = entry.getKey(); final DnsCheckResponse dnsCheckResponse = entry.getValue(); updateContext.addDnsCheckResponse(dnsCheckRequest, dnsCheckResponse); for (final Message message : dnsCheckResponse.getMessages()) { updateContext.addMessage(dnsCheckRequest.getUpdate(), message); } } } @Autowired DnsChecker(final DnsGateway dnsGateway,
final LoggerContext loggerContext,
@Value("${whois.zonemaster.baseUrl:}") final String baseUrl); } | DnsChecker { public void checkAll(final UpdateRequest updateRequest, final UpdateContext updateContext) { if (!dnsCheckEnabled) { return; } Set<DnsCheckRequest> dnsCheckRequestSet = Sets.newLinkedHashSet(); for (Update update : updateRequest.getUpdates()) { if (isDnsCheckRequired(update)) { dnsCheckRequestSet.add(createDnsCheckRequest(update)); } } if (dnsCheckRequestSet.isEmpty()) { return; } final Stopwatch stopwatch = Stopwatch.createStarted(); final Map<DnsCheckRequest, DnsCheckResponse> dnsCheckResponseMap = dnsGateway.performDnsChecks(dnsCheckRequestSet); loggerContext.log(new Message(Messages.Type.INFO, "Called dnsGateway with %d requests and processed in %s", dnsCheckRequestSet.size(), stopwatch.stop().toString())); for (Map.Entry<DnsCheckRequest, DnsCheckResponse> entry : dnsCheckResponseMap.entrySet()) { final DnsCheckRequest dnsCheckRequest = entry.getKey(); final DnsCheckResponse dnsCheckResponse = entry.getValue(); updateContext.addDnsCheckResponse(dnsCheckRequest, dnsCheckResponse); for (final Message message : dnsCheckResponse.getMessages()) { updateContext.addMessage(dnsCheckRequest.getUpdate(), message); } } } @Autowired DnsChecker(final DnsGateway dnsGateway,
final LoggerContext loggerContext,
@Value("${whois.zonemaster.baseUrl:}") final String baseUrl); void checkAll(final UpdateRequest updateRequest, final UpdateContext updateContext); } | DnsChecker { public void checkAll(final UpdateRequest updateRequest, final UpdateContext updateContext) { if (!dnsCheckEnabled) { return; } Set<DnsCheckRequest> dnsCheckRequestSet = Sets.newLinkedHashSet(); for (Update update : updateRequest.getUpdates()) { if (isDnsCheckRequired(update)) { dnsCheckRequestSet.add(createDnsCheckRequest(update)); } } if (dnsCheckRequestSet.isEmpty()) { return; } final Stopwatch stopwatch = Stopwatch.createStarted(); final Map<DnsCheckRequest, DnsCheckResponse> dnsCheckResponseMap = dnsGateway.performDnsChecks(dnsCheckRequestSet); loggerContext.log(new Message(Messages.Type.INFO, "Called dnsGateway with %d requests and processed in %s", dnsCheckRequestSet.size(), stopwatch.stop().toString())); for (Map.Entry<DnsCheckRequest, DnsCheckResponse> entry : dnsCheckResponseMap.entrySet()) { final DnsCheckRequest dnsCheckRequest = entry.getKey(); final DnsCheckResponse dnsCheckResponse = entry.getValue(); updateContext.addDnsCheckResponse(dnsCheckRequest, dnsCheckResponse); for (final Message message : dnsCheckResponse.getMessages()) { updateContext.addMessage(dnsCheckRequest.getUpdate(), message); } } } @Autowired DnsChecker(final DnsGateway dnsGateway,
final LoggerContext loggerContext,
@Value("${whois.zonemaster.baseUrl:}") final String baseUrl); void checkAll(final UpdateRequest updateRequest, final UpdateContext updateContext); } |
@Test public void check_errors() { when(update.getOperation()).thenReturn(Operation.UNSPECIFIED); when(update.getType()).thenReturn(ObjectType.DOMAIN); when(update.isOverride()).thenReturn(false); when(update.getSubmittedObject()).thenReturn(RpslObject.parse("" + "domain: 36.84.80.in-addr.arpa\n" )); when(dnsGateway.performDnsChecks(any(Set.class))).thenAnswer((Answer<Map<DnsCheckRequest, DnsCheckResponse>>) invocation -> { DnsCheckRequest arg = (DnsCheckRequest)(((Set)invocation.getArguments()[0]).iterator().next()); return Collections.singletonMap(arg, new DnsCheckResponse(UpdateMessages.dnsCheckTimeout())); }); subject.checkAll(updateRequest, updateContext); verify(updateContext).addMessage(update, UpdateMessages.dnsCheckTimeout()); } | public void checkAll(final UpdateRequest updateRequest, final UpdateContext updateContext) { if (!dnsCheckEnabled) { return; } Set<DnsCheckRequest> dnsCheckRequestSet = Sets.newLinkedHashSet(); for (Update update : updateRequest.getUpdates()) { if (isDnsCheckRequired(update)) { dnsCheckRequestSet.add(createDnsCheckRequest(update)); } } if (dnsCheckRequestSet.isEmpty()) { return; } final Stopwatch stopwatch = Stopwatch.createStarted(); final Map<DnsCheckRequest, DnsCheckResponse> dnsCheckResponseMap = dnsGateway.performDnsChecks(dnsCheckRequestSet); loggerContext.log(new Message(Messages.Type.INFO, "Called dnsGateway with %d requests and processed in %s", dnsCheckRequestSet.size(), stopwatch.stop().toString())); for (Map.Entry<DnsCheckRequest, DnsCheckResponse> entry : dnsCheckResponseMap.entrySet()) { final DnsCheckRequest dnsCheckRequest = entry.getKey(); final DnsCheckResponse dnsCheckResponse = entry.getValue(); updateContext.addDnsCheckResponse(dnsCheckRequest, dnsCheckResponse); for (final Message message : dnsCheckResponse.getMessages()) { updateContext.addMessage(dnsCheckRequest.getUpdate(), message); } } } | DnsChecker { public void checkAll(final UpdateRequest updateRequest, final UpdateContext updateContext) { if (!dnsCheckEnabled) { return; } Set<DnsCheckRequest> dnsCheckRequestSet = Sets.newLinkedHashSet(); for (Update update : updateRequest.getUpdates()) { if (isDnsCheckRequired(update)) { dnsCheckRequestSet.add(createDnsCheckRequest(update)); } } if (dnsCheckRequestSet.isEmpty()) { return; } final Stopwatch stopwatch = Stopwatch.createStarted(); final Map<DnsCheckRequest, DnsCheckResponse> dnsCheckResponseMap = dnsGateway.performDnsChecks(dnsCheckRequestSet); loggerContext.log(new Message(Messages.Type.INFO, "Called dnsGateway with %d requests and processed in %s", dnsCheckRequestSet.size(), stopwatch.stop().toString())); for (Map.Entry<DnsCheckRequest, DnsCheckResponse> entry : dnsCheckResponseMap.entrySet()) { final DnsCheckRequest dnsCheckRequest = entry.getKey(); final DnsCheckResponse dnsCheckResponse = entry.getValue(); updateContext.addDnsCheckResponse(dnsCheckRequest, dnsCheckResponse); for (final Message message : dnsCheckResponse.getMessages()) { updateContext.addMessage(dnsCheckRequest.getUpdate(), message); } } } } | DnsChecker { public void checkAll(final UpdateRequest updateRequest, final UpdateContext updateContext) { if (!dnsCheckEnabled) { return; } Set<DnsCheckRequest> dnsCheckRequestSet = Sets.newLinkedHashSet(); for (Update update : updateRequest.getUpdates()) { if (isDnsCheckRequired(update)) { dnsCheckRequestSet.add(createDnsCheckRequest(update)); } } if (dnsCheckRequestSet.isEmpty()) { return; } final Stopwatch stopwatch = Stopwatch.createStarted(); final Map<DnsCheckRequest, DnsCheckResponse> dnsCheckResponseMap = dnsGateway.performDnsChecks(dnsCheckRequestSet); loggerContext.log(new Message(Messages.Type.INFO, "Called dnsGateway with %d requests and processed in %s", dnsCheckRequestSet.size(), stopwatch.stop().toString())); for (Map.Entry<DnsCheckRequest, DnsCheckResponse> entry : dnsCheckResponseMap.entrySet()) { final DnsCheckRequest dnsCheckRequest = entry.getKey(); final DnsCheckResponse dnsCheckResponse = entry.getValue(); updateContext.addDnsCheckResponse(dnsCheckRequest, dnsCheckResponse); for (final Message message : dnsCheckResponse.getMessages()) { updateContext.addMessage(dnsCheckRequest.getUpdate(), message); } } } @Autowired DnsChecker(final DnsGateway dnsGateway,
final LoggerContext loggerContext,
@Value("${whois.zonemaster.baseUrl:}") final String baseUrl); } | DnsChecker { public void checkAll(final UpdateRequest updateRequest, final UpdateContext updateContext) { if (!dnsCheckEnabled) { return; } Set<DnsCheckRequest> dnsCheckRequestSet = Sets.newLinkedHashSet(); for (Update update : updateRequest.getUpdates()) { if (isDnsCheckRequired(update)) { dnsCheckRequestSet.add(createDnsCheckRequest(update)); } } if (dnsCheckRequestSet.isEmpty()) { return; } final Stopwatch stopwatch = Stopwatch.createStarted(); final Map<DnsCheckRequest, DnsCheckResponse> dnsCheckResponseMap = dnsGateway.performDnsChecks(dnsCheckRequestSet); loggerContext.log(new Message(Messages.Type.INFO, "Called dnsGateway with %d requests and processed in %s", dnsCheckRequestSet.size(), stopwatch.stop().toString())); for (Map.Entry<DnsCheckRequest, DnsCheckResponse> entry : dnsCheckResponseMap.entrySet()) { final DnsCheckRequest dnsCheckRequest = entry.getKey(); final DnsCheckResponse dnsCheckResponse = entry.getValue(); updateContext.addDnsCheckResponse(dnsCheckRequest, dnsCheckResponse); for (final Message message : dnsCheckResponse.getMessages()) { updateContext.addMessage(dnsCheckRequest.getUpdate(), message); } } } @Autowired DnsChecker(final DnsGateway dnsGateway,
final LoggerContext loggerContext,
@Value("${whois.zonemaster.baseUrl:}") final String baseUrl); void checkAll(final UpdateRequest updateRequest, final UpdateContext updateContext); } | DnsChecker { public void checkAll(final UpdateRequest updateRequest, final UpdateContext updateContext) { if (!dnsCheckEnabled) { return; } Set<DnsCheckRequest> dnsCheckRequestSet = Sets.newLinkedHashSet(); for (Update update : updateRequest.getUpdates()) { if (isDnsCheckRequired(update)) { dnsCheckRequestSet.add(createDnsCheckRequest(update)); } } if (dnsCheckRequestSet.isEmpty()) { return; } final Stopwatch stopwatch = Stopwatch.createStarted(); final Map<DnsCheckRequest, DnsCheckResponse> dnsCheckResponseMap = dnsGateway.performDnsChecks(dnsCheckRequestSet); loggerContext.log(new Message(Messages.Type.INFO, "Called dnsGateway with %d requests and processed in %s", dnsCheckRequestSet.size(), stopwatch.stop().toString())); for (Map.Entry<DnsCheckRequest, DnsCheckResponse> entry : dnsCheckResponseMap.entrySet()) { final DnsCheckRequest dnsCheckRequest = entry.getKey(); final DnsCheckResponse dnsCheckResponse = entry.getValue(); updateContext.addDnsCheckResponse(dnsCheckRequest, dnsCheckResponse); for (final Message message : dnsCheckResponse.getMessages()) { updateContext.addMessage(dnsCheckRequest.getUpdate(), message); } } } @Autowired DnsChecker(final DnsGateway dnsGateway,
final LoggerContext loggerContext,
@Value("${whois.zonemaster.baseUrl:}") final String baseUrl); void checkAll(final UpdateRequest updateRequest, final UpdateContext updateContext); } |
@Test public void check_disabled() { subject = new DnsChecker(dnsGateway, loggerContext, ""); when(update.getOperation()).thenReturn(Operation.UNSPECIFIED); when(update.getType()).thenReturn(ObjectType.DOMAIN); when(update.isOverride()).thenReturn(false); when(update.getSubmittedObject()).thenReturn(RpslObject.parse("" + "domain: 36.84.80.in-addr.arpa\n" )); subject.checkAll(updateRequest, updateContext); verifyZeroInteractions(dnsGateway); } | public void checkAll(final UpdateRequest updateRequest, final UpdateContext updateContext) { if (!dnsCheckEnabled) { return; } Set<DnsCheckRequest> dnsCheckRequestSet = Sets.newLinkedHashSet(); for (Update update : updateRequest.getUpdates()) { if (isDnsCheckRequired(update)) { dnsCheckRequestSet.add(createDnsCheckRequest(update)); } } if (dnsCheckRequestSet.isEmpty()) { return; } final Stopwatch stopwatch = Stopwatch.createStarted(); final Map<DnsCheckRequest, DnsCheckResponse> dnsCheckResponseMap = dnsGateway.performDnsChecks(dnsCheckRequestSet); loggerContext.log(new Message(Messages.Type.INFO, "Called dnsGateway with %d requests and processed in %s", dnsCheckRequestSet.size(), stopwatch.stop().toString())); for (Map.Entry<DnsCheckRequest, DnsCheckResponse> entry : dnsCheckResponseMap.entrySet()) { final DnsCheckRequest dnsCheckRequest = entry.getKey(); final DnsCheckResponse dnsCheckResponse = entry.getValue(); updateContext.addDnsCheckResponse(dnsCheckRequest, dnsCheckResponse); for (final Message message : dnsCheckResponse.getMessages()) { updateContext.addMessage(dnsCheckRequest.getUpdate(), message); } } } | DnsChecker { public void checkAll(final UpdateRequest updateRequest, final UpdateContext updateContext) { if (!dnsCheckEnabled) { return; } Set<DnsCheckRequest> dnsCheckRequestSet = Sets.newLinkedHashSet(); for (Update update : updateRequest.getUpdates()) { if (isDnsCheckRequired(update)) { dnsCheckRequestSet.add(createDnsCheckRequest(update)); } } if (dnsCheckRequestSet.isEmpty()) { return; } final Stopwatch stopwatch = Stopwatch.createStarted(); final Map<DnsCheckRequest, DnsCheckResponse> dnsCheckResponseMap = dnsGateway.performDnsChecks(dnsCheckRequestSet); loggerContext.log(new Message(Messages.Type.INFO, "Called dnsGateway with %d requests and processed in %s", dnsCheckRequestSet.size(), stopwatch.stop().toString())); for (Map.Entry<DnsCheckRequest, DnsCheckResponse> entry : dnsCheckResponseMap.entrySet()) { final DnsCheckRequest dnsCheckRequest = entry.getKey(); final DnsCheckResponse dnsCheckResponse = entry.getValue(); updateContext.addDnsCheckResponse(dnsCheckRequest, dnsCheckResponse); for (final Message message : dnsCheckResponse.getMessages()) { updateContext.addMessage(dnsCheckRequest.getUpdate(), message); } } } } | DnsChecker { public void checkAll(final UpdateRequest updateRequest, final UpdateContext updateContext) { if (!dnsCheckEnabled) { return; } Set<DnsCheckRequest> dnsCheckRequestSet = Sets.newLinkedHashSet(); for (Update update : updateRequest.getUpdates()) { if (isDnsCheckRequired(update)) { dnsCheckRequestSet.add(createDnsCheckRequest(update)); } } if (dnsCheckRequestSet.isEmpty()) { return; } final Stopwatch stopwatch = Stopwatch.createStarted(); final Map<DnsCheckRequest, DnsCheckResponse> dnsCheckResponseMap = dnsGateway.performDnsChecks(dnsCheckRequestSet); loggerContext.log(new Message(Messages.Type.INFO, "Called dnsGateway with %d requests and processed in %s", dnsCheckRequestSet.size(), stopwatch.stop().toString())); for (Map.Entry<DnsCheckRequest, DnsCheckResponse> entry : dnsCheckResponseMap.entrySet()) { final DnsCheckRequest dnsCheckRequest = entry.getKey(); final DnsCheckResponse dnsCheckResponse = entry.getValue(); updateContext.addDnsCheckResponse(dnsCheckRequest, dnsCheckResponse); for (final Message message : dnsCheckResponse.getMessages()) { updateContext.addMessage(dnsCheckRequest.getUpdate(), message); } } } @Autowired DnsChecker(final DnsGateway dnsGateway,
final LoggerContext loggerContext,
@Value("${whois.zonemaster.baseUrl:}") final String baseUrl); } | DnsChecker { public void checkAll(final UpdateRequest updateRequest, final UpdateContext updateContext) { if (!dnsCheckEnabled) { return; } Set<DnsCheckRequest> dnsCheckRequestSet = Sets.newLinkedHashSet(); for (Update update : updateRequest.getUpdates()) { if (isDnsCheckRequired(update)) { dnsCheckRequestSet.add(createDnsCheckRequest(update)); } } if (dnsCheckRequestSet.isEmpty()) { return; } final Stopwatch stopwatch = Stopwatch.createStarted(); final Map<DnsCheckRequest, DnsCheckResponse> dnsCheckResponseMap = dnsGateway.performDnsChecks(dnsCheckRequestSet); loggerContext.log(new Message(Messages.Type.INFO, "Called dnsGateway with %d requests and processed in %s", dnsCheckRequestSet.size(), stopwatch.stop().toString())); for (Map.Entry<DnsCheckRequest, DnsCheckResponse> entry : dnsCheckResponseMap.entrySet()) { final DnsCheckRequest dnsCheckRequest = entry.getKey(); final DnsCheckResponse dnsCheckResponse = entry.getValue(); updateContext.addDnsCheckResponse(dnsCheckRequest, dnsCheckResponse); for (final Message message : dnsCheckResponse.getMessages()) { updateContext.addMessage(dnsCheckRequest.getUpdate(), message); } } } @Autowired DnsChecker(final DnsGateway dnsGateway,
final LoggerContext loggerContext,
@Value("${whois.zonemaster.baseUrl:}") final String baseUrl); void checkAll(final UpdateRequest updateRequest, final UpdateContext updateContext); } | DnsChecker { public void checkAll(final UpdateRequest updateRequest, final UpdateContext updateContext) { if (!dnsCheckEnabled) { return; } Set<DnsCheckRequest> dnsCheckRequestSet = Sets.newLinkedHashSet(); for (Update update : updateRequest.getUpdates()) { if (isDnsCheckRequired(update)) { dnsCheckRequestSet.add(createDnsCheckRequest(update)); } } if (dnsCheckRequestSet.isEmpty()) { return; } final Stopwatch stopwatch = Stopwatch.createStarted(); final Map<DnsCheckRequest, DnsCheckResponse> dnsCheckResponseMap = dnsGateway.performDnsChecks(dnsCheckRequestSet); loggerContext.log(new Message(Messages.Type.INFO, "Called dnsGateway with %d requests and processed in %s", dnsCheckRequestSet.size(), stopwatch.stop().toString())); for (Map.Entry<DnsCheckRequest, DnsCheckResponse> entry : dnsCheckResponseMap.entrySet()) { final DnsCheckRequest dnsCheckRequest = entry.getKey(); final DnsCheckResponse dnsCheckResponse = entry.getValue(); updateContext.addDnsCheckResponse(dnsCheckRequest, dnsCheckResponse); for (final Message message : dnsCheckResponse.getMessages()) { updateContext.addMessage(dnsCheckRequest.getUpdate(), message); } } } @Autowired DnsChecker(final DnsGateway dnsGateway,
final LoggerContext loggerContext,
@Value("${whois.zonemaster.baseUrl:}") final String baseUrl); void checkAll(final UpdateRequest updateRequest, final UpdateContext updateContext); } |
@Test public void supports_autnum_create() { when(update.getAction()).thenReturn(Action.CREATE); when(update.getType()).thenReturn(ObjectType.AUT_NUM); final boolean supported = subject.supports(update); assertThat(supported, is(true)); } | @Override public boolean supports(final PreparedUpdate update) { return update.getType().equals(ObjectType.AUT_NUM) && update.getAction().equals(Action.CREATE); } | AutnumAuthentication extends AuthenticationStrategyBase { @Override public boolean supports(final PreparedUpdate update) { return update.getType().equals(ObjectType.AUT_NUM) && update.getAction().equals(Action.CREATE); } } | AutnumAuthentication extends AuthenticationStrategyBase { @Override public boolean supports(final PreparedUpdate update) { return update.getType().equals(ObjectType.AUT_NUM) && update.getAction().equals(Action.CREATE); } @Autowired AutnumAuthentication(final RpslObjectDao objectDao, final AuthenticationModule authenticationModule); } | AutnumAuthentication extends AuthenticationStrategyBase { @Override public boolean supports(final PreparedUpdate update) { return update.getType().equals(ObjectType.AUT_NUM) && update.getAction().equals(Action.CREATE); } @Autowired AutnumAuthentication(final RpslObjectDao objectDao, final AuthenticationModule authenticationModule); @Override boolean supports(final PreparedUpdate update); @Override List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext); } | AutnumAuthentication extends AuthenticationStrategyBase { @Override public boolean supports(final PreparedUpdate update) { return update.getType().equals(ObjectType.AUT_NUM) && update.getAction().equals(Action.CREATE); } @Autowired AutnumAuthentication(final RpslObjectDao objectDao, final AuthenticationModule authenticationModule); @Override boolean supports(final PreparedUpdate update); @Override List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext); } |
@Test public void supports_other_than_autnum_create() { for (final ObjectType objectType : ObjectType.values()) { if (ObjectType.AUT_NUM.equals(objectType)) { continue; } when(update.getAction()).thenReturn(Action.CREATE); when(update.getType()).thenReturn(ObjectType.AS_BLOCK); final boolean supported = subject.supports(update); assertThat(supported, is(false)); reset(update); } } | @Override public boolean supports(final PreparedUpdate update) { return update.getType().equals(ObjectType.AUT_NUM) && update.getAction().equals(Action.CREATE); } | AutnumAuthentication extends AuthenticationStrategyBase { @Override public boolean supports(final PreparedUpdate update) { return update.getType().equals(ObjectType.AUT_NUM) && update.getAction().equals(Action.CREATE); } } | AutnumAuthentication extends AuthenticationStrategyBase { @Override public boolean supports(final PreparedUpdate update) { return update.getType().equals(ObjectType.AUT_NUM) && update.getAction().equals(Action.CREATE); } @Autowired AutnumAuthentication(final RpslObjectDao objectDao, final AuthenticationModule authenticationModule); } | AutnumAuthentication extends AuthenticationStrategyBase { @Override public boolean supports(final PreparedUpdate update) { return update.getType().equals(ObjectType.AUT_NUM) && update.getAction().equals(Action.CREATE); } @Autowired AutnumAuthentication(final RpslObjectDao objectDao, final AuthenticationModule authenticationModule); @Override boolean supports(final PreparedUpdate update); @Override List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext); } | AutnumAuthentication extends AuthenticationStrategyBase { @Override public boolean supports(final PreparedUpdate update) { return update.getType().equals(ObjectType.AUT_NUM) && update.getAction().equals(Action.CREATE); } @Autowired AutnumAuthentication(final RpslObjectDao objectDao, final AuthenticationModule authenticationModule); @Override boolean supports(final PreparedUpdate update); @Override List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext); } |
@Test public void supports_autnum_modify() { when(update.getAction()).thenReturn(Action.MODIFY); when(update.getType()).thenReturn(ObjectType.AUT_NUM); final boolean supported = subject.supports(update); assertThat(supported, is(false)); } | @Override public boolean supports(final PreparedUpdate update) { return update.getType().equals(ObjectType.AUT_NUM) && update.getAction().equals(Action.CREATE); } | AutnumAuthentication extends AuthenticationStrategyBase { @Override public boolean supports(final PreparedUpdate update) { return update.getType().equals(ObjectType.AUT_NUM) && update.getAction().equals(Action.CREATE); } } | AutnumAuthentication extends AuthenticationStrategyBase { @Override public boolean supports(final PreparedUpdate update) { return update.getType().equals(ObjectType.AUT_NUM) && update.getAction().equals(Action.CREATE); } @Autowired AutnumAuthentication(final RpslObjectDao objectDao, final AuthenticationModule authenticationModule); } | AutnumAuthentication extends AuthenticationStrategyBase { @Override public boolean supports(final PreparedUpdate update) { return update.getType().equals(ObjectType.AUT_NUM) && update.getAction().equals(Action.CREATE); } @Autowired AutnumAuthentication(final RpslObjectDao objectDao, final AuthenticationModule authenticationModule); @Override boolean supports(final PreparedUpdate update); @Override List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext); } | AutnumAuthentication extends AuthenticationStrategyBase { @Override public boolean supports(final PreparedUpdate update) { return update.getType().equals(ObjectType.AUT_NUM) && update.getAction().equals(Action.CREATE); } @Autowired AutnumAuthentication(final RpslObjectDao objectDao, final AuthenticationModule authenticationModule); @Override boolean supports(final PreparedUpdate update); @Override List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext); } |
@Test public void supports_autnum_delete() { when(update.getAction()).thenReturn(Action.DELETE); when(update.getType()).thenReturn(ObjectType.AUT_NUM); final boolean supported = subject.supports(update); assertThat(supported, is(false)); } | @Override public boolean supports(final PreparedUpdate update) { return update.getType().equals(ObjectType.AUT_NUM) && update.getAction().equals(Action.CREATE); } | AutnumAuthentication extends AuthenticationStrategyBase { @Override public boolean supports(final PreparedUpdate update) { return update.getType().equals(ObjectType.AUT_NUM) && update.getAction().equals(Action.CREATE); } } | AutnumAuthentication extends AuthenticationStrategyBase { @Override public boolean supports(final PreparedUpdate update) { return update.getType().equals(ObjectType.AUT_NUM) && update.getAction().equals(Action.CREATE); } @Autowired AutnumAuthentication(final RpslObjectDao objectDao, final AuthenticationModule authenticationModule); } | AutnumAuthentication extends AuthenticationStrategyBase { @Override public boolean supports(final PreparedUpdate update) { return update.getType().equals(ObjectType.AUT_NUM) && update.getAction().equals(Action.CREATE); } @Autowired AutnumAuthentication(final RpslObjectDao objectDao, final AuthenticationModule authenticationModule); @Override boolean supports(final PreparedUpdate update); @Override List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext); } | AutnumAuthentication extends AuthenticationStrategyBase { @Override public boolean supports(final PreparedUpdate update) { return update.getType().equals(ObjectType.AUT_NUM) && update.getAction().equals(Action.CREATE); } @Autowired AutnumAuthentication(final RpslObjectDao objectDao, final AuthenticationModule authenticationModule); @Override boolean supports(final PreparedUpdate update); @Override List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext); } |
@Test public void authenticated_by_mntlower_succeeds() { when(update.getUpdatedObject()).thenReturn(RpslObject.parse("aut-num: AS3333")); when(objectDao.findAsBlock(3333, 3333)).thenReturn(RpslObject.parse("as-block: AS3209 - AS3353\nmnt-lower: LOW-MNT")); final ArrayList<RpslObject> parentMaintainers = Lists.newArrayList(RpslObject.parse("mntner: LOW-MNT")); when(objectDao.getByKeys(eq(ObjectType.MNTNER), anyCollection())).thenReturn(parentMaintainers); when(authenticationModule.authenticate(update, updateContext, parentMaintainers)).thenReturn(parentMaintainers); final List<RpslObject> authenticatedBy = subject.authenticate(update, updateContext); assertThat(authenticatedBy.equals(parentMaintainers), is(true)); verifyZeroInteractions(updateContext); } | @Override public List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext) { final RpslObject object = update.getUpdatedObject(); final CIString pkey = object.getKey(); final long number = Long.parseLong(pkey.toString().substring("AS".length())); final RpslObject asBlock = objectDao.findAsBlock(number, number); if (asBlock == null) { throw new AuthenticationFailedException(UpdateMessages.noParentAsBlockFound(pkey), Collections.<RpslObject>emptyList()); } AttributeType attributeType = AttributeType.MNT_LOWER; Collection<CIString> parentMnts = asBlock.getValuesForAttribute(attributeType); if (parentMnts.isEmpty()) { attributeType = AttributeType.MNT_BY; parentMnts = asBlock.getValuesForAttribute(attributeType); } final List<RpslObject> maintainers = objectDao.getByKeys(ObjectType.MNTNER, parentMnts); final List<RpslObject> authenticatedBy = authenticationModule.authenticate(update, updateContext, maintainers); if (authenticatedBy.isEmpty()) { throw new AuthenticationFailedException(UpdateMessages.authenticationFailed(asBlock, attributeType, maintainers), maintainers); } return authenticatedBy; } | AutnumAuthentication extends AuthenticationStrategyBase { @Override public List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext) { final RpslObject object = update.getUpdatedObject(); final CIString pkey = object.getKey(); final long number = Long.parseLong(pkey.toString().substring("AS".length())); final RpslObject asBlock = objectDao.findAsBlock(number, number); if (asBlock == null) { throw new AuthenticationFailedException(UpdateMessages.noParentAsBlockFound(pkey), Collections.<RpslObject>emptyList()); } AttributeType attributeType = AttributeType.MNT_LOWER; Collection<CIString> parentMnts = asBlock.getValuesForAttribute(attributeType); if (parentMnts.isEmpty()) { attributeType = AttributeType.MNT_BY; parentMnts = asBlock.getValuesForAttribute(attributeType); } final List<RpslObject> maintainers = objectDao.getByKeys(ObjectType.MNTNER, parentMnts); final List<RpslObject> authenticatedBy = authenticationModule.authenticate(update, updateContext, maintainers); if (authenticatedBy.isEmpty()) { throw new AuthenticationFailedException(UpdateMessages.authenticationFailed(asBlock, attributeType, maintainers), maintainers); } return authenticatedBy; } } | AutnumAuthentication extends AuthenticationStrategyBase { @Override public List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext) { final RpslObject object = update.getUpdatedObject(); final CIString pkey = object.getKey(); final long number = Long.parseLong(pkey.toString().substring("AS".length())); final RpslObject asBlock = objectDao.findAsBlock(number, number); if (asBlock == null) { throw new AuthenticationFailedException(UpdateMessages.noParentAsBlockFound(pkey), Collections.<RpslObject>emptyList()); } AttributeType attributeType = AttributeType.MNT_LOWER; Collection<CIString> parentMnts = asBlock.getValuesForAttribute(attributeType); if (parentMnts.isEmpty()) { attributeType = AttributeType.MNT_BY; parentMnts = asBlock.getValuesForAttribute(attributeType); } final List<RpslObject> maintainers = objectDao.getByKeys(ObjectType.MNTNER, parentMnts); final List<RpslObject> authenticatedBy = authenticationModule.authenticate(update, updateContext, maintainers); if (authenticatedBy.isEmpty()) { throw new AuthenticationFailedException(UpdateMessages.authenticationFailed(asBlock, attributeType, maintainers), maintainers); } return authenticatedBy; } @Autowired AutnumAuthentication(final RpslObjectDao objectDao, final AuthenticationModule authenticationModule); } | AutnumAuthentication extends AuthenticationStrategyBase { @Override public List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext) { final RpslObject object = update.getUpdatedObject(); final CIString pkey = object.getKey(); final long number = Long.parseLong(pkey.toString().substring("AS".length())); final RpslObject asBlock = objectDao.findAsBlock(number, number); if (asBlock == null) { throw new AuthenticationFailedException(UpdateMessages.noParentAsBlockFound(pkey), Collections.<RpslObject>emptyList()); } AttributeType attributeType = AttributeType.MNT_LOWER; Collection<CIString> parentMnts = asBlock.getValuesForAttribute(attributeType); if (parentMnts.isEmpty()) { attributeType = AttributeType.MNT_BY; parentMnts = asBlock.getValuesForAttribute(attributeType); } final List<RpslObject> maintainers = objectDao.getByKeys(ObjectType.MNTNER, parentMnts); final List<RpslObject> authenticatedBy = authenticationModule.authenticate(update, updateContext, maintainers); if (authenticatedBy.isEmpty()) { throw new AuthenticationFailedException(UpdateMessages.authenticationFailed(asBlock, attributeType, maintainers), maintainers); } return authenticatedBy; } @Autowired AutnumAuthentication(final RpslObjectDao objectDao, final AuthenticationModule authenticationModule); @Override boolean supports(final PreparedUpdate update); @Override List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext); } | AutnumAuthentication extends AuthenticationStrategyBase { @Override public List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext) { final RpslObject object = update.getUpdatedObject(); final CIString pkey = object.getKey(); final long number = Long.parseLong(pkey.toString().substring("AS".length())); final RpslObject asBlock = objectDao.findAsBlock(number, number); if (asBlock == null) { throw new AuthenticationFailedException(UpdateMessages.noParentAsBlockFound(pkey), Collections.<RpslObject>emptyList()); } AttributeType attributeType = AttributeType.MNT_LOWER; Collection<CIString> parentMnts = asBlock.getValuesForAttribute(attributeType); if (parentMnts.isEmpty()) { attributeType = AttributeType.MNT_BY; parentMnts = asBlock.getValuesForAttribute(attributeType); } final List<RpslObject> maintainers = objectDao.getByKeys(ObjectType.MNTNER, parentMnts); final List<RpslObject> authenticatedBy = authenticationModule.authenticate(update, updateContext, maintainers); if (authenticatedBy.isEmpty()) { throw new AuthenticationFailedException(UpdateMessages.authenticationFailed(asBlock, attributeType, maintainers), maintainers); } return authenticatedBy; } @Autowired AutnumAuthentication(final RpslObjectDao objectDao, final AuthenticationModule authenticationModule); @Override boolean supports(final PreparedUpdate update); @Override List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext); } |
@Test public void transform_key_domain_no_dot() { final RpslObject rpslObject = RpslObject.parse("domain: 17.45.212.in-addr.arpa"); final CIString result = attributeSanitizer.sanitizeKey(rpslObject); assertThat(result.toString(), is("17.45.212.in-addr.arpa")); } | public CIString sanitizeKey(final RpslObject originalObject) { final List<RpslAttribute> keyRelatedAttributes = getKeyRelatedAttributes(originalObject); return new RpslObject(sanitizeKeyAttributes(keyRelatedAttributes)).getKey(); } | AttributeSanitizer { public CIString sanitizeKey(final RpslObject originalObject) { final List<RpslAttribute> keyRelatedAttributes = getKeyRelatedAttributes(originalObject); return new RpslObject(sanitizeKeyAttributes(keyRelatedAttributes)).getKey(); } } | AttributeSanitizer { public CIString sanitizeKey(final RpslObject originalObject) { final List<RpslAttribute> keyRelatedAttributes = getKeyRelatedAttributes(originalObject); return new RpslObject(sanitizeKeyAttributes(keyRelatedAttributes)).getKey(); } @Autowired AttributeSanitizer(DateTimeProvider dateTimeProvider); } | AttributeSanitizer { public CIString sanitizeKey(final RpslObject originalObject) { final List<RpslAttribute> keyRelatedAttributes = getKeyRelatedAttributes(originalObject); return new RpslObject(sanitizeKeyAttributes(keyRelatedAttributes)).getKey(); } @Autowired AttributeSanitizer(DateTimeProvider dateTimeProvider); CIString sanitizeKey(final RpslObject originalObject); RpslObject sanitize(final RpslObject object, final ObjectMessages objectMessages); } | AttributeSanitizer { public CIString sanitizeKey(final RpslObject originalObject) { final List<RpslAttribute> keyRelatedAttributes = getKeyRelatedAttributes(originalObject); return new RpslObject(sanitizeKeyAttributes(keyRelatedAttributes)).getKey(); } @Autowired AttributeSanitizer(DateTimeProvider dateTimeProvider); CIString sanitizeKey(final RpslObject originalObject); RpslObject sanitize(final RpslObject object, final ObjectMessages objectMessages); } |
@Test public void createExportFileWriters() { final List<ExportFileWriter> exportFileWriters = subject.createExportFileWriters(folder.getRoot(), LAST_SERIAL); assertThat(exportFileWriters.isEmpty(), Matchers.is(false)); final File[] files = folder.getRoot().listFiles(); assertNotNull(files); assertThat(files.length, Matchers.is(3)); for (final File file : files) { if (! (file.getAbsolutePath().endsWith("internal") || file.getAbsolutePath().endsWith("dbase") || file.getAbsolutePath().endsWith("dbase_new"))) { Assert.fail("Unexpected folder: " + file.getAbsolutePath()); } } } | public List<ExportFileWriter> createExportFileWriters(final File baseDir, final int lastSerial) { final File fullDir = new File(baseDir, legacyExternalExportDir); final File fullDirNew = new File(baseDir, externalExportDir); final File splitDir = new File(baseDir, legacyExternalExportDir + File.separator + SPLITFILE_FOLDERNAME); final File splitDirNew = new File(baseDir, externalExportDir + File.separator + SPLITFILE_FOLDERNAME); final File internalDir = new File(baseDir, internalExportDir + File.separator + SPLITFILE_FOLDERNAME); initDirs(fullDirNew, fullDir, splitDirNew, splitDir, internalDir); try { FileCopyUtils.copy(String.valueOf(lastSerial).getBytes(StandardCharsets.ISO_8859_1), new File(fullDirNew, CURRENTSERIAL_FILENAME)); FileCopyUtils.copy(String.valueOf(lastSerial).getBytes(StandardCharsets.ISO_8859_1), new File(fullDir, CURRENTSERIAL_FILENAME)); FileCopyUtils.copy(String.valueOf(lastSerial).getBytes(StandardCharsets.ISO_8859_1), new File(fullDirNew, CURRENTSERIAL_NONAUTH_FILENAME)); FileCopyUtils.copy(String.valueOf(lastSerial).getBytes(StandardCharsets.ISO_8859_1), new File(fullDir, CURRENTSERIAL_NONAUTH_FILENAME)); } catch (IOException e) { throw new RuntimeException("Writing current serial", e); } final FilenameStrategy singleFile = new FilenameStrategy.SingleFile(); final FilenameStrategy splitFile = new FilenameStrategy.SplitFile(); final FilenameStrategy nonAuthSingleFile = new FilenameStrategy.NonAuthSingleFile(); final FilenameStrategy nonAuthSplitFile = new FilenameStrategy.NonAuthSplitFile(); final ExportFilter sourceFilter = new ExportFilter.SourceExportFilter(source, ImmutableSet.copyOf(ObjectType.values())); final ExportFilter nonAuthSourceFilter = new ExportFilter.SourceExportFilter(nonAuthSource, Sets.immutableEnumSet(AUT_NUM, ROUTE, ROUTE6), false); return Lists.newArrayList( new ExportFileWriter(fullDir, singleFile, new DecorationStrategy.DummifyLegacy(dummifierNrtm), sourceFilter), new ExportFileWriter(splitDir, splitFile, new DecorationStrategy.DummifyLegacy(dummifierNrtm), sourceFilter), new ExportFileWriter(fullDirNew, singleFile, new DecorationStrategy.DummifyCurrent(dummifierCurrent), sourceFilter), new ExportFileWriter(splitDirNew, splitFile, new DecorationStrategy.DummifyCurrent(dummifierCurrent), sourceFilter), new ExportFileWriter(internalDir, splitFile, new DecorationStrategy.None(), sourceFilter), new ExportFileWriter(fullDir, nonAuthSingleFile, new DecorationStrategy.DummifyLegacy(dummifierNrtm), nonAuthSourceFilter), new ExportFileWriter(splitDir, nonAuthSplitFile, new DecorationStrategy.DummifyLegacy(dummifierNrtm), nonAuthSourceFilter), new ExportFileWriter(fullDirNew, nonAuthSingleFile, new DecorationStrategy.DummifyCurrent(dummifierCurrent), nonAuthSourceFilter), new ExportFileWriter(splitDirNew, nonAuthSplitFile, new DecorationStrategy.DummifyCurrent(dummifierCurrent), nonAuthSourceFilter), new ExportFileWriter(internalDir, nonAuthSplitFile, new DecorationStrategy.None(), nonAuthSourceFilter) ); } | ExportFileWriterFactory { public List<ExportFileWriter> createExportFileWriters(final File baseDir, final int lastSerial) { final File fullDir = new File(baseDir, legacyExternalExportDir); final File fullDirNew = new File(baseDir, externalExportDir); final File splitDir = new File(baseDir, legacyExternalExportDir + File.separator + SPLITFILE_FOLDERNAME); final File splitDirNew = new File(baseDir, externalExportDir + File.separator + SPLITFILE_FOLDERNAME); final File internalDir = new File(baseDir, internalExportDir + File.separator + SPLITFILE_FOLDERNAME); initDirs(fullDirNew, fullDir, splitDirNew, splitDir, internalDir); try { FileCopyUtils.copy(String.valueOf(lastSerial).getBytes(StandardCharsets.ISO_8859_1), new File(fullDirNew, CURRENTSERIAL_FILENAME)); FileCopyUtils.copy(String.valueOf(lastSerial).getBytes(StandardCharsets.ISO_8859_1), new File(fullDir, CURRENTSERIAL_FILENAME)); FileCopyUtils.copy(String.valueOf(lastSerial).getBytes(StandardCharsets.ISO_8859_1), new File(fullDirNew, CURRENTSERIAL_NONAUTH_FILENAME)); FileCopyUtils.copy(String.valueOf(lastSerial).getBytes(StandardCharsets.ISO_8859_1), new File(fullDir, CURRENTSERIAL_NONAUTH_FILENAME)); } catch (IOException e) { throw new RuntimeException("Writing current serial", e); } final FilenameStrategy singleFile = new FilenameStrategy.SingleFile(); final FilenameStrategy splitFile = new FilenameStrategy.SplitFile(); final FilenameStrategy nonAuthSingleFile = new FilenameStrategy.NonAuthSingleFile(); final FilenameStrategy nonAuthSplitFile = new FilenameStrategy.NonAuthSplitFile(); final ExportFilter sourceFilter = new ExportFilter.SourceExportFilter(source, ImmutableSet.copyOf(ObjectType.values())); final ExportFilter nonAuthSourceFilter = new ExportFilter.SourceExportFilter(nonAuthSource, Sets.immutableEnumSet(AUT_NUM, ROUTE, ROUTE6), false); return Lists.newArrayList( new ExportFileWriter(fullDir, singleFile, new DecorationStrategy.DummifyLegacy(dummifierNrtm), sourceFilter), new ExportFileWriter(splitDir, splitFile, new DecorationStrategy.DummifyLegacy(dummifierNrtm), sourceFilter), new ExportFileWriter(fullDirNew, singleFile, new DecorationStrategy.DummifyCurrent(dummifierCurrent), sourceFilter), new ExportFileWriter(splitDirNew, splitFile, new DecorationStrategy.DummifyCurrent(dummifierCurrent), sourceFilter), new ExportFileWriter(internalDir, splitFile, new DecorationStrategy.None(), sourceFilter), new ExportFileWriter(fullDir, nonAuthSingleFile, new DecorationStrategy.DummifyLegacy(dummifierNrtm), nonAuthSourceFilter), new ExportFileWriter(splitDir, nonAuthSplitFile, new DecorationStrategy.DummifyLegacy(dummifierNrtm), nonAuthSourceFilter), new ExportFileWriter(fullDirNew, nonAuthSingleFile, new DecorationStrategy.DummifyCurrent(dummifierCurrent), nonAuthSourceFilter), new ExportFileWriter(splitDirNew, nonAuthSplitFile, new DecorationStrategy.DummifyCurrent(dummifierCurrent), nonAuthSourceFilter), new ExportFileWriter(internalDir, nonAuthSplitFile, new DecorationStrategy.None(), nonAuthSourceFilter) ); } } | ExportFileWriterFactory { public List<ExportFileWriter> createExportFileWriters(final File baseDir, final int lastSerial) { final File fullDir = new File(baseDir, legacyExternalExportDir); final File fullDirNew = new File(baseDir, externalExportDir); final File splitDir = new File(baseDir, legacyExternalExportDir + File.separator + SPLITFILE_FOLDERNAME); final File splitDirNew = new File(baseDir, externalExportDir + File.separator + SPLITFILE_FOLDERNAME); final File internalDir = new File(baseDir, internalExportDir + File.separator + SPLITFILE_FOLDERNAME); initDirs(fullDirNew, fullDir, splitDirNew, splitDir, internalDir); try { FileCopyUtils.copy(String.valueOf(lastSerial).getBytes(StandardCharsets.ISO_8859_1), new File(fullDirNew, CURRENTSERIAL_FILENAME)); FileCopyUtils.copy(String.valueOf(lastSerial).getBytes(StandardCharsets.ISO_8859_1), new File(fullDir, CURRENTSERIAL_FILENAME)); FileCopyUtils.copy(String.valueOf(lastSerial).getBytes(StandardCharsets.ISO_8859_1), new File(fullDirNew, CURRENTSERIAL_NONAUTH_FILENAME)); FileCopyUtils.copy(String.valueOf(lastSerial).getBytes(StandardCharsets.ISO_8859_1), new File(fullDir, CURRENTSERIAL_NONAUTH_FILENAME)); } catch (IOException e) { throw new RuntimeException("Writing current serial", e); } final FilenameStrategy singleFile = new FilenameStrategy.SingleFile(); final FilenameStrategy splitFile = new FilenameStrategy.SplitFile(); final FilenameStrategy nonAuthSingleFile = new FilenameStrategy.NonAuthSingleFile(); final FilenameStrategy nonAuthSplitFile = new FilenameStrategy.NonAuthSplitFile(); final ExportFilter sourceFilter = new ExportFilter.SourceExportFilter(source, ImmutableSet.copyOf(ObjectType.values())); final ExportFilter nonAuthSourceFilter = new ExportFilter.SourceExportFilter(nonAuthSource, Sets.immutableEnumSet(AUT_NUM, ROUTE, ROUTE6), false); return Lists.newArrayList( new ExportFileWriter(fullDir, singleFile, new DecorationStrategy.DummifyLegacy(dummifierNrtm), sourceFilter), new ExportFileWriter(splitDir, splitFile, new DecorationStrategy.DummifyLegacy(dummifierNrtm), sourceFilter), new ExportFileWriter(fullDirNew, singleFile, new DecorationStrategy.DummifyCurrent(dummifierCurrent), sourceFilter), new ExportFileWriter(splitDirNew, splitFile, new DecorationStrategy.DummifyCurrent(dummifierCurrent), sourceFilter), new ExportFileWriter(internalDir, splitFile, new DecorationStrategy.None(), sourceFilter), new ExportFileWriter(fullDir, nonAuthSingleFile, new DecorationStrategy.DummifyLegacy(dummifierNrtm), nonAuthSourceFilter), new ExportFileWriter(splitDir, nonAuthSplitFile, new DecorationStrategy.DummifyLegacy(dummifierNrtm), nonAuthSourceFilter), new ExportFileWriter(fullDirNew, nonAuthSingleFile, new DecorationStrategy.DummifyCurrent(dummifierCurrent), nonAuthSourceFilter), new ExportFileWriter(splitDirNew, nonAuthSplitFile, new DecorationStrategy.DummifyCurrent(dummifierCurrent), nonAuthSourceFilter), new ExportFileWriter(internalDir, nonAuthSplitFile, new DecorationStrategy.None(), nonAuthSourceFilter) ); } @Autowired ExportFileWriterFactory(final DummifierNrtm dummifierNrtm, final DummifierCurrent dummifierCurrent,
@Value("${dir.rpsl.export.internal}") final String internalExportDir,
@Value("${dir.rpsl.export.external}") final String externalExportDir,
@Value("${dir.rpsl.export.external.legacy}") final String legacyExternalExportDir,
@Value("${whois.source}") final String source,
@Value("${whois.nonauth.source}") final String nonAuthSource); } | ExportFileWriterFactory { public List<ExportFileWriter> createExportFileWriters(final File baseDir, final int lastSerial) { final File fullDir = new File(baseDir, legacyExternalExportDir); final File fullDirNew = new File(baseDir, externalExportDir); final File splitDir = new File(baseDir, legacyExternalExportDir + File.separator + SPLITFILE_FOLDERNAME); final File splitDirNew = new File(baseDir, externalExportDir + File.separator + SPLITFILE_FOLDERNAME); final File internalDir = new File(baseDir, internalExportDir + File.separator + SPLITFILE_FOLDERNAME); initDirs(fullDirNew, fullDir, splitDirNew, splitDir, internalDir); try { FileCopyUtils.copy(String.valueOf(lastSerial).getBytes(StandardCharsets.ISO_8859_1), new File(fullDirNew, CURRENTSERIAL_FILENAME)); FileCopyUtils.copy(String.valueOf(lastSerial).getBytes(StandardCharsets.ISO_8859_1), new File(fullDir, CURRENTSERIAL_FILENAME)); FileCopyUtils.copy(String.valueOf(lastSerial).getBytes(StandardCharsets.ISO_8859_1), new File(fullDirNew, CURRENTSERIAL_NONAUTH_FILENAME)); FileCopyUtils.copy(String.valueOf(lastSerial).getBytes(StandardCharsets.ISO_8859_1), new File(fullDir, CURRENTSERIAL_NONAUTH_FILENAME)); } catch (IOException e) { throw new RuntimeException("Writing current serial", e); } final FilenameStrategy singleFile = new FilenameStrategy.SingleFile(); final FilenameStrategy splitFile = new FilenameStrategy.SplitFile(); final FilenameStrategy nonAuthSingleFile = new FilenameStrategy.NonAuthSingleFile(); final FilenameStrategy nonAuthSplitFile = new FilenameStrategy.NonAuthSplitFile(); final ExportFilter sourceFilter = new ExportFilter.SourceExportFilter(source, ImmutableSet.copyOf(ObjectType.values())); final ExportFilter nonAuthSourceFilter = new ExportFilter.SourceExportFilter(nonAuthSource, Sets.immutableEnumSet(AUT_NUM, ROUTE, ROUTE6), false); return Lists.newArrayList( new ExportFileWriter(fullDir, singleFile, new DecorationStrategy.DummifyLegacy(dummifierNrtm), sourceFilter), new ExportFileWriter(splitDir, splitFile, new DecorationStrategy.DummifyLegacy(dummifierNrtm), sourceFilter), new ExportFileWriter(fullDirNew, singleFile, new DecorationStrategy.DummifyCurrent(dummifierCurrent), sourceFilter), new ExportFileWriter(splitDirNew, splitFile, new DecorationStrategy.DummifyCurrent(dummifierCurrent), sourceFilter), new ExportFileWriter(internalDir, splitFile, new DecorationStrategy.None(), sourceFilter), new ExportFileWriter(fullDir, nonAuthSingleFile, new DecorationStrategy.DummifyLegacy(dummifierNrtm), nonAuthSourceFilter), new ExportFileWriter(splitDir, nonAuthSplitFile, new DecorationStrategy.DummifyLegacy(dummifierNrtm), nonAuthSourceFilter), new ExportFileWriter(fullDirNew, nonAuthSingleFile, new DecorationStrategy.DummifyCurrent(dummifierCurrent), nonAuthSourceFilter), new ExportFileWriter(splitDirNew, nonAuthSplitFile, new DecorationStrategy.DummifyCurrent(dummifierCurrent), nonAuthSourceFilter), new ExportFileWriter(internalDir, nonAuthSplitFile, new DecorationStrategy.None(), nonAuthSourceFilter) ); } @Autowired ExportFileWriterFactory(final DummifierNrtm dummifierNrtm, final DummifierCurrent dummifierCurrent,
@Value("${dir.rpsl.export.internal}") final String internalExportDir,
@Value("${dir.rpsl.export.external}") final String externalExportDir,
@Value("${dir.rpsl.export.external.legacy}") final String legacyExternalExportDir,
@Value("${whois.source}") final String source,
@Value("${whois.nonauth.source}") final String nonAuthSource); List<ExportFileWriter> createExportFileWriters(final File baseDir, final int lastSerial); boolean isExportDir(final File dir); } | ExportFileWriterFactory { public List<ExportFileWriter> createExportFileWriters(final File baseDir, final int lastSerial) { final File fullDir = new File(baseDir, legacyExternalExportDir); final File fullDirNew = new File(baseDir, externalExportDir); final File splitDir = new File(baseDir, legacyExternalExportDir + File.separator + SPLITFILE_FOLDERNAME); final File splitDirNew = new File(baseDir, externalExportDir + File.separator + SPLITFILE_FOLDERNAME); final File internalDir = new File(baseDir, internalExportDir + File.separator + SPLITFILE_FOLDERNAME); initDirs(fullDirNew, fullDir, splitDirNew, splitDir, internalDir); try { FileCopyUtils.copy(String.valueOf(lastSerial).getBytes(StandardCharsets.ISO_8859_1), new File(fullDirNew, CURRENTSERIAL_FILENAME)); FileCopyUtils.copy(String.valueOf(lastSerial).getBytes(StandardCharsets.ISO_8859_1), new File(fullDir, CURRENTSERIAL_FILENAME)); FileCopyUtils.copy(String.valueOf(lastSerial).getBytes(StandardCharsets.ISO_8859_1), new File(fullDirNew, CURRENTSERIAL_NONAUTH_FILENAME)); FileCopyUtils.copy(String.valueOf(lastSerial).getBytes(StandardCharsets.ISO_8859_1), new File(fullDir, CURRENTSERIAL_NONAUTH_FILENAME)); } catch (IOException e) { throw new RuntimeException("Writing current serial", e); } final FilenameStrategy singleFile = new FilenameStrategy.SingleFile(); final FilenameStrategy splitFile = new FilenameStrategy.SplitFile(); final FilenameStrategy nonAuthSingleFile = new FilenameStrategy.NonAuthSingleFile(); final FilenameStrategy nonAuthSplitFile = new FilenameStrategy.NonAuthSplitFile(); final ExportFilter sourceFilter = new ExportFilter.SourceExportFilter(source, ImmutableSet.copyOf(ObjectType.values())); final ExportFilter nonAuthSourceFilter = new ExportFilter.SourceExportFilter(nonAuthSource, Sets.immutableEnumSet(AUT_NUM, ROUTE, ROUTE6), false); return Lists.newArrayList( new ExportFileWriter(fullDir, singleFile, new DecorationStrategy.DummifyLegacy(dummifierNrtm), sourceFilter), new ExportFileWriter(splitDir, splitFile, new DecorationStrategy.DummifyLegacy(dummifierNrtm), sourceFilter), new ExportFileWriter(fullDirNew, singleFile, new DecorationStrategy.DummifyCurrent(dummifierCurrent), sourceFilter), new ExportFileWriter(splitDirNew, splitFile, new DecorationStrategy.DummifyCurrent(dummifierCurrent), sourceFilter), new ExportFileWriter(internalDir, splitFile, new DecorationStrategy.None(), sourceFilter), new ExportFileWriter(fullDir, nonAuthSingleFile, new DecorationStrategy.DummifyLegacy(dummifierNrtm), nonAuthSourceFilter), new ExportFileWriter(splitDir, nonAuthSplitFile, new DecorationStrategy.DummifyLegacy(dummifierNrtm), nonAuthSourceFilter), new ExportFileWriter(fullDirNew, nonAuthSingleFile, new DecorationStrategy.DummifyCurrent(dummifierCurrent), nonAuthSourceFilter), new ExportFileWriter(splitDirNew, nonAuthSplitFile, new DecorationStrategy.DummifyCurrent(dummifierCurrent), nonAuthSourceFilter), new ExportFileWriter(internalDir, nonAuthSplitFile, new DecorationStrategy.None(), nonAuthSourceFilter) ); } @Autowired ExportFileWriterFactory(final DummifierNrtm dummifierNrtm, final DummifierCurrent dummifierCurrent,
@Value("${dir.rpsl.export.internal}") final String internalExportDir,
@Value("${dir.rpsl.export.external}") final String externalExportDir,
@Value("${dir.rpsl.export.external.legacy}") final String legacyExternalExportDir,
@Value("${whois.source}") final String source,
@Value("${whois.nonauth.source}") final String nonAuthSource); List<ExportFileWriter> createExportFileWriters(final File baseDir, final int lastSerial); boolean isExportDir(final File dir); } |
@Test(expected = AuthenticationFailedException.class) public void authenticated_by_mntlower_fails() { when(update.getUpdatedObject()).thenReturn(RpslObject.parse("aut-num: AS3333")); when(objectDao.findAsBlock(3333, 3333)).thenReturn(RpslObject.parse("as-block: AS3209 - AS3353\nmnt-by: TEST-MNT\nmnt-lower: LOW-MNT")); final ArrayList<RpslObject> parentMaintainers = Lists.newArrayList(RpslObject.parse("mntner: LOW-MNT")); when(objectDao.getByKeys(eq(ObjectType.MNTNER), anyCollection())).thenReturn(parentMaintainers); when(authenticationModule.authenticate(update, updateContext, parentMaintainers)).thenReturn(Lists.<RpslObject>newArrayList()); subject.authenticate(update, updateContext); } | @Override public List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext) { final RpslObject object = update.getUpdatedObject(); final CIString pkey = object.getKey(); final long number = Long.parseLong(pkey.toString().substring("AS".length())); final RpslObject asBlock = objectDao.findAsBlock(number, number); if (asBlock == null) { throw new AuthenticationFailedException(UpdateMessages.noParentAsBlockFound(pkey), Collections.<RpslObject>emptyList()); } AttributeType attributeType = AttributeType.MNT_LOWER; Collection<CIString> parentMnts = asBlock.getValuesForAttribute(attributeType); if (parentMnts.isEmpty()) { attributeType = AttributeType.MNT_BY; parentMnts = asBlock.getValuesForAttribute(attributeType); } final List<RpslObject> maintainers = objectDao.getByKeys(ObjectType.MNTNER, parentMnts); final List<RpslObject> authenticatedBy = authenticationModule.authenticate(update, updateContext, maintainers); if (authenticatedBy.isEmpty()) { throw new AuthenticationFailedException(UpdateMessages.authenticationFailed(asBlock, attributeType, maintainers), maintainers); } return authenticatedBy; } | AutnumAuthentication extends AuthenticationStrategyBase { @Override public List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext) { final RpslObject object = update.getUpdatedObject(); final CIString pkey = object.getKey(); final long number = Long.parseLong(pkey.toString().substring("AS".length())); final RpslObject asBlock = objectDao.findAsBlock(number, number); if (asBlock == null) { throw new AuthenticationFailedException(UpdateMessages.noParentAsBlockFound(pkey), Collections.<RpslObject>emptyList()); } AttributeType attributeType = AttributeType.MNT_LOWER; Collection<CIString> parentMnts = asBlock.getValuesForAttribute(attributeType); if (parentMnts.isEmpty()) { attributeType = AttributeType.MNT_BY; parentMnts = asBlock.getValuesForAttribute(attributeType); } final List<RpslObject> maintainers = objectDao.getByKeys(ObjectType.MNTNER, parentMnts); final List<RpslObject> authenticatedBy = authenticationModule.authenticate(update, updateContext, maintainers); if (authenticatedBy.isEmpty()) { throw new AuthenticationFailedException(UpdateMessages.authenticationFailed(asBlock, attributeType, maintainers), maintainers); } return authenticatedBy; } } | AutnumAuthentication extends AuthenticationStrategyBase { @Override public List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext) { final RpslObject object = update.getUpdatedObject(); final CIString pkey = object.getKey(); final long number = Long.parseLong(pkey.toString().substring("AS".length())); final RpslObject asBlock = objectDao.findAsBlock(number, number); if (asBlock == null) { throw new AuthenticationFailedException(UpdateMessages.noParentAsBlockFound(pkey), Collections.<RpslObject>emptyList()); } AttributeType attributeType = AttributeType.MNT_LOWER; Collection<CIString> parentMnts = asBlock.getValuesForAttribute(attributeType); if (parentMnts.isEmpty()) { attributeType = AttributeType.MNT_BY; parentMnts = asBlock.getValuesForAttribute(attributeType); } final List<RpslObject> maintainers = objectDao.getByKeys(ObjectType.MNTNER, parentMnts); final List<RpslObject> authenticatedBy = authenticationModule.authenticate(update, updateContext, maintainers); if (authenticatedBy.isEmpty()) { throw new AuthenticationFailedException(UpdateMessages.authenticationFailed(asBlock, attributeType, maintainers), maintainers); } return authenticatedBy; } @Autowired AutnumAuthentication(final RpslObjectDao objectDao, final AuthenticationModule authenticationModule); } | AutnumAuthentication extends AuthenticationStrategyBase { @Override public List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext) { final RpslObject object = update.getUpdatedObject(); final CIString pkey = object.getKey(); final long number = Long.parseLong(pkey.toString().substring("AS".length())); final RpslObject asBlock = objectDao.findAsBlock(number, number); if (asBlock == null) { throw new AuthenticationFailedException(UpdateMessages.noParentAsBlockFound(pkey), Collections.<RpslObject>emptyList()); } AttributeType attributeType = AttributeType.MNT_LOWER; Collection<CIString> parentMnts = asBlock.getValuesForAttribute(attributeType); if (parentMnts.isEmpty()) { attributeType = AttributeType.MNT_BY; parentMnts = asBlock.getValuesForAttribute(attributeType); } final List<RpslObject> maintainers = objectDao.getByKeys(ObjectType.MNTNER, parentMnts); final List<RpslObject> authenticatedBy = authenticationModule.authenticate(update, updateContext, maintainers); if (authenticatedBy.isEmpty()) { throw new AuthenticationFailedException(UpdateMessages.authenticationFailed(asBlock, attributeType, maintainers), maintainers); } return authenticatedBy; } @Autowired AutnumAuthentication(final RpslObjectDao objectDao, final AuthenticationModule authenticationModule); @Override boolean supports(final PreparedUpdate update); @Override List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext); } | AutnumAuthentication extends AuthenticationStrategyBase { @Override public List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext) { final RpslObject object = update.getUpdatedObject(); final CIString pkey = object.getKey(); final long number = Long.parseLong(pkey.toString().substring("AS".length())); final RpslObject asBlock = objectDao.findAsBlock(number, number); if (asBlock == null) { throw new AuthenticationFailedException(UpdateMessages.noParentAsBlockFound(pkey), Collections.<RpslObject>emptyList()); } AttributeType attributeType = AttributeType.MNT_LOWER; Collection<CIString> parentMnts = asBlock.getValuesForAttribute(attributeType); if (parentMnts.isEmpty()) { attributeType = AttributeType.MNT_BY; parentMnts = asBlock.getValuesForAttribute(attributeType); } final List<RpslObject> maintainers = objectDao.getByKeys(ObjectType.MNTNER, parentMnts); final List<RpslObject> authenticatedBy = authenticationModule.authenticate(update, updateContext, maintainers); if (authenticatedBy.isEmpty()) { throw new AuthenticationFailedException(UpdateMessages.authenticationFailed(asBlock, attributeType, maintainers), maintainers); } return authenticatedBy; } @Autowired AutnumAuthentication(final RpslObjectDao objectDao, final AuthenticationModule authenticationModule); @Override boolean supports(final PreparedUpdate update); @Override List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext); } |
@Test(expected = AuthenticationFailedException.class) public void cant_find_asblock() { when(update.getUpdatedObject()).thenReturn(RpslObject.parse("aut-num: AS3333")); when(objectDao.findAsBlock(3333, 3333)).thenReturn(null); subject.authenticate(update, updateContext); } | @Override public List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext) { final RpslObject object = update.getUpdatedObject(); final CIString pkey = object.getKey(); final long number = Long.parseLong(pkey.toString().substring("AS".length())); final RpslObject asBlock = objectDao.findAsBlock(number, number); if (asBlock == null) { throw new AuthenticationFailedException(UpdateMessages.noParentAsBlockFound(pkey), Collections.<RpslObject>emptyList()); } AttributeType attributeType = AttributeType.MNT_LOWER; Collection<CIString> parentMnts = asBlock.getValuesForAttribute(attributeType); if (parentMnts.isEmpty()) { attributeType = AttributeType.MNT_BY; parentMnts = asBlock.getValuesForAttribute(attributeType); } final List<RpslObject> maintainers = objectDao.getByKeys(ObjectType.MNTNER, parentMnts); final List<RpslObject> authenticatedBy = authenticationModule.authenticate(update, updateContext, maintainers); if (authenticatedBy.isEmpty()) { throw new AuthenticationFailedException(UpdateMessages.authenticationFailed(asBlock, attributeType, maintainers), maintainers); } return authenticatedBy; } | AutnumAuthentication extends AuthenticationStrategyBase { @Override public List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext) { final RpslObject object = update.getUpdatedObject(); final CIString pkey = object.getKey(); final long number = Long.parseLong(pkey.toString().substring("AS".length())); final RpslObject asBlock = objectDao.findAsBlock(number, number); if (asBlock == null) { throw new AuthenticationFailedException(UpdateMessages.noParentAsBlockFound(pkey), Collections.<RpslObject>emptyList()); } AttributeType attributeType = AttributeType.MNT_LOWER; Collection<CIString> parentMnts = asBlock.getValuesForAttribute(attributeType); if (parentMnts.isEmpty()) { attributeType = AttributeType.MNT_BY; parentMnts = asBlock.getValuesForAttribute(attributeType); } final List<RpslObject> maintainers = objectDao.getByKeys(ObjectType.MNTNER, parentMnts); final List<RpslObject> authenticatedBy = authenticationModule.authenticate(update, updateContext, maintainers); if (authenticatedBy.isEmpty()) { throw new AuthenticationFailedException(UpdateMessages.authenticationFailed(asBlock, attributeType, maintainers), maintainers); } return authenticatedBy; } } | AutnumAuthentication extends AuthenticationStrategyBase { @Override public List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext) { final RpslObject object = update.getUpdatedObject(); final CIString pkey = object.getKey(); final long number = Long.parseLong(pkey.toString().substring("AS".length())); final RpslObject asBlock = objectDao.findAsBlock(number, number); if (asBlock == null) { throw new AuthenticationFailedException(UpdateMessages.noParentAsBlockFound(pkey), Collections.<RpslObject>emptyList()); } AttributeType attributeType = AttributeType.MNT_LOWER; Collection<CIString> parentMnts = asBlock.getValuesForAttribute(attributeType); if (parentMnts.isEmpty()) { attributeType = AttributeType.MNT_BY; parentMnts = asBlock.getValuesForAttribute(attributeType); } final List<RpslObject> maintainers = objectDao.getByKeys(ObjectType.MNTNER, parentMnts); final List<RpslObject> authenticatedBy = authenticationModule.authenticate(update, updateContext, maintainers); if (authenticatedBy.isEmpty()) { throw new AuthenticationFailedException(UpdateMessages.authenticationFailed(asBlock, attributeType, maintainers), maintainers); } return authenticatedBy; } @Autowired AutnumAuthentication(final RpslObjectDao objectDao, final AuthenticationModule authenticationModule); } | AutnumAuthentication extends AuthenticationStrategyBase { @Override public List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext) { final RpslObject object = update.getUpdatedObject(); final CIString pkey = object.getKey(); final long number = Long.parseLong(pkey.toString().substring("AS".length())); final RpslObject asBlock = objectDao.findAsBlock(number, number); if (asBlock == null) { throw new AuthenticationFailedException(UpdateMessages.noParentAsBlockFound(pkey), Collections.<RpslObject>emptyList()); } AttributeType attributeType = AttributeType.MNT_LOWER; Collection<CIString> parentMnts = asBlock.getValuesForAttribute(attributeType); if (parentMnts.isEmpty()) { attributeType = AttributeType.MNT_BY; parentMnts = asBlock.getValuesForAttribute(attributeType); } final List<RpslObject> maintainers = objectDao.getByKeys(ObjectType.MNTNER, parentMnts); final List<RpslObject> authenticatedBy = authenticationModule.authenticate(update, updateContext, maintainers); if (authenticatedBy.isEmpty()) { throw new AuthenticationFailedException(UpdateMessages.authenticationFailed(asBlock, attributeType, maintainers), maintainers); } return authenticatedBy; } @Autowired AutnumAuthentication(final RpslObjectDao objectDao, final AuthenticationModule authenticationModule); @Override boolean supports(final PreparedUpdate update); @Override List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext); } | AutnumAuthentication extends AuthenticationStrategyBase { @Override public List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext) { final RpslObject object = update.getUpdatedObject(); final CIString pkey = object.getKey(); final long number = Long.parseLong(pkey.toString().substring("AS".length())); final RpslObject asBlock = objectDao.findAsBlock(number, number); if (asBlock == null) { throw new AuthenticationFailedException(UpdateMessages.noParentAsBlockFound(pkey), Collections.<RpslObject>emptyList()); } AttributeType attributeType = AttributeType.MNT_LOWER; Collection<CIString> parentMnts = asBlock.getValuesForAttribute(attributeType); if (parentMnts.isEmpty()) { attributeType = AttributeType.MNT_BY; parentMnts = asBlock.getValuesForAttribute(attributeType); } final List<RpslObject> maintainers = objectDao.getByKeys(ObjectType.MNTNER, parentMnts); final List<RpslObject> authenticatedBy = authenticationModule.authenticate(update, updateContext, maintainers); if (authenticatedBy.isEmpty()) { throw new AuthenticationFailedException(UpdateMessages.authenticationFailed(asBlock, attributeType, maintainers), maintainers); } return authenticatedBy; } @Autowired AutnumAuthentication(final RpslObjectDao objectDao, final AuthenticationModule authenticationModule); @Override boolean supports(final PreparedUpdate update); @Override List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext); } |
@Test public void authenticated_by_mntby_succeeds() { when(update.getUpdatedObject()).thenReturn(RpslObject.parse("aut-num: AS3333")); when(objectDao.findAsBlock(3333, 3333)).thenReturn(RpslObject.parse("as-block: AS3209 - AS3353\nmnt-by: TEST-MNT")); final ArrayList<RpslObject> parentMaintainers = Lists.newArrayList(RpslObject.parse("mntner: TEST-MNT")); when(objectDao.getByKeys(eq(ObjectType.MNTNER), anyCollection())).thenReturn(parentMaintainers); when(authenticationModule.authenticate(update, updateContext, parentMaintainers)).thenReturn(parentMaintainers); final List<RpslObject> authenticatedBy = subject.authenticate(update, updateContext); assertThat(authenticatedBy.equals(parentMaintainers), is(true)); verifyZeroInteractions(updateContext); } | @Override public List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext) { final RpslObject object = update.getUpdatedObject(); final CIString pkey = object.getKey(); final long number = Long.parseLong(pkey.toString().substring("AS".length())); final RpslObject asBlock = objectDao.findAsBlock(number, number); if (asBlock == null) { throw new AuthenticationFailedException(UpdateMessages.noParentAsBlockFound(pkey), Collections.<RpslObject>emptyList()); } AttributeType attributeType = AttributeType.MNT_LOWER; Collection<CIString> parentMnts = asBlock.getValuesForAttribute(attributeType); if (parentMnts.isEmpty()) { attributeType = AttributeType.MNT_BY; parentMnts = asBlock.getValuesForAttribute(attributeType); } final List<RpslObject> maintainers = objectDao.getByKeys(ObjectType.MNTNER, parentMnts); final List<RpslObject> authenticatedBy = authenticationModule.authenticate(update, updateContext, maintainers); if (authenticatedBy.isEmpty()) { throw new AuthenticationFailedException(UpdateMessages.authenticationFailed(asBlock, attributeType, maintainers), maintainers); } return authenticatedBy; } | AutnumAuthentication extends AuthenticationStrategyBase { @Override public List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext) { final RpslObject object = update.getUpdatedObject(); final CIString pkey = object.getKey(); final long number = Long.parseLong(pkey.toString().substring("AS".length())); final RpslObject asBlock = objectDao.findAsBlock(number, number); if (asBlock == null) { throw new AuthenticationFailedException(UpdateMessages.noParentAsBlockFound(pkey), Collections.<RpslObject>emptyList()); } AttributeType attributeType = AttributeType.MNT_LOWER; Collection<CIString> parentMnts = asBlock.getValuesForAttribute(attributeType); if (parentMnts.isEmpty()) { attributeType = AttributeType.MNT_BY; parentMnts = asBlock.getValuesForAttribute(attributeType); } final List<RpslObject> maintainers = objectDao.getByKeys(ObjectType.MNTNER, parentMnts); final List<RpslObject> authenticatedBy = authenticationModule.authenticate(update, updateContext, maintainers); if (authenticatedBy.isEmpty()) { throw new AuthenticationFailedException(UpdateMessages.authenticationFailed(asBlock, attributeType, maintainers), maintainers); } return authenticatedBy; } } | AutnumAuthentication extends AuthenticationStrategyBase { @Override public List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext) { final RpslObject object = update.getUpdatedObject(); final CIString pkey = object.getKey(); final long number = Long.parseLong(pkey.toString().substring("AS".length())); final RpslObject asBlock = objectDao.findAsBlock(number, number); if (asBlock == null) { throw new AuthenticationFailedException(UpdateMessages.noParentAsBlockFound(pkey), Collections.<RpslObject>emptyList()); } AttributeType attributeType = AttributeType.MNT_LOWER; Collection<CIString> parentMnts = asBlock.getValuesForAttribute(attributeType); if (parentMnts.isEmpty()) { attributeType = AttributeType.MNT_BY; parentMnts = asBlock.getValuesForAttribute(attributeType); } final List<RpslObject> maintainers = objectDao.getByKeys(ObjectType.MNTNER, parentMnts); final List<RpslObject> authenticatedBy = authenticationModule.authenticate(update, updateContext, maintainers); if (authenticatedBy.isEmpty()) { throw new AuthenticationFailedException(UpdateMessages.authenticationFailed(asBlock, attributeType, maintainers), maintainers); } return authenticatedBy; } @Autowired AutnumAuthentication(final RpslObjectDao objectDao, final AuthenticationModule authenticationModule); } | AutnumAuthentication extends AuthenticationStrategyBase { @Override public List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext) { final RpslObject object = update.getUpdatedObject(); final CIString pkey = object.getKey(); final long number = Long.parseLong(pkey.toString().substring("AS".length())); final RpslObject asBlock = objectDao.findAsBlock(number, number); if (asBlock == null) { throw new AuthenticationFailedException(UpdateMessages.noParentAsBlockFound(pkey), Collections.<RpslObject>emptyList()); } AttributeType attributeType = AttributeType.MNT_LOWER; Collection<CIString> parentMnts = asBlock.getValuesForAttribute(attributeType); if (parentMnts.isEmpty()) { attributeType = AttributeType.MNT_BY; parentMnts = asBlock.getValuesForAttribute(attributeType); } final List<RpslObject> maintainers = objectDao.getByKeys(ObjectType.MNTNER, parentMnts); final List<RpslObject> authenticatedBy = authenticationModule.authenticate(update, updateContext, maintainers); if (authenticatedBy.isEmpty()) { throw new AuthenticationFailedException(UpdateMessages.authenticationFailed(asBlock, attributeType, maintainers), maintainers); } return authenticatedBy; } @Autowired AutnumAuthentication(final RpslObjectDao objectDao, final AuthenticationModule authenticationModule); @Override boolean supports(final PreparedUpdate update); @Override List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext); } | AutnumAuthentication extends AuthenticationStrategyBase { @Override public List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext) { final RpslObject object = update.getUpdatedObject(); final CIString pkey = object.getKey(); final long number = Long.parseLong(pkey.toString().substring("AS".length())); final RpslObject asBlock = objectDao.findAsBlock(number, number); if (asBlock == null) { throw new AuthenticationFailedException(UpdateMessages.noParentAsBlockFound(pkey), Collections.<RpslObject>emptyList()); } AttributeType attributeType = AttributeType.MNT_LOWER; Collection<CIString> parentMnts = asBlock.getValuesForAttribute(attributeType); if (parentMnts.isEmpty()) { attributeType = AttributeType.MNT_BY; parentMnts = asBlock.getValuesForAttribute(attributeType); } final List<RpslObject> maintainers = objectDao.getByKeys(ObjectType.MNTNER, parentMnts); final List<RpslObject> authenticatedBy = authenticationModule.authenticate(update, updateContext, maintainers); if (authenticatedBy.isEmpty()) { throw new AuthenticationFailedException(UpdateMessages.authenticationFailed(asBlock, attributeType, maintainers), maintainers); } return authenticatedBy; } @Autowired AutnumAuthentication(final RpslObjectDao objectDao, final AuthenticationModule authenticationModule); @Override boolean supports(final PreparedUpdate update); @Override List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext); } |
@Test(expected = AuthenticationFailedException.class) public void authenticated_by_mntby_fails() { when(update.getUpdatedObject()).thenReturn(RpslObject.parse("aut-num: AS3333")); when(objectDao.findAsBlock(3333, 3333)).thenReturn(RpslObject.parse("as-block: AS3209 - AS3353\nmnt-by: TEST-MNT")); final ArrayList<RpslObject> parentMaintainers = Lists.newArrayList(RpslObject.parse("mntner: TEST-MNT")); when(objectDao.getByKeys(eq(ObjectType.MNTNER), anyCollection())).thenReturn(parentMaintainers); when(authenticationModule.authenticate(update, updateContext, parentMaintainers)).thenReturn(Lists.<RpslObject>newArrayList()); subject.authenticate(update, updateContext); } | @Override public List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext) { final RpslObject object = update.getUpdatedObject(); final CIString pkey = object.getKey(); final long number = Long.parseLong(pkey.toString().substring("AS".length())); final RpslObject asBlock = objectDao.findAsBlock(number, number); if (asBlock == null) { throw new AuthenticationFailedException(UpdateMessages.noParentAsBlockFound(pkey), Collections.<RpslObject>emptyList()); } AttributeType attributeType = AttributeType.MNT_LOWER; Collection<CIString> parentMnts = asBlock.getValuesForAttribute(attributeType); if (parentMnts.isEmpty()) { attributeType = AttributeType.MNT_BY; parentMnts = asBlock.getValuesForAttribute(attributeType); } final List<RpslObject> maintainers = objectDao.getByKeys(ObjectType.MNTNER, parentMnts); final List<RpslObject> authenticatedBy = authenticationModule.authenticate(update, updateContext, maintainers); if (authenticatedBy.isEmpty()) { throw new AuthenticationFailedException(UpdateMessages.authenticationFailed(asBlock, attributeType, maintainers), maintainers); } return authenticatedBy; } | AutnumAuthentication extends AuthenticationStrategyBase { @Override public List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext) { final RpslObject object = update.getUpdatedObject(); final CIString pkey = object.getKey(); final long number = Long.parseLong(pkey.toString().substring("AS".length())); final RpslObject asBlock = objectDao.findAsBlock(number, number); if (asBlock == null) { throw new AuthenticationFailedException(UpdateMessages.noParentAsBlockFound(pkey), Collections.<RpslObject>emptyList()); } AttributeType attributeType = AttributeType.MNT_LOWER; Collection<CIString> parentMnts = asBlock.getValuesForAttribute(attributeType); if (parentMnts.isEmpty()) { attributeType = AttributeType.MNT_BY; parentMnts = asBlock.getValuesForAttribute(attributeType); } final List<RpslObject> maintainers = objectDao.getByKeys(ObjectType.MNTNER, parentMnts); final List<RpslObject> authenticatedBy = authenticationModule.authenticate(update, updateContext, maintainers); if (authenticatedBy.isEmpty()) { throw new AuthenticationFailedException(UpdateMessages.authenticationFailed(asBlock, attributeType, maintainers), maintainers); } return authenticatedBy; } } | AutnumAuthentication extends AuthenticationStrategyBase { @Override public List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext) { final RpslObject object = update.getUpdatedObject(); final CIString pkey = object.getKey(); final long number = Long.parseLong(pkey.toString().substring("AS".length())); final RpslObject asBlock = objectDao.findAsBlock(number, number); if (asBlock == null) { throw new AuthenticationFailedException(UpdateMessages.noParentAsBlockFound(pkey), Collections.<RpslObject>emptyList()); } AttributeType attributeType = AttributeType.MNT_LOWER; Collection<CIString> parentMnts = asBlock.getValuesForAttribute(attributeType); if (parentMnts.isEmpty()) { attributeType = AttributeType.MNT_BY; parentMnts = asBlock.getValuesForAttribute(attributeType); } final List<RpslObject> maintainers = objectDao.getByKeys(ObjectType.MNTNER, parentMnts); final List<RpslObject> authenticatedBy = authenticationModule.authenticate(update, updateContext, maintainers); if (authenticatedBy.isEmpty()) { throw new AuthenticationFailedException(UpdateMessages.authenticationFailed(asBlock, attributeType, maintainers), maintainers); } return authenticatedBy; } @Autowired AutnumAuthentication(final RpslObjectDao objectDao, final AuthenticationModule authenticationModule); } | AutnumAuthentication extends AuthenticationStrategyBase { @Override public List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext) { final RpslObject object = update.getUpdatedObject(); final CIString pkey = object.getKey(); final long number = Long.parseLong(pkey.toString().substring("AS".length())); final RpslObject asBlock = objectDao.findAsBlock(number, number); if (asBlock == null) { throw new AuthenticationFailedException(UpdateMessages.noParentAsBlockFound(pkey), Collections.<RpslObject>emptyList()); } AttributeType attributeType = AttributeType.MNT_LOWER; Collection<CIString> parentMnts = asBlock.getValuesForAttribute(attributeType); if (parentMnts.isEmpty()) { attributeType = AttributeType.MNT_BY; parentMnts = asBlock.getValuesForAttribute(attributeType); } final List<RpslObject> maintainers = objectDao.getByKeys(ObjectType.MNTNER, parentMnts); final List<RpslObject> authenticatedBy = authenticationModule.authenticate(update, updateContext, maintainers); if (authenticatedBy.isEmpty()) { throw new AuthenticationFailedException(UpdateMessages.authenticationFailed(asBlock, attributeType, maintainers), maintainers); } return authenticatedBy; } @Autowired AutnumAuthentication(final RpslObjectDao objectDao, final AuthenticationModule authenticationModule); @Override boolean supports(final PreparedUpdate update); @Override List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext); } | AutnumAuthentication extends AuthenticationStrategyBase { @Override public List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext) { final RpslObject object = update.getUpdatedObject(); final CIString pkey = object.getKey(); final long number = Long.parseLong(pkey.toString().substring("AS".length())); final RpslObject asBlock = objectDao.findAsBlock(number, number); if (asBlock == null) { throw new AuthenticationFailedException(UpdateMessages.noParentAsBlockFound(pkey), Collections.<RpslObject>emptyList()); } AttributeType attributeType = AttributeType.MNT_LOWER; Collection<CIString> parentMnts = asBlock.getValuesForAttribute(attributeType); if (parentMnts.isEmpty()) { attributeType = AttributeType.MNT_BY; parentMnts = asBlock.getValuesForAttribute(attributeType); } final List<RpslObject> maintainers = objectDao.getByKeys(ObjectType.MNTNER, parentMnts); final List<RpslObject> authenticatedBy = authenticationModule.authenticate(update, updateContext, maintainers); if (authenticatedBy.isEmpty()) { throw new AuthenticationFailedException(UpdateMessages.authenticationFailed(asBlock, attributeType, maintainers), maintainers); } return authenticatedBy; } @Autowired AutnumAuthentication(final RpslObjectDao objectDao, final AuthenticationModule authenticationModule); @Override boolean supports(final PreparedUpdate update); @Override List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext); } |
@Test public void max_value() { final long maxValue = (1L << 32) - 1; final RpslObject autNum = RpslObject.parse("aut-num: AS" + maxValue); final RpslObject asBlock = RpslObject.parse("as-block: AS" + (maxValue - 1) + " - AS" + maxValue + "\nmnt-by: TEST-MNT"); when(update.getUpdatedObject()).thenReturn(autNum); when(objectDao.findAsBlock(maxValue, maxValue)).thenReturn(asBlock); final ArrayList<RpslObject> parentMaintainers = Lists.newArrayList(RpslObject.parse("mntner: TEST-MNT")); when(objectDao.getByKeys(eq(ObjectType.MNTNER), anyCollection())).thenReturn(parentMaintainers); when(authenticationModule.authenticate(update, updateContext, parentMaintainers)).thenReturn(parentMaintainers); subject.authenticate(update, updateContext); verifyZeroInteractions(updateContext); } | @Override public List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext) { final RpslObject object = update.getUpdatedObject(); final CIString pkey = object.getKey(); final long number = Long.parseLong(pkey.toString().substring("AS".length())); final RpslObject asBlock = objectDao.findAsBlock(number, number); if (asBlock == null) { throw new AuthenticationFailedException(UpdateMessages.noParentAsBlockFound(pkey), Collections.<RpslObject>emptyList()); } AttributeType attributeType = AttributeType.MNT_LOWER; Collection<CIString> parentMnts = asBlock.getValuesForAttribute(attributeType); if (parentMnts.isEmpty()) { attributeType = AttributeType.MNT_BY; parentMnts = asBlock.getValuesForAttribute(attributeType); } final List<RpslObject> maintainers = objectDao.getByKeys(ObjectType.MNTNER, parentMnts); final List<RpslObject> authenticatedBy = authenticationModule.authenticate(update, updateContext, maintainers); if (authenticatedBy.isEmpty()) { throw new AuthenticationFailedException(UpdateMessages.authenticationFailed(asBlock, attributeType, maintainers), maintainers); } return authenticatedBy; } | AutnumAuthentication extends AuthenticationStrategyBase { @Override public List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext) { final RpslObject object = update.getUpdatedObject(); final CIString pkey = object.getKey(); final long number = Long.parseLong(pkey.toString().substring("AS".length())); final RpslObject asBlock = objectDao.findAsBlock(number, number); if (asBlock == null) { throw new AuthenticationFailedException(UpdateMessages.noParentAsBlockFound(pkey), Collections.<RpslObject>emptyList()); } AttributeType attributeType = AttributeType.MNT_LOWER; Collection<CIString> parentMnts = asBlock.getValuesForAttribute(attributeType); if (parentMnts.isEmpty()) { attributeType = AttributeType.MNT_BY; parentMnts = asBlock.getValuesForAttribute(attributeType); } final List<RpslObject> maintainers = objectDao.getByKeys(ObjectType.MNTNER, parentMnts); final List<RpslObject> authenticatedBy = authenticationModule.authenticate(update, updateContext, maintainers); if (authenticatedBy.isEmpty()) { throw new AuthenticationFailedException(UpdateMessages.authenticationFailed(asBlock, attributeType, maintainers), maintainers); } return authenticatedBy; } } | AutnumAuthentication extends AuthenticationStrategyBase { @Override public List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext) { final RpslObject object = update.getUpdatedObject(); final CIString pkey = object.getKey(); final long number = Long.parseLong(pkey.toString().substring("AS".length())); final RpslObject asBlock = objectDao.findAsBlock(number, number); if (asBlock == null) { throw new AuthenticationFailedException(UpdateMessages.noParentAsBlockFound(pkey), Collections.<RpslObject>emptyList()); } AttributeType attributeType = AttributeType.MNT_LOWER; Collection<CIString> parentMnts = asBlock.getValuesForAttribute(attributeType); if (parentMnts.isEmpty()) { attributeType = AttributeType.MNT_BY; parentMnts = asBlock.getValuesForAttribute(attributeType); } final List<RpslObject> maintainers = objectDao.getByKeys(ObjectType.MNTNER, parentMnts); final List<RpslObject> authenticatedBy = authenticationModule.authenticate(update, updateContext, maintainers); if (authenticatedBy.isEmpty()) { throw new AuthenticationFailedException(UpdateMessages.authenticationFailed(asBlock, attributeType, maintainers), maintainers); } return authenticatedBy; } @Autowired AutnumAuthentication(final RpslObjectDao objectDao, final AuthenticationModule authenticationModule); } | AutnumAuthentication extends AuthenticationStrategyBase { @Override public List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext) { final RpslObject object = update.getUpdatedObject(); final CIString pkey = object.getKey(); final long number = Long.parseLong(pkey.toString().substring("AS".length())); final RpslObject asBlock = objectDao.findAsBlock(number, number); if (asBlock == null) { throw new AuthenticationFailedException(UpdateMessages.noParentAsBlockFound(pkey), Collections.<RpslObject>emptyList()); } AttributeType attributeType = AttributeType.MNT_LOWER; Collection<CIString> parentMnts = asBlock.getValuesForAttribute(attributeType); if (parentMnts.isEmpty()) { attributeType = AttributeType.MNT_BY; parentMnts = asBlock.getValuesForAttribute(attributeType); } final List<RpslObject> maintainers = objectDao.getByKeys(ObjectType.MNTNER, parentMnts); final List<RpslObject> authenticatedBy = authenticationModule.authenticate(update, updateContext, maintainers); if (authenticatedBy.isEmpty()) { throw new AuthenticationFailedException(UpdateMessages.authenticationFailed(asBlock, attributeType, maintainers), maintainers); } return authenticatedBy; } @Autowired AutnumAuthentication(final RpslObjectDao objectDao, final AuthenticationModule authenticationModule); @Override boolean supports(final PreparedUpdate update); @Override List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext); } | AutnumAuthentication extends AuthenticationStrategyBase { @Override public List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext) { final RpslObject object = update.getUpdatedObject(); final CIString pkey = object.getKey(); final long number = Long.parseLong(pkey.toString().substring("AS".length())); final RpslObject asBlock = objectDao.findAsBlock(number, number); if (asBlock == null) { throw new AuthenticationFailedException(UpdateMessages.noParentAsBlockFound(pkey), Collections.<RpslObject>emptyList()); } AttributeType attributeType = AttributeType.MNT_LOWER; Collection<CIString> parentMnts = asBlock.getValuesForAttribute(attributeType); if (parentMnts.isEmpty()) { attributeType = AttributeType.MNT_BY; parentMnts = asBlock.getValuesForAttribute(attributeType); } final List<RpslObject> maintainers = objectDao.getByKeys(ObjectType.MNTNER, parentMnts); final List<RpslObject> authenticatedBy = authenticationModule.authenticate(update, updateContext, maintainers); if (authenticatedBy.isEmpty()) { throw new AuthenticationFailedException(UpdateMessages.authenticationFailed(asBlock, attributeType, maintainers), maintainers); } return authenticatedBy; } @Autowired AutnumAuthentication(final RpslObjectDao objectDao, final AuthenticationModule authenticationModule); @Override boolean supports(final PreparedUpdate update); @Override List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext); } |
@Test public void operates_on_updates_with_new_mntirts() { when(update.getNewValues(AttributeType.MNT_IRT)).thenReturn(ciSet("IRT-MNT")); assertThat(subject.supports(update), is(true)); } | @Override public boolean supports(final PreparedUpdate update) { return !update.getNewValues(AttributeType.MNT_IRT).isEmpty(); } | MntIrtAuthentication extends AuthenticationStrategyBase { @Override public boolean supports(final PreparedUpdate update) { return !update.getNewValues(AttributeType.MNT_IRT).isEmpty(); } } | MntIrtAuthentication extends AuthenticationStrategyBase { @Override public boolean supports(final PreparedUpdate update) { return !update.getNewValues(AttributeType.MNT_IRT).isEmpty(); } @Autowired MntIrtAuthentication(final AuthenticationModule credentialValidators, final RpslObjectDao rpslObjectDao); } | MntIrtAuthentication extends AuthenticationStrategyBase { @Override public boolean supports(final PreparedUpdate update) { return !update.getNewValues(AttributeType.MNT_IRT).isEmpty(); } @Autowired MntIrtAuthentication(final AuthenticationModule credentialValidators, final RpslObjectDao rpslObjectDao); @Override boolean supports(final PreparedUpdate update); @Override List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext); } | MntIrtAuthentication extends AuthenticationStrategyBase { @Override public boolean supports(final PreparedUpdate update) { return !update.getNewValues(AttributeType.MNT_IRT).isEmpty(); } @Autowired MntIrtAuthentication(final AuthenticationModule credentialValidators, final RpslObjectDao rpslObjectDao); @Override boolean supports(final PreparedUpdate update); @Override List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext); } |
@Test public void does_not_support_updates_with_same_mntirts() { when(update.getNewValues(AttributeType.MNT_IRT)).thenReturn(Sets.<CIString>newHashSet()); assertThat(subject.supports(update), is(false)); } | @Override public boolean supports(final PreparedUpdate update) { return !update.getNewValues(AttributeType.MNT_IRT).isEmpty(); } | MntIrtAuthentication extends AuthenticationStrategyBase { @Override public boolean supports(final PreparedUpdate update) { return !update.getNewValues(AttributeType.MNT_IRT).isEmpty(); } } | MntIrtAuthentication extends AuthenticationStrategyBase { @Override public boolean supports(final PreparedUpdate update) { return !update.getNewValues(AttributeType.MNT_IRT).isEmpty(); } @Autowired MntIrtAuthentication(final AuthenticationModule credentialValidators, final RpslObjectDao rpslObjectDao); } | MntIrtAuthentication extends AuthenticationStrategyBase { @Override public boolean supports(final PreparedUpdate update) { return !update.getNewValues(AttributeType.MNT_IRT).isEmpty(); } @Autowired MntIrtAuthentication(final AuthenticationModule credentialValidators, final RpslObjectDao rpslObjectDao); @Override boolean supports(final PreparedUpdate update); @Override List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext); } | MntIrtAuthentication extends AuthenticationStrategyBase { @Override public boolean supports(final PreparedUpdate update) { return !update.getNewValues(AttributeType.MNT_IRT).isEmpty(); } @Autowired MntIrtAuthentication(final AuthenticationModule credentialValidators, final RpslObjectDao rpslObjectDao); @Override boolean supports(final PreparedUpdate update); @Override List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext); } |
@Test public void authentication_succeeds() { when(update.getType()).thenReturn(ObjectType.INETNUM); when(update.getNewValues(AttributeType.MNT_IRT)).thenReturn(ciSet("IRT-MNT")); when(update.getReferenceObject()).thenReturn(RpslObject.parse("inetnum: 192.0/24")); when(update.getUpdatedObject()).thenReturn(RpslObject.parse("inetnum: 192.0/24\nmnt-irt: IRT-MNT")); final RpslObject irt = RpslObject.parse("irt: IRT-MNT"); final ArrayList<RpslObject> irts = Lists.newArrayList(irt); when(rpslObjectDao.getByKeys(ObjectType.IRT, ciSet("IRT-MNT"))).thenReturn(irts); when(credentialValidators.authenticate(eq(update), eq(updateContext), anyCollection())).thenReturn(irts); final List<RpslObject> result = subject.authenticate(update, updateContext); assertThat(result.size(), is(1)); assertThat(result.get(0), is(irt)); verifyZeroInteractions(updateContext); } | @Override public List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext) { final Collection<CIString> keys = update.getNewValues(AttributeType.MNT_IRT); final List<RpslObject> candidates = rpslObjectDao.getByKeys(ObjectType.IRT, keys); if (isSelfReference(update, keys)) { candidates.add(update.getUpdatedObject()); } final List<RpslObject> authenticatedBy = credentialValidators.authenticate(update, updateContext, candidates); if (authenticatedBy.isEmpty()) { throw new AuthenticationFailedException(UpdateMessages.authenticationFailed(update.getReferenceObject(), AttributeType.MNT_IRT, candidates), candidates); } return authenticatedBy; } | MntIrtAuthentication extends AuthenticationStrategyBase { @Override public List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext) { final Collection<CIString> keys = update.getNewValues(AttributeType.MNT_IRT); final List<RpslObject> candidates = rpslObjectDao.getByKeys(ObjectType.IRT, keys); if (isSelfReference(update, keys)) { candidates.add(update.getUpdatedObject()); } final List<RpslObject> authenticatedBy = credentialValidators.authenticate(update, updateContext, candidates); if (authenticatedBy.isEmpty()) { throw new AuthenticationFailedException(UpdateMessages.authenticationFailed(update.getReferenceObject(), AttributeType.MNT_IRT, candidates), candidates); } return authenticatedBy; } } | MntIrtAuthentication extends AuthenticationStrategyBase { @Override public List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext) { final Collection<CIString> keys = update.getNewValues(AttributeType.MNT_IRT); final List<RpslObject> candidates = rpslObjectDao.getByKeys(ObjectType.IRT, keys); if (isSelfReference(update, keys)) { candidates.add(update.getUpdatedObject()); } final List<RpslObject> authenticatedBy = credentialValidators.authenticate(update, updateContext, candidates); if (authenticatedBy.isEmpty()) { throw new AuthenticationFailedException(UpdateMessages.authenticationFailed(update.getReferenceObject(), AttributeType.MNT_IRT, candidates), candidates); } return authenticatedBy; } @Autowired MntIrtAuthentication(final AuthenticationModule credentialValidators, final RpslObjectDao rpslObjectDao); } | MntIrtAuthentication extends AuthenticationStrategyBase { @Override public List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext) { final Collection<CIString> keys = update.getNewValues(AttributeType.MNT_IRT); final List<RpslObject> candidates = rpslObjectDao.getByKeys(ObjectType.IRT, keys); if (isSelfReference(update, keys)) { candidates.add(update.getUpdatedObject()); } final List<RpslObject> authenticatedBy = credentialValidators.authenticate(update, updateContext, candidates); if (authenticatedBy.isEmpty()) { throw new AuthenticationFailedException(UpdateMessages.authenticationFailed(update.getReferenceObject(), AttributeType.MNT_IRT, candidates), candidates); } return authenticatedBy; } @Autowired MntIrtAuthentication(final AuthenticationModule credentialValidators, final RpslObjectDao rpslObjectDao); @Override boolean supports(final PreparedUpdate update); @Override List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext); } | MntIrtAuthentication extends AuthenticationStrategyBase { @Override public List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext) { final Collection<CIString> keys = update.getNewValues(AttributeType.MNT_IRT); final List<RpslObject> candidates = rpslObjectDao.getByKeys(ObjectType.IRT, keys); if (isSelfReference(update, keys)) { candidates.add(update.getUpdatedObject()); } final List<RpslObject> authenticatedBy = credentialValidators.authenticate(update, updateContext, candidates); if (authenticatedBy.isEmpty()) { throw new AuthenticationFailedException(UpdateMessages.authenticationFailed(update.getReferenceObject(), AttributeType.MNT_IRT, candidates), candidates); } return authenticatedBy; } @Autowired MntIrtAuthentication(final AuthenticationModule credentialValidators, final RpslObjectDao rpslObjectDao); @Override boolean supports(final PreparedUpdate update); @Override List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext); } |
@Test(expected = AuthenticationFailedException.class) public void authentication_fails() { when(update.getType()).thenReturn(ObjectType.INETNUM); when(update.getReferenceObject()).thenReturn(RpslObject.parse("inetnum: 192.0/24\nmnt-irt: IRT-MNT")); final RpslObject irt = RpslObject.parse("irt: IRT-MNT"); final ArrayList<RpslObject> irts = Lists.newArrayList(irt); when(rpslObjectDao.getByKeys(ObjectType.IRT, ciSet("IRT-MNT"))).thenReturn(irts); when(credentialValidators.authenticate(eq(update), eq(updateContext), anyCollection())).thenReturn(Lists.<RpslObject>newArrayList()); subject.authenticate(update, updateContext); } | @Override public List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext) { final Collection<CIString> keys = update.getNewValues(AttributeType.MNT_IRT); final List<RpslObject> candidates = rpslObjectDao.getByKeys(ObjectType.IRT, keys); if (isSelfReference(update, keys)) { candidates.add(update.getUpdatedObject()); } final List<RpslObject> authenticatedBy = credentialValidators.authenticate(update, updateContext, candidates); if (authenticatedBy.isEmpty()) { throw new AuthenticationFailedException(UpdateMessages.authenticationFailed(update.getReferenceObject(), AttributeType.MNT_IRT, candidates), candidates); } return authenticatedBy; } | MntIrtAuthentication extends AuthenticationStrategyBase { @Override public List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext) { final Collection<CIString> keys = update.getNewValues(AttributeType.MNT_IRT); final List<RpslObject> candidates = rpslObjectDao.getByKeys(ObjectType.IRT, keys); if (isSelfReference(update, keys)) { candidates.add(update.getUpdatedObject()); } final List<RpslObject> authenticatedBy = credentialValidators.authenticate(update, updateContext, candidates); if (authenticatedBy.isEmpty()) { throw new AuthenticationFailedException(UpdateMessages.authenticationFailed(update.getReferenceObject(), AttributeType.MNT_IRT, candidates), candidates); } return authenticatedBy; } } | MntIrtAuthentication extends AuthenticationStrategyBase { @Override public List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext) { final Collection<CIString> keys = update.getNewValues(AttributeType.MNT_IRT); final List<RpslObject> candidates = rpslObjectDao.getByKeys(ObjectType.IRT, keys); if (isSelfReference(update, keys)) { candidates.add(update.getUpdatedObject()); } final List<RpslObject> authenticatedBy = credentialValidators.authenticate(update, updateContext, candidates); if (authenticatedBy.isEmpty()) { throw new AuthenticationFailedException(UpdateMessages.authenticationFailed(update.getReferenceObject(), AttributeType.MNT_IRT, candidates), candidates); } return authenticatedBy; } @Autowired MntIrtAuthentication(final AuthenticationModule credentialValidators, final RpslObjectDao rpslObjectDao); } | MntIrtAuthentication extends AuthenticationStrategyBase { @Override public List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext) { final Collection<CIString> keys = update.getNewValues(AttributeType.MNT_IRT); final List<RpslObject> candidates = rpslObjectDao.getByKeys(ObjectType.IRT, keys); if (isSelfReference(update, keys)) { candidates.add(update.getUpdatedObject()); } final List<RpslObject> authenticatedBy = credentialValidators.authenticate(update, updateContext, candidates); if (authenticatedBy.isEmpty()) { throw new AuthenticationFailedException(UpdateMessages.authenticationFailed(update.getReferenceObject(), AttributeType.MNT_IRT, candidates), candidates); } return authenticatedBy; } @Autowired MntIrtAuthentication(final AuthenticationModule credentialValidators, final RpslObjectDao rpslObjectDao); @Override boolean supports(final PreparedUpdate update); @Override List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext); } | MntIrtAuthentication extends AuthenticationStrategyBase { @Override public List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext) { final Collection<CIString> keys = update.getNewValues(AttributeType.MNT_IRT); final List<RpslObject> candidates = rpslObjectDao.getByKeys(ObjectType.IRT, keys); if (isSelfReference(update, keys)) { candidates.add(update.getUpdatedObject()); } final List<RpslObject> authenticatedBy = credentialValidators.authenticate(update, updateContext, candidates); if (authenticatedBy.isEmpty()) { throw new AuthenticationFailedException(UpdateMessages.authenticationFailed(update.getReferenceObject(), AttributeType.MNT_IRT, candidates), candidates); } return authenticatedBy; } @Autowired MntIrtAuthentication(final AuthenticationModule credentialValidators, final RpslObjectDao rpslObjectDao); @Override boolean supports(final PreparedUpdate update); @Override List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext); } |
@Test public void supports_every_object_with_a_mntby_attribute() { when(update.getType()).thenReturn(ObjectType.POEM); assertThat(subject.supports(update), is(true)); when(update.getType()).thenReturn(ObjectType.INETNUM); assertThat(subject.supports(update), is(true)); verifyZeroInteractions(maintainers); } | @Override public boolean supports(final PreparedUpdate update) { return ObjectTemplate.getTemplate(update.getType()).hasAttribute(AttributeType.MNT_BY); } | MntByAuthentication extends AuthenticationStrategyBase { @Override public boolean supports(final PreparedUpdate update) { return ObjectTemplate.getTemplate(update.getType()).hasAttribute(AttributeType.MNT_BY); } } | MntByAuthentication extends AuthenticationStrategyBase { @Override public boolean supports(final PreparedUpdate update) { return ObjectTemplate.getTemplate(update.getType()).hasAttribute(AttributeType.MNT_BY); } @Autowired MntByAuthentication(final Maintainers maintainers,
final AuthenticationModule authenticationModule,
final RpslObjectDao rpslObjectDao,
final SsoTranslator ssoTranslator,
final Ipv4Tree ipv4Tree,
final Ipv6Tree ipv6Tree); } | MntByAuthentication extends AuthenticationStrategyBase { @Override public boolean supports(final PreparedUpdate update) { return ObjectTemplate.getTemplate(update.getType()).hasAttribute(AttributeType.MNT_BY); } @Autowired MntByAuthentication(final Maintainers maintainers,
final AuthenticationModule authenticationModule,
final RpslObjectDao rpslObjectDao,
final SsoTranslator ssoTranslator,
final Ipv4Tree ipv4Tree,
final Ipv6Tree ipv6Tree); @Override boolean supports(final PreparedUpdate update); @Override List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext); } | MntByAuthentication extends AuthenticationStrategyBase { @Override public boolean supports(final PreparedUpdate update) { return ObjectTemplate.getTemplate(update.getType()).hasAttribute(AttributeType.MNT_BY); } @Autowired MntByAuthentication(final Maintainers maintainers,
final AuthenticationModule authenticationModule,
final RpslObjectDao rpslObjectDao,
final SsoTranslator ssoTranslator,
final Ipv4Tree ipv4Tree,
final Ipv6Tree ipv6Tree); @Override boolean supports(final PreparedUpdate update); @Override List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext); } |
@Test public void transform_domain_with_trailing_dot() { final RpslObject rpslObject = RpslObject.parse("domain: 17.45.212.in-addr.arpa."); final RpslObject result = attributeSanitizer.sanitize(rpslObject, objectMessages); assertThat(result.getKey().toString(), is("17.45.212.in-addr.arpa")); assertThat(result.getValueForAttribute(AttributeType.DOMAIN).toString(), is("17.45.212.in-addr.arpa")); verify(objectMessages).addMessage(result.getTypeAttribute(), ValidationMessages.attributeValueConverted("17.45.212.in-addr.arpa.", "17.45.212.in-addr.arpa")); verifyNoMoreInteractions(objectMessages); } | public RpslObject sanitize(final RpslObject object, final ObjectMessages objectMessages) { final Map<RpslAttribute, RpslAttribute> replacements = Maps.newHashMap(); for (final RpslAttribute attribute : object.getAttributes()) { final AttributeType type = attribute.getType(); String newValue = null; final Sanitizer sanitizer = SANITIZER_MAP.get(type); if (sanitizer == null) { continue; } try { newValue = sanitizer.sanitize(attribute); } catch (IllegalArgumentException ignored) { LOGGER.debug("{}: {}", ignored.getClass().getName(), ignored.getMessage()); } if (newValue == null) { continue; } final List<Message> attributeMessages = Lists.newArrayList(); if (!sanitizer.silent() && !attribute.getCleanValue().toString().equals(newValue)) { attributeMessages.add(ValidationMessages.attributeValueConverted(attribute.getCleanValue(), newValue)); } if (keyAttributes.contains(type) && attribute.getValue().indexOf('\n') != -1) { attributeMessages.add(ValidationMessages.continuationLinesRemoved()); } if (keyAttributes.contains(type) && attribute.getValue().indexOf('#') != -1) { attributeMessages.add(ValidationMessages.remarksReformatted()); } final String replacement = newValue + getCommentReplacement(attribute); final RpslAttribute transformed = new RpslAttribute(attribute.getKey(), replacement); replacements.put(attribute, transformed); for (final Message attributeMessage : attributeMessages) { objectMessages.addMessage(transformed, attributeMessage); } } return new RpslObjectBuilder(object).replaceAttributes(replacements).get(); } | AttributeSanitizer { public RpslObject sanitize(final RpslObject object, final ObjectMessages objectMessages) { final Map<RpslAttribute, RpslAttribute> replacements = Maps.newHashMap(); for (final RpslAttribute attribute : object.getAttributes()) { final AttributeType type = attribute.getType(); String newValue = null; final Sanitizer sanitizer = SANITIZER_MAP.get(type); if (sanitizer == null) { continue; } try { newValue = sanitizer.sanitize(attribute); } catch (IllegalArgumentException ignored) { LOGGER.debug("{}: {}", ignored.getClass().getName(), ignored.getMessage()); } if (newValue == null) { continue; } final List<Message> attributeMessages = Lists.newArrayList(); if (!sanitizer.silent() && !attribute.getCleanValue().toString().equals(newValue)) { attributeMessages.add(ValidationMessages.attributeValueConverted(attribute.getCleanValue(), newValue)); } if (keyAttributes.contains(type) && attribute.getValue().indexOf('\n') != -1) { attributeMessages.add(ValidationMessages.continuationLinesRemoved()); } if (keyAttributes.contains(type) && attribute.getValue().indexOf('#') != -1) { attributeMessages.add(ValidationMessages.remarksReformatted()); } final String replacement = newValue + getCommentReplacement(attribute); final RpslAttribute transformed = new RpslAttribute(attribute.getKey(), replacement); replacements.put(attribute, transformed); for (final Message attributeMessage : attributeMessages) { objectMessages.addMessage(transformed, attributeMessage); } } return new RpslObjectBuilder(object).replaceAttributes(replacements).get(); } } | AttributeSanitizer { public RpslObject sanitize(final RpslObject object, final ObjectMessages objectMessages) { final Map<RpslAttribute, RpslAttribute> replacements = Maps.newHashMap(); for (final RpslAttribute attribute : object.getAttributes()) { final AttributeType type = attribute.getType(); String newValue = null; final Sanitizer sanitizer = SANITIZER_MAP.get(type); if (sanitizer == null) { continue; } try { newValue = sanitizer.sanitize(attribute); } catch (IllegalArgumentException ignored) { LOGGER.debug("{}: {}", ignored.getClass().getName(), ignored.getMessage()); } if (newValue == null) { continue; } final List<Message> attributeMessages = Lists.newArrayList(); if (!sanitizer.silent() && !attribute.getCleanValue().toString().equals(newValue)) { attributeMessages.add(ValidationMessages.attributeValueConverted(attribute.getCleanValue(), newValue)); } if (keyAttributes.contains(type) && attribute.getValue().indexOf('\n') != -1) { attributeMessages.add(ValidationMessages.continuationLinesRemoved()); } if (keyAttributes.contains(type) && attribute.getValue().indexOf('#') != -1) { attributeMessages.add(ValidationMessages.remarksReformatted()); } final String replacement = newValue + getCommentReplacement(attribute); final RpslAttribute transformed = new RpslAttribute(attribute.getKey(), replacement); replacements.put(attribute, transformed); for (final Message attributeMessage : attributeMessages) { objectMessages.addMessage(transformed, attributeMessage); } } return new RpslObjectBuilder(object).replaceAttributes(replacements).get(); } @Autowired AttributeSanitizer(DateTimeProvider dateTimeProvider); } | AttributeSanitizer { public RpslObject sanitize(final RpslObject object, final ObjectMessages objectMessages) { final Map<RpslAttribute, RpslAttribute> replacements = Maps.newHashMap(); for (final RpslAttribute attribute : object.getAttributes()) { final AttributeType type = attribute.getType(); String newValue = null; final Sanitizer sanitizer = SANITIZER_MAP.get(type); if (sanitizer == null) { continue; } try { newValue = sanitizer.sanitize(attribute); } catch (IllegalArgumentException ignored) { LOGGER.debug("{}: {}", ignored.getClass().getName(), ignored.getMessage()); } if (newValue == null) { continue; } final List<Message> attributeMessages = Lists.newArrayList(); if (!sanitizer.silent() && !attribute.getCleanValue().toString().equals(newValue)) { attributeMessages.add(ValidationMessages.attributeValueConverted(attribute.getCleanValue(), newValue)); } if (keyAttributes.contains(type) && attribute.getValue().indexOf('\n') != -1) { attributeMessages.add(ValidationMessages.continuationLinesRemoved()); } if (keyAttributes.contains(type) && attribute.getValue().indexOf('#') != -1) { attributeMessages.add(ValidationMessages.remarksReformatted()); } final String replacement = newValue + getCommentReplacement(attribute); final RpslAttribute transformed = new RpslAttribute(attribute.getKey(), replacement); replacements.put(attribute, transformed); for (final Message attributeMessage : attributeMessages) { objectMessages.addMessage(transformed, attributeMessage); } } return new RpslObjectBuilder(object).replaceAttributes(replacements).get(); } @Autowired AttributeSanitizer(DateTimeProvider dateTimeProvider); CIString sanitizeKey(final RpslObject originalObject); RpslObject sanitize(final RpslObject object, final ObjectMessages objectMessages); } | AttributeSanitizer { public RpslObject sanitize(final RpslObject object, final ObjectMessages objectMessages) { final Map<RpslAttribute, RpslAttribute> replacements = Maps.newHashMap(); for (final RpslAttribute attribute : object.getAttributes()) { final AttributeType type = attribute.getType(); String newValue = null; final Sanitizer sanitizer = SANITIZER_MAP.get(type); if (sanitizer == null) { continue; } try { newValue = sanitizer.sanitize(attribute); } catch (IllegalArgumentException ignored) { LOGGER.debug("{}: {}", ignored.getClass().getName(), ignored.getMessage()); } if (newValue == null) { continue; } final List<Message> attributeMessages = Lists.newArrayList(); if (!sanitizer.silent() && !attribute.getCleanValue().toString().equals(newValue)) { attributeMessages.add(ValidationMessages.attributeValueConverted(attribute.getCleanValue(), newValue)); } if (keyAttributes.contains(type) && attribute.getValue().indexOf('\n') != -1) { attributeMessages.add(ValidationMessages.continuationLinesRemoved()); } if (keyAttributes.contains(type) && attribute.getValue().indexOf('#') != -1) { attributeMessages.add(ValidationMessages.remarksReformatted()); } final String replacement = newValue + getCommentReplacement(attribute); final RpslAttribute transformed = new RpslAttribute(attribute.getKey(), replacement); replacements.put(attribute, transformed); for (final Message attributeMessage : attributeMessages) { objectMessages.addMessage(transformed, attributeMessage); } } return new RpslObjectBuilder(object).replaceAttributes(replacements).get(); } @Autowired AttributeSanitizer(DateTimeProvider dateTimeProvider); CIString sanitizeKey(final RpslObject originalObject); RpslObject sanitize(final RpslObject object, final ObjectMessages objectMessages); } |
@Test public void authenticate_succeeds() { final RpslObject org = RpslObject.parse("organisation: ORG1\nmnt-by: TEST-MNT"); when(update.getReferenceObject()).thenReturn(org); when(update.getType()).thenReturn(ObjectType.ORGANISATION); when(update.getUpdatedObject()).thenReturn(RpslObject.parse("organisation: ORG1\nmnt-by: TEST-MNT\nnotify: TEST-MNT")); final RpslObject maintainer = RpslObject.parse("mntner: TEST-MNT"); final ArrayList<RpslObject> candidates = Lists.newArrayList(maintainer); when(rpslObjectDao.getByKeys(ObjectType.MNTNER, org.getValuesForAttribute(AttributeType.MNT_BY))).thenReturn(candidates); when(credentialValidators.authenticate(update, updateContext, candidates)).thenReturn(candidates); final List<RpslObject> result = subject.authenticate(update, updateContext); assertThat(result.size(), is(1)); assertThat(result.get(0), is(maintainer)); verifyZeroInteractions(updateContext); verifyZeroInteractions(maintainers); } | @Override public List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext) { try { return authenticateMntBy(update, updateContext); } catch (AuthenticationFailedException e) { return authenticateByAddressSpaceHolder(update, updateContext, e); } } | MntByAuthentication extends AuthenticationStrategyBase { @Override public List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext) { try { return authenticateMntBy(update, updateContext); } catch (AuthenticationFailedException e) { return authenticateByAddressSpaceHolder(update, updateContext, e); } } } | MntByAuthentication extends AuthenticationStrategyBase { @Override public List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext) { try { return authenticateMntBy(update, updateContext); } catch (AuthenticationFailedException e) { return authenticateByAddressSpaceHolder(update, updateContext, e); } } @Autowired MntByAuthentication(final Maintainers maintainers,
final AuthenticationModule authenticationModule,
final RpslObjectDao rpslObjectDao,
final SsoTranslator ssoTranslator,
final Ipv4Tree ipv4Tree,
final Ipv6Tree ipv6Tree); } | MntByAuthentication extends AuthenticationStrategyBase { @Override public List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext) { try { return authenticateMntBy(update, updateContext); } catch (AuthenticationFailedException e) { return authenticateByAddressSpaceHolder(update, updateContext, e); } } @Autowired MntByAuthentication(final Maintainers maintainers,
final AuthenticationModule authenticationModule,
final RpslObjectDao rpslObjectDao,
final SsoTranslator ssoTranslator,
final Ipv4Tree ipv4Tree,
final Ipv6Tree ipv6Tree); @Override boolean supports(final PreparedUpdate update); @Override List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext); } | MntByAuthentication extends AuthenticationStrategyBase { @Override public List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext) { try { return authenticateMntBy(update, updateContext); } catch (AuthenticationFailedException e) { return authenticateByAddressSpaceHolder(update, updateContext, e); } } @Autowired MntByAuthentication(final Maintainers maintainers,
final AuthenticationModule authenticationModule,
final RpslObjectDao rpslObjectDao,
final SsoTranslator ssoTranslator,
final Ipv4Tree ipv4Tree,
final Ipv6Tree ipv6Tree); @Override boolean supports(final PreparedUpdate update); @Override List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext); } |
@Test(expected = AuthenticationFailedException.class) public void authenticate_fails() { final RpslObject person = RpslObject.parse("person: Some One\nnic-hdl: TEST-NIC\nmnt-by: TEST-MNT"); when(update.getAction()).thenReturn(Action.MODIFY); when(update.getReferenceObject()).thenReturn(person); when(update.getType()).thenReturn(person.getType()); when(update.getUpdatedObject()).thenReturn(person); final RpslObject maintainer = RpslObject.parse("mntner: TEST-MNT"); final ArrayList<RpslObject> candidates = Lists.newArrayList(maintainer); when(rpslObjectDao.getByKeys(ObjectType.MNTNER, person.getValuesForAttribute(AttributeType.MNT_BY))).thenReturn(candidates); when(credentialValidators.authenticate(update, updateContext, candidates)).thenReturn(Lists.<RpslObject>newArrayList()); subject.authenticate(update, updateContext); verify(maintainers).isRsMaintainer(ciSet("RS-MNT")); verifyNoMoreInteractions(maintainers); } | @Override public List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext) { try { return authenticateMntBy(update, updateContext); } catch (AuthenticationFailedException e) { return authenticateByAddressSpaceHolder(update, updateContext, e); } } | MntByAuthentication extends AuthenticationStrategyBase { @Override public List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext) { try { return authenticateMntBy(update, updateContext); } catch (AuthenticationFailedException e) { return authenticateByAddressSpaceHolder(update, updateContext, e); } } } | MntByAuthentication extends AuthenticationStrategyBase { @Override public List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext) { try { return authenticateMntBy(update, updateContext); } catch (AuthenticationFailedException e) { return authenticateByAddressSpaceHolder(update, updateContext, e); } } @Autowired MntByAuthentication(final Maintainers maintainers,
final AuthenticationModule authenticationModule,
final RpslObjectDao rpslObjectDao,
final SsoTranslator ssoTranslator,
final Ipv4Tree ipv4Tree,
final Ipv6Tree ipv6Tree); } | MntByAuthentication extends AuthenticationStrategyBase { @Override public List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext) { try { return authenticateMntBy(update, updateContext); } catch (AuthenticationFailedException e) { return authenticateByAddressSpaceHolder(update, updateContext, e); } } @Autowired MntByAuthentication(final Maintainers maintainers,
final AuthenticationModule authenticationModule,
final RpslObjectDao rpslObjectDao,
final SsoTranslator ssoTranslator,
final Ipv4Tree ipv4Tree,
final Ipv6Tree ipv6Tree); @Override boolean supports(final PreparedUpdate update); @Override List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext); } | MntByAuthentication extends AuthenticationStrategyBase { @Override public List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext) { try { return authenticateMntBy(update, updateContext); } catch (AuthenticationFailedException e) { return authenticateByAddressSpaceHolder(update, updateContext, e); } } @Autowired MntByAuthentication(final Maintainers maintainers,
final AuthenticationModule authenticationModule,
final RpslObjectDao rpslObjectDao,
final SsoTranslator ssoTranslator,
final Ipv4Tree ipv4Tree,
final Ipv6Tree ipv6Tree); @Override boolean supports(final PreparedUpdate update); @Override List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext); } |
@Test public void authenticate_create_self_reference_succeeds() { final RpslObject mntner = RpslObject.parse("mntner: TEST-MNT\nmnt-by: TEST-MNT"); when(update.getType()).thenReturn(mntner.getType()); when(update.getReferenceObject()).thenReturn(mntner); when(update.getUpdatedObject()).thenReturn(mntner); when(update.getAction()).thenReturn(Action.CREATE); final ArrayList<RpslObject> candidates = Lists.newArrayList(mntner); when(rpslObjectDao.getByKeys(ObjectType.MNTNER, mntner.getValuesForAttribute(AttributeType.MNT_BY))).thenReturn(Lists.<RpslObject>newArrayList()); when(credentialValidators.authenticate(update, updateContext, candidates)).thenReturn(candidates); when(ssoTranslator.translateFromCacheAuthToUuid(updateContext, mntner)).thenReturn(mntner); final List<RpslObject> result = subject.authenticate(update, updateContext); assertThat(result.size(), is(1)); assertThat(result.get(0), is(mntner)); verifyZeroInteractions(updateContext); verifyZeroInteractions(maintainers); } | @Override public List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext) { try { return authenticateMntBy(update, updateContext); } catch (AuthenticationFailedException e) { return authenticateByAddressSpaceHolder(update, updateContext, e); } } | MntByAuthentication extends AuthenticationStrategyBase { @Override public List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext) { try { return authenticateMntBy(update, updateContext); } catch (AuthenticationFailedException e) { return authenticateByAddressSpaceHolder(update, updateContext, e); } } } | MntByAuthentication extends AuthenticationStrategyBase { @Override public List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext) { try { return authenticateMntBy(update, updateContext); } catch (AuthenticationFailedException e) { return authenticateByAddressSpaceHolder(update, updateContext, e); } } @Autowired MntByAuthentication(final Maintainers maintainers,
final AuthenticationModule authenticationModule,
final RpslObjectDao rpslObjectDao,
final SsoTranslator ssoTranslator,
final Ipv4Tree ipv4Tree,
final Ipv6Tree ipv6Tree); } | MntByAuthentication extends AuthenticationStrategyBase { @Override public List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext) { try { return authenticateMntBy(update, updateContext); } catch (AuthenticationFailedException e) { return authenticateByAddressSpaceHolder(update, updateContext, e); } } @Autowired MntByAuthentication(final Maintainers maintainers,
final AuthenticationModule authenticationModule,
final RpslObjectDao rpslObjectDao,
final SsoTranslator ssoTranslator,
final Ipv4Tree ipv4Tree,
final Ipv6Tree ipv6Tree); @Override boolean supports(final PreparedUpdate update); @Override List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext); } | MntByAuthentication extends AuthenticationStrategyBase { @Override public List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext) { try { return authenticateMntBy(update, updateContext); } catch (AuthenticationFailedException e) { return authenticateByAddressSpaceHolder(update, updateContext, e); } } @Autowired MntByAuthentication(final Maintainers maintainers,
final AuthenticationModule authenticationModule,
final RpslObjectDao rpslObjectDao,
final SsoTranslator ssoTranslator,
final Ipv4Tree ipv4Tree,
final Ipv6Tree ipv6Tree); @Override boolean supports(final PreparedUpdate update); @Override List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext); } |
@Test public void authenticate_modify_original_object_has_no_mntby_update() { when(update.getAction()).thenReturn(Action.MODIFY); final RpslObject original = RpslObject.parse("person: Mr Hubbard\nnic-hdl: TEST-NIC"); when(update.getReferenceObject()).thenReturn(original); final RpslObject updated = RpslObject.parse("person: Mr Hubbard\nnic-hdl: TEST-NIC\nmnt-by: TEST-MNT"); when(update.getUpdatedObject()).thenReturn(updated); when(update.getType()).thenReturn(ObjectType.PERSON); final List<RpslObject> candidates = Lists.newArrayList(RpslObject.parse("mntner: TEST-MNT")); when(rpslObjectDao.getByKeys(eq(ObjectType.MNTNER), anyCollection())).thenReturn(candidates); when(credentialValidators.authenticate(update, updateContext, candidates)).thenReturn(candidates); final List<RpslObject> authenticate = subject.authenticate(update, updateContext); assertThat(authenticate, is(candidates)); verifyZeroInteractions(maintainers); } | @Override public List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext) { try { return authenticateMntBy(update, updateContext); } catch (AuthenticationFailedException e) { return authenticateByAddressSpaceHolder(update, updateContext, e); } } | MntByAuthentication extends AuthenticationStrategyBase { @Override public List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext) { try { return authenticateMntBy(update, updateContext); } catch (AuthenticationFailedException e) { return authenticateByAddressSpaceHolder(update, updateContext, e); } } } | MntByAuthentication extends AuthenticationStrategyBase { @Override public List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext) { try { return authenticateMntBy(update, updateContext); } catch (AuthenticationFailedException e) { return authenticateByAddressSpaceHolder(update, updateContext, e); } } @Autowired MntByAuthentication(final Maintainers maintainers,
final AuthenticationModule authenticationModule,
final RpslObjectDao rpslObjectDao,
final SsoTranslator ssoTranslator,
final Ipv4Tree ipv4Tree,
final Ipv6Tree ipv6Tree); } | MntByAuthentication extends AuthenticationStrategyBase { @Override public List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext) { try { return authenticateMntBy(update, updateContext); } catch (AuthenticationFailedException e) { return authenticateByAddressSpaceHolder(update, updateContext, e); } } @Autowired MntByAuthentication(final Maintainers maintainers,
final AuthenticationModule authenticationModule,
final RpslObjectDao rpslObjectDao,
final SsoTranslator ssoTranslator,
final Ipv4Tree ipv4Tree,
final Ipv6Tree ipv6Tree); @Override boolean supports(final PreparedUpdate update); @Override List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext); } | MntByAuthentication extends AuthenticationStrategyBase { @Override public List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext) { try { return authenticateMntBy(update, updateContext); } catch (AuthenticationFailedException e) { return authenticateByAddressSpaceHolder(update, updateContext, e); } } @Autowired MntByAuthentication(final Maintainers maintainers,
final AuthenticationModule authenticationModule,
final RpslObjectDao rpslObjectDao,
final SsoTranslator ssoTranslator,
final Ipv4Tree ipv4Tree,
final Ipv6Tree ipv6Tree); @Override boolean supports(final PreparedUpdate update); @Override List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext); } |
Subsets and Splits