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 testDateToString_null() { assertNull(FormatHelper.dateToString(null)); } | public static String dateToString(final TemporalAccessor temporalAccessor) { if (temporalAccessor == null) { return null; } return DATE_FORMAT.format(temporalAccessor); } | FormatHelper { public static String dateToString(final TemporalAccessor temporalAccessor) { if (temporalAccessor == null) { return null; } return DATE_FORMAT.format(temporalAccessor); } } | FormatHelper { public static String dateToString(final TemporalAccessor temporalAccessor) { if (temporalAccessor == null) { return null; } return DATE_FORMAT.format(temporalAccessor); } private FormatHelper(); } | FormatHelper { public static String dateToString(final TemporalAccessor temporalAccessor) { if (temporalAccessor == null) { return null; } return DATE_FORMAT.format(temporalAccessor); } private FormatHelper(); static String dateToString(final TemporalAccessor temporalAccessor); static String dateTimeToString(final TemporalAccessor temporalAccessor); static String dateTimeToUtcString(final TemporalAccessor temporalAccessor); static String prettyPrint(final String prefix, final String value, final int indentation, final int maxLineLength); static String prettyPrint(final String prefix, final String value, final int indentation, final int maxLineLength, boolean repeatPrefix); } | FormatHelper { public static String dateToString(final TemporalAccessor temporalAccessor) { if (temporalAccessor == null) { return null; } return DATE_FORMAT.format(temporalAccessor); } private FormatHelper(); static String dateToString(final TemporalAccessor temporalAccessor); static String dateTimeToString(final TemporalAccessor temporalAccessor); static String dateTimeToUtcString(final TemporalAccessor temporalAccessor); static String prettyPrint(final String prefix, final String value, final int indentation, final int maxLineLength); static String prettyPrint(final String prefix, final String value, final int indentation, final int maxLineLength, boolean repeatPrefix); } |
@Test public void resolveAutoKeys_reference_auto() { RpslObject person = RpslObject.parse("" + "person: John Doe\n" + "nic-hdl: AUTO-1\n"); subject.resolveAutoKeys(person, update, updateContext, Action.CREATE); RpslObject mntner = RpslObject.parse("" + "mntner: TST-MNT\n" + "admin-c: AUTO-1\n"); final RpslObject rpslObject = subject.resolveAutoKeys(mntner, update, updateContext, Action.CREATE); assertThat(rpslObject.toString(), is("" + "mntner: TST-MNT\n" + "admin-c: J1-RIPE\n")); verify(autoKeyFactory, times(1)).generate(anyString(), any(RpslObject.class)); } | public RpslObject resolveAutoKeys(final RpslObject object, final Update update, final UpdateContext updateContext, final Action action) { final Map<RpslAttribute, RpslAttribute> attributesToReplace = Maps.newHashMap(); if (Action.CREATE.equals(action)) { claimOrGenerateAutoKeys(update, object, updateContext, attributesToReplace); } resolveAutoKeyReferences(update, object, updateContext, attributesToReplace); if (attributesToReplace.isEmpty()) { return object; } return new RpslObjectBuilder(object).replaceAttributes(attributesToReplace).get(); } | AutoKeyResolver { public RpslObject resolveAutoKeys(final RpslObject object, final Update update, final UpdateContext updateContext, final Action action) { final Map<RpslAttribute, RpslAttribute> attributesToReplace = Maps.newHashMap(); if (Action.CREATE.equals(action)) { claimOrGenerateAutoKeys(update, object, updateContext, attributesToReplace); } resolveAutoKeyReferences(update, object, updateContext, attributesToReplace); if (attributesToReplace.isEmpty()) { return object; } return new RpslObjectBuilder(object).replaceAttributes(attributesToReplace).get(); } } | AutoKeyResolver { public RpslObject resolveAutoKeys(final RpslObject object, final Update update, final UpdateContext updateContext, final Action action) { final Map<RpslAttribute, RpslAttribute> attributesToReplace = Maps.newHashMap(); if (Action.CREATE.equals(action)) { claimOrGenerateAutoKeys(update, object, updateContext, attributesToReplace); } resolveAutoKeyReferences(update, object, updateContext, attributesToReplace); if (attributesToReplace.isEmpty()) { return object; } return new RpslObjectBuilder(object).replaceAttributes(attributesToReplace).get(); } @Autowired AutoKeyResolver(final AutoKeyFactory... autoKeyFactories); } | AutoKeyResolver { public RpslObject resolveAutoKeys(final RpslObject object, final Update update, final UpdateContext updateContext, final Action action) { final Map<RpslAttribute, RpslAttribute> attributesToReplace = Maps.newHashMap(); if (Action.CREATE.equals(action)) { claimOrGenerateAutoKeys(update, object, updateContext, attributesToReplace); } resolveAutoKeyReferences(update, object, updateContext, attributesToReplace); if (attributesToReplace.isEmpty()) { return object; } return new RpslObjectBuilder(object).replaceAttributes(attributesToReplace).get(); } @Autowired AutoKeyResolver(final AutoKeyFactory... autoKeyFactories); RpslObject resolveAutoKeys(final RpslObject object, final Update update, final UpdateContext updateContext, final Action action); } | AutoKeyResolver { public RpslObject resolveAutoKeys(final RpslObject object, final Update update, final UpdateContext updateContext, final Action action) { final Map<RpslAttribute, RpslAttribute> attributesToReplace = Maps.newHashMap(); if (Action.CREATE.equals(action)) { claimOrGenerateAutoKeys(update, object, updateContext, attributesToReplace); } resolveAutoKeyReferences(update, object, updateContext, attributesToReplace); if (attributesToReplace.isEmpty()) { return object; } return new RpslObjectBuilder(object).replaceAttributes(attributesToReplace).get(); } @Autowired AutoKeyResolver(final AutoKeyFactory... autoKeyFactories); RpslObject resolveAutoKeys(final RpslObject object, final Update update, final UpdateContext updateContext, final Action action); } |
@Test public void resolveAutoKeys_self_reference() { RpslObject person = RpslObject.parse("" + "person: John Doe\n" + "nic-hdl: AUTO-1\n" + "tech-c: AUTO-1\n" + "remarks: AUTO-1"); final RpslObject rpslObject = subject.resolveAutoKeys(person, update, updateContext, Action.CREATE); assertThat(rpslObject.toString(), is("" + "person: John Doe\n" + "nic-hdl: J1-RIPE\n" + "tech-c: J1-RIPE\n" + "remarks: AUTO-1\n")); verify(autoKeyFactory, times(1)).generate(anyString(), any(RpslObject.class)); } | public RpslObject resolveAutoKeys(final RpslObject object, final Update update, final UpdateContext updateContext, final Action action) { final Map<RpslAttribute, RpslAttribute> attributesToReplace = Maps.newHashMap(); if (Action.CREATE.equals(action)) { claimOrGenerateAutoKeys(update, object, updateContext, attributesToReplace); } resolveAutoKeyReferences(update, object, updateContext, attributesToReplace); if (attributesToReplace.isEmpty()) { return object; } return new RpslObjectBuilder(object).replaceAttributes(attributesToReplace).get(); } | AutoKeyResolver { public RpslObject resolveAutoKeys(final RpslObject object, final Update update, final UpdateContext updateContext, final Action action) { final Map<RpslAttribute, RpslAttribute> attributesToReplace = Maps.newHashMap(); if (Action.CREATE.equals(action)) { claimOrGenerateAutoKeys(update, object, updateContext, attributesToReplace); } resolveAutoKeyReferences(update, object, updateContext, attributesToReplace); if (attributesToReplace.isEmpty()) { return object; } return new RpslObjectBuilder(object).replaceAttributes(attributesToReplace).get(); } } | AutoKeyResolver { public RpslObject resolveAutoKeys(final RpslObject object, final Update update, final UpdateContext updateContext, final Action action) { final Map<RpslAttribute, RpslAttribute> attributesToReplace = Maps.newHashMap(); if (Action.CREATE.equals(action)) { claimOrGenerateAutoKeys(update, object, updateContext, attributesToReplace); } resolveAutoKeyReferences(update, object, updateContext, attributesToReplace); if (attributesToReplace.isEmpty()) { return object; } return new RpslObjectBuilder(object).replaceAttributes(attributesToReplace).get(); } @Autowired AutoKeyResolver(final AutoKeyFactory... autoKeyFactories); } | AutoKeyResolver { public RpslObject resolveAutoKeys(final RpslObject object, final Update update, final UpdateContext updateContext, final Action action) { final Map<RpslAttribute, RpslAttribute> attributesToReplace = Maps.newHashMap(); if (Action.CREATE.equals(action)) { claimOrGenerateAutoKeys(update, object, updateContext, attributesToReplace); } resolveAutoKeyReferences(update, object, updateContext, attributesToReplace); if (attributesToReplace.isEmpty()) { return object; } return new RpslObjectBuilder(object).replaceAttributes(attributesToReplace).get(); } @Autowired AutoKeyResolver(final AutoKeyFactory... autoKeyFactories); RpslObject resolveAutoKeys(final RpslObject object, final Update update, final UpdateContext updateContext, final Action action); } | AutoKeyResolver { public RpslObject resolveAutoKeys(final RpslObject object, final Update update, final UpdateContext updateContext, final Action action) { final Map<RpslAttribute, RpslAttribute> attributesToReplace = Maps.newHashMap(); if (Action.CREATE.equals(action)) { claimOrGenerateAutoKeys(update, object, updateContext, attributesToReplace); } resolveAutoKeyReferences(update, object, updateContext, attributesToReplace); if (attributesToReplace.isEmpty()) { return object; } return new RpslObjectBuilder(object).replaceAttributes(attributesToReplace).get(); } @Autowired AutoKeyResolver(final AutoKeyFactory... autoKeyFactories); RpslObject resolveAutoKeys(final RpslObject object, final Update update, final UpdateContext updateContext, final Action action); } |
@Test public void resolveAutoKeys_modify() throws Exception { RpslObject person = RpslObject.parse("" + "person: John Doe\n" + "nic-hdl: JD1-RIPE\n"); subject.resolveAutoKeys(person, update, updateContext, Action.MODIFY); verify(autoKeyFactory, never()).claim(anyString()); verify(autoKeyFactory, never()).generate(anyString(), any(RpslObject.class)); } | public RpslObject resolveAutoKeys(final RpslObject object, final Update update, final UpdateContext updateContext, final Action action) { final Map<RpslAttribute, RpslAttribute> attributesToReplace = Maps.newHashMap(); if (Action.CREATE.equals(action)) { claimOrGenerateAutoKeys(update, object, updateContext, attributesToReplace); } resolveAutoKeyReferences(update, object, updateContext, attributesToReplace); if (attributesToReplace.isEmpty()) { return object; } return new RpslObjectBuilder(object).replaceAttributes(attributesToReplace).get(); } | AutoKeyResolver { public RpslObject resolveAutoKeys(final RpslObject object, final Update update, final UpdateContext updateContext, final Action action) { final Map<RpslAttribute, RpslAttribute> attributesToReplace = Maps.newHashMap(); if (Action.CREATE.equals(action)) { claimOrGenerateAutoKeys(update, object, updateContext, attributesToReplace); } resolveAutoKeyReferences(update, object, updateContext, attributesToReplace); if (attributesToReplace.isEmpty()) { return object; } return new RpslObjectBuilder(object).replaceAttributes(attributesToReplace).get(); } } | AutoKeyResolver { public RpslObject resolveAutoKeys(final RpslObject object, final Update update, final UpdateContext updateContext, final Action action) { final Map<RpslAttribute, RpslAttribute> attributesToReplace = Maps.newHashMap(); if (Action.CREATE.equals(action)) { claimOrGenerateAutoKeys(update, object, updateContext, attributesToReplace); } resolveAutoKeyReferences(update, object, updateContext, attributesToReplace); if (attributesToReplace.isEmpty()) { return object; } return new RpslObjectBuilder(object).replaceAttributes(attributesToReplace).get(); } @Autowired AutoKeyResolver(final AutoKeyFactory... autoKeyFactories); } | AutoKeyResolver { public RpslObject resolveAutoKeys(final RpslObject object, final Update update, final UpdateContext updateContext, final Action action) { final Map<RpslAttribute, RpslAttribute> attributesToReplace = Maps.newHashMap(); if (Action.CREATE.equals(action)) { claimOrGenerateAutoKeys(update, object, updateContext, attributesToReplace); } resolveAutoKeyReferences(update, object, updateContext, attributesToReplace); if (attributesToReplace.isEmpty()) { return object; } return new RpslObjectBuilder(object).replaceAttributes(attributesToReplace).get(); } @Autowired AutoKeyResolver(final AutoKeyFactory... autoKeyFactories); RpslObject resolveAutoKeys(final RpslObject object, final Update update, final UpdateContext updateContext, final Action action); } | AutoKeyResolver { public RpslObject resolveAutoKeys(final RpslObject object, final Update update, final UpdateContext updateContext, final Action action) { final Map<RpslAttribute, RpslAttribute> attributesToReplace = Maps.newHashMap(); if (Action.CREATE.equals(action)) { claimOrGenerateAutoKeys(update, object, updateContext, attributesToReplace); } resolveAutoKeyReferences(update, object, updateContext, attributesToReplace); if (attributesToReplace.isEmpty()) { return object; } return new RpslObjectBuilder(object).replaceAttributes(attributesToReplace).get(); } @Autowired AutoKeyResolver(final AutoKeyFactory... autoKeyFactories); RpslObject resolveAutoKeys(final RpslObject object, final Update update, final UpdateContext updateContext, final Action action); } |
@Test public void resolveAutoKeys_key_specified_available_create() throws Exception { RpslObject person = RpslObject.parse("" + "person: John Doe\n" + "nic-hdl: JD1-RIPE\n"); when(autoKeyFactory.claim(anyString())).thenReturn(new NicHandle("JD", 1, "RIPE")); final RpslObject rpslObject = subject.resolveAutoKeys(person, update, updateContext, Action.CREATE); assertThat(rpslObject, is(person)); verify(autoKeyFactory).claim("JD1-RIPE"); verify(autoKeyFactory, never()).generate(anyString(), any(RpslObject.class)); } | public RpslObject resolveAutoKeys(final RpslObject object, final Update update, final UpdateContext updateContext, final Action action) { final Map<RpslAttribute, RpslAttribute> attributesToReplace = Maps.newHashMap(); if (Action.CREATE.equals(action)) { claimOrGenerateAutoKeys(update, object, updateContext, attributesToReplace); } resolveAutoKeyReferences(update, object, updateContext, attributesToReplace); if (attributesToReplace.isEmpty()) { return object; } return new RpslObjectBuilder(object).replaceAttributes(attributesToReplace).get(); } | AutoKeyResolver { public RpslObject resolveAutoKeys(final RpslObject object, final Update update, final UpdateContext updateContext, final Action action) { final Map<RpslAttribute, RpslAttribute> attributesToReplace = Maps.newHashMap(); if (Action.CREATE.equals(action)) { claimOrGenerateAutoKeys(update, object, updateContext, attributesToReplace); } resolveAutoKeyReferences(update, object, updateContext, attributesToReplace); if (attributesToReplace.isEmpty()) { return object; } return new RpslObjectBuilder(object).replaceAttributes(attributesToReplace).get(); } } | AutoKeyResolver { public RpslObject resolveAutoKeys(final RpslObject object, final Update update, final UpdateContext updateContext, final Action action) { final Map<RpslAttribute, RpslAttribute> attributesToReplace = Maps.newHashMap(); if (Action.CREATE.equals(action)) { claimOrGenerateAutoKeys(update, object, updateContext, attributesToReplace); } resolveAutoKeyReferences(update, object, updateContext, attributesToReplace); if (attributesToReplace.isEmpty()) { return object; } return new RpslObjectBuilder(object).replaceAttributes(attributesToReplace).get(); } @Autowired AutoKeyResolver(final AutoKeyFactory... autoKeyFactories); } | AutoKeyResolver { public RpslObject resolveAutoKeys(final RpslObject object, final Update update, final UpdateContext updateContext, final Action action) { final Map<RpslAttribute, RpslAttribute> attributesToReplace = Maps.newHashMap(); if (Action.CREATE.equals(action)) { claimOrGenerateAutoKeys(update, object, updateContext, attributesToReplace); } resolveAutoKeyReferences(update, object, updateContext, attributesToReplace); if (attributesToReplace.isEmpty()) { return object; } return new RpslObjectBuilder(object).replaceAttributes(attributesToReplace).get(); } @Autowired AutoKeyResolver(final AutoKeyFactory... autoKeyFactories); RpslObject resolveAutoKeys(final RpslObject object, final Update update, final UpdateContext updateContext, final Action action); } | AutoKeyResolver { public RpslObject resolveAutoKeys(final RpslObject object, final Update update, final UpdateContext updateContext, final Action action) { final Map<RpslAttribute, RpslAttribute> attributesToReplace = Maps.newHashMap(); if (Action.CREATE.equals(action)) { claimOrGenerateAutoKeys(update, object, updateContext, attributesToReplace); } resolveAutoKeyReferences(update, object, updateContext, attributesToReplace); if (attributesToReplace.isEmpty()) { return object; } return new RpslObjectBuilder(object).replaceAttributes(attributesToReplace).get(); } @Autowired AutoKeyResolver(final AutoKeyFactory... autoKeyFactories); RpslObject resolveAutoKeys(final RpslObject object, final Update update, final UpdateContext updateContext, final Action action); } |
@Test public void resolveAutoKeys_key_specified_invalid() throws Exception { RpslObject person = RpslObject.parse("" + "person: John Doe\n" + "nic-hdl: INVALID_NIC_HANDLE\n"); when(autoKeyFactory.claim(anyString())).thenThrow(new ClaimException(ValidationMessages.syntaxError("INVALID_NIC_HANDLE", ""))); final RpslObject rpslObject = subject.resolveAutoKeys(person, update, updateContext, Action.CREATE); assertThat(rpslObject, is(person)); verify(autoKeyFactory).claim("INVALID_NIC_HANDLE"); verify(autoKeyFactory, never()).generate(anyString(), any(RpslObject.class)); assertThat(updateContext.getMessages(update).getMessages(person.getAttributes().get(1)).getAllMessages(), contains(ValidationMessages.syntaxError("INVALID_NIC_HANDLE", ""))); } | public RpslObject resolveAutoKeys(final RpslObject object, final Update update, final UpdateContext updateContext, final Action action) { final Map<RpslAttribute, RpslAttribute> attributesToReplace = Maps.newHashMap(); if (Action.CREATE.equals(action)) { claimOrGenerateAutoKeys(update, object, updateContext, attributesToReplace); } resolveAutoKeyReferences(update, object, updateContext, attributesToReplace); if (attributesToReplace.isEmpty()) { return object; } return new RpslObjectBuilder(object).replaceAttributes(attributesToReplace).get(); } | AutoKeyResolver { public RpslObject resolveAutoKeys(final RpslObject object, final Update update, final UpdateContext updateContext, final Action action) { final Map<RpslAttribute, RpslAttribute> attributesToReplace = Maps.newHashMap(); if (Action.CREATE.equals(action)) { claimOrGenerateAutoKeys(update, object, updateContext, attributesToReplace); } resolveAutoKeyReferences(update, object, updateContext, attributesToReplace); if (attributesToReplace.isEmpty()) { return object; } return new RpslObjectBuilder(object).replaceAttributes(attributesToReplace).get(); } } | AutoKeyResolver { public RpslObject resolveAutoKeys(final RpslObject object, final Update update, final UpdateContext updateContext, final Action action) { final Map<RpslAttribute, RpslAttribute> attributesToReplace = Maps.newHashMap(); if (Action.CREATE.equals(action)) { claimOrGenerateAutoKeys(update, object, updateContext, attributesToReplace); } resolveAutoKeyReferences(update, object, updateContext, attributesToReplace); if (attributesToReplace.isEmpty()) { return object; } return new RpslObjectBuilder(object).replaceAttributes(attributesToReplace).get(); } @Autowired AutoKeyResolver(final AutoKeyFactory... autoKeyFactories); } | AutoKeyResolver { public RpslObject resolveAutoKeys(final RpslObject object, final Update update, final UpdateContext updateContext, final Action action) { final Map<RpslAttribute, RpslAttribute> attributesToReplace = Maps.newHashMap(); if (Action.CREATE.equals(action)) { claimOrGenerateAutoKeys(update, object, updateContext, attributesToReplace); } resolveAutoKeyReferences(update, object, updateContext, attributesToReplace); if (attributesToReplace.isEmpty()) { return object; } return new RpslObjectBuilder(object).replaceAttributes(attributesToReplace).get(); } @Autowired AutoKeyResolver(final AutoKeyFactory... autoKeyFactories); RpslObject resolveAutoKeys(final RpslObject object, final Update update, final UpdateContext updateContext, final Action action); } | AutoKeyResolver { public RpslObject resolveAutoKeys(final RpslObject object, final Update update, final UpdateContext updateContext, final Action action) { final Map<RpslAttribute, RpslAttribute> attributesToReplace = Maps.newHashMap(); if (Action.CREATE.equals(action)) { claimOrGenerateAutoKeys(update, object, updateContext, attributesToReplace); } resolveAutoKeyReferences(update, object, updateContext, attributesToReplace); if (attributesToReplace.isEmpty()) { return object; } return new RpslObjectBuilder(object).replaceAttributes(attributesToReplace).get(); } @Autowired AutoKeyResolver(final AutoKeyFactory... autoKeyFactories); RpslObject resolveAutoKeys(final RpslObject object, final Update update, final UpdateContext updateContext, final Action action); } |
@Test public void resolveAutoKeys_key_specified_not_available_create() throws Exception { RpslObject person = RpslObject.parse("" + "person: John Doe\n" + "nic-hdl: JD1-RIPE\n"); when(autoKeyFactory.claim(anyString())).thenThrow(new ClaimException(UpdateMessages.nicHandleNotAvailable("JD1-RIPE"))); final RpslObject rpslObject = subject.resolveAutoKeys(person, update, updateContext, Action.CREATE); assertThat(rpslObject, is(person)); verify(autoKeyFactory).claim("JD1-RIPE"); verify(autoKeyFactory, never()).generate(anyString(), any(RpslObject.class)); assertThat(updateContext.getMessages(update).hasErrors(), is(true)); assertThat(updateContext.getMessages(update).getMessages(person.getAttributes().get(1)).getAllMessages(), contains(UpdateMessages.nicHandleNotAvailable("JD1-RIPE"))); } | public RpslObject resolveAutoKeys(final RpslObject object, final Update update, final UpdateContext updateContext, final Action action) { final Map<RpslAttribute, RpslAttribute> attributesToReplace = Maps.newHashMap(); if (Action.CREATE.equals(action)) { claimOrGenerateAutoKeys(update, object, updateContext, attributesToReplace); } resolveAutoKeyReferences(update, object, updateContext, attributesToReplace); if (attributesToReplace.isEmpty()) { return object; } return new RpslObjectBuilder(object).replaceAttributes(attributesToReplace).get(); } | AutoKeyResolver { public RpslObject resolveAutoKeys(final RpslObject object, final Update update, final UpdateContext updateContext, final Action action) { final Map<RpslAttribute, RpslAttribute> attributesToReplace = Maps.newHashMap(); if (Action.CREATE.equals(action)) { claimOrGenerateAutoKeys(update, object, updateContext, attributesToReplace); } resolveAutoKeyReferences(update, object, updateContext, attributesToReplace); if (attributesToReplace.isEmpty()) { return object; } return new RpslObjectBuilder(object).replaceAttributes(attributesToReplace).get(); } } | AutoKeyResolver { public RpslObject resolveAutoKeys(final RpslObject object, final Update update, final UpdateContext updateContext, final Action action) { final Map<RpslAttribute, RpslAttribute> attributesToReplace = Maps.newHashMap(); if (Action.CREATE.equals(action)) { claimOrGenerateAutoKeys(update, object, updateContext, attributesToReplace); } resolveAutoKeyReferences(update, object, updateContext, attributesToReplace); if (attributesToReplace.isEmpty()) { return object; } return new RpslObjectBuilder(object).replaceAttributes(attributesToReplace).get(); } @Autowired AutoKeyResolver(final AutoKeyFactory... autoKeyFactories); } | AutoKeyResolver { public RpslObject resolveAutoKeys(final RpslObject object, final Update update, final UpdateContext updateContext, final Action action) { final Map<RpslAttribute, RpslAttribute> attributesToReplace = Maps.newHashMap(); if (Action.CREATE.equals(action)) { claimOrGenerateAutoKeys(update, object, updateContext, attributesToReplace); } resolveAutoKeyReferences(update, object, updateContext, attributesToReplace); if (attributesToReplace.isEmpty()) { return object; } return new RpslObjectBuilder(object).replaceAttributes(attributesToReplace).get(); } @Autowired AutoKeyResolver(final AutoKeyFactory... autoKeyFactories); RpslObject resolveAutoKeys(final RpslObject object, final Update update, final UpdateContext updateContext, final Action action); } | AutoKeyResolver { public RpslObject resolveAutoKeys(final RpslObject object, final Update update, final UpdateContext updateContext, final Action action) { final Map<RpslAttribute, RpslAttribute> attributesToReplace = Maps.newHashMap(); if (Action.CREATE.equals(action)) { claimOrGenerateAutoKeys(update, object, updateContext, attributesToReplace); } resolveAutoKeyReferences(update, object, updateContext, attributesToReplace); if (attributesToReplace.isEmpty()) { return object; } return new RpslObjectBuilder(object).replaceAttributes(attributesToReplace).get(); } @Autowired AutoKeyResolver(final AutoKeyFactory... autoKeyFactories); RpslObject resolveAutoKeys(final RpslObject object, final Update update, final UpdateContext updateContext, final Action action); } |
@Test public void resolveAutoKeys_reference_not_found() { when(autoKeyFactory.getKeyPlaceholder(anyString())).thenReturn(ciString("AUTO-1")); RpslObject mntner = RpslObject.parse("" + "mntner: TST-MNT\n" + "admin-c: AUTO-1\n"); final RpslObject rpslObject = subject.resolveAutoKeys(mntner, update, updateContext, Action.MODIFY); assertThat(rpslObject.toString(), is("" + "mntner: TST-MNT\n" + "admin-c: AUTO-1\n")); assertThat(updateContext.getMessages(update).hasErrors(), is(true)); assertThat(updateContext.getMessages(update).getMessages(mntner.getAttributes().get(1)).getAllMessages(), contains(UpdateMessages.referenceNotFound("AUTO-1"))); } | public RpslObject resolveAutoKeys(final RpslObject object, final Update update, final UpdateContext updateContext, final Action action) { final Map<RpslAttribute, RpslAttribute> attributesToReplace = Maps.newHashMap(); if (Action.CREATE.equals(action)) { claimOrGenerateAutoKeys(update, object, updateContext, attributesToReplace); } resolveAutoKeyReferences(update, object, updateContext, attributesToReplace); if (attributesToReplace.isEmpty()) { return object; } return new RpslObjectBuilder(object).replaceAttributes(attributesToReplace).get(); } | AutoKeyResolver { public RpslObject resolveAutoKeys(final RpslObject object, final Update update, final UpdateContext updateContext, final Action action) { final Map<RpslAttribute, RpslAttribute> attributesToReplace = Maps.newHashMap(); if (Action.CREATE.equals(action)) { claimOrGenerateAutoKeys(update, object, updateContext, attributesToReplace); } resolveAutoKeyReferences(update, object, updateContext, attributesToReplace); if (attributesToReplace.isEmpty()) { return object; } return new RpslObjectBuilder(object).replaceAttributes(attributesToReplace).get(); } } | AutoKeyResolver { public RpslObject resolveAutoKeys(final RpslObject object, final Update update, final UpdateContext updateContext, final Action action) { final Map<RpslAttribute, RpslAttribute> attributesToReplace = Maps.newHashMap(); if (Action.CREATE.equals(action)) { claimOrGenerateAutoKeys(update, object, updateContext, attributesToReplace); } resolveAutoKeyReferences(update, object, updateContext, attributesToReplace); if (attributesToReplace.isEmpty()) { return object; } return new RpslObjectBuilder(object).replaceAttributes(attributesToReplace).get(); } @Autowired AutoKeyResolver(final AutoKeyFactory... autoKeyFactories); } | AutoKeyResolver { public RpslObject resolveAutoKeys(final RpslObject object, final Update update, final UpdateContext updateContext, final Action action) { final Map<RpslAttribute, RpslAttribute> attributesToReplace = Maps.newHashMap(); if (Action.CREATE.equals(action)) { claimOrGenerateAutoKeys(update, object, updateContext, attributesToReplace); } resolveAutoKeyReferences(update, object, updateContext, attributesToReplace); if (attributesToReplace.isEmpty()) { return object; } return new RpslObjectBuilder(object).replaceAttributes(attributesToReplace).get(); } @Autowired AutoKeyResolver(final AutoKeyFactory... autoKeyFactories); RpslObject resolveAutoKeys(final RpslObject object, final Update update, final UpdateContext updateContext, final Action action); } | AutoKeyResolver { public RpslObject resolveAutoKeys(final RpslObject object, final Update update, final UpdateContext updateContext, final Action action) { final Map<RpslAttribute, RpslAttribute> attributesToReplace = Maps.newHashMap(); if (Action.CREATE.equals(action)) { claimOrGenerateAutoKeys(update, object, updateContext, attributesToReplace); } resolveAutoKeyReferences(update, object, updateContext, attributesToReplace); if (attributesToReplace.isEmpty()) { return object; } return new RpslObjectBuilder(object).replaceAttributes(attributesToReplace).get(); } @Autowired AutoKeyResolver(final AutoKeyFactory... autoKeyFactories); RpslObject resolveAutoKeys(final RpslObject object, final Update update, final UpdateContext updateContext, final Action action); } |
@Test(expected = IllegalArgumentException.class) public void generate_invalid_placeHolder() { subject.generate("AUTO", RpslObject.parse("person: name")); } | @Override public NicHandle generate(final String keyPlaceHolder, final RpslObject object) { return generateForName(keyPlaceHolder, object.getTypeAttribute().getCleanValue().toString()); } | NicHandleFactory extends AbstractAutoKeyFactory<NicHandle> { @Override public NicHandle generate(final String keyPlaceHolder, final RpslObject object) { return generateForName(keyPlaceHolder, object.getTypeAttribute().getCleanValue().toString()); } } | NicHandleFactory extends AbstractAutoKeyFactory<NicHandle> { @Override public NicHandle generate(final String keyPlaceHolder, final RpslObject object) { return generateForName(keyPlaceHolder, object.getTypeAttribute().getCleanValue().toString()); } @Autowired NicHandleFactory(final NicHandleRepository nicHandleRepository, final CountryCodeRepository countryCodeRepository); } | NicHandleFactory extends AbstractAutoKeyFactory<NicHandle> { @Override public NicHandle generate(final String keyPlaceHolder, final RpslObject object) { return generateForName(keyPlaceHolder, object.getTypeAttribute().getCleanValue().toString()); } @Autowired NicHandleFactory(final NicHandleRepository nicHandleRepository, final CountryCodeRepository countryCodeRepository); @Override AttributeType getAttributeType(); @Override NicHandle generate(final String keyPlaceHolder, final RpslObject object); @Override NicHandle claim(final String key); boolean isAvailable(final String key); } | NicHandleFactory extends AbstractAutoKeyFactory<NicHandle> { @Override public NicHandle generate(final String keyPlaceHolder, final RpslObject object) { return generateForName(keyPlaceHolder, object.getTypeAttribute().getCleanValue().toString()); } @Autowired NicHandleFactory(final NicHandleRepository nicHandleRepository, final CountryCodeRepository countryCodeRepository); @Override AttributeType getAttributeType(); @Override NicHandle generate(final String keyPlaceHolder, final RpslObject object); @Override NicHandle claim(final String key); boolean isAvailable(final String key); } |
@Test public void generate_specified_space() { when(nicHandleRepository.claimNextAvailableIndex("DW", SOURCE)).thenReturn(new NicHandle("DW", 10, SOURCE)); final NicHandle nicHandle = subject.generate("AUTO-1234567DW", RpslObject.parse("person: name\nnic-hdl: AUTO-1234567DW")); assertThat(nicHandle.toString(), is("DW10-RIPE")); } | @Override public NicHandle generate(final String keyPlaceHolder, final RpslObject object) { return generateForName(keyPlaceHolder, object.getTypeAttribute().getCleanValue().toString()); } | NicHandleFactory extends AbstractAutoKeyFactory<NicHandle> { @Override public NicHandle generate(final String keyPlaceHolder, final RpslObject object) { return generateForName(keyPlaceHolder, object.getTypeAttribute().getCleanValue().toString()); } } | NicHandleFactory extends AbstractAutoKeyFactory<NicHandle> { @Override public NicHandle generate(final String keyPlaceHolder, final RpslObject object) { return generateForName(keyPlaceHolder, object.getTypeAttribute().getCleanValue().toString()); } @Autowired NicHandleFactory(final NicHandleRepository nicHandleRepository, final CountryCodeRepository countryCodeRepository); } | NicHandleFactory extends AbstractAutoKeyFactory<NicHandle> { @Override public NicHandle generate(final String keyPlaceHolder, final RpslObject object) { return generateForName(keyPlaceHolder, object.getTypeAttribute().getCleanValue().toString()); } @Autowired NicHandleFactory(final NicHandleRepository nicHandleRepository, final CountryCodeRepository countryCodeRepository); @Override AttributeType getAttributeType(); @Override NicHandle generate(final String keyPlaceHolder, final RpslObject object); @Override NicHandle claim(final String key); boolean isAvailable(final String key); } | NicHandleFactory extends AbstractAutoKeyFactory<NicHandle> { @Override public NicHandle generate(final String keyPlaceHolder, final RpslObject object) { return generateForName(keyPlaceHolder, object.getTypeAttribute().getCleanValue().toString()); } @Autowired NicHandleFactory(final NicHandleRepository nicHandleRepository, final CountryCodeRepository countryCodeRepository); @Override AttributeType getAttributeType(); @Override NicHandle generate(final String keyPlaceHolder, final RpslObject object); @Override NicHandle claim(final String key); boolean isAvailable(final String key); } |
@Test public void generate_unspecified_space() { when(nicHandleRepository.claimNextAvailableIndex("JAS", SOURCE)).thenReturn(new NicHandle("JAS", 10, SOURCE)); final NicHandle nicHandle = subject.generate("AUTO-111", RpslObject.parse("person: John Archibald Smith\nnic-hdl: AUTO-111")); assertThat(nicHandle.toString(), is("JAS10-RIPE")); } | @Override public NicHandle generate(final String keyPlaceHolder, final RpslObject object) { return generateForName(keyPlaceHolder, object.getTypeAttribute().getCleanValue().toString()); } | NicHandleFactory extends AbstractAutoKeyFactory<NicHandle> { @Override public NicHandle generate(final String keyPlaceHolder, final RpslObject object) { return generateForName(keyPlaceHolder, object.getTypeAttribute().getCleanValue().toString()); } } | NicHandleFactory extends AbstractAutoKeyFactory<NicHandle> { @Override public NicHandle generate(final String keyPlaceHolder, final RpslObject object) { return generateForName(keyPlaceHolder, object.getTypeAttribute().getCleanValue().toString()); } @Autowired NicHandleFactory(final NicHandleRepository nicHandleRepository, final CountryCodeRepository countryCodeRepository); } | NicHandleFactory extends AbstractAutoKeyFactory<NicHandle> { @Override public NicHandle generate(final String keyPlaceHolder, final RpslObject object) { return generateForName(keyPlaceHolder, object.getTypeAttribute().getCleanValue().toString()); } @Autowired NicHandleFactory(final NicHandleRepository nicHandleRepository, final CountryCodeRepository countryCodeRepository); @Override AttributeType getAttributeType(); @Override NicHandle generate(final String keyPlaceHolder, final RpslObject object); @Override NicHandle claim(final String key); boolean isAvailable(final String key); } | NicHandleFactory extends AbstractAutoKeyFactory<NicHandle> { @Override public NicHandle generate(final String keyPlaceHolder, final RpslObject object) { return generateForName(keyPlaceHolder, object.getTypeAttribute().getCleanValue().toString()); } @Autowired NicHandleFactory(final NicHandleRepository nicHandleRepository, final CountryCodeRepository countryCodeRepository); @Override AttributeType getAttributeType(); @Override NicHandle generate(final String keyPlaceHolder, final RpslObject object); @Override NicHandle claim(final String key); boolean isAvailable(final String key); } |
@Test public void testDateToString_date() { assertThat(FormatHelper.dateToString(LocalDate.of(2001, 10, 1)), is("2001-10-01")); } | public static String dateToString(final TemporalAccessor temporalAccessor) { if (temporalAccessor == null) { return null; } return DATE_FORMAT.format(temporalAccessor); } | FormatHelper { public static String dateToString(final TemporalAccessor temporalAccessor) { if (temporalAccessor == null) { return null; } return DATE_FORMAT.format(temporalAccessor); } } | FormatHelper { public static String dateToString(final TemporalAccessor temporalAccessor) { if (temporalAccessor == null) { return null; } return DATE_FORMAT.format(temporalAccessor); } private FormatHelper(); } | FormatHelper { public static String dateToString(final TemporalAccessor temporalAccessor) { if (temporalAccessor == null) { return null; } return DATE_FORMAT.format(temporalAccessor); } private FormatHelper(); static String dateToString(final TemporalAccessor temporalAccessor); static String dateTimeToString(final TemporalAccessor temporalAccessor); static String dateTimeToUtcString(final TemporalAccessor temporalAccessor); static String prettyPrint(final String prefix, final String value, final int indentation, final int maxLineLength); static String prettyPrint(final String prefix, final String value, final int indentation, final int maxLineLength, boolean repeatPrefix); } | FormatHelper { public static String dateToString(final TemporalAccessor temporalAccessor) { if (temporalAccessor == null) { return null; } return DATE_FORMAT.format(temporalAccessor); } private FormatHelper(); static String dateToString(final TemporalAccessor temporalAccessor); static String dateTimeToString(final TemporalAccessor temporalAccessor); static String dateTimeToUtcString(final TemporalAccessor temporalAccessor); static String prettyPrint(final String prefix, final String value, final int indentation, final int maxLineLength); static String prettyPrint(final String prefix, final String value, final int indentation, final int maxLineLength, boolean repeatPrefix); } |
@Test public void generate_unspecified_lower() { when(nicHandleRepository.claimNextAvailableIndex("SN", SOURCE)).thenReturn(new NicHandle("SN", 10, SOURCE)); final NicHandle nicHandle = subject.generate("AUTO-111", RpslObject.parse("person: some name\nnic-hdl: AUTO-111")); assertThat(nicHandle.toString(), is("SN10-RIPE")); } | @Override public NicHandle generate(final String keyPlaceHolder, final RpslObject object) { return generateForName(keyPlaceHolder, object.getTypeAttribute().getCleanValue().toString()); } | NicHandleFactory extends AbstractAutoKeyFactory<NicHandle> { @Override public NicHandle generate(final String keyPlaceHolder, final RpslObject object) { return generateForName(keyPlaceHolder, object.getTypeAttribute().getCleanValue().toString()); } } | NicHandleFactory extends AbstractAutoKeyFactory<NicHandle> { @Override public NicHandle generate(final String keyPlaceHolder, final RpslObject object) { return generateForName(keyPlaceHolder, object.getTypeAttribute().getCleanValue().toString()); } @Autowired NicHandleFactory(final NicHandleRepository nicHandleRepository, final CountryCodeRepository countryCodeRepository); } | NicHandleFactory extends AbstractAutoKeyFactory<NicHandle> { @Override public NicHandle generate(final String keyPlaceHolder, final RpslObject object) { return generateForName(keyPlaceHolder, object.getTypeAttribute().getCleanValue().toString()); } @Autowired NicHandleFactory(final NicHandleRepository nicHandleRepository, final CountryCodeRepository countryCodeRepository); @Override AttributeType getAttributeType(); @Override NicHandle generate(final String keyPlaceHolder, final RpslObject object); @Override NicHandle claim(final String key); boolean isAvailable(final String key); } | NicHandleFactory extends AbstractAutoKeyFactory<NicHandle> { @Override public NicHandle generate(final String keyPlaceHolder, final RpslObject object) { return generateForName(keyPlaceHolder, object.getTypeAttribute().getCleanValue().toString()); } @Autowired NicHandleFactory(final NicHandleRepository nicHandleRepository, final CountryCodeRepository countryCodeRepository); @Override AttributeType getAttributeType(); @Override NicHandle generate(final String keyPlaceHolder, final RpslObject object); @Override NicHandle claim(final String key); boolean isAvailable(final String key); } |
@Test public void generate_unspecified_long() { when(nicHandleRepository.claimNextAvailableIndex("SATG", SOURCE)).thenReturn(new NicHandle("SATG", 10, SOURCE)); final NicHandle nicHandle = subject.generate("AUTO-1234567", RpslObject.parse("person: Satellite advisory Technologies Group Ltd\nnic-hdl: AUTO-1234567")); assertThat(nicHandle.toString(), is("SATG10-RIPE")); } | @Override public NicHandle generate(final String keyPlaceHolder, final RpslObject object) { return generateForName(keyPlaceHolder, object.getTypeAttribute().getCleanValue().toString()); } | NicHandleFactory extends AbstractAutoKeyFactory<NicHandle> { @Override public NicHandle generate(final String keyPlaceHolder, final RpslObject object) { return generateForName(keyPlaceHolder, object.getTypeAttribute().getCleanValue().toString()); } } | NicHandleFactory extends AbstractAutoKeyFactory<NicHandle> { @Override public NicHandle generate(final String keyPlaceHolder, final RpslObject object) { return generateForName(keyPlaceHolder, object.getTypeAttribute().getCleanValue().toString()); } @Autowired NicHandleFactory(final NicHandleRepository nicHandleRepository, final CountryCodeRepository countryCodeRepository); } | NicHandleFactory extends AbstractAutoKeyFactory<NicHandle> { @Override public NicHandle generate(final String keyPlaceHolder, final RpslObject object) { return generateForName(keyPlaceHolder, object.getTypeAttribute().getCleanValue().toString()); } @Autowired NicHandleFactory(final NicHandleRepository nicHandleRepository, final CountryCodeRepository countryCodeRepository); @Override AttributeType getAttributeType(); @Override NicHandle generate(final String keyPlaceHolder, final RpslObject object); @Override NicHandle claim(final String key); boolean isAvailable(final String key); } | NicHandleFactory extends AbstractAutoKeyFactory<NicHandle> { @Override public NicHandle generate(final String keyPlaceHolder, final RpslObject object) { return generateForName(keyPlaceHolder, object.getTypeAttribute().getCleanValue().toString()); } @Autowired NicHandleFactory(final NicHandleRepository nicHandleRepository, final CountryCodeRepository countryCodeRepository); @Override AttributeType getAttributeType(); @Override NicHandle generate(final String keyPlaceHolder, final RpslObject object); @Override NicHandle claim(final String key); boolean isAvailable(final String key); } |
@Test public void getAttributeType() { assertThat(subject.getAttributeType(), is(AttributeType.NIC_HDL)); } | @Override public AttributeType getAttributeType() { return AttributeType.NIC_HDL; } | NicHandleFactory extends AbstractAutoKeyFactory<NicHandle> { @Override public AttributeType getAttributeType() { return AttributeType.NIC_HDL; } } | NicHandleFactory extends AbstractAutoKeyFactory<NicHandle> { @Override public AttributeType getAttributeType() { return AttributeType.NIC_HDL; } @Autowired NicHandleFactory(final NicHandleRepository nicHandleRepository, final CountryCodeRepository countryCodeRepository); } | NicHandleFactory extends AbstractAutoKeyFactory<NicHandle> { @Override public AttributeType getAttributeType() { return AttributeType.NIC_HDL; } @Autowired NicHandleFactory(final NicHandleRepository nicHandleRepository, final CountryCodeRepository countryCodeRepository); @Override AttributeType getAttributeType(); @Override NicHandle generate(final String keyPlaceHolder, final RpslObject object); @Override NicHandle claim(final String key); boolean isAvailable(final String key); } | NicHandleFactory extends AbstractAutoKeyFactory<NicHandle> { @Override public AttributeType getAttributeType() { return AttributeType.NIC_HDL; } @Autowired NicHandleFactory(final NicHandleRepository nicHandleRepository, final CountryCodeRepository countryCodeRepository); @Override AttributeType getAttributeType(); @Override NicHandle generate(final String keyPlaceHolder, final RpslObject object); @Override NicHandle claim(final String key); boolean isAvailable(final String key); } |
@Test public void claim() throws Exception { final NicHandle nicHandle = new NicHandle("DW", 10, "RIPE"); when(nicHandleRepository.claimSpecified(nicHandle)).thenReturn(true); assertThat(subject.claim("DW10-RIPE"), is(nicHandle)); } | @Override public NicHandle claim(final String key) throws ClaimException { final NicHandle nicHandle = parseNicHandle(key); if (!nicHandleRepository.claimSpecified(nicHandle)) { throw new ClaimException(UpdateMessages.nicHandleNotAvailable(nicHandle.toString())); } return nicHandle; } | NicHandleFactory extends AbstractAutoKeyFactory<NicHandle> { @Override public NicHandle claim(final String key) throws ClaimException { final NicHandle nicHandle = parseNicHandle(key); if (!nicHandleRepository.claimSpecified(nicHandle)) { throw new ClaimException(UpdateMessages.nicHandleNotAvailable(nicHandle.toString())); } return nicHandle; } } | NicHandleFactory extends AbstractAutoKeyFactory<NicHandle> { @Override public NicHandle claim(final String key) throws ClaimException { final NicHandle nicHandle = parseNicHandle(key); if (!nicHandleRepository.claimSpecified(nicHandle)) { throw new ClaimException(UpdateMessages.nicHandleNotAvailable(nicHandle.toString())); } return nicHandle; } @Autowired NicHandleFactory(final NicHandleRepository nicHandleRepository, final CountryCodeRepository countryCodeRepository); } | NicHandleFactory extends AbstractAutoKeyFactory<NicHandle> { @Override public NicHandle claim(final String key) throws ClaimException { final NicHandle nicHandle = parseNicHandle(key); if (!nicHandleRepository.claimSpecified(nicHandle)) { throw new ClaimException(UpdateMessages.nicHandleNotAvailable(nicHandle.toString())); } return nicHandle; } @Autowired NicHandleFactory(final NicHandleRepository nicHandleRepository, final CountryCodeRepository countryCodeRepository); @Override AttributeType getAttributeType(); @Override NicHandle generate(final String keyPlaceHolder, final RpslObject object); @Override NicHandle claim(final String key); boolean isAvailable(final String key); } | NicHandleFactory extends AbstractAutoKeyFactory<NicHandle> { @Override public NicHandle claim(final String key) throws ClaimException { final NicHandle nicHandle = parseNicHandle(key); if (!nicHandleRepository.claimSpecified(nicHandle)) { throw new ClaimException(UpdateMessages.nicHandleNotAvailable(nicHandle.toString())); } return nicHandle; } @Autowired NicHandleFactory(final NicHandleRepository nicHandleRepository, final CountryCodeRepository countryCodeRepository); @Override AttributeType getAttributeType(); @Override NicHandle generate(final String keyPlaceHolder, final RpslObject object); @Override NicHandle claim(final String key); boolean isAvailable(final String key); } |
@Test public void claim_not_available() { when(nicHandleRepository.claimSpecified(new NicHandle("DW", 10, "RIPE"))).thenReturn(false); try { subject.claim("DW10-RIPE"); fail("Claim succeeded?"); } catch (ClaimException e) { assertThat(e.getErrorMessage(), is(UpdateMessages.nicHandleNotAvailable("DW10-RIPE"))); } } | @Override public NicHandle claim(final String key) throws ClaimException { final NicHandle nicHandle = parseNicHandle(key); if (!nicHandleRepository.claimSpecified(nicHandle)) { throw new ClaimException(UpdateMessages.nicHandleNotAvailable(nicHandle.toString())); } return nicHandle; } | NicHandleFactory extends AbstractAutoKeyFactory<NicHandle> { @Override public NicHandle claim(final String key) throws ClaimException { final NicHandle nicHandle = parseNicHandle(key); if (!nicHandleRepository.claimSpecified(nicHandle)) { throw new ClaimException(UpdateMessages.nicHandleNotAvailable(nicHandle.toString())); } return nicHandle; } } | NicHandleFactory extends AbstractAutoKeyFactory<NicHandle> { @Override public NicHandle claim(final String key) throws ClaimException { final NicHandle nicHandle = parseNicHandle(key); if (!nicHandleRepository.claimSpecified(nicHandle)) { throw new ClaimException(UpdateMessages.nicHandleNotAvailable(nicHandle.toString())); } return nicHandle; } @Autowired NicHandleFactory(final NicHandleRepository nicHandleRepository, final CountryCodeRepository countryCodeRepository); } | NicHandleFactory extends AbstractAutoKeyFactory<NicHandle> { @Override public NicHandle claim(final String key) throws ClaimException { final NicHandle nicHandle = parseNicHandle(key); if (!nicHandleRepository.claimSpecified(nicHandle)) { throw new ClaimException(UpdateMessages.nicHandleNotAvailable(nicHandle.toString())); } return nicHandle; } @Autowired NicHandleFactory(final NicHandleRepository nicHandleRepository, final CountryCodeRepository countryCodeRepository); @Override AttributeType getAttributeType(); @Override NicHandle generate(final String keyPlaceHolder, final RpslObject object); @Override NicHandle claim(final String key); boolean isAvailable(final String key); } | NicHandleFactory extends AbstractAutoKeyFactory<NicHandle> { @Override public NicHandle claim(final String key) throws ClaimException { final NicHandle nicHandle = parseNicHandle(key); if (!nicHandleRepository.claimSpecified(nicHandle)) { throw new ClaimException(UpdateMessages.nicHandleNotAvailable(nicHandle.toString())); } return nicHandle; } @Autowired NicHandleFactory(final NicHandleRepository nicHandleRepository, final CountryCodeRepository countryCodeRepository); @Override AttributeType getAttributeType(); @Override NicHandle generate(final String keyPlaceHolder, final RpslObject object); @Override NicHandle claim(final String key); boolean isAvailable(final String key); } |
@Test public void claim_invalid_handle() { try { subject.claim("INVALID_HANDLE"); fail("Claim succeeded?"); } catch (ClaimException e) { assertThat(e.getErrorMessage(), is(ValidationMessages.syntaxError("INVALID_HANDLE"))); } } | @Override public NicHandle claim(final String key) throws ClaimException { final NicHandle nicHandle = parseNicHandle(key); if (!nicHandleRepository.claimSpecified(nicHandle)) { throw new ClaimException(UpdateMessages.nicHandleNotAvailable(nicHandle.toString())); } return nicHandle; } | NicHandleFactory extends AbstractAutoKeyFactory<NicHandle> { @Override public NicHandle claim(final String key) throws ClaimException { final NicHandle nicHandle = parseNicHandle(key); if (!nicHandleRepository.claimSpecified(nicHandle)) { throw new ClaimException(UpdateMessages.nicHandleNotAvailable(nicHandle.toString())); } return nicHandle; } } | NicHandleFactory extends AbstractAutoKeyFactory<NicHandle> { @Override public NicHandle claim(final String key) throws ClaimException { final NicHandle nicHandle = parseNicHandle(key); if (!nicHandleRepository.claimSpecified(nicHandle)) { throw new ClaimException(UpdateMessages.nicHandleNotAvailable(nicHandle.toString())); } return nicHandle; } @Autowired NicHandleFactory(final NicHandleRepository nicHandleRepository, final CountryCodeRepository countryCodeRepository); } | NicHandleFactory extends AbstractAutoKeyFactory<NicHandle> { @Override public NicHandle claim(final String key) throws ClaimException { final NicHandle nicHandle = parseNicHandle(key); if (!nicHandleRepository.claimSpecified(nicHandle)) { throw new ClaimException(UpdateMessages.nicHandleNotAvailable(nicHandle.toString())); } return nicHandle; } @Autowired NicHandleFactory(final NicHandleRepository nicHandleRepository, final CountryCodeRepository countryCodeRepository); @Override AttributeType getAttributeType(); @Override NicHandle generate(final String keyPlaceHolder, final RpslObject object); @Override NicHandle claim(final String key); boolean isAvailable(final String key); } | NicHandleFactory extends AbstractAutoKeyFactory<NicHandle> { @Override public NicHandle claim(final String key) throws ClaimException { final NicHandle nicHandle = parseNicHandle(key); if (!nicHandleRepository.claimSpecified(nicHandle)) { throw new ClaimException(UpdateMessages.nicHandleNotAvailable(nicHandle.toString())); } return nicHandle; } @Autowired NicHandleFactory(final NicHandleRepository nicHandleRepository, final CountryCodeRepository countryCodeRepository); @Override AttributeType getAttributeType(); @Override NicHandle generate(final String keyPlaceHolder, final RpslObject object); @Override NicHandle claim(final String key); boolean isAvailable(final String key); } |
@Test(expected = IllegalArgumentException.class) public void generate_invalid_placeHolder() { subject.generate("AUTO", RpslObject.parse("organisation: AUTO\norg-name: name")); } | @Override public OrganisationId generate(final String keyPlaceHolder, final RpslObject object) { return generateForName(keyPlaceHolder, object.getValueForAttribute(AttributeType.ORG_NAME).toString()); } | OrganisationIdFactory extends AbstractAutoKeyFactory<OrganisationId> { @Override public OrganisationId generate(final String keyPlaceHolder, final RpslObject object) { return generateForName(keyPlaceHolder, object.getValueForAttribute(AttributeType.ORG_NAME).toString()); } } | OrganisationIdFactory extends AbstractAutoKeyFactory<OrganisationId> { @Override public OrganisationId generate(final String keyPlaceHolder, final RpslObject object) { return generateForName(keyPlaceHolder, object.getValueForAttribute(AttributeType.ORG_NAME).toString()); } @Autowired OrganisationIdFactory(final OrganisationIdRepository organisationIdRepository); } | OrganisationIdFactory extends AbstractAutoKeyFactory<OrganisationId> { @Override public OrganisationId generate(final String keyPlaceHolder, final RpslObject object) { return generateForName(keyPlaceHolder, object.getValueForAttribute(AttributeType.ORG_NAME).toString()); } @Autowired OrganisationIdFactory(final OrganisationIdRepository organisationIdRepository); @Override AttributeType getAttributeType(); @Override OrganisationId generate(final String keyPlaceHolder, final RpslObject object); @Override OrganisationId claim(final String key); } | OrganisationIdFactory extends AbstractAutoKeyFactory<OrganisationId> { @Override public OrganisationId generate(final String keyPlaceHolder, final RpslObject object) { return generateForName(keyPlaceHolder, object.getValueForAttribute(AttributeType.ORG_NAME).toString()); } @Autowired OrganisationIdFactory(final OrganisationIdRepository organisationIdRepository); @Override AttributeType getAttributeType(); @Override OrganisationId generate(final String keyPlaceHolder, final RpslObject object); @Override OrganisationId claim(final String key); } |
@Test public void generate_specified_space() { when(organisationIdRepository.claimNextAvailableIndex("DW", SOURCE)).thenReturn(new OrganisationId("DW", 10, SOURCE)); final OrganisationId organisationId = subject.generate("AUTO-1234567DW", RpslObject.parse("organisation: AUTO\norg-name: name")); assertThat(organisationId.toString(), is("ORG-DW10-RIPE")); } | @Override public OrganisationId generate(final String keyPlaceHolder, final RpslObject object) { return generateForName(keyPlaceHolder, object.getValueForAttribute(AttributeType.ORG_NAME).toString()); } | OrganisationIdFactory extends AbstractAutoKeyFactory<OrganisationId> { @Override public OrganisationId generate(final String keyPlaceHolder, final RpslObject object) { return generateForName(keyPlaceHolder, object.getValueForAttribute(AttributeType.ORG_NAME).toString()); } } | OrganisationIdFactory extends AbstractAutoKeyFactory<OrganisationId> { @Override public OrganisationId generate(final String keyPlaceHolder, final RpslObject object) { return generateForName(keyPlaceHolder, object.getValueForAttribute(AttributeType.ORG_NAME).toString()); } @Autowired OrganisationIdFactory(final OrganisationIdRepository organisationIdRepository); } | OrganisationIdFactory extends AbstractAutoKeyFactory<OrganisationId> { @Override public OrganisationId generate(final String keyPlaceHolder, final RpslObject object) { return generateForName(keyPlaceHolder, object.getValueForAttribute(AttributeType.ORG_NAME).toString()); } @Autowired OrganisationIdFactory(final OrganisationIdRepository organisationIdRepository); @Override AttributeType getAttributeType(); @Override OrganisationId generate(final String keyPlaceHolder, final RpslObject object); @Override OrganisationId claim(final String key); } | OrganisationIdFactory extends AbstractAutoKeyFactory<OrganisationId> { @Override public OrganisationId generate(final String keyPlaceHolder, final RpslObject object) { return generateForName(keyPlaceHolder, object.getValueForAttribute(AttributeType.ORG_NAME).toString()); } @Autowired OrganisationIdFactory(final OrganisationIdRepository organisationIdRepository); @Override AttributeType getAttributeType(); @Override OrganisationId generate(final String keyPlaceHolder, final RpslObject object); @Override OrganisationId claim(final String key); } |
@Test public void generate_unspecified_space_single_word_name() { when(organisationIdRepository.claimNextAvailableIndex("TA", SOURCE)).thenReturn(new OrganisationId("TA", 1, SOURCE)); RpslObject orgObject = RpslObject.parse("organisation: AUTO-1\norg-name: Tesco"); final OrganisationId organisationId = subject.generate("AUTO-1", orgObject); assertThat(organisationId.toString(), is("ORG-TA1-RIPE")); } | @Override public OrganisationId generate(final String keyPlaceHolder, final RpslObject object) { return generateForName(keyPlaceHolder, object.getValueForAttribute(AttributeType.ORG_NAME).toString()); } | OrganisationIdFactory extends AbstractAutoKeyFactory<OrganisationId> { @Override public OrganisationId generate(final String keyPlaceHolder, final RpslObject object) { return generateForName(keyPlaceHolder, object.getValueForAttribute(AttributeType.ORG_NAME).toString()); } } | OrganisationIdFactory extends AbstractAutoKeyFactory<OrganisationId> { @Override public OrganisationId generate(final String keyPlaceHolder, final RpslObject object) { return generateForName(keyPlaceHolder, object.getValueForAttribute(AttributeType.ORG_NAME).toString()); } @Autowired OrganisationIdFactory(final OrganisationIdRepository organisationIdRepository); } | OrganisationIdFactory extends AbstractAutoKeyFactory<OrganisationId> { @Override public OrganisationId generate(final String keyPlaceHolder, final RpslObject object) { return generateForName(keyPlaceHolder, object.getValueForAttribute(AttributeType.ORG_NAME).toString()); } @Autowired OrganisationIdFactory(final OrganisationIdRepository organisationIdRepository); @Override AttributeType getAttributeType(); @Override OrganisationId generate(final String keyPlaceHolder, final RpslObject object); @Override OrganisationId claim(final String key); } | OrganisationIdFactory extends AbstractAutoKeyFactory<OrganisationId> { @Override public OrganisationId generate(final String keyPlaceHolder, final RpslObject object) { return generateForName(keyPlaceHolder, object.getValueForAttribute(AttributeType.ORG_NAME).toString()); } @Autowired OrganisationIdFactory(final OrganisationIdRepository organisationIdRepository); @Override AttributeType getAttributeType(); @Override OrganisationId generate(final String keyPlaceHolder, final RpslObject object); @Override OrganisationId claim(final String key); } |
@Test public void generate_unspecified_space() { when(organisationIdRepository.claimNextAvailableIndex("SATG", SOURCE)).thenReturn(new OrganisationId("SATG", 10, SOURCE)); final OrganisationId organisationId = subject.generate("AUTO-111", RpslObject.parse("organisation: AUTO\norg-name: Satellite advisory Technologies Group Ltd")); assertThat(organisationId.toString(), is("ORG-SATG10-RIPE")); } | @Override public OrganisationId generate(final String keyPlaceHolder, final RpslObject object) { return generateForName(keyPlaceHolder, object.getValueForAttribute(AttributeType.ORG_NAME).toString()); } | OrganisationIdFactory extends AbstractAutoKeyFactory<OrganisationId> { @Override public OrganisationId generate(final String keyPlaceHolder, final RpslObject object) { return generateForName(keyPlaceHolder, object.getValueForAttribute(AttributeType.ORG_NAME).toString()); } } | OrganisationIdFactory extends AbstractAutoKeyFactory<OrganisationId> { @Override public OrganisationId generate(final String keyPlaceHolder, final RpslObject object) { return generateForName(keyPlaceHolder, object.getValueForAttribute(AttributeType.ORG_NAME).toString()); } @Autowired OrganisationIdFactory(final OrganisationIdRepository organisationIdRepository); } | OrganisationIdFactory extends AbstractAutoKeyFactory<OrganisationId> { @Override public OrganisationId generate(final String keyPlaceHolder, final RpslObject object) { return generateForName(keyPlaceHolder, object.getValueForAttribute(AttributeType.ORG_NAME).toString()); } @Autowired OrganisationIdFactory(final OrganisationIdRepository organisationIdRepository); @Override AttributeType getAttributeType(); @Override OrganisationId generate(final String keyPlaceHolder, final RpslObject object); @Override OrganisationId claim(final String key); } | OrganisationIdFactory extends AbstractAutoKeyFactory<OrganisationId> { @Override public OrganisationId generate(final String keyPlaceHolder, final RpslObject object) { return generateForName(keyPlaceHolder, object.getValueForAttribute(AttributeType.ORG_NAME).toString()); } @Autowired OrganisationIdFactory(final OrganisationIdRepository organisationIdRepository); @Override AttributeType getAttributeType(); @Override OrganisationId generate(final String keyPlaceHolder, final RpslObject object); @Override OrganisationId claim(final String key); } |
@Test public void testDateToString_dateTime() throws Exception { assertThat(FormatHelper.dateToString(LocalDateTime.of(2001, 10, 1, 12, 0, 0)), is("2001-10-01")); } | public static String dateToString(final TemporalAccessor temporalAccessor) { if (temporalAccessor == null) { return null; } return DATE_FORMAT.format(temporalAccessor); } | FormatHelper { public static String dateToString(final TemporalAccessor temporalAccessor) { if (temporalAccessor == null) { return null; } return DATE_FORMAT.format(temporalAccessor); } } | FormatHelper { public static String dateToString(final TemporalAccessor temporalAccessor) { if (temporalAccessor == null) { return null; } return DATE_FORMAT.format(temporalAccessor); } private FormatHelper(); } | FormatHelper { public static String dateToString(final TemporalAccessor temporalAccessor) { if (temporalAccessor == null) { return null; } return DATE_FORMAT.format(temporalAccessor); } private FormatHelper(); static String dateToString(final TemporalAccessor temporalAccessor); static String dateTimeToString(final TemporalAccessor temporalAccessor); static String dateTimeToUtcString(final TemporalAccessor temporalAccessor); static String prettyPrint(final String prefix, final String value, final int indentation, final int maxLineLength); static String prettyPrint(final String prefix, final String value, final int indentation, final int maxLineLength, boolean repeatPrefix); } | FormatHelper { public static String dateToString(final TemporalAccessor temporalAccessor) { if (temporalAccessor == null) { return null; } return DATE_FORMAT.format(temporalAccessor); } private FormatHelper(); static String dateToString(final TemporalAccessor temporalAccessor); static String dateTimeToString(final TemporalAccessor temporalAccessor); static String dateTimeToUtcString(final TemporalAccessor temporalAccessor); static String prettyPrint(final String prefix, final String value, final int indentation, final int maxLineLength); static String prettyPrint(final String prefix, final String value, final int indentation, final int maxLineLength, boolean repeatPrefix); } |
@Test public void getAttributeType() { assertThat(subject.getAttributeType(), is(AttributeType.ORGANISATION)); } | @Override public AttributeType getAttributeType() { return AttributeType.ORGANISATION; } | OrganisationIdFactory extends AbstractAutoKeyFactory<OrganisationId> { @Override public AttributeType getAttributeType() { return AttributeType.ORGANISATION; } } | OrganisationIdFactory extends AbstractAutoKeyFactory<OrganisationId> { @Override public AttributeType getAttributeType() { return AttributeType.ORGANISATION; } @Autowired OrganisationIdFactory(final OrganisationIdRepository organisationIdRepository); } | OrganisationIdFactory extends AbstractAutoKeyFactory<OrganisationId> { @Override public AttributeType getAttributeType() { return AttributeType.ORGANISATION; } @Autowired OrganisationIdFactory(final OrganisationIdRepository organisationIdRepository); @Override AttributeType getAttributeType(); @Override OrganisationId generate(final String keyPlaceHolder, final RpslObject object); @Override OrganisationId claim(final String key); } | OrganisationIdFactory extends AbstractAutoKeyFactory<OrganisationId> { @Override public AttributeType getAttributeType() { return AttributeType.ORGANISATION; } @Autowired OrganisationIdFactory(final OrganisationIdRepository organisationIdRepository); @Override AttributeType getAttributeType(); @Override OrganisationId generate(final String keyPlaceHolder, final RpslObject object); @Override OrganisationId claim(final String key); } |
@Test public void claim() throws Exception { try { subject.claim("ORG-DW10-RIPE"); fail("claim() supported?"); } catch (ClaimException e) { assertThat(e.getErrorMessage(), is(ValidationMessages.syntaxError("ORG-DW10-RIPE (must be AUTO-nnn for create)"))); } } | @Override public OrganisationId claim(final String key) throws ClaimException { throw new ClaimException(ValidationMessages.syntaxError(key, "must be AUTO-nnn for create")); } | OrganisationIdFactory extends AbstractAutoKeyFactory<OrganisationId> { @Override public OrganisationId claim(final String key) throws ClaimException { throw new ClaimException(ValidationMessages.syntaxError(key, "must be AUTO-nnn for create")); } } | OrganisationIdFactory extends AbstractAutoKeyFactory<OrganisationId> { @Override public OrganisationId claim(final String key) throws ClaimException { throw new ClaimException(ValidationMessages.syntaxError(key, "must be AUTO-nnn for create")); } @Autowired OrganisationIdFactory(final OrganisationIdRepository organisationIdRepository); } | OrganisationIdFactory extends AbstractAutoKeyFactory<OrganisationId> { @Override public OrganisationId claim(final String key) throws ClaimException { throw new ClaimException(ValidationMessages.syntaxError(key, "must be AUTO-nnn for create")); } @Autowired OrganisationIdFactory(final OrganisationIdRepository organisationIdRepository); @Override AttributeType getAttributeType(); @Override OrganisationId generate(final String keyPlaceHolder, final RpslObject object); @Override OrganisationId claim(final String key); } | OrganisationIdFactory extends AbstractAutoKeyFactory<OrganisationId> { @Override public OrganisationId claim(final String key) throws ClaimException { throw new ClaimException(ValidationMessages.syntaxError(key, "must be AUTO-nnn for create")); } @Autowired OrganisationIdFactory(final OrganisationIdRepository organisationIdRepository); @Override AttributeType getAttributeType(); @Override OrganisationId generate(final String keyPlaceHolder, final RpslObject object); @Override OrganisationId claim(final String key); } |
@Test public void isX509Key() throws IOException { assertThat(X509CertificateWrapper.looksLikeX509Key(x509Keycert), is(true)); assertThat(X509CertificateWrapper.looksLikeX509Key(pgpKeycert), is(false)); } | static boolean looksLikeX509Key(final RpslObject rpslObject) { final String pgpKey = RpslObjectFilter.getCertificateFromKeyCert(rpslObject); return pgpKey.indexOf(X509_HEADER) != -1 && pgpKey.indexOf(X509_FOOTER) != -1; } | X509CertificateWrapper implements KeyWrapper { static boolean looksLikeX509Key(final RpslObject rpslObject) { final String pgpKey = RpslObjectFilter.getCertificateFromKeyCert(rpslObject); return pgpKey.indexOf(X509_HEADER) != -1 && pgpKey.indexOf(X509_FOOTER) != -1; } } | X509CertificateWrapper implements KeyWrapper { static boolean looksLikeX509Key(final RpslObject rpslObject) { final String pgpKey = RpslObjectFilter.getCertificateFromKeyCert(rpslObject); return pgpKey.indexOf(X509_HEADER) != -1 && pgpKey.indexOf(X509_FOOTER) != -1; } private X509CertificateWrapper(final X509Certificate certificate); } | X509CertificateWrapper implements KeyWrapper { static boolean looksLikeX509Key(final RpslObject rpslObject) { final String pgpKey = RpslObjectFilter.getCertificateFromKeyCert(rpslObject); return pgpKey.indexOf(X509_HEADER) != -1 && pgpKey.indexOf(X509_FOOTER) != -1; } private X509CertificateWrapper(final X509Certificate certificate); static X509CertificateWrapper parse(final RpslObject rpslObject); static X509CertificateWrapper parse(final byte[] certificate); @Override boolean equals(final Object o); @Override int hashCode(); X509Certificate getCertificate(); @Override String getMethod(); @Override List<String> getOwners(); @Override String getFingerprint(); boolean isNotYetValid(final DateTimeProvider dateTimeProvider); boolean isExpired(final DateTimeProvider dateTimeProvider); } | X509CertificateWrapper implements KeyWrapper { static boolean looksLikeX509Key(final RpslObject rpslObject) { final String pgpKey = RpslObjectFilter.getCertificateFromKeyCert(rpslObject); return pgpKey.indexOf(X509_HEADER) != -1 && pgpKey.indexOf(X509_FOOTER) != -1; } private X509CertificateWrapper(final X509Certificate certificate); static X509CertificateWrapper parse(final RpslObject rpslObject); static X509CertificateWrapper parse(final byte[] certificate); @Override boolean equals(final Object o); @Override int hashCode(); X509Certificate getCertificate(); @Override String getMethod(); @Override List<String> getOwners(); @Override String getFingerprint(); boolean isNotYetValid(final DateTimeProvider dateTimeProvider); boolean isExpired(final DateTimeProvider dateTimeProvider); static final String X509_HEADER; static final String X509_FOOTER; } |
@Test public void getMethod() { X509CertificateWrapper subject = X509CertificateWrapper.parse(x509Keycert); assertThat(subject.getMethod(), is("X509")); } | @Override public String getMethod() { return METHOD; } | X509CertificateWrapper implements KeyWrapper { @Override public String getMethod() { return METHOD; } } | X509CertificateWrapper implements KeyWrapper { @Override public String getMethod() { return METHOD; } private X509CertificateWrapper(final X509Certificate certificate); } | X509CertificateWrapper implements KeyWrapper { @Override public String getMethod() { return METHOD; } private X509CertificateWrapper(final X509Certificate certificate); static X509CertificateWrapper parse(final RpslObject rpslObject); static X509CertificateWrapper parse(final byte[] certificate); @Override boolean equals(final Object o); @Override int hashCode(); X509Certificate getCertificate(); @Override String getMethod(); @Override List<String> getOwners(); @Override String getFingerprint(); boolean isNotYetValid(final DateTimeProvider dateTimeProvider); boolean isExpired(final DateTimeProvider dateTimeProvider); } | X509CertificateWrapper implements KeyWrapper { @Override public String getMethod() { return METHOD; } private X509CertificateWrapper(final X509Certificate certificate); static X509CertificateWrapper parse(final RpslObject rpslObject); static X509CertificateWrapper parse(final byte[] certificate); @Override boolean equals(final Object o); @Override int hashCode(); X509Certificate getCertificate(); @Override String getMethod(); @Override List<String> getOwners(); @Override String getFingerprint(); boolean isNotYetValid(final DateTimeProvider dateTimeProvider); boolean isExpired(final DateTimeProvider dateTimeProvider); static final String X509_HEADER; static final String X509_FOOTER; } |
@Test public void getFingerprint() { X509CertificateWrapper subject = X509CertificateWrapper.parse(x509Keycert); assertThat(subject.getFingerprint(), is("16:4F:B6:A4:D9:BC:0C:92:D4:48:13:FE:B6:EF:E2:82")); } | @Override public String getFingerprint() { try { MessageDigest md = MessageDigest.getInstance("MD5"); byte[] der = certificate.getEncoded(); md.update(der); byte[] digest = md.digest(); StringBuilder builder = new StringBuilder(); for (byte next : digest) { if (builder.length() > 0) { builder.append(':'); } builder.append(String.format("%02X", next)); } return builder.toString(); } catch (NoSuchAlgorithmException e) { throw new IllegalArgumentException("Invalid X509 Certificate", e); } catch (CertificateEncodingException e) { throw new IllegalArgumentException("Invalid X509 Certificate", e); } } | X509CertificateWrapper implements KeyWrapper { @Override public String getFingerprint() { try { MessageDigest md = MessageDigest.getInstance("MD5"); byte[] der = certificate.getEncoded(); md.update(der); byte[] digest = md.digest(); StringBuilder builder = new StringBuilder(); for (byte next : digest) { if (builder.length() > 0) { builder.append(':'); } builder.append(String.format("%02X", next)); } return builder.toString(); } catch (NoSuchAlgorithmException e) { throw new IllegalArgumentException("Invalid X509 Certificate", e); } catch (CertificateEncodingException e) { throw new IllegalArgumentException("Invalid X509 Certificate", e); } } } | X509CertificateWrapper implements KeyWrapper { @Override public String getFingerprint() { try { MessageDigest md = MessageDigest.getInstance("MD5"); byte[] der = certificate.getEncoded(); md.update(der); byte[] digest = md.digest(); StringBuilder builder = new StringBuilder(); for (byte next : digest) { if (builder.length() > 0) { builder.append(':'); } builder.append(String.format("%02X", next)); } return builder.toString(); } catch (NoSuchAlgorithmException e) { throw new IllegalArgumentException("Invalid X509 Certificate", e); } catch (CertificateEncodingException e) { throw new IllegalArgumentException("Invalid X509 Certificate", e); } } private X509CertificateWrapper(final X509Certificate certificate); } | X509CertificateWrapper implements KeyWrapper { @Override public String getFingerprint() { try { MessageDigest md = MessageDigest.getInstance("MD5"); byte[] der = certificate.getEncoded(); md.update(der); byte[] digest = md.digest(); StringBuilder builder = new StringBuilder(); for (byte next : digest) { if (builder.length() > 0) { builder.append(':'); } builder.append(String.format("%02X", next)); } return builder.toString(); } catch (NoSuchAlgorithmException e) { throw new IllegalArgumentException("Invalid X509 Certificate", e); } catch (CertificateEncodingException e) { throw new IllegalArgumentException("Invalid X509 Certificate", e); } } private X509CertificateWrapper(final X509Certificate certificate); static X509CertificateWrapper parse(final RpslObject rpslObject); static X509CertificateWrapper parse(final byte[] certificate); @Override boolean equals(final Object o); @Override int hashCode(); X509Certificate getCertificate(); @Override String getMethod(); @Override List<String> getOwners(); @Override String getFingerprint(); boolean isNotYetValid(final DateTimeProvider dateTimeProvider); boolean isExpired(final DateTimeProvider dateTimeProvider); } | X509CertificateWrapper implements KeyWrapper { @Override public String getFingerprint() { try { MessageDigest md = MessageDigest.getInstance("MD5"); byte[] der = certificate.getEncoded(); md.update(der); byte[] digest = md.digest(); StringBuilder builder = new StringBuilder(); for (byte next : digest) { if (builder.length() > 0) { builder.append(':'); } builder.append(String.format("%02X", next)); } return builder.toString(); } catch (NoSuchAlgorithmException e) { throw new IllegalArgumentException("Invalid X509 Certificate", e); } catch (CertificateEncodingException e) { throw new IllegalArgumentException("Invalid X509 Certificate", e); } } private X509CertificateWrapper(final X509Certificate certificate); static X509CertificateWrapper parse(final RpslObject rpslObject); static X509CertificateWrapper parse(final byte[] certificate); @Override boolean equals(final Object o); @Override int hashCode(); X509Certificate getCertificate(); @Override String getMethod(); @Override List<String> getOwners(); @Override String getFingerprint(); boolean isNotYetValid(final DateTimeProvider dateTimeProvider); boolean isExpired(final DateTimeProvider dateTimeProvider); static final String X509_HEADER; static final String X509_FOOTER; } |
@Test public void isExpired() { X509CertificateWrapper subject = X509CertificateWrapper.parse(x509Keycert); assertThat(subject.isExpired(dateTimeProvider), is(false)); when(dateTimeProvider.getCurrentDateTime()).thenReturn(LocalDateTime.now().plusYears(100)); assertThat(subject.isExpired(dateTimeProvider), is(true)); } | public boolean isExpired(final DateTimeProvider dateTimeProvider) { final LocalDateTime notAfter = DateUtil.fromDate(certificate.getNotAfter()); return notAfter.isBefore(dateTimeProvider.getCurrentDateTime()); } | X509CertificateWrapper implements KeyWrapper { public boolean isExpired(final DateTimeProvider dateTimeProvider) { final LocalDateTime notAfter = DateUtil.fromDate(certificate.getNotAfter()); return notAfter.isBefore(dateTimeProvider.getCurrentDateTime()); } } | X509CertificateWrapper implements KeyWrapper { public boolean isExpired(final DateTimeProvider dateTimeProvider) { final LocalDateTime notAfter = DateUtil.fromDate(certificate.getNotAfter()); return notAfter.isBefore(dateTimeProvider.getCurrentDateTime()); } private X509CertificateWrapper(final X509Certificate certificate); } | X509CertificateWrapper implements KeyWrapper { public boolean isExpired(final DateTimeProvider dateTimeProvider) { final LocalDateTime notAfter = DateUtil.fromDate(certificate.getNotAfter()); return notAfter.isBefore(dateTimeProvider.getCurrentDateTime()); } private X509CertificateWrapper(final X509Certificate certificate); static X509CertificateWrapper parse(final RpslObject rpslObject); static X509CertificateWrapper parse(final byte[] certificate); @Override boolean equals(final Object o); @Override int hashCode(); X509Certificate getCertificate(); @Override String getMethod(); @Override List<String> getOwners(); @Override String getFingerprint(); boolean isNotYetValid(final DateTimeProvider dateTimeProvider); boolean isExpired(final DateTimeProvider dateTimeProvider); } | X509CertificateWrapper implements KeyWrapper { public boolean isExpired(final DateTimeProvider dateTimeProvider) { final LocalDateTime notAfter = DateUtil.fromDate(certificate.getNotAfter()); return notAfter.isBefore(dateTimeProvider.getCurrentDateTime()); } private X509CertificateWrapper(final X509Certificate certificate); static X509CertificateWrapper parse(final RpslObject rpslObject); static X509CertificateWrapper parse(final byte[] certificate); @Override boolean equals(final Object o); @Override int hashCode(); X509Certificate getCertificate(); @Override String getMethod(); @Override List<String> getOwners(); @Override String getFingerprint(); boolean isNotYetValid(final DateTimeProvider dateTimeProvider); boolean isExpired(final DateTimeProvider dateTimeProvider); static final String X509_HEADER; static final String X509_FOOTER; } |
@Test(expected = IllegalArgumentException.class) public void invalidCertificateBase64IsTruncated() { final RpslObject keycert = RpslObject.parse( "key-cert: X509-3465\n" + "method: X509\n" + "owner: /description=570433-veZWA34E9nftz1i7/C=PL/ST=Foo/L=Bar/CN=Test/[email protected]\n" + "fingerpr: 07:AC:10:C0:22:64:84:E7:00:18:5A:29:F0:54:2C:F3\n" + "certif: -----BEGIN CERTIFICATE-----\n" + "certif: MIIHaTCCBlGgAwIBAgICGSowDQYJKoZIhvcNAQEFBQAwgYwxCzAJBgNVBAYTAklM\n" + "certif: UK1J2P3MpSIP8TFJp8fIJDlad3hoRsZeNxuV6D8=\n" + "certif: -----END CERTIFICATE-----\n" + "mnt-by: UPD-MNT\n" + "source: TEST"); X509CertificateWrapper.parse(keycert); } | public static X509CertificateWrapper parse(final RpslObject rpslObject) { if (!looksLikeX509Key(rpslObject)) { throw new IllegalArgumentException("The supplied object has no key"); } try { return parse(RpslObjectFilter.getCertificateFromKeyCert(rpslObject).getBytes(StandardCharsets.ISO_8859_1)); } catch (StreamParsingException e) { throw new IllegalArgumentException("Error parsing X509 certificate from key-cert object", e); } } | X509CertificateWrapper implements KeyWrapper { public static X509CertificateWrapper parse(final RpslObject rpslObject) { if (!looksLikeX509Key(rpslObject)) { throw new IllegalArgumentException("The supplied object has no key"); } try { return parse(RpslObjectFilter.getCertificateFromKeyCert(rpslObject).getBytes(StandardCharsets.ISO_8859_1)); } catch (StreamParsingException e) { throw new IllegalArgumentException("Error parsing X509 certificate from key-cert object", e); } } } | X509CertificateWrapper implements KeyWrapper { public static X509CertificateWrapper parse(final RpslObject rpslObject) { if (!looksLikeX509Key(rpslObject)) { throw new IllegalArgumentException("The supplied object has no key"); } try { return parse(RpslObjectFilter.getCertificateFromKeyCert(rpslObject).getBytes(StandardCharsets.ISO_8859_1)); } catch (StreamParsingException e) { throw new IllegalArgumentException("Error parsing X509 certificate from key-cert object", e); } } private X509CertificateWrapper(final X509Certificate certificate); } | X509CertificateWrapper implements KeyWrapper { public static X509CertificateWrapper parse(final RpslObject rpslObject) { if (!looksLikeX509Key(rpslObject)) { throw new IllegalArgumentException("The supplied object has no key"); } try { return parse(RpslObjectFilter.getCertificateFromKeyCert(rpslObject).getBytes(StandardCharsets.ISO_8859_1)); } catch (StreamParsingException e) { throw new IllegalArgumentException("Error parsing X509 certificate from key-cert object", e); } } private X509CertificateWrapper(final X509Certificate certificate); static X509CertificateWrapper parse(final RpslObject rpslObject); static X509CertificateWrapper parse(final byte[] certificate); @Override boolean equals(final Object o); @Override int hashCode(); X509Certificate getCertificate(); @Override String getMethod(); @Override List<String> getOwners(); @Override String getFingerprint(); boolean isNotYetValid(final DateTimeProvider dateTimeProvider); boolean isExpired(final DateTimeProvider dateTimeProvider); } | X509CertificateWrapper implements KeyWrapper { public static X509CertificateWrapper parse(final RpslObject rpslObject) { if (!looksLikeX509Key(rpslObject)) { throw new IllegalArgumentException("The supplied object has no key"); } try { return parse(RpslObjectFilter.getCertificateFromKeyCert(rpslObject).getBytes(StandardCharsets.ISO_8859_1)); } catch (StreamParsingException e) { throw new IllegalArgumentException("Error parsing X509 certificate from key-cert object", e); } } private X509CertificateWrapper(final X509Certificate certificate); static X509CertificateWrapper parse(final RpslObject rpslObject); static X509CertificateWrapper parse(final byte[] certificate); @Override boolean equals(final Object o); @Override int hashCode(); X509Certificate getCertificate(); @Override String getMethod(); @Override List<String> getOwners(); @Override String getFingerprint(); boolean isNotYetValid(final DateTimeProvider dateTimeProvider); boolean isExpired(final DateTimeProvider dateTimeProvider); static final String X509_HEADER; static final String X509_FOOTER; } |
@Test(expected = IllegalArgumentException.class) public void invalidCertificateNoBase64Data() { final RpslObject keycert = RpslObject.parse( "key-cert: X509-3465\n" + "method: X509\n" + "owner: /description=570433-veZWA34E9nftz1i7/C=PL/ST=Foo/L=Bar/CN=Test/[email protected]\n" + "fingerpr: 07:AC:10:C0:22:64:84:E7:00:18:5A:29:F0:54:2C:F3\n" + "certif: -----BEGIN CERTIFICATE-----\n" + "certif: -----END CERTIFICATE-----\n" + "mnt-by: UPD-MNT\n" + "source: TEST"); X509CertificateWrapper.parse(keycert); } | public static X509CertificateWrapper parse(final RpslObject rpslObject) { if (!looksLikeX509Key(rpslObject)) { throw new IllegalArgumentException("The supplied object has no key"); } try { return parse(RpslObjectFilter.getCertificateFromKeyCert(rpslObject).getBytes(StandardCharsets.ISO_8859_1)); } catch (StreamParsingException e) { throw new IllegalArgumentException("Error parsing X509 certificate from key-cert object", e); } } | X509CertificateWrapper implements KeyWrapper { public static X509CertificateWrapper parse(final RpslObject rpslObject) { if (!looksLikeX509Key(rpslObject)) { throw new IllegalArgumentException("The supplied object has no key"); } try { return parse(RpslObjectFilter.getCertificateFromKeyCert(rpslObject).getBytes(StandardCharsets.ISO_8859_1)); } catch (StreamParsingException e) { throw new IllegalArgumentException("Error parsing X509 certificate from key-cert object", e); } } } | X509CertificateWrapper implements KeyWrapper { public static X509CertificateWrapper parse(final RpslObject rpslObject) { if (!looksLikeX509Key(rpslObject)) { throw new IllegalArgumentException("The supplied object has no key"); } try { return parse(RpslObjectFilter.getCertificateFromKeyCert(rpslObject).getBytes(StandardCharsets.ISO_8859_1)); } catch (StreamParsingException e) { throw new IllegalArgumentException("Error parsing X509 certificate from key-cert object", e); } } private X509CertificateWrapper(final X509Certificate certificate); } | X509CertificateWrapper implements KeyWrapper { public static X509CertificateWrapper parse(final RpslObject rpslObject) { if (!looksLikeX509Key(rpslObject)) { throw new IllegalArgumentException("The supplied object has no key"); } try { return parse(RpslObjectFilter.getCertificateFromKeyCert(rpslObject).getBytes(StandardCharsets.ISO_8859_1)); } catch (StreamParsingException e) { throw new IllegalArgumentException("Error parsing X509 certificate from key-cert object", e); } } private X509CertificateWrapper(final X509Certificate certificate); static X509CertificateWrapper parse(final RpslObject rpslObject); static X509CertificateWrapper parse(final byte[] certificate); @Override boolean equals(final Object o); @Override int hashCode(); X509Certificate getCertificate(); @Override String getMethod(); @Override List<String> getOwners(); @Override String getFingerprint(); boolean isNotYetValid(final DateTimeProvider dateTimeProvider); boolean isExpired(final DateTimeProvider dateTimeProvider); } | X509CertificateWrapper implements KeyWrapper { public static X509CertificateWrapper parse(final RpslObject rpslObject) { if (!looksLikeX509Key(rpslObject)) { throw new IllegalArgumentException("The supplied object has no key"); } try { return parse(RpslObjectFilter.getCertificateFromKeyCert(rpslObject).getBytes(StandardCharsets.ISO_8859_1)); } catch (StreamParsingException e) { throw new IllegalArgumentException("Error parsing X509 certificate from key-cert object", e); } } private X509CertificateWrapper(final X509Certificate certificate); static X509CertificateWrapper parse(final RpslObject rpslObject); static X509CertificateWrapper parse(final byte[] certificate); @Override boolean equals(final Object o); @Override int hashCode(); X509Certificate getCertificate(); @Override String getMethod(); @Override List<String> getOwners(); @Override String getFingerprint(); boolean isNotYetValid(final DateTimeProvider dateTimeProvider); boolean isExpired(final DateTimeProvider dateTimeProvider); static final String X509_HEADER; static final String X509_FOOTER; } |
@Test(expected = IllegalArgumentException.class) public void invalidCertificateInvalidBase64Data() { final RpslObject keycert = RpslObject.parse( "key-cert: X509-3465\n" + "method: X509\n" + "owner: /description=570433-veZWA34E9nftz1i7/C=PL/ST=Foo/L=Bar/CN=Test/[email protected]\n" + "fingerpr: 07:AC:10:C0:22:64:84:E7:00:18:5A:29:F0:54:2C:F3\n" + "certif: -----BEGIN CERTIFICATE-----\n" + "certif: xxx\n" + "certif: -----END CERTIFICATE-----\n" + "mnt-by: UPD-MNT\n" + "source: TEST"); X509CertificateWrapper.parse(keycert); } | public static X509CertificateWrapper parse(final RpslObject rpslObject) { if (!looksLikeX509Key(rpslObject)) { throw new IllegalArgumentException("The supplied object has no key"); } try { return parse(RpslObjectFilter.getCertificateFromKeyCert(rpslObject).getBytes(StandardCharsets.ISO_8859_1)); } catch (StreamParsingException e) { throw new IllegalArgumentException("Error parsing X509 certificate from key-cert object", e); } } | X509CertificateWrapper implements KeyWrapper { public static X509CertificateWrapper parse(final RpslObject rpslObject) { if (!looksLikeX509Key(rpslObject)) { throw new IllegalArgumentException("The supplied object has no key"); } try { return parse(RpslObjectFilter.getCertificateFromKeyCert(rpslObject).getBytes(StandardCharsets.ISO_8859_1)); } catch (StreamParsingException e) { throw new IllegalArgumentException("Error parsing X509 certificate from key-cert object", e); } } } | X509CertificateWrapper implements KeyWrapper { public static X509CertificateWrapper parse(final RpslObject rpslObject) { if (!looksLikeX509Key(rpslObject)) { throw new IllegalArgumentException("The supplied object has no key"); } try { return parse(RpslObjectFilter.getCertificateFromKeyCert(rpslObject).getBytes(StandardCharsets.ISO_8859_1)); } catch (StreamParsingException e) { throw new IllegalArgumentException("Error parsing X509 certificate from key-cert object", e); } } private X509CertificateWrapper(final X509Certificate certificate); } | X509CertificateWrapper implements KeyWrapper { public static X509CertificateWrapper parse(final RpslObject rpslObject) { if (!looksLikeX509Key(rpslObject)) { throw new IllegalArgumentException("The supplied object has no key"); } try { return parse(RpslObjectFilter.getCertificateFromKeyCert(rpslObject).getBytes(StandardCharsets.ISO_8859_1)); } catch (StreamParsingException e) { throw new IllegalArgumentException("Error parsing X509 certificate from key-cert object", e); } } private X509CertificateWrapper(final X509Certificate certificate); static X509CertificateWrapper parse(final RpslObject rpslObject); static X509CertificateWrapper parse(final byte[] certificate); @Override boolean equals(final Object o); @Override int hashCode(); X509Certificate getCertificate(); @Override String getMethod(); @Override List<String> getOwners(); @Override String getFingerprint(); boolean isNotYetValid(final DateTimeProvider dateTimeProvider); boolean isExpired(final DateTimeProvider dateTimeProvider); } | X509CertificateWrapper implements KeyWrapper { public static X509CertificateWrapper parse(final RpslObject rpslObject) { if (!looksLikeX509Key(rpslObject)) { throw new IllegalArgumentException("The supplied object has no key"); } try { return parse(RpslObjectFilter.getCertificateFromKeyCert(rpslObject).getBytes(StandardCharsets.ISO_8859_1)); } catch (StreamParsingException e) { throw new IllegalArgumentException("Error parsing X509 certificate from key-cert object", e); } } private X509CertificateWrapper(final X509Certificate certificate); static X509CertificateWrapper parse(final RpslObject rpslObject); static X509CertificateWrapper parse(final byte[] certificate); @Override boolean equals(final Object o); @Override int hashCode(); X509Certificate getCertificate(); @Override String getMethod(); @Override List<String> getOwners(); @Override String getFingerprint(); boolean isNotYetValid(final DateTimeProvider dateTimeProvider); boolean isExpired(final DateTimeProvider dateTimeProvider); static final String X509_HEADER; static final String X509_FOOTER; } |
@Test(expected = IllegalArgumentException.class) public void invalidCertificateNoCertifLines() { final RpslObject keycert = RpslObject.parse( "key-cert: X509-3465\n" + "method: X509\n" + "owner: /description=570433-veZWA34E9nftz1i7/C=PL/ST=Foo/L=Bar/CN=Test/[email protected]\n" + "fingerpr: 07:AC:10:C0:22:64:84:E7:00:18:5A:29:F0:54:2C:F3\n" + "mnt-by: UPD-MNT\n" + "source: TEST"); X509CertificateWrapper.parse(keycert); } | public static X509CertificateWrapper parse(final RpslObject rpslObject) { if (!looksLikeX509Key(rpslObject)) { throw new IllegalArgumentException("The supplied object has no key"); } try { return parse(RpslObjectFilter.getCertificateFromKeyCert(rpslObject).getBytes(StandardCharsets.ISO_8859_1)); } catch (StreamParsingException e) { throw new IllegalArgumentException("Error parsing X509 certificate from key-cert object", e); } } | X509CertificateWrapper implements KeyWrapper { public static X509CertificateWrapper parse(final RpslObject rpslObject) { if (!looksLikeX509Key(rpslObject)) { throw new IllegalArgumentException("The supplied object has no key"); } try { return parse(RpslObjectFilter.getCertificateFromKeyCert(rpslObject).getBytes(StandardCharsets.ISO_8859_1)); } catch (StreamParsingException e) { throw new IllegalArgumentException("Error parsing X509 certificate from key-cert object", e); } } } | X509CertificateWrapper implements KeyWrapper { public static X509CertificateWrapper parse(final RpslObject rpslObject) { if (!looksLikeX509Key(rpslObject)) { throw new IllegalArgumentException("The supplied object has no key"); } try { return parse(RpslObjectFilter.getCertificateFromKeyCert(rpslObject).getBytes(StandardCharsets.ISO_8859_1)); } catch (StreamParsingException e) { throw new IllegalArgumentException("Error parsing X509 certificate from key-cert object", e); } } private X509CertificateWrapper(final X509Certificate certificate); } | X509CertificateWrapper implements KeyWrapper { public static X509CertificateWrapper parse(final RpslObject rpslObject) { if (!looksLikeX509Key(rpslObject)) { throw new IllegalArgumentException("The supplied object has no key"); } try { return parse(RpslObjectFilter.getCertificateFromKeyCert(rpslObject).getBytes(StandardCharsets.ISO_8859_1)); } catch (StreamParsingException e) { throw new IllegalArgumentException("Error parsing X509 certificate from key-cert object", e); } } private X509CertificateWrapper(final X509Certificate certificate); static X509CertificateWrapper parse(final RpslObject rpslObject); static X509CertificateWrapper parse(final byte[] certificate); @Override boolean equals(final Object o); @Override int hashCode(); X509Certificate getCertificate(); @Override String getMethod(); @Override List<String> getOwners(); @Override String getFingerprint(); boolean isNotYetValid(final DateTimeProvider dateTimeProvider); boolean isExpired(final DateTimeProvider dateTimeProvider); } | X509CertificateWrapper implements KeyWrapper { public static X509CertificateWrapper parse(final RpslObject rpslObject) { if (!looksLikeX509Key(rpslObject)) { throw new IllegalArgumentException("The supplied object has no key"); } try { return parse(RpslObjectFilter.getCertificateFromKeyCert(rpslObject).getBytes(StandardCharsets.ISO_8859_1)); } catch (StreamParsingException e) { throw new IllegalArgumentException("Error parsing X509 certificate from key-cert object", e); } } private X509CertificateWrapper(final X509Certificate certificate); static X509CertificateWrapper parse(final RpslObject rpslObject); static X509CertificateWrapper parse(final byte[] certificate); @Override boolean equals(final Object o); @Override int hashCode(); X509Certificate getCertificate(); @Override String getMethod(); @Override List<String> getOwners(); @Override String getFingerprint(); boolean isNotYetValid(final DateTimeProvider dateTimeProvider); boolean isExpired(final DateTimeProvider dateTimeProvider); static final String X509_HEADER; static final String X509_FOOTER; } |
@Test public void testDateTimeToString_null() { assertNull(FormatHelper.dateTimeToString(null)); } | public static String dateTimeToString(final TemporalAccessor temporalAccessor) { if (temporalAccessor == null) { return null; } if (temporalAccessor.isSupported(ChronoField.HOUR_OF_DAY)) { return DATE_TIME_FORMAT.format(temporalAccessor); } return DATE_FORMAT.format(temporalAccessor); } | FormatHelper { public static String dateTimeToString(final TemporalAccessor temporalAccessor) { if (temporalAccessor == null) { return null; } if (temporalAccessor.isSupported(ChronoField.HOUR_OF_DAY)) { return DATE_TIME_FORMAT.format(temporalAccessor); } return DATE_FORMAT.format(temporalAccessor); } } | FormatHelper { public static String dateTimeToString(final TemporalAccessor temporalAccessor) { if (temporalAccessor == null) { return null; } if (temporalAccessor.isSupported(ChronoField.HOUR_OF_DAY)) { return DATE_TIME_FORMAT.format(temporalAccessor); } return DATE_FORMAT.format(temporalAccessor); } private FormatHelper(); } | FormatHelper { public static String dateTimeToString(final TemporalAccessor temporalAccessor) { if (temporalAccessor == null) { return null; } if (temporalAccessor.isSupported(ChronoField.HOUR_OF_DAY)) { return DATE_TIME_FORMAT.format(temporalAccessor); } return DATE_FORMAT.format(temporalAccessor); } private FormatHelper(); static String dateToString(final TemporalAccessor temporalAccessor); static String dateTimeToString(final TemporalAccessor temporalAccessor); static String dateTimeToUtcString(final TemporalAccessor temporalAccessor); static String prettyPrint(final String prefix, final String value, final int indentation, final int maxLineLength); static String prettyPrint(final String prefix, final String value, final int indentation, final int maxLineLength, boolean repeatPrefix); } | FormatHelper { public static String dateTimeToString(final TemporalAccessor temporalAccessor) { if (temporalAccessor == null) { return null; } if (temporalAccessor.isSupported(ChronoField.HOUR_OF_DAY)) { return DATE_TIME_FORMAT.format(temporalAccessor); } return DATE_FORMAT.format(temporalAccessor); } private FormatHelper(); static String dateToString(final TemporalAccessor temporalAccessor); static String dateTimeToString(final TemporalAccessor temporalAccessor); static String dateTimeToUtcString(final TemporalAccessor temporalAccessor); static String prettyPrint(final String prefix, final String value, final int indentation, final int maxLineLength); static String prettyPrint(final String prefix, final String value, final int indentation, final int maxLineLength, boolean repeatPrefix); } |
@Test public void createKeyWrapper_invalid_pgp_key() { final RpslObject rpslObject = RpslObject.parse("" + "key-cert: PGPKEY-28F6CD6C\n" + "method: PGP\n" + "owner: DFN-CERT (2003), ENCRYPTION Key\n" + "fingerpr: 1C40 500A 1DC4 A8D8 D3EA ABF9 EE99 1EE2 28F6 CD6C\n" + "certif: -----BEGIN PGP PUBLIC KEY BLOCK-----\n" + "certif: Version: GnuPG v1.4.11 (Darwin)\n" + "certif:\n" + "certif: -----END PGP PUBLIC KEY BLOCK-----\n" + "mnt-by: UPD-MNT\n" + "notify: [email protected]\n" + "source: TEST\n" ); final KeyWrapper keyWrapper = subject.createKeyWrapper(rpslObject, updateContainer, updateContext); assertNull(keyWrapper); } | @CheckForNull public KeyWrapper createKeyWrapper(final RpslObject object, final UpdateContainer updateContainer, final UpdateContext updateContext) { try { if (PgpPublicKeyWrapper.looksLikePgpKey(object)) { return PgpPublicKeyWrapper.parse(object); } else if (X509CertificateWrapper.looksLikeX509Key(object)) { return X509CertificateWrapper.parse(object); } else { updateContext.addMessage(updateContainer, new Message(Messages.Type.ERROR, "The supplied object has no key")); } } catch (IllegalArgumentException e) { final Message errorMessage = new Message(Messages.Type.ERROR, e.getMessage()); final List<RpslAttribute> attributes = object.findAttributes(AttributeType.CERTIF); if (attributes.isEmpty()) { updateContext.addMessage(updateContainer, errorMessage); } else { updateContext.addMessage(updateContainer, attributes.get(attributes.size() - 1), errorMessage); } } return null; } | KeyWrapperFactory { @CheckForNull public KeyWrapper createKeyWrapper(final RpslObject object, final UpdateContainer updateContainer, final UpdateContext updateContext) { try { if (PgpPublicKeyWrapper.looksLikePgpKey(object)) { return PgpPublicKeyWrapper.parse(object); } else if (X509CertificateWrapper.looksLikeX509Key(object)) { return X509CertificateWrapper.parse(object); } else { updateContext.addMessage(updateContainer, new Message(Messages.Type.ERROR, "The supplied object has no key")); } } catch (IllegalArgumentException e) { final Message errorMessage = new Message(Messages.Type.ERROR, e.getMessage()); final List<RpslAttribute> attributes = object.findAttributes(AttributeType.CERTIF); if (attributes.isEmpty()) { updateContext.addMessage(updateContainer, errorMessage); } else { updateContext.addMessage(updateContainer, attributes.get(attributes.size() - 1), errorMessage); } } return null; } } | KeyWrapperFactory { @CheckForNull public KeyWrapper createKeyWrapper(final RpslObject object, final UpdateContainer updateContainer, final UpdateContext updateContext) { try { if (PgpPublicKeyWrapper.looksLikePgpKey(object)) { return PgpPublicKeyWrapper.parse(object); } else if (X509CertificateWrapper.looksLikeX509Key(object)) { return X509CertificateWrapper.parse(object); } else { updateContext.addMessage(updateContainer, new Message(Messages.Type.ERROR, "The supplied object has no key")); } } catch (IllegalArgumentException e) { final Message errorMessage = new Message(Messages.Type.ERROR, e.getMessage()); final List<RpslAttribute> attributes = object.findAttributes(AttributeType.CERTIF); if (attributes.isEmpty()) { updateContext.addMessage(updateContainer, errorMessage); } else { updateContext.addMessage(updateContainer, attributes.get(attributes.size() - 1), errorMessage); } } return null; } } | KeyWrapperFactory { @CheckForNull public KeyWrapper createKeyWrapper(final RpslObject object, final UpdateContainer updateContainer, final UpdateContext updateContext) { try { if (PgpPublicKeyWrapper.looksLikePgpKey(object)) { return PgpPublicKeyWrapper.parse(object); } else if (X509CertificateWrapper.looksLikeX509Key(object)) { return X509CertificateWrapper.parse(object); } else { updateContext.addMessage(updateContainer, new Message(Messages.Type.ERROR, "The supplied object has no key")); } } catch (IllegalArgumentException e) { final Message errorMessage = new Message(Messages.Type.ERROR, e.getMessage()); final List<RpslAttribute> attributes = object.findAttributes(AttributeType.CERTIF); if (attributes.isEmpty()) { updateContext.addMessage(updateContainer, errorMessage); } else { updateContext.addMessage(updateContainer, attributes.get(attributes.size() - 1), errorMessage); } } return null; } @CheckForNull KeyWrapper createKeyWrapper(final RpslObject object, final UpdateContainer updateContainer, final UpdateContext updateContext); } | KeyWrapperFactory { @CheckForNull public KeyWrapper createKeyWrapper(final RpslObject object, final UpdateContainer updateContainer, final UpdateContext updateContext) { try { if (PgpPublicKeyWrapper.looksLikePgpKey(object)) { return PgpPublicKeyWrapper.parse(object); } else if (X509CertificateWrapper.looksLikeX509Key(object)) { return X509CertificateWrapper.parse(object); } else { updateContext.addMessage(updateContainer, new Message(Messages.Type.ERROR, "The supplied object has no key")); } } catch (IllegalArgumentException e) { final Message errorMessage = new Message(Messages.Type.ERROR, e.getMessage()); final List<RpslAttribute> attributes = object.findAttributes(AttributeType.CERTIF); if (attributes.isEmpty()) { updateContext.addMessage(updateContainer, errorMessage); } else { updateContext.addMessage(updateContainer, attributes.get(attributes.size() - 1), errorMessage); } } return null; } @CheckForNull KeyWrapper createKeyWrapper(final RpslObject object, final UpdateContainer updateContainer, final UpdateContext updateContext); } |
@Test public void createKeyWrapper_invalid_x509_key() { final RpslObject rpslObject = RpslObject.parse("" + "key-cert: AUTO-1\n" + "method: X509\n" + "owner: /CN=4a96eecf-9d1c-4e12-8add-5ea5522976d8\n" + "fingerpr: 82:7C:C5:40:D1:DB:AE:6A:FA:F8:40:3E:3C:9C:27:7C\n" + "certif: -----BEGIN CERTIFICATE-----\n" + "certif: -----END CERTIFICATE-----\n" + "mnt-by: UPD-MNT\n" + "remarks: remark\n" + "source: TEST\n" ); final KeyWrapper keyWrapper = subject.createKeyWrapper(rpslObject, updateContainer, updateContext); assertNull(keyWrapper); } | @CheckForNull public KeyWrapper createKeyWrapper(final RpslObject object, final UpdateContainer updateContainer, final UpdateContext updateContext) { try { if (PgpPublicKeyWrapper.looksLikePgpKey(object)) { return PgpPublicKeyWrapper.parse(object); } else if (X509CertificateWrapper.looksLikeX509Key(object)) { return X509CertificateWrapper.parse(object); } else { updateContext.addMessage(updateContainer, new Message(Messages.Type.ERROR, "The supplied object has no key")); } } catch (IllegalArgumentException e) { final Message errorMessage = new Message(Messages.Type.ERROR, e.getMessage()); final List<RpslAttribute> attributes = object.findAttributes(AttributeType.CERTIF); if (attributes.isEmpty()) { updateContext.addMessage(updateContainer, errorMessage); } else { updateContext.addMessage(updateContainer, attributes.get(attributes.size() - 1), errorMessage); } } return null; } | KeyWrapperFactory { @CheckForNull public KeyWrapper createKeyWrapper(final RpslObject object, final UpdateContainer updateContainer, final UpdateContext updateContext) { try { if (PgpPublicKeyWrapper.looksLikePgpKey(object)) { return PgpPublicKeyWrapper.parse(object); } else if (X509CertificateWrapper.looksLikeX509Key(object)) { return X509CertificateWrapper.parse(object); } else { updateContext.addMessage(updateContainer, new Message(Messages.Type.ERROR, "The supplied object has no key")); } } catch (IllegalArgumentException e) { final Message errorMessage = new Message(Messages.Type.ERROR, e.getMessage()); final List<RpslAttribute> attributes = object.findAttributes(AttributeType.CERTIF); if (attributes.isEmpty()) { updateContext.addMessage(updateContainer, errorMessage); } else { updateContext.addMessage(updateContainer, attributes.get(attributes.size() - 1), errorMessage); } } return null; } } | KeyWrapperFactory { @CheckForNull public KeyWrapper createKeyWrapper(final RpslObject object, final UpdateContainer updateContainer, final UpdateContext updateContext) { try { if (PgpPublicKeyWrapper.looksLikePgpKey(object)) { return PgpPublicKeyWrapper.parse(object); } else if (X509CertificateWrapper.looksLikeX509Key(object)) { return X509CertificateWrapper.parse(object); } else { updateContext.addMessage(updateContainer, new Message(Messages.Type.ERROR, "The supplied object has no key")); } } catch (IllegalArgumentException e) { final Message errorMessage = new Message(Messages.Type.ERROR, e.getMessage()); final List<RpslAttribute> attributes = object.findAttributes(AttributeType.CERTIF); if (attributes.isEmpty()) { updateContext.addMessage(updateContainer, errorMessage); } else { updateContext.addMessage(updateContainer, attributes.get(attributes.size() - 1), errorMessage); } } return null; } } | KeyWrapperFactory { @CheckForNull public KeyWrapper createKeyWrapper(final RpslObject object, final UpdateContainer updateContainer, final UpdateContext updateContext) { try { if (PgpPublicKeyWrapper.looksLikePgpKey(object)) { return PgpPublicKeyWrapper.parse(object); } else if (X509CertificateWrapper.looksLikeX509Key(object)) { return X509CertificateWrapper.parse(object); } else { updateContext.addMessage(updateContainer, new Message(Messages.Type.ERROR, "The supplied object has no key")); } } catch (IllegalArgumentException e) { final Message errorMessage = new Message(Messages.Type.ERROR, e.getMessage()); final List<RpslAttribute> attributes = object.findAttributes(AttributeType.CERTIF); if (attributes.isEmpty()) { updateContext.addMessage(updateContainer, errorMessage); } else { updateContext.addMessage(updateContainer, attributes.get(attributes.size() - 1), errorMessage); } } return null; } @CheckForNull KeyWrapper createKeyWrapper(final RpslObject object, final UpdateContainer updateContainer, final UpdateContext updateContext); } | KeyWrapperFactory { @CheckForNull public KeyWrapper createKeyWrapper(final RpslObject object, final UpdateContainer updateContainer, final UpdateContext updateContext) { try { if (PgpPublicKeyWrapper.looksLikePgpKey(object)) { return PgpPublicKeyWrapper.parse(object); } else if (X509CertificateWrapper.looksLikeX509Key(object)) { return X509CertificateWrapper.parse(object); } else { updateContext.addMessage(updateContainer, new Message(Messages.Type.ERROR, "The supplied object has no key")); } } catch (IllegalArgumentException e) { final Message errorMessage = new Message(Messages.Type.ERROR, e.getMessage()); final List<RpslAttribute> attributes = object.findAttributes(AttributeType.CERTIF); if (attributes.isEmpty()) { updateContext.addMessage(updateContainer, errorMessage); } else { updateContext.addMessage(updateContainer, attributes.get(attributes.size() - 1), errorMessage); } } return null; } @CheckForNull KeyWrapper createKeyWrapper(final RpslObject object, final UpdateContainer updateContainer, final UpdateContext updateContext); } |
@Test public void createKeyWrapper_pgp_key() { final RpslObject rpslObject = RpslObject.parse("" + "key-cert: X509-1\n" + "method: X509\n" + "owner: /C=NL/O=RIPE NCC/OU=Members/CN=zz.example.denis/[email protected]\n" + "fingerpr: E7:0F:3B:D4:2F:DD:F5:84:3F:4C:D2:98:78:F3:10:3D\n" + "certif: -----BEGIN CERTIFICATE-----\n" + "certif: MIIC8DCCAlmgAwIBAgICBIQwDQYJKoZIhvcNAQEEBQAwXjELMAkGA1UEBhMCTkwx\n" + "certif: ETAPBgNVBAoTCFJJUEUgTkNDMR0wGwYDVQQLExRSSVBFIE5DQyBMSVIgTmV0d29y\n" + "certif: azEdMBsGA1UEAxMUUklQRSBOQ0MgTElSIFJvb3QgQ0EwHhcNMDQwOTI3MTI1NDAx\n" + "certif: WhcNMDUwOTI3MTI1NDAxWjBsMQswCQYDVQQGEwJOTDERMA8GA1UEChMIUklQRSBO\n" + "certif: Q0MxEDAOBgNVBAsTB01lbWJlcnMxGTAXBgNVBAMTEHp6LmV4YW1wbGUuZGVuaXMx\n" + "certif: HTAbBgkqhkiG9w0BCQEWDmRlbmlzQHJpcGUubmV0MFwwDQYJKoZIhvcNAQEBBQAD\n" + "certif: SwAwSAJBAKdZEYY0pCb5updB808+y8CjNsnraQ/3sBL3/184TqD4AE/TSOdZJ2oU\n" + "certif: HmEpfm6ECkbHOJ1NtMwRjAbkk/rWiBMCAwEAAaOB8jCB7zAJBgNVHRMEAjAAMBEG\n" + "certif: CWCGSAGG+EIBAQQEAwIFoDALBgNVHQ8EBAMCBeAwGgYJYIZIAYb4QgENBA0WC1JJ\n" + "certif: UEUgTkNDIENBMB0GA1UdDgQWBBQk0+qAmXPImzyVTOGARwNPHAX0GTCBhgYDVR0j\n" + "certif: BH8wfYAUI8r2d8CnSt174cfhUw2KNga3Px6hYqRgMF4xCzAJBgNVBAYTAk5MMREw\n" + "certif: DwYDVQQKEwhSSVBFIE5DQzEdMBsGA1UECxMUUklQRSBOQ0MgTElSIE5ldHdvcmsx\n" + "certif: HTAbBgNVBAMTFFJJUEUgTkNDIExJUiBSb290IENBggEAMA0GCSqGSIb3DQEBBAUA\n" + "certif: A4GBAAxojauJHRm3XtPfOCe4B5iz8uVt/EeKhM4gjHGJrUbkAlftLJYUe2Vx8HcH\n" + "certif: O4b+9E098Rt6MfFF+1dYNz7/NgiIpR7BlmdWzPCyhfgxJxTM9m9B7B/6noDU+aaf\n" + "certif: w0L5DyjKGe0dbjMKtaDdgQhxj8aBHNnQVbS9Oqhvmc65XgNi\n" + "certif: -----END CERTIFICATE-----\n" + "mnt-by: UPD-MNT\n" + "source: TEST\n" ); final KeyWrapper keyWrapper = subject.createKeyWrapper(rpslObject, updateContainer, updateContext); assertTrue(keyWrapper instanceof X509CertificateWrapper); } | @CheckForNull public KeyWrapper createKeyWrapper(final RpslObject object, final UpdateContainer updateContainer, final UpdateContext updateContext) { try { if (PgpPublicKeyWrapper.looksLikePgpKey(object)) { return PgpPublicKeyWrapper.parse(object); } else if (X509CertificateWrapper.looksLikeX509Key(object)) { return X509CertificateWrapper.parse(object); } else { updateContext.addMessage(updateContainer, new Message(Messages.Type.ERROR, "The supplied object has no key")); } } catch (IllegalArgumentException e) { final Message errorMessage = new Message(Messages.Type.ERROR, e.getMessage()); final List<RpslAttribute> attributes = object.findAttributes(AttributeType.CERTIF); if (attributes.isEmpty()) { updateContext.addMessage(updateContainer, errorMessage); } else { updateContext.addMessage(updateContainer, attributes.get(attributes.size() - 1), errorMessage); } } return null; } | KeyWrapperFactory { @CheckForNull public KeyWrapper createKeyWrapper(final RpslObject object, final UpdateContainer updateContainer, final UpdateContext updateContext) { try { if (PgpPublicKeyWrapper.looksLikePgpKey(object)) { return PgpPublicKeyWrapper.parse(object); } else if (X509CertificateWrapper.looksLikeX509Key(object)) { return X509CertificateWrapper.parse(object); } else { updateContext.addMessage(updateContainer, new Message(Messages.Type.ERROR, "The supplied object has no key")); } } catch (IllegalArgumentException e) { final Message errorMessage = new Message(Messages.Type.ERROR, e.getMessage()); final List<RpslAttribute> attributes = object.findAttributes(AttributeType.CERTIF); if (attributes.isEmpty()) { updateContext.addMessage(updateContainer, errorMessage); } else { updateContext.addMessage(updateContainer, attributes.get(attributes.size() - 1), errorMessage); } } return null; } } | KeyWrapperFactory { @CheckForNull public KeyWrapper createKeyWrapper(final RpslObject object, final UpdateContainer updateContainer, final UpdateContext updateContext) { try { if (PgpPublicKeyWrapper.looksLikePgpKey(object)) { return PgpPublicKeyWrapper.parse(object); } else if (X509CertificateWrapper.looksLikeX509Key(object)) { return X509CertificateWrapper.parse(object); } else { updateContext.addMessage(updateContainer, new Message(Messages.Type.ERROR, "The supplied object has no key")); } } catch (IllegalArgumentException e) { final Message errorMessage = new Message(Messages.Type.ERROR, e.getMessage()); final List<RpslAttribute> attributes = object.findAttributes(AttributeType.CERTIF); if (attributes.isEmpty()) { updateContext.addMessage(updateContainer, errorMessage); } else { updateContext.addMessage(updateContainer, attributes.get(attributes.size() - 1), errorMessage); } } return null; } } | KeyWrapperFactory { @CheckForNull public KeyWrapper createKeyWrapper(final RpslObject object, final UpdateContainer updateContainer, final UpdateContext updateContext) { try { if (PgpPublicKeyWrapper.looksLikePgpKey(object)) { return PgpPublicKeyWrapper.parse(object); } else if (X509CertificateWrapper.looksLikeX509Key(object)) { return X509CertificateWrapper.parse(object); } else { updateContext.addMessage(updateContainer, new Message(Messages.Type.ERROR, "The supplied object has no key")); } } catch (IllegalArgumentException e) { final Message errorMessage = new Message(Messages.Type.ERROR, e.getMessage()); final List<RpslAttribute> attributes = object.findAttributes(AttributeType.CERTIF); if (attributes.isEmpty()) { updateContext.addMessage(updateContainer, errorMessage); } else { updateContext.addMessage(updateContainer, attributes.get(attributes.size() - 1), errorMessage); } } return null; } @CheckForNull KeyWrapper createKeyWrapper(final RpslObject object, final UpdateContainer updateContainer, final UpdateContext updateContext); } | KeyWrapperFactory { @CheckForNull public KeyWrapper createKeyWrapper(final RpslObject object, final UpdateContainer updateContainer, final UpdateContext updateContext) { try { if (PgpPublicKeyWrapper.looksLikePgpKey(object)) { return PgpPublicKeyWrapper.parse(object); } else if (X509CertificateWrapper.looksLikeX509Key(object)) { return X509CertificateWrapper.parse(object); } else { updateContext.addMessage(updateContainer, new Message(Messages.Type.ERROR, "The supplied object has no key")); } } catch (IllegalArgumentException e) { final Message errorMessage = new Message(Messages.Type.ERROR, e.getMessage()); final List<RpslAttribute> attributes = object.findAttributes(AttributeType.CERTIF); if (attributes.isEmpty()) { updateContext.addMessage(updateContainer, errorMessage); } else { updateContext.addMessage(updateContainer, attributes.get(attributes.size() - 1), errorMessage); } } return null; } @CheckForNull KeyWrapper createKeyWrapper(final RpslObject object, final UpdateContainer updateContainer, final UpdateContext updateContext); } |
@Test public void createKeyWrapper_x509_key() { final RpslObject rpslObject = RpslObject.parse("" + "key-cert: PGPKEY-81CCF97D\n" + "method: PGP\n" + "owner: Unknown <[email protected]>\n" + "fingerpr: EDDF 375A B830 D1BB 26E5 ED3B 76CA 91EF 81CC F97D\n" + "certif: -----BEGIN PGP PUBLIC KEY BLOCK-----\n" + "certif: Version: GnuPG v1.4.12 (Darwin)\n" + "certif: Comment: GPGTools - http: "certif:\n" + "certif: mQENBFC0yvUBCACn2JKwa5e8Sj3QknEnD5ypvmzNWwYbDhLjmD06wuZxt7Wpgm4+\n" + "certif: yO68swuow09jsrh2DAl2nKQ7YaODEipis0d4H2i0mSswlsC7xbmpx3dRP/yOu4WH\n" + "certif: 2kZciQYxC1NY9J3CNIZxgw6zcghJhtm+LT7OzPS8s3qp+w5nj+vKY09A+BK8yHBN\n" + "certif: E+VPeLOAi+D97s+Da/UZWkZxFJHdV+cAzQ05ARqXKXeadfFdbkx0Eq2R0RZm9R+L\n" + "certif: A9tPUhtw5wk1gFMsN7c5NKwTUQ/0HTTgA5eyKMnTKAdwhIY5/VDxUd1YprnK+Ebd\n" + "certif: YNZh+L39kqoUL6lqeu0dUzYp2Ll7R2IURaXNABEBAAG0I25vcmVwbHlAcmlwZS5u\n" + "certif: ZXQgPG5vcmVwbHlAcmlwZS5uZXQ+iQE4BBMBAgAiBQJQtMr1AhsDBgsJCAcDAgYV\n" + "certif: CAIJCgsEFgIDAQIeAQIXgAAKCRC7zLstV2OVDdjSCACYAyyWr83Df/zzOWGP+qMF\n" + "certif: Vukj8xhaM5f5MGb9FjMKClo6ezT4hLjQ8hfxAAZxndwAXoz46RbDUsAe/aBwdwKB\n" + "certif: 0owcacoaxUd0i+gVEn7CBHPVUfNIuNemcrf1N7aqBkpBLf+NINZ2+3c3t14k1BGe\n" + "certif: xCInxEqHnq4zbUmunCNYjHoKbUj6Aq7janyC7W1MIIAcOY9/PvWQyf3VnERQImgt\n" + "certif: 0fhiekCr6tRbANJ4qFoJQSM/ACoVkpDvb5PHZuZXf/v+XB1DV7gZHjJeZA+Jto5Z\n" + "certif: xrmS5E+HEHVBO8RsBOWDlmWCcZ4k9olxp7/z++mADXPprmLaK8vjQmiC2q/KOTVA\n" + "certif: uQENBFC0yvUBCADTYI6i4baHAkeY2lR2rebpTu1nRHbIET20II8/ZmZDK8E2Lwyv\n" + "certif: eWold6pAWDq9E23J9xAWL4QUQRQ4V+28+lknMySXbU3uFLXGAs6W9PrZXGcmy/12\n" + "certif: pZ+82hHckh+jN9xUTtF89NK/wHh09SAxDa/ST/z/Dj0k3pQWzgBdi36jwEFtHhck\n" + "certif: xFwGst5Cv8SLvA9/DaP75m9VDJsmsSwh/6JqMUb+hY71Dr7oxlIFLdsREsFVzVec\n" + "certif: YHsKINlZKh60dA/Br+CC7fClBycEsR4Z7akw9cPLWIGnjvw2+nq9miE005QLqRy4\n" + "certif: dsrwydbMGplaE/mZc0d2WnNyiCBXAHB5UhmZABEBAAGJAR8EGAECAAkFAlC0yvUC\n" + "certif: GwwACgkQu8y7LVdjlQ1GMAgAgUohj4q3mAJPR6d5pJ8Ig5E3QK87z3lIpgxHbYR4\n" + "certif: HNaR0NIV/GAt/uca11DtIdj3kBAj69QSPqNVRqaZja3NyhNWQM4OPDWKIUZfolF3\n" + "certif: eY2q58kEhxhz3JKJt4z45TnFY2GFGqYwFPQ94z1S9FOJCifL/dLpwPBSKucCac9y\n" + "certif: 6KiKfjEehZ4VqmtM/SvN23GiI/OOdlHL/xnU4NgZ90GHmmQFfdUiX36jWK99LBqC\n" + "certif: RNW8V2MV+rElPVRHev+nw7vgCM0ewXZwQB/bBLbBrayx8LzGtMvAo4kDJ1kpQpip\n" + "certif: a/bmKCK6E+Z9aph5uoke8bKoybIoQ2K3OQ4Mh8yiI+AjiQ==\n" + "certif: =HQmg\n" + "certif: -----END PGP PUBLIC KEY BLOCK-----\n" + "mnt-by: UPD-MNT\n" + "notify: [email protected]\n" + "source: TEST\n" ); final KeyWrapper keyWrapper = subject.createKeyWrapper(rpslObject, updateContainer, updateContext); assertTrue(keyWrapper instanceof PgpPublicKeyWrapper); } | @CheckForNull public KeyWrapper createKeyWrapper(final RpslObject object, final UpdateContainer updateContainer, final UpdateContext updateContext) { try { if (PgpPublicKeyWrapper.looksLikePgpKey(object)) { return PgpPublicKeyWrapper.parse(object); } else if (X509CertificateWrapper.looksLikeX509Key(object)) { return X509CertificateWrapper.parse(object); } else { updateContext.addMessage(updateContainer, new Message(Messages.Type.ERROR, "The supplied object has no key")); } } catch (IllegalArgumentException e) { final Message errorMessage = new Message(Messages.Type.ERROR, e.getMessage()); final List<RpslAttribute> attributes = object.findAttributes(AttributeType.CERTIF); if (attributes.isEmpty()) { updateContext.addMessage(updateContainer, errorMessage); } else { updateContext.addMessage(updateContainer, attributes.get(attributes.size() - 1), errorMessage); } } return null; } | KeyWrapperFactory { @CheckForNull public KeyWrapper createKeyWrapper(final RpslObject object, final UpdateContainer updateContainer, final UpdateContext updateContext) { try { if (PgpPublicKeyWrapper.looksLikePgpKey(object)) { return PgpPublicKeyWrapper.parse(object); } else if (X509CertificateWrapper.looksLikeX509Key(object)) { return X509CertificateWrapper.parse(object); } else { updateContext.addMessage(updateContainer, new Message(Messages.Type.ERROR, "The supplied object has no key")); } } catch (IllegalArgumentException e) { final Message errorMessage = new Message(Messages.Type.ERROR, e.getMessage()); final List<RpslAttribute> attributes = object.findAttributes(AttributeType.CERTIF); if (attributes.isEmpty()) { updateContext.addMessage(updateContainer, errorMessage); } else { updateContext.addMessage(updateContainer, attributes.get(attributes.size() - 1), errorMessage); } } return null; } } | KeyWrapperFactory { @CheckForNull public KeyWrapper createKeyWrapper(final RpslObject object, final UpdateContainer updateContainer, final UpdateContext updateContext) { try { if (PgpPublicKeyWrapper.looksLikePgpKey(object)) { return PgpPublicKeyWrapper.parse(object); } else if (X509CertificateWrapper.looksLikeX509Key(object)) { return X509CertificateWrapper.parse(object); } else { updateContext.addMessage(updateContainer, new Message(Messages.Type.ERROR, "The supplied object has no key")); } } catch (IllegalArgumentException e) { final Message errorMessage = new Message(Messages.Type.ERROR, e.getMessage()); final List<RpslAttribute> attributes = object.findAttributes(AttributeType.CERTIF); if (attributes.isEmpty()) { updateContext.addMessage(updateContainer, errorMessage); } else { updateContext.addMessage(updateContainer, attributes.get(attributes.size() - 1), errorMessage); } } return null; } } | KeyWrapperFactory { @CheckForNull public KeyWrapper createKeyWrapper(final RpslObject object, final UpdateContainer updateContainer, final UpdateContext updateContext) { try { if (PgpPublicKeyWrapper.looksLikePgpKey(object)) { return PgpPublicKeyWrapper.parse(object); } else if (X509CertificateWrapper.looksLikeX509Key(object)) { return X509CertificateWrapper.parse(object); } else { updateContext.addMessage(updateContainer, new Message(Messages.Type.ERROR, "The supplied object has no key")); } } catch (IllegalArgumentException e) { final Message errorMessage = new Message(Messages.Type.ERROR, e.getMessage()); final List<RpslAttribute> attributes = object.findAttributes(AttributeType.CERTIF); if (attributes.isEmpty()) { updateContext.addMessage(updateContainer, errorMessage); } else { updateContext.addMessage(updateContainer, attributes.get(attributes.size() - 1), errorMessage); } } return null; } @CheckForNull KeyWrapper createKeyWrapper(final RpslObject object, final UpdateContainer updateContainer, final UpdateContext updateContext); } | KeyWrapperFactory { @CheckForNull public KeyWrapper createKeyWrapper(final RpslObject object, final UpdateContainer updateContainer, final UpdateContext updateContext) { try { if (PgpPublicKeyWrapper.looksLikePgpKey(object)) { return PgpPublicKeyWrapper.parse(object); } else if (X509CertificateWrapper.looksLikeX509Key(object)) { return X509CertificateWrapper.parse(object); } else { updateContext.addMessage(updateContainer, new Message(Messages.Type.ERROR, "The supplied object has no key")); } } catch (IllegalArgumentException e) { final Message errorMessage = new Message(Messages.Type.ERROR, e.getMessage()); final List<RpslAttribute> attributes = object.findAttributes(AttributeType.CERTIF); if (attributes.isEmpty()) { updateContext.addMessage(updateContainer, errorMessage); } else { updateContext.addMessage(updateContainer, attributes.get(attributes.size() - 1), errorMessage); } } return null; } @CheckForNull KeyWrapper createKeyWrapper(final RpslObject object, final UpdateContainer updateContainer, final UpdateContext updateContext); } |
@Test public void isPgpKey() { assertThat(PgpPublicKeyWrapper.looksLikePgpKey(pgpKeycert), is(true)); assertThat(PgpPublicKeyWrapper.looksLikePgpKey(x509Keycert), is(false)); } | static boolean looksLikePgpKey(final RpslObject rpslObject) { final String pgpKey = RpslObjectFilter.getCertificateFromKeyCert(rpslObject); return pgpKey.indexOf(PGP_HEADER) != -1 && pgpKey.indexOf(PGP_FOOTER) != -1; } | PgpPublicKeyWrapper implements KeyWrapper { static boolean looksLikePgpKey(final RpslObject rpslObject) { final String pgpKey = RpslObjectFilter.getCertificateFromKeyCert(rpslObject); return pgpKey.indexOf(PGP_HEADER) != -1 && pgpKey.indexOf(PGP_FOOTER) != -1; } } | PgpPublicKeyWrapper implements KeyWrapper { static boolean looksLikePgpKey(final RpslObject rpslObject) { final String pgpKey = RpslObjectFilter.getCertificateFromKeyCert(rpslObject); return pgpKey.indexOf(PGP_HEADER) != -1 && pgpKey.indexOf(PGP_FOOTER) != -1; } PgpPublicKeyWrapper(final PGPPublicKey masterKey, final List<PGPPublicKey> subKeys); } | PgpPublicKeyWrapper implements KeyWrapper { static boolean looksLikePgpKey(final RpslObject rpslObject) { final String pgpKey = RpslObjectFilter.getCertificateFromKeyCert(rpslObject); return pgpKey.indexOf(PGP_HEADER) != -1 && pgpKey.indexOf(PGP_FOOTER) != -1; } PgpPublicKeyWrapper(final PGPPublicKey masterKey, final List<PGPPublicKey> subKeys); static PgpPublicKeyWrapper parse(final RpslObject object); PGPPublicKey getPublicKey(); List<PGPPublicKey> getSubKeys(); @Override String getMethod(); @Override List<String> getOwners(); @Override String getFingerprint(); boolean isExpired(final DateTimeProvider dateTimeProvider); boolean isRevoked(); @Override boolean equals(final Object o); @Override int hashCode(); } | PgpPublicKeyWrapper implements KeyWrapper { static boolean looksLikePgpKey(final RpslObject rpslObject) { final String pgpKey = RpslObjectFilter.getCertificateFromKeyCert(rpslObject); return pgpKey.indexOf(PGP_HEADER) != -1 && pgpKey.indexOf(PGP_FOOTER) != -1; } PgpPublicKeyWrapper(final PGPPublicKey masterKey, final List<PGPPublicKey> subKeys); static PgpPublicKeyWrapper parse(final RpslObject object); PGPPublicKey getPublicKey(); List<PGPPublicKey> getSubKeys(); @Override String getMethod(); @Override List<String> getOwners(); @Override String getFingerprint(); boolean isExpired(final DateTimeProvider dateTimeProvider); boolean isRevoked(); @Override boolean equals(final Object o); @Override int hashCode(); } |
@Test public void multiplePublicKeys() throws Exception { try { PgpPublicKeyWrapper.parse(RpslObject.parse(getResource("keycerts/PGPKEY-MULTIPLE-PUBLIC-KEYS.TXT"))); fail(); } catch (IllegalArgumentException e) { assertThat(e.getMessage(), is("The supplied object has multiple keys")); } } | public static PgpPublicKeyWrapper parse(final RpslObject object) { if (!looksLikePgpKey(object)) { throw new IllegalArgumentException("The supplied object has no key"); } try { final byte[] bytes = RpslObjectFilter.getCertificateFromKeyCert(object).getBytes(StandardCharsets.ISO_8859_1); final ArmoredInputStream armoredInputStream = (ArmoredInputStream) PGPUtil.getDecoderStream(new ByteArrayInputStream(bytes)); PGPPublicKey masterKey = null; List<PGPPublicKey> subKeys = Lists.newArrayList(); @SuppressWarnings("unchecked") final Iterator<PGPPublicKeyRing> keyRingsIterator = new BcPGPPublicKeyRingCollection(armoredInputStream).getKeyRings(); while (keyRingsIterator.hasNext()) { @SuppressWarnings("unchecked") final Iterator<PGPPublicKey> keyIterator = keyRingsIterator.next().getPublicKeys(); while (keyIterator.hasNext()) { final PGPPublicKey key = keyIterator.next(); if (key.isMasterKey()) { if (masterKey == null) { masterKey = key; } else { throw new IllegalArgumentException("The supplied object has multiple keys"); } } else { if (masterKey == null) { continue; } final Iterator<PGPSignature> signatureIterator = key.getSignaturesOfType(PGPSignature.SUBKEY_BINDING); while (signatureIterator.hasNext()) { final PGPSignature signature = signatureIterator.next(); if (!hasFlag(signature, PGPKeyFlags.CAN_SIGN)) { continue; } JcaPGPContentVerifierBuilderProvider provider = new JcaPGPContentVerifierBuilderProvider().setProvider(PROVIDER); signature.init(provider, masterKey); try { if (signature.verifyCertification(masterKey, key)) { subKeys.add(key); } } catch (PGPException e) { throw new IllegalStateException(e); } } } } } if (masterKey == null) { throw new IllegalArgumentException("The supplied object has no key"); } return new PgpPublicKeyWrapper(masterKey, subKeys); } catch (IOException | PGPException e) { throw new IllegalArgumentException("The supplied object has no key"); } catch (IllegalArgumentException e) { throw e; } catch (Exception e) { LOGGER.warn("Unexpected error, throwing no key by default", e); throw new IllegalArgumentException("The supplied object has no key"); } } | PgpPublicKeyWrapper implements KeyWrapper { public static PgpPublicKeyWrapper parse(final RpslObject object) { if (!looksLikePgpKey(object)) { throw new IllegalArgumentException("The supplied object has no key"); } try { final byte[] bytes = RpslObjectFilter.getCertificateFromKeyCert(object).getBytes(StandardCharsets.ISO_8859_1); final ArmoredInputStream armoredInputStream = (ArmoredInputStream) PGPUtil.getDecoderStream(new ByteArrayInputStream(bytes)); PGPPublicKey masterKey = null; List<PGPPublicKey> subKeys = Lists.newArrayList(); @SuppressWarnings("unchecked") final Iterator<PGPPublicKeyRing> keyRingsIterator = new BcPGPPublicKeyRingCollection(armoredInputStream).getKeyRings(); while (keyRingsIterator.hasNext()) { @SuppressWarnings("unchecked") final Iterator<PGPPublicKey> keyIterator = keyRingsIterator.next().getPublicKeys(); while (keyIterator.hasNext()) { final PGPPublicKey key = keyIterator.next(); if (key.isMasterKey()) { if (masterKey == null) { masterKey = key; } else { throw new IllegalArgumentException("The supplied object has multiple keys"); } } else { if (masterKey == null) { continue; } final Iterator<PGPSignature> signatureIterator = key.getSignaturesOfType(PGPSignature.SUBKEY_BINDING); while (signatureIterator.hasNext()) { final PGPSignature signature = signatureIterator.next(); if (!hasFlag(signature, PGPKeyFlags.CAN_SIGN)) { continue; } JcaPGPContentVerifierBuilderProvider provider = new JcaPGPContentVerifierBuilderProvider().setProvider(PROVIDER); signature.init(provider, masterKey); try { if (signature.verifyCertification(masterKey, key)) { subKeys.add(key); } } catch (PGPException e) { throw new IllegalStateException(e); } } } } } if (masterKey == null) { throw new IllegalArgumentException("The supplied object has no key"); } return new PgpPublicKeyWrapper(masterKey, subKeys); } catch (IOException | PGPException e) { throw new IllegalArgumentException("The supplied object has no key"); } catch (IllegalArgumentException e) { throw e; } catch (Exception e) { LOGGER.warn("Unexpected error, throwing no key by default", e); throw new IllegalArgumentException("The supplied object has no key"); } } } | PgpPublicKeyWrapper implements KeyWrapper { public static PgpPublicKeyWrapper parse(final RpslObject object) { if (!looksLikePgpKey(object)) { throw new IllegalArgumentException("The supplied object has no key"); } try { final byte[] bytes = RpslObjectFilter.getCertificateFromKeyCert(object).getBytes(StandardCharsets.ISO_8859_1); final ArmoredInputStream armoredInputStream = (ArmoredInputStream) PGPUtil.getDecoderStream(new ByteArrayInputStream(bytes)); PGPPublicKey masterKey = null; List<PGPPublicKey> subKeys = Lists.newArrayList(); @SuppressWarnings("unchecked") final Iterator<PGPPublicKeyRing> keyRingsIterator = new BcPGPPublicKeyRingCollection(armoredInputStream).getKeyRings(); while (keyRingsIterator.hasNext()) { @SuppressWarnings("unchecked") final Iterator<PGPPublicKey> keyIterator = keyRingsIterator.next().getPublicKeys(); while (keyIterator.hasNext()) { final PGPPublicKey key = keyIterator.next(); if (key.isMasterKey()) { if (masterKey == null) { masterKey = key; } else { throw new IllegalArgumentException("The supplied object has multiple keys"); } } else { if (masterKey == null) { continue; } final Iterator<PGPSignature> signatureIterator = key.getSignaturesOfType(PGPSignature.SUBKEY_BINDING); while (signatureIterator.hasNext()) { final PGPSignature signature = signatureIterator.next(); if (!hasFlag(signature, PGPKeyFlags.CAN_SIGN)) { continue; } JcaPGPContentVerifierBuilderProvider provider = new JcaPGPContentVerifierBuilderProvider().setProvider(PROVIDER); signature.init(provider, masterKey); try { if (signature.verifyCertification(masterKey, key)) { subKeys.add(key); } } catch (PGPException e) { throw new IllegalStateException(e); } } } } } if (masterKey == null) { throw new IllegalArgumentException("The supplied object has no key"); } return new PgpPublicKeyWrapper(masterKey, subKeys); } catch (IOException | PGPException e) { throw new IllegalArgumentException("The supplied object has no key"); } catch (IllegalArgumentException e) { throw e; } catch (Exception e) { LOGGER.warn("Unexpected error, throwing no key by default", e); throw new IllegalArgumentException("The supplied object has no key"); } } PgpPublicKeyWrapper(final PGPPublicKey masterKey, final List<PGPPublicKey> subKeys); } | PgpPublicKeyWrapper implements KeyWrapper { public static PgpPublicKeyWrapper parse(final RpslObject object) { if (!looksLikePgpKey(object)) { throw new IllegalArgumentException("The supplied object has no key"); } try { final byte[] bytes = RpslObjectFilter.getCertificateFromKeyCert(object).getBytes(StandardCharsets.ISO_8859_1); final ArmoredInputStream armoredInputStream = (ArmoredInputStream) PGPUtil.getDecoderStream(new ByteArrayInputStream(bytes)); PGPPublicKey masterKey = null; List<PGPPublicKey> subKeys = Lists.newArrayList(); @SuppressWarnings("unchecked") final Iterator<PGPPublicKeyRing> keyRingsIterator = new BcPGPPublicKeyRingCollection(armoredInputStream).getKeyRings(); while (keyRingsIterator.hasNext()) { @SuppressWarnings("unchecked") final Iterator<PGPPublicKey> keyIterator = keyRingsIterator.next().getPublicKeys(); while (keyIterator.hasNext()) { final PGPPublicKey key = keyIterator.next(); if (key.isMasterKey()) { if (masterKey == null) { masterKey = key; } else { throw new IllegalArgumentException("The supplied object has multiple keys"); } } else { if (masterKey == null) { continue; } final Iterator<PGPSignature> signatureIterator = key.getSignaturesOfType(PGPSignature.SUBKEY_BINDING); while (signatureIterator.hasNext()) { final PGPSignature signature = signatureIterator.next(); if (!hasFlag(signature, PGPKeyFlags.CAN_SIGN)) { continue; } JcaPGPContentVerifierBuilderProvider provider = new JcaPGPContentVerifierBuilderProvider().setProvider(PROVIDER); signature.init(provider, masterKey); try { if (signature.verifyCertification(masterKey, key)) { subKeys.add(key); } } catch (PGPException e) { throw new IllegalStateException(e); } } } } } if (masterKey == null) { throw new IllegalArgumentException("The supplied object has no key"); } return new PgpPublicKeyWrapper(masterKey, subKeys); } catch (IOException | PGPException e) { throw new IllegalArgumentException("The supplied object has no key"); } catch (IllegalArgumentException e) { throw e; } catch (Exception e) { LOGGER.warn("Unexpected error, throwing no key by default", e); throw new IllegalArgumentException("The supplied object has no key"); } } PgpPublicKeyWrapper(final PGPPublicKey masterKey, final List<PGPPublicKey> subKeys); static PgpPublicKeyWrapper parse(final RpslObject object); PGPPublicKey getPublicKey(); List<PGPPublicKey> getSubKeys(); @Override String getMethod(); @Override List<String> getOwners(); @Override String getFingerprint(); boolean isExpired(final DateTimeProvider dateTimeProvider); boolean isRevoked(); @Override boolean equals(final Object o); @Override int hashCode(); } | PgpPublicKeyWrapper implements KeyWrapper { public static PgpPublicKeyWrapper parse(final RpslObject object) { if (!looksLikePgpKey(object)) { throw new IllegalArgumentException("The supplied object has no key"); } try { final byte[] bytes = RpslObjectFilter.getCertificateFromKeyCert(object).getBytes(StandardCharsets.ISO_8859_1); final ArmoredInputStream armoredInputStream = (ArmoredInputStream) PGPUtil.getDecoderStream(new ByteArrayInputStream(bytes)); PGPPublicKey masterKey = null; List<PGPPublicKey> subKeys = Lists.newArrayList(); @SuppressWarnings("unchecked") final Iterator<PGPPublicKeyRing> keyRingsIterator = new BcPGPPublicKeyRingCollection(armoredInputStream).getKeyRings(); while (keyRingsIterator.hasNext()) { @SuppressWarnings("unchecked") final Iterator<PGPPublicKey> keyIterator = keyRingsIterator.next().getPublicKeys(); while (keyIterator.hasNext()) { final PGPPublicKey key = keyIterator.next(); if (key.isMasterKey()) { if (masterKey == null) { masterKey = key; } else { throw new IllegalArgumentException("The supplied object has multiple keys"); } } else { if (masterKey == null) { continue; } final Iterator<PGPSignature> signatureIterator = key.getSignaturesOfType(PGPSignature.SUBKEY_BINDING); while (signatureIterator.hasNext()) { final PGPSignature signature = signatureIterator.next(); if (!hasFlag(signature, PGPKeyFlags.CAN_SIGN)) { continue; } JcaPGPContentVerifierBuilderProvider provider = new JcaPGPContentVerifierBuilderProvider().setProvider(PROVIDER); signature.init(provider, masterKey); try { if (signature.verifyCertification(masterKey, key)) { subKeys.add(key); } } catch (PGPException e) { throw new IllegalStateException(e); } } } } } if (masterKey == null) { throw new IllegalArgumentException("The supplied object has no key"); } return new PgpPublicKeyWrapper(masterKey, subKeys); } catch (IOException | PGPException e) { throw new IllegalArgumentException("The supplied object has no key"); } catch (IllegalArgumentException e) { throw e; } catch (Exception e) { LOGGER.warn("Unexpected error, throwing no key by default", e); throw new IllegalArgumentException("The supplied object has no key"); } } PgpPublicKeyWrapper(final PGPPublicKey masterKey, final List<PGPPublicKey> subKeys); static PgpPublicKeyWrapper parse(final RpslObject object); PGPPublicKey getPublicKey(); List<PGPPublicKey> getSubKeys(); @Override String getMethod(); @Override List<String> getOwners(); @Override String getFingerprint(); boolean isExpired(final DateTimeProvider dateTimeProvider); boolean isRevoked(); @Override boolean equals(final Object o); @Override int hashCode(); } |
@Test public void parsePrivateKey() throws Exception { try { PgpPublicKeyWrapper.parse(RpslObject.parse(getResource("keycerts/PGPKEY-PRIVATE-KEY.TXT"))); fail(); } catch (IllegalArgumentException e) { assertThat(e.getMessage(), is("The supplied object has no key")); } } | public static PgpPublicKeyWrapper parse(final RpslObject object) { if (!looksLikePgpKey(object)) { throw new IllegalArgumentException("The supplied object has no key"); } try { final byte[] bytes = RpslObjectFilter.getCertificateFromKeyCert(object).getBytes(StandardCharsets.ISO_8859_1); final ArmoredInputStream armoredInputStream = (ArmoredInputStream) PGPUtil.getDecoderStream(new ByteArrayInputStream(bytes)); PGPPublicKey masterKey = null; List<PGPPublicKey> subKeys = Lists.newArrayList(); @SuppressWarnings("unchecked") final Iterator<PGPPublicKeyRing> keyRingsIterator = new BcPGPPublicKeyRingCollection(armoredInputStream).getKeyRings(); while (keyRingsIterator.hasNext()) { @SuppressWarnings("unchecked") final Iterator<PGPPublicKey> keyIterator = keyRingsIterator.next().getPublicKeys(); while (keyIterator.hasNext()) { final PGPPublicKey key = keyIterator.next(); if (key.isMasterKey()) { if (masterKey == null) { masterKey = key; } else { throw new IllegalArgumentException("The supplied object has multiple keys"); } } else { if (masterKey == null) { continue; } final Iterator<PGPSignature> signatureIterator = key.getSignaturesOfType(PGPSignature.SUBKEY_BINDING); while (signatureIterator.hasNext()) { final PGPSignature signature = signatureIterator.next(); if (!hasFlag(signature, PGPKeyFlags.CAN_SIGN)) { continue; } JcaPGPContentVerifierBuilderProvider provider = new JcaPGPContentVerifierBuilderProvider().setProvider(PROVIDER); signature.init(provider, masterKey); try { if (signature.verifyCertification(masterKey, key)) { subKeys.add(key); } } catch (PGPException e) { throw new IllegalStateException(e); } } } } } if (masterKey == null) { throw new IllegalArgumentException("The supplied object has no key"); } return new PgpPublicKeyWrapper(masterKey, subKeys); } catch (IOException | PGPException e) { throw new IllegalArgumentException("The supplied object has no key"); } catch (IllegalArgumentException e) { throw e; } catch (Exception e) { LOGGER.warn("Unexpected error, throwing no key by default", e); throw new IllegalArgumentException("The supplied object has no key"); } } | PgpPublicKeyWrapper implements KeyWrapper { public static PgpPublicKeyWrapper parse(final RpslObject object) { if (!looksLikePgpKey(object)) { throw new IllegalArgumentException("The supplied object has no key"); } try { final byte[] bytes = RpslObjectFilter.getCertificateFromKeyCert(object).getBytes(StandardCharsets.ISO_8859_1); final ArmoredInputStream armoredInputStream = (ArmoredInputStream) PGPUtil.getDecoderStream(new ByteArrayInputStream(bytes)); PGPPublicKey masterKey = null; List<PGPPublicKey> subKeys = Lists.newArrayList(); @SuppressWarnings("unchecked") final Iterator<PGPPublicKeyRing> keyRingsIterator = new BcPGPPublicKeyRingCollection(armoredInputStream).getKeyRings(); while (keyRingsIterator.hasNext()) { @SuppressWarnings("unchecked") final Iterator<PGPPublicKey> keyIterator = keyRingsIterator.next().getPublicKeys(); while (keyIterator.hasNext()) { final PGPPublicKey key = keyIterator.next(); if (key.isMasterKey()) { if (masterKey == null) { masterKey = key; } else { throw new IllegalArgumentException("The supplied object has multiple keys"); } } else { if (masterKey == null) { continue; } final Iterator<PGPSignature> signatureIterator = key.getSignaturesOfType(PGPSignature.SUBKEY_BINDING); while (signatureIterator.hasNext()) { final PGPSignature signature = signatureIterator.next(); if (!hasFlag(signature, PGPKeyFlags.CAN_SIGN)) { continue; } JcaPGPContentVerifierBuilderProvider provider = new JcaPGPContentVerifierBuilderProvider().setProvider(PROVIDER); signature.init(provider, masterKey); try { if (signature.verifyCertification(masterKey, key)) { subKeys.add(key); } } catch (PGPException e) { throw new IllegalStateException(e); } } } } } if (masterKey == null) { throw new IllegalArgumentException("The supplied object has no key"); } return new PgpPublicKeyWrapper(masterKey, subKeys); } catch (IOException | PGPException e) { throw new IllegalArgumentException("The supplied object has no key"); } catch (IllegalArgumentException e) { throw e; } catch (Exception e) { LOGGER.warn("Unexpected error, throwing no key by default", e); throw new IllegalArgumentException("The supplied object has no key"); } } } | PgpPublicKeyWrapper implements KeyWrapper { public static PgpPublicKeyWrapper parse(final RpslObject object) { if (!looksLikePgpKey(object)) { throw new IllegalArgumentException("The supplied object has no key"); } try { final byte[] bytes = RpslObjectFilter.getCertificateFromKeyCert(object).getBytes(StandardCharsets.ISO_8859_1); final ArmoredInputStream armoredInputStream = (ArmoredInputStream) PGPUtil.getDecoderStream(new ByteArrayInputStream(bytes)); PGPPublicKey masterKey = null; List<PGPPublicKey> subKeys = Lists.newArrayList(); @SuppressWarnings("unchecked") final Iterator<PGPPublicKeyRing> keyRingsIterator = new BcPGPPublicKeyRingCollection(armoredInputStream).getKeyRings(); while (keyRingsIterator.hasNext()) { @SuppressWarnings("unchecked") final Iterator<PGPPublicKey> keyIterator = keyRingsIterator.next().getPublicKeys(); while (keyIterator.hasNext()) { final PGPPublicKey key = keyIterator.next(); if (key.isMasterKey()) { if (masterKey == null) { masterKey = key; } else { throw new IllegalArgumentException("The supplied object has multiple keys"); } } else { if (masterKey == null) { continue; } final Iterator<PGPSignature> signatureIterator = key.getSignaturesOfType(PGPSignature.SUBKEY_BINDING); while (signatureIterator.hasNext()) { final PGPSignature signature = signatureIterator.next(); if (!hasFlag(signature, PGPKeyFlags.CAN_SIGN)) { continue; } JcaPGPContentVerifierBuilderProvider provider = new JcaPGPContentVerifierBuilderProvider().setProvider(PROVIDER); signature.init(provider, masterKey); try { if (signature.verifyCertification(masterKey, key)) { subKeys.add(key); } } catch (PGPException e) { throw new IllegalStateException(e); } } } } } if (masterKey == null) { throw new IllegalArgumentException("The supplied object has no key"); } return new PgpPublicKeyWrapper(masterKey, subKeys); } catch (IOException | PGPException e) { throw new IllegalArgumentException("The supplied object has no key"); } catch (IllegalArgumentException e) { throw e; } catch (Exception e) { LOGGER.warn("Unexpected error, throwing no key by default", e); throw new IllegalArgumentException("The supplied object has no key"); } } PgpPublicKeyWrapper(final PGPPublicKey masterKey, final List<PGPPublicKey> subKeys); } | PgpPublicKeyWrapper implements KeyWrapper { public static PgpPublicKeyWrapper parse(final RpslObject object) { if (!looksLikePgpKey(object)) { throw new IllegalArgumentException("The supplied object has no key"); } try { final byte[] bytes = RpslObjectFilter.getCertificateFromKeyCert(object).getBytes(StandardCharsets.ISO_8859_1); final ArmoredInputStream armoredInputStream = (ArmoredInputStream) PGPUtil.getDecoderStream(new ByteArrayInputStream(bytes)); PGPPublicKey masterKey = null; List<PGPPublicKey> subKeys = Lists.newArrayList(); @SuppressWarnings("unchecked") final Iterator<PGPPublicKeyRing> keyRingsIterator = new BcPGPPublicKeyRingCollection(armoredInputStream).getKeyRings(); while (keyRingsIterator.hasNext()) { @SuppressWarnings("unchecked") final Iterator<PGPPublicKey> keyIterator = keyRingsIterator.next().getPublicKeys(); while (keyIterator.hasNext()) { final PGPPublicKey key = keyIterator.next(); if (key.isMasterKey()) { if (masterKey == null) { masterKey = key; } else { throw new IllegalArgumentException("The supplied object has multiple keys"); } } else { if (masterKey == null) { continue; } final Iterator<PGPSignature> signatureIterator = key.getSignaturesOfType(PGPSignature.SUBKEY_BINDING); while (signatureIterator.hasNext()) { final PGPSignature signature = signatureIterator.next(); if (!hasFlag(signature, PGPKeyFlags.CAN_SIGN)) { continue; } JcaPGPContentVerifierBuilderProvider provider = new JcaPGPContentVerifierBuilderProvider().setProvider(PROVIDER); signature.init(provider, masterKey); try { if (signature.verifyCertification(masterKey, key)) { subKeys.add(key); } } catch (PGPException e) { throw new IllegalStateException(e); } } } } } if (masterKey == null) { throw new IllegalArgumentException("The supplied object has no key"); } return new PgpPublicKeyWrapper(masterKey, subKeys); } catch (IOException | PGPException e) { throw new IllegalArgumentException("The supplied object has no key"); } catch (IllegalArgumentException e) { throw e; } catch (Exception e) { LOGGER.warn("Unexpected error, throwing no key by default", e); throw new IllegalArgumentException("The supplied object has no key"); } } PgpPublicKeyWrapper(final PGPPublicKey masterKey, final List<PGPPublicKey> subKeys); static PgpPublicKeyWrapper parse(final RpslObject object); PGPPublicKey getPublicKey(); List<PGPPublicKey> getSubKeys(); @Override String getMethod(); @Override List<String> getOwners(); @Override String getFingerprint(); boolean isExpired(final DateTimeProvider dateTimeProvider); boolean isRevoked(); @Override boolean equals(final Object o); @Override int hashCode(); } | PgpPublicKeyWrapper implements KeyWrapper { public static PgpPublicKeyWrapper parse(final RpslObject object) { if (!looksLikePgpKey(object)) { throw new IllegalArgumentException("The supplied object has no key"); } try { final byte[] bytes = RpslObjectFilter.getCertificateFromKeyCert(object).getBytes(StandardCharsets.ISO_8859_1); final ArmoredInputStream armoredInputStream = (ArmoredInputStream) PGPUtil.getDecoderStream(new ByteArrayInputStream(bytes)); PGPPublicKey masterKey = null; List<PGPPublicKey> subKeys = Lists.newArrayList(); @SuppressWarnings("unchecked") final Iterator<PGPPublicKeyRing> keyRingsIterator = new BcPGPPublicKeyRingCollection(armoredInputStream).getKeyRings(); while (keyRingsIterator.hasNext()) { @SuppressWarnings("unchecked") final Iterator<PGPPublicKey> keyIterator = keyRingsIterator.next().getPublicKeys(); while (keyIterator.hasNext()) { final PGPPublicKey key = keyIterator.next(); if (key.isMasterKey()) { if (masterKey == null) { masterKey = key; } else { throw new IllegalArgumentException("The supplied object has multiple keys"); } } else { if (masterKey == null) { continue; } final Iterator<PGPSignature> signatureIterator = key.getSignaturesOfType(PGPSignature.SUBKEY_BINDING); while (signatureIterator.hasNext()) { final PGPSignature signature = signatureIterator.next(); if (!hasFlag(signature, PGPKeyFlags.CAN_SIGN)) { continue; } JcaPGPContentVerifierBuilderProvider provider = new JcaPGPContentVerifierBuilderProvider().setProvider(PROVIDER); signature.init(provider, masterKey); try { if (signature.verifyCertification(masterKey, key)) { subKeys.add(key); } } catch (PGPException e) { throw new IllegalStateException(e); } } } } } if (masterKey == null) { throw new IllegalArgumentException("The supplied object has no key"); } return new PgpPublicKeyWrapper(masterKey, subKeys); } catch (IOException | PGPException e) { throw new IllegalArgumentException("The supplied object has no key"); } catch (IllegalArgumentException e) { throw e; } catch (Exception e) { LOGGER.warn("Unexpected error, throwing no key by default", e); throw new IllegalArgumentException("The supplied object has no key"); } } PgpPublicKeyWrapper(final PGPPublicKey masterKey, final List<PGPPublicKey> subKeys); static PgpPublicKeyWrapper parse(final RpslObject object); PGPPublicKey getPublicKey(); List<PGPPublicKey> getSubKeys(); @Override String getMethod(); @Override List<String> getOwners(); @Override String getFingerprint(); boolean isExpired(final DateTimeProvider dateTimeProvider); boolean isRevoked(); @Override boolean equals(final Object o); @Override int hashCode(); } |
@Test public void isExpired() { final PgpPublicKeyWrapper subject = PgpPublicKeyWrapper.parse( RpslObject.parse( "key-cert: PGPKEY-C88CA438\n" + "method: PGP\n" + "owner: Expired <[email protected]>\n" + "fingerpr: 610A 2457 2BA3 A575 5F85 4DD8 5E62 6C72 C88C A438\n" + "certif: -----BEGIN PGP PUBLIC KEY BLOCK-----\n" + "certif: Version: GnuPG v1.4.12 (Darwin)\n" + "certif: Comment: GPGTools - http: "certif:\n" + "certif: mI0EUOoKSgEEAMvJBJzUBKDA8BGK+KpJMuGSOXnQgvymxgyOUOBVkLpeOcPQMy1A\n" + "certif: 4fffXJ4V0xdlqtikDATCnSIBS17ihi7xD8fUvKF4dJrq+rmaVULoy06B68IcfYKQ\n" + "certif: yoRJqGii/1Z47FuudeJp1axQs1JER3OJ64IHuLblFIT7oS+YWBLopc1JABEBAAG0\n" + "certif: GkV4cGlyZWQgPGV4cGlyZWRAcmlwZS5uZXQ+iL4EEwECACgFAlDqCkoCGwMFCQAB\n" + "certif: UYAGCwkIBwMCBhUIAgkKCwQWAgMBAh4BAheAAAoJEF5ibHLIjKQ4tEMD/j8VYxdY\n" + "certif: V6JM8rDokg+zNE4Ifc7nGaUrsrF2YRmcIg6OXVhPGLIqfQB2IsKub595sA1vgwNs\n" + "certif: +Cg0tzaQfzWh2Nz5NxFGnDHm5tPfOfiADwpMuLtZby390Wpbwk7VGZMqfcDXt3uy\n" + "certif: Ch4rvayDTtzQqDVqo1kLgK5dIc/UIlX3jaxWuI0EUOoKSgEEANYcEMxrEGD4LSgk\n" + "certif: vHVECSOB0q32CN/wSrvVzL6hP8RuO0gwwVQH1V8KCYiY6kDEk33Qb4f1bTo+Wbi6\n" + "certif: 9yFvn1OvLh3/idb3U1qSq2+Y6Snl/kvgoVJQuS9x1NePtCYL2kheTAGiswg6CxTF\n" + "certif: RZ3c7CaNHsCbUdIpQmNUxfcWBH3PABEBAAGIpQQYAQIADwUCUOoKSgIbDAUJAAFR\n" + "certif: gAAKCRBeYmxyyIykON13BACeqmXZNe9H/SK2AMiFLIx2Zfyw/P0cKabn3Iaan7iF\n" + "certif: kSwrZQhF4571MBxb9U41Giiyza/t7vLQH1S+FYFUqfWCa8p1VQDRavi4wDgy2PDp\n" + "certif: ouhDqH+Mfkqb7yv40kYOUJ02eKkdgSgwTEcpfwq9GU4kJLVO5O3Y3nOEAx736gPQ\n" + "certif: xw==\n" + "certif: =XcVO\n" + "certif: -----END PGP PUBLIC KEY BLOCK-----\n" + "mnt-by: UPD-MNT\n" + "source: TEST")); assertThat(subject.isExpired(dateTimeProvider), is(true)); } | public boolean isExpired(final DateTimeProvider dateTimeProvider) { final long validSeconds = masterKey.getValidSeconds(); if (validSeconds > 0) { final int days = Long.valueOf(Long.divideUnsigned(validSeconds, SECONDS_IN_ONE_DAY)).intValue(); final LocalDateTime expired = (DateUtil.fromDate(masterKey.getCreationTime())).plusDays(days); return expired.isBefore(dateTimeProvider.getCurrentDateTime()); } return false; } | PgpPublicKeyWrapper implements KeyWrapper { public boolean isExpired(final DateTimeProvider dateTimeProvider) { final long validSeconds = masterKey.getValidSeconds(); if (validSeconds > 0) { final int days = Long.valueOf(Long.divideUnsigned(validSeconds, SECONDS_IN_ONE_DAY)).intValue(); final LocalDateTime expired = (DateUtil.fromDate(masterKey.getCreationTime())).plusDays(days); return expired.isBefore(dateTimeProvider.getCurrentDateTime()); } return false; } } | PgpPublicKeyWrapper implements KeyWrapper { public boolean isExpired(final DateTimeProvider dateTimeProvider) { final long validSeconds = masterKey.getValidSeconds(); if (validSeconds > 0) { final int days = Long.valueOf(Long.divideUnsigned(validSeconds, SECONDS_IN_ONE_DAY)).intValue(); final LocalDateTime expired = (DateUtil.fromDate(masterKey.getCreationTime())).plusDays(days); return expired.isBefore(dateTimeProvider.getCurrentDateTime()); } return false; } PgpPublicKeyWrapper(final PGPPublicKey masterKey, final List<PGPPublicKey> subKeys); } | PgpPublicKeyWrapper implements KeyWrapper { public boolean isExpired(final DateTimeProvider dateTimeProvider) { final long validSeconds = masterKey.getValidSeconds(); if (validSeconds > 0) { final int days = Long.valueOf(Long.divideUnsigned(validSeconds, SECONDS_IN_ONE_DAY)).intValue(); final LocalDateTime expired = (DateUtil.fromDate(masterKey.getCreationTime())).plusDays(days); return expired.isBefore(dateTimeProvider.getCurrentDateTime()); } return false; } PgpPublicKeyWrapper(final PGPPublicKey masterKey, final List<PGPPublicKey> subKeys); static PgpPublicKeyWrapper parse(final RpslObject object); PGPPublicKey getPublicKey(); List<PGPPublicKey> getSubKeys(); @Override String getMethod(); @Override List<String> getOwners(); @Override String getFingerprint(); boolean isExpired(final DateTimeProvider dateTimeProvider); boolean isRevoked(); @Override boolean equals(final Object o); @Override int hashCode(); } | PgpPublicKeyWrapper implements KeyWrapper { public boolean isExpired(final DateTimeProvider dateTimeProvider) { final long validSeconds = masterKey.getValidSeconds(); if (validSeconds > 0) { final int days = Long.valueOf(Long.divideUnsigned(validSeconds, SECONDS_IN_ONE_DAY)).intValue(); final LocalDateTime expired = (DateUtil.fromDate(masterKey.getCreationTime())).plusDays(days); return expired.isBefore(dateTimeProvider.getCurrentDateTime()); } return false; } PgpPublicKeyWrapper(final PGPPublicKey masterKey, final List<PGPPublicKey> subKeys); static PgpPublicKeyWrapper parse(final RpslObject object); PGPPublicKey getPublicKey(); List<PGPPublicKey> getSubKeys(); @Override String getMethod(); @Override List<String> getOwners(); @Override String getFingerprint(); boolean isExpired(final DateTimeProvider dateTimeProvider); boolean isRevoked(); @Override boolean equals(final Object o); @Override int hashCode(); } |
@Test public void unreadableKeyring() { try { PgpPublicKeyWrapper.parse( RpslObject.parse( "key-cert: PGPKEY-2424420B\n" + "method: PGP\n" + "owner: Test User <[email protected]>\n" + "fingerpr: 3F0D 878A 9352 5F7C 4BED F475 A72E FF2A 2424 420B\n" + "certif: -----BEGIN PGP PUBLIC KEY BLOCK-----\n" + "certif: Comment: GPGTools - http: "certif:=20\n" + "certif: mDMEXDSFIBYJKwYBBAHaRw8BAQdAApW0Ud7TmlaWDeMN6nfxRSRbC5sE8U+oKc8Y\n" + "certif: 4nQWT7C0HFRlc3QgVXNlciA8bm9yZXBseUByaXBlLm5ldD6IkAQTFggAOBYhBD8N\n" + "certif: h4qTUl98S+30dacu/yokJEILBQJcNIUgAhsDBQsJCAcCBhUKCQgLAgQWAgMBAh4B\n" + "certif: AheAAAoJEKcu/yokJEIL4cwA/2jOgBV0OHylbE5iDx1VIoMnIJCS12JODgwqwMms\n" + "certif: rbVfAP9RAtdxNqdt/Bwu5mX6fTSGSff6yicqzGretWlkRh8aBbg4BFw0hSASCisG\n" + "certif: AQQBl1UBBQEBB0Dx8kHIOKw/klxcIYcYhY28leG80qnPMgP4wgRK5JpefQMBCAeI\n" + "certif: eAQYFggAIBYhBD8Nh4qTUl98S+30dacu/yokJEILBQJcNIUgAhsMAAoJEKcu/yok\n" + "certif: JEILEp4BAJLGZuQ5qJkl8eqGKb6BCVmoynaFTutYbm2IIed6pmDJAQCa7CqeUY1V\n" + "certif: duNXCkPvStUGG6dIRgtWlW7vwSVwgnd3BA==\n" + "certif: =GGwH\n" + "certif: -----END PGP PUBLIC KEY BLOCK-----\n" + "admin-c: AA1-RIPE\n" + "tech-c: AA1-RIPE\n" + "mnt-by: UPD-MNT\n" + "source: TEST")); fail(); } catch (IllegalArgumentException e) { assertThat(e.getMessage(), is("The supplied object has no key")); } } | public static PgpPublicKeyWrapper parse(final RpslObject object) { if (!looksLikePgpKey(object)) { throw new IllegalArgumentException("The supplied object has no key"); } try { final byte[] bytes = RpslObjectFilter.getCertificateFromKeyCert(object).getBytes(StandardCharsets.ISO_8859_1); final ArmoredInputStream armoredInputStream = (ArmoredInputStream) PGPUtil.getDecoderStream(new ByteArrayInputStream(bytes)); PGPPublicKey masterKey = null; List<PGPPublicKey> subKeys = Lists.newArrayList(); @SuppressWarnings("unchecked") final Iterator<PGPPublicKeyRing> keyRingsIterator = new BcPGPPublicKeyRingCollection(armoredInputStream).getKeyRings(); while (keyRingsIterator.hasNext()) { @SuppressWarnings("unchecked") final Iterator<PGPPublicKey> keyIterator = keyRingsIterator.next().getPublicKeys(); while (keyIterator.hasNext()) { final PGPPublicKey key = keyIterator.next(); if (key.isMasterKey()) { if (masterKey == null) { masterKey = key; } else { throw new IllegalArgumentException("The supplied object has multiple keys"); } } else { if (masterKey == null) { continue; } final Iterator<PGPSignature> signatureIterator = key.getSignaturesOfType(PGPSignature.SUBKEY_BINDING); while (signatureIterator.hasNext()) { final PGPSignature signature = signatureIterator.next(); if (!hasFlag(signature, PGPKeyFlags.CAN_SIGN)) { continue; } JcaPGPContentVerifierBuilderProvider provider = new JcaPGPContentVerifierBuilderProvider().setProvider(PROVIDER); signature.init(provider, masterKey); try { if (signature.verifyCertification(masterKey, key)) { subKeys.add(key); } } catch (PGPException e) { throw new IllegalStateException(e); } } } } } if (masterKey == null) { throw new IllegalArgumentException("The supplied object has no key"); } return new PgpPublicKeyWrapper(masterKey, subKeys); } catch (IOException | PGPException e) { throw new IllegalArgumentException("The supplied object has no key"); } catch (IllegalArgumentException e) { throw e; } catch (Exception e) { LOGGER.warn("Unexpected error, throwing no key by default", e); throw new IllegalArgumentException("The supplied object has no key"); } } | PgpPublicKeyWrapper implements KeyWrapper { public static PgpPublicKeyWrapper parse(final RpslObject object) { if (!looksLikePgpKey(object)) { throw new IllegalArgumentException("The supplied object has no key"); } try { final byte[] bytes = RpslObjectFilter.getCertificateFromKeyCert(object).getBytes(StandardCharsets.ISO_8859_1); final ArmoredInputStream armoredInputStream = (ArmoredInputStream) PGPUtil.getDecoderStream(new ByteArrayInputStream(bytes)); PGPPublicKey masterKey = null; List<PGPPublicKey> subKeys = Lists.newArrayList(); @SuppressWarnings("unchecked") final Iterator<PGPPublicKeyRing> keyRingsIterator = new BcPGPPublicKeyRingCollection(armoredInputStream).getKeyRings(); while (keyRingsIterator.hasNext()) { @SuppressWarnings("unchecked") final Iterator<PGPPublicKey> keyIterator = keyRingsIterator.next().getPublicKeys(); while (keyIterator.hasNext()) { final PGPPublicKey key = keyIterator.next(); if (key.isMasterKey()) { if (masterKey == null) { masterKey = key; } else { throw new IllegalArgumentException("The supplied object has multiple keys"); } } else { if (masterKey == null) { continue; } final Iterator<PGPSignature> signatureIterator = key.getSignaturesOfType(PGPSignature.SUBKEY_BINDING); while (signatureIterator.hasNext()) { final PGPSignature signature = signatureIterator.next(); if (!hasFlag(signature, PGPKeyFlags.CAN_SIGN)) { continue; } JcaPGPContentVerifierBuilderProvider provider = new JcaPGPContentVerifierBuilderProvider().setProvider(PROVIDER); signature.init(provider, masterKey); try { if (signature.verifyCertification(masterKey, key)) { subKeys.add(key); } } catch (PGPException e) { throw new IllegalStateException(e); } } } } } if (masterKey == null) { throw new IllegalArgumentException("The supplied object has no key"); } return new PgpPublicKeyWrapper(masterKey, subKeys); } catch (IOException | PGPException e) { throw new IllegalArgumentException("The supplied object has no key"); } catch (IllegalArgumentException e) { throw e; } catch (Exception e) { LOGGER.warn("Unexpected error, throwing no key by default", e); throw new IllegalArgumentException("The supplied object has no key"); } } } | PgpPublicKeyWrapper implements KeyWrapper { public static PgpPublicKeyWrapper parse(final RpslObject object) { if (!looksLikePgpKey(object)) { throw new IllegalArgumentException("The supplied object has no key"); } try { final byte[] bytes = RpslObjectFilter.getCertificateFromKeyCert(object).getBytes(StandardCharsets.ISO_8859_1); final ArmoredInputStream armoredInputStream = (ArmoredInputStream) PGPUtil.getDecoderStream(new ByteArrayInputStream(bytes)); PGPPublicKey masterKey = null; List<PGPPublicKey> subKeys = Lists.newArrayList(); @SuppressWarnings("unchecked") final Iterator<PGPPublicKeyRing> keyRingsIterator = new BcPGPPublicKeyRingCollection(armoredInputStream).getKeyRings(); while (keyRingsIterator.hasNext()) { @SuppressWarnings("unchecked") final Iterator<PGPPublicKey> keyIterator = keyRingsIterator.next().getPublicKeys(); while (keyIterator.hasNext()) { final PGPPublicKey key = keyIterator.next(); if (key.isMasterKey()) { if (masterKey == null) { masterKey = key; } else { throw new IllegalArgumentException("The supplied object has multiple keys"); } } else { if (masterKey == null) { continue; } final Iterator<PGPSignature> signatureIterator = key.getSignaturesOfType(PGPSignature.SUBKEY_BINDING); while (signatureIterator.hasNext()) { final PGPSignature signature = signatureIterator.next(); if (!hasFlag(signature, PGPKeyFlags.CAN_SIGN)) { continue; } JcaPGPContentVerifierBuilderProvider provider = new JcaPGPContentVerifierBuilderProvider().setProvider(PROVIDER); signature.init(provider, masterKey); try { if (signature.verifyCertification(masterKey, key)) { subKeys.add(key); } } catch (PGPException e) { throw new IllegalStateException(e); } } } } } if (masterKey == null) { throw new IllegalArgumentException("The supplied object has no key"); } return new PgpPublicKeyWrapper(masterKey, subKeys); } catch (IOException | PGPException e) { throw new IllegalArgumentException("The supplied object has no key"); } catch (IllegalArgumentException e) { throw e; } catch (Exception e) { LOGGER.warn("Unexpected error, throwing no key by default", e); throw new IllegalArgumentException("The supplied object has no key"); } } PgpPublicKeyWrapper(final PGPPublicKey masterKey, final List<PGPPublicKey> subKeys); } | PgpPublicKeyWrapper implements KeyWrapper { public static PgpPublicKeyWrapper parse(final RpslObject object) { if (!looksLikePgpKey(object)) { throw new IllegalArgumentException("The supplied object has no key"); } try { final byte[] bytes = RpslObjectFilter.getCertificateFromKeyCert(object).getBytes(StandardCharsets.ISO_8859_1); final ArmoredInputStream armoredInputStream = (ArmoredInputStream) PGPUtil.getDecoderStream(new ByteArrayInputStream(bytes)); PGPPublicKey masterKey = null; List<PGPPublicKey> subKeys = Lists.newArrayList(); @SuppressWarnings("unchecked") final Iterator<PGPPublicKeyRing> keyRingsIterator = new BcPGPPublicKeyRingCollection(armoredInputStream).getKeyRings(); while (keyRingsIterator.hasNext()) { @SuppressWarnings("unchecked") final Iterator<PGPPublicKey> keyIterator = keyRingsIterator.next().getPublicKeys(); while (keyIterator.hasNext()) { final PGPPublicKey key = keyIterator.next(); if (key.isMasterKey()) { if (masterKey == null) { masterKey = key; } else { throw new IllegalArgumentException("The supplied object has multiple keys"); } } else { if (masterKey == null) { continue; } final Iterator<PGPSignature> signatureIterator = key.getSignaturesOfType(PGPSignature.SUBKEY_BINDING); while (signatureIterator.hasNext()) { final PGPSignature signature = signatureIterator.next(); if (!hasFlag(signature, PGPKeyFlags.CAN_SIGN)) { continue; } JcaPGPContentVerifierBuilderProvider provider = new JcaPGPContentVerifierBuilderProvider().setProvider(PROVIDER); signature.init(provider, masterKey); try { if (signature.verifyCertification(masterKey, key)) { subKeys.add(key); } } catch (PGPException e) { throw new IllegalStateException(e); } } } } } if (masterKey == null) { throw new IllegalArgumentException("The supplied object has no key"); } return new PgpPublicKeyWrapper(masterKey, subKeys); } catch (IOException | PGPException e) { throw new IllegalArgumentException("The supplied object has no key"); } catch (IllegalArgumentException e) { throw e; } catch (Exception e) { LOGGER.warn("Unexpected error, throwing no key by default", e); throw new IllegalArgumentException("The supplied object has no key"); } } PgpPublicKeyWrapper(final PGPPublicKey masterKey, final List<PGPPublicKey> subKeys); static PgpPublicKeyWrapper parse(final RpslObject object); PGPPublicKey getPublicKey(); List<PGPPublicKey> getSubKeys(); @Override String getMethod(); @Override List<String> getOwners(); @Override String getFingerprint(); boolean isExpired(final DateTimeProvider dateTimeProvider); boolean isRevoked(); @Override boolean equals(final Object o); @Override int hashCode(); } | PgpPublicKeyWrapper implements KeyWrapper { public static PgpPublicKeyWrapper parse(final RpslObject object) { if (!looksLikePgpKey(object)) { throw new IllegalArgumentException("The supplied object has no key"); } try { final byte[] bytes = RpslObjectFilter.getCertificateFromKeyCert(object).getBytes(StandardCharsets.ISO_8859_1); final ArmoredInputStream armoredInputStream = (ArmoredInputStream) PGPUtil.getDecoderStream(new ByteArrayInputStream(bytes)); PGPPublicKey masterKey = null; List<PGPPublicKey> subKeys = Lists.newArrayList(); @SuppressWarnings("unchecked") final Iterator<PGPPublicKeyRing> keyRingsIterator = new BcPGPPublicKeyRingCollection(armoredInputStream).getKeyRings(); while (keyRingsIterator.hasNext()) { @SuppressWarnings("unchecked") final Iterator<PGPPublicKey> keyIterator = keyRingsIterator.next().getPublicKeys(); while (keyIterator.hasNext()) { final PGPPublicKey key = keyIterator.next(); if (key.isMasterKey()) { if (masterKey == null) { masterKey = key; } else { throw new IllegalArgumentException("The supplied object has multiple keys"); } } else { if (masterKey == null) { continue; } final Iterator<PGPSignature> signatureIterator = key.getSignaturesOfType(PGPSignature.SUBKEY_BINDING); while (signatureIterator.hasNext()) { final PGPSignature signature = signatureIterator.next(); if (!hasFlag(signature, PGPKeyFlags.CAN_SIGN)) { continue; } JcaPGPContentVerifierBuilderProvider provider = new JcaPGPContentVerifierBuilderProvider().setProvider(PROVIDER); signature.init(provider, masterKey); try { if (signature.verifyCertification(masterKey, key)) { subKeys.add(key); } } catch (PGPException e) { throw new IllegalStateException(e); } } } } } if (masterKey == null) { throw new IllegalArgumentException("The supplied object has no key"); } return new PgpPublicKeyWrapper(masterKey, subKeys); } catch (IOException | PGPException e) { throw new IllegalArgumentException("The supplied object has no key"); } catch (IllegalArgumentException e) { throw e; } catch (Exception e) { LOGGER.warn("Unexpected error, throwing no key by default", e); throw new IllegalArgumentException("The supplied object has no key"); } } PgpPublicKeyWrapper(final PGPPublicKey masterKey, final List<PGPPublicKey> subKeys); static PgpPublicKeyWrapper parse(final RpslObject object); PGPPublicKey getPublicKey(); List<PGPPublicKey> getSubKeys(); @Override String getMethod(); @Override List<String> getOwners(); @Override String getFingerprint(); boolean isExpired(final DateTimeProvider dateTimeProvider); boolean isRevoked(); @Override boolean equals(final Object o); @Override int hashCode(); } |
@Test public void isRevoked() { final PgpPublicKeyWrapper subject = PgpPublicKeyWrapper.parse( RpslObject.parse( "key-cert: PGPKEY-A48E76B2\n" + "method: PGP\n" + "owner: Revoked <[email protected]>\n" + "fingerpr: D9A8 D291 0E72 DE20 FE50 C8FD FC24 50DF A48E 76B2\n" + "certif: -----BEGIN PGP PUBLIC KEY BLOCK-----\n" + "certif: Version: GnuPG v1.4.12 (Darwin)\n" + "certif: Comment: GPGTools - http: "certif: \n" + "certif: mI0EUOtGSgEEALdT44Ijp/M+KUvuSjLR "certif: 4gdXcsgpHjbcqe1KO00obtB74scD50l4sm9XPPr6tMK9I7MgwRlgRoJDWmw3lTFG\n" + "certif: 7H1MSqI+RY9EcXTxbtfflfkoexvwIhheHge9OUNsdbgX4Su/Tv6KCVYxABEBAAGI\n" + "certif: nwQgAQIACQUCUOtIJwIdAgAKCRD8JFDfpI52spqaBACUfqolAt+ubV5+9hlF9RuD\n" + "certif: oE0B/OBmB/YwdNIs90s/zBwdiC8F6fB0dMJS0prFfOIJHCoMP6cSLUX83LjimNUk\n" + "certif: b6yYrNaFwAacWQaIA4lgw6GEsvo9tT0ZKZ7/tmcAl0uE3xJ5SyLMaJ5+2ayZ4U6O\n" + "certif: 6r/ZepAn4V0+zJAecy8BabQaUmV2b2tlZCA8cmV2b2tlZEByaXBlLm5ldD6IuAQT\n" + "certif: AQIAIgUCUOtGSgIbAwYLCQgHAwIGFQgCCQoLBBYCAwECHgECF4AACgkQ/CRQ36SO\n" + "certif: drJJnwP+KU0nu8SfDb60Vvmhv2NceH5kPeAHJY3h4p6JSvo5b+RwjhxVQ2j7j4t2\n" + "certif: du9ozj+DrCpaQ4WfOttwg+wgFOSxhcV6y/o60BZMXCYf3DSP0wQiIC/w4vAQq1+U\n" + "certif: bNfDnGKhvJp7zob2BLTlpTi16APghTjnIXMVuUFfjFqURaemVT+4jQRQ60ZKAQQA\n" + "certif: 1lvszl35cbExUezs+Uf2IoXrbqGNw4S7fIJogZigxeUkcgd+uK3aoL+zMlGOJuv1\n" + "certif: OyTh4rQfi+U99aVHQazRO4KSFsB1JjmlizRBkHtRJ5/4u5v8gzUa92Jj1MXHs0gS\n" + "certif: qQ0cCdRUMnZxcgg+4mYslUp2pC/vzk0II2HEnSQa/UsAEQEAAYifBBgBAgAJBQJQ\n" + "certif: 60ZKAhsMAAoJEPwkUN+kjnay+jwEAJWGJFkFX1XdvGtbs7bPCdcMcJ3c/rj1vO91\n" + "certif: gNAjK/onsAzsBzsOSOx2eCEb4ftDASLmvnuK2h+lYLn5GOy0QpmCsZ37E3RcnhZq\n" + "certif: uKUMNY9A83YE8MV8MZXzds4p6XG1+YR7bP9nmgKqsLG9stCPAugVQqxVBbcQRsRV\n" + "certif: dnTzEonl\n" + "certif: =fnvN\n" + "certif: -----END PGP PUBLIC KEY BLOCK-----\n" + "mnt-by: UPD-MNT\n" + "source: TEST")); assertThat(subject.isRevoked(), is(true)); } | public boolean isRevoked() { return masterKey.hasRevocation(); } | PgpPublicKeyWrapper implements KeyWrapper { public boolean isRevoked() { return masterKey.hasRevocation(); } } | PgpPublicKeyWrapper implements KeyWrapper { public boolean isRevoked() { return masterKey.hasRevocation(); } PgpPublicKeyWrapper(final PGPPublicKey masterKey, final List<PGPPublicKey> subKeys); } | PgpPublicKeyWrapper implements KeyWrapper { public boolean isRevoked() { return masterKey.hasRevocation(); } PgpPublicKeyWrapper(final PGPPublicKey masterKey, final List<PGPPublicKey> subKeys); static PgpPublicKeyWrapper parse(final RpslObject object); PGPPublicKey getPublicKey(); List<PGPPublicKey> getSubKeys(); @Override String getMethod(); @Override List<String> getOwners(); @Override String getFingerprint(); boolean isExpired(final DateTimeProvider dateTimeProvider); boolean isRevoked(); @Override boolean equals(final Object o); @Override int hashCode(); } | PgpPublicKeyWrapper implements KeyWrapper { public boolean isRevoked() { return masterKey.hasRevocation(); } PgpPublicKeyWrapper(final PGPPublicKey masterKey, final List<PGPPublicKey> subKeys); static PgpPublicKeyWrapper parse(final RpslObject object); PGPPublicKey getPublicKey(); List<PGPPublicKey> getSubKeys(); @Override String getMethod(); @Override List<String> getOwners(); @Override String getFingerprint(); boolean isExpired(final DateTimeProvider dateTimeProvider); boolean isRevoked(); @Override boolean equals(final Object o); @Override int hashCode(); } |
@Test public void testDateTimeToString_date() { assertThat(FormatHelper.dateTimeToString(LocalDate.of(2001, 10, 1)), is("2001-10-01")); } | public static String dateTimeToString(final TemporalAccessor temporalAccessor) { if (temporalAccessor == null) { return null; } if (temporalAccessor.isSupported(ChronoField.HOUR_OF_DAY)) { return DATE_TIME_FORMAT.format(temporalAccessor); } return DATE_FORMAT.format(temporalAccessor); } | FormatHelper { public static String dateTimeToString(final TemporalAccessor temporalAccessor) { if (temporalAccessor == null) { return null; } if (temporalAccessor.isSupported(ChronoField.HOUR_OF_DAY)) { return DATE_TIME_FORMAT.format(temporalAccessor); } return DATE_FORMAT.format(temporalAccessor); } } | FormatHelper { public static String dateTimeToString(final TemporalAccessor temporalAccessor) { if (temporalAccessor == null) { return null; } if (temporalAccessor.isSupported(ChronoField.HOUR_OF_DAY)) { return DATE_TIME_FORMAT.format(temporalAccessor); } return DATE_FORMAT.format(temporalAccessor); } private FormatHelper(); } | FormatHelper { public static String dateTimeToString(final TemporalAccessor temporalAccessor) { if (temporalAccessor == null) { return null; } if (temporalAccessor.isSupported(ChronoField.HOUR_OF_DAY)) { return DATE_TIME_FORMAT.format(temporalAccessor); } return DATE_FORMAT.format(temporalAccessor); } private FormatHelper(); static String dateToString(final TemporalAccessor temporalAccessor); static String dateTimeToString(final TemporalAccessor temporalAccessor); static String dateTimeToUtcString(final TemporalAccessor temporalAccessor); static String prettyPrint(final String prefix, final String value, final int indentation, final int maxLineLength); static String prettyPrint(final String prefix, final String value, final int indentation, final int maxLineLength, boolean repeatPrefix); } | FormatHelper { public static String dateTimeToString(final TemporalAccessor temporalAccessor) { if (temporalAccessor == null) { return null; } if (temporalAccessor.isSupported(ChronoField.HOUR_OF_DAY)) { return DATE_TIME_FORMAT.format(temporalAccessor); } return DATE_FORMAT.format(temporalAccessor); } private FormatHelper(); static String dateToString(final TemporalAccessor temporalAccessor); static String dateTimeToString(final TemporalAccessor temporalAccessor); static String dateTimeToUtcString(final TemporalAccessor temporalAccessor); static String prettyPrint(final String prefix, final String value, final int indentation, final int maxLineLength); static String prettyPrint(final String prefix, final String value, final int indentation, final int maxLineLength, boolean repeatPrefix); } |
@Test public void verify_smime_plaintext() throws Exception { final String signedData = ( "Content-Transfer-Encoding: 7bit\n" + "Content-Type: text/plain;\n" + "\tcharset=us-ascii\n" + "\n" + "person: First Person\n" + "address: St James Street\n" + "address: Burnley\n" + "address: UK\n" + "phone: +44 282 420469\n" + "nic-hdl: FP1-TEST\n" + "mnt-by: OWNER-MNT\n" + "changed: [email protected] 20121016\n" + "source: TEST\n\n").replaceAll("\\n", "\r\n"); final String signature = "MIAGCSqGSIb3DQEHAqCAMIACAQExCzAJBgUrDgMCGgUAMIAGCSqGSIb3DQEHAQAAoIIDtTCCA7Ew\n" + "ggMaoAMCAQICAgF8MA0GCSqGSIb3DQEBBAUAMIGFMQswCQYDVQQGEwJOTDEWMBQGA1UECBMNTm9v\n" + "cmQtSG9sbGFuZDESMBAGA1UEBxMJQW1zdGVyZGFtMREwDwYDVQQKEwhSSVBFIE5DQzEMMAoGA1UE\n" + "CxMDT1BTMQwwCgYDVQQDEwNDQTIxGzAZBgkqhkiG9w0BCQEWDG9wc0ByaXBlLm5ldDAeFw0xMTEy\n" + "MDExMjM3MjNaFw0yMTExMjgxMjM3MjNaMIGAMQswCQYDVQQGEwJOTDEWMBQGA1UECBMNTm9vcmQt\n" + "SG9sbGFuZDERMA8GA1UEChMIUklQRSBOQ0MxCzAJBgNVBAsTAkRCMRcwFQYDVQQDEw5FZHdhcmQg\n" + "U2hyeWFuZTEgMB4GCSqGSIb3DQEJARYRZXNocnlhbmVAcmlwZS5uZXQwgZ8wDQYJKoZIhvcNAQEB\n" + "BQADgY0AMIGJAoGBAMNs8uEHIiGdYms93PWA4bysV3IUwsabb+fwP6ACS9Jc8OaRQkT+1oK1sfw+\n" + "yX0YloCwJXtnAYDeKHoaPNiJ+dro3GN6BiijjV72KyKThHxWmZwXeqOKVCReREVNNlkuJTvziani\n" + "cZhlr9+bxhwRho1mkEvBmxEzPZTYKl0vQpd1AgMBAAGjggExMIIBLTAJBgNVHRMEAjAAMCwGCWCG\n" + "SAGG+EIBDQQfFh1PcGVuU1NMIEdlbmVyYXRlZCBDZXJ0aWZpY2F0ZTAdBgNVHQ4EFgQUwSiXle3q\n" + "9cufhKDVUCxrEPhj/9cwgbIGA1UdIwSBqjCBp4AUviRV1EFXFxVsA8ildF9OwyDKY9ihgYukgYgw\n" + "gYUxCzAJBgNVBAYTAk5MMRYwFAYDVQQIEw1Ob29yZC1Ib2xsYW5kMRIwEAYDVQQHEwlBbXN0ZXJk\n" + "YW0xETAPBgNVBAoTCFJJUEUgTkNDMQwwCgYDVQQLEwNPUFMxDDAKBgNVBAMTA0NBMjEbMBkGCSqG\n" + "SIb3DQEJARYMb3BzQHJpcGUubmV0ggEAMB4GA1UdEQQXMBWCE2UzLTIuc2luZ3cucmlwZS5uZXQw\n" + "DQYJKoZIhvcNAQEEBQADgYEAU5D2f5WK8AO5keVVf1/kj+wY/mRis9C7nXyhmQgrNcxzxqq+0Q7Q\n" + "mAYsNWMKDLZRemks4FfTGTmVT2SosQntXQBUoR1FGD3LQYLDZ2p1d7A6falUNu0PR8yAqJpT2Q2E\n" + "acKOic/UwHXhVorC1gbKZ5fN0dbUHqSk1zm41VQpobAxggLWMIIC0gIBATCBjDCBhTELMAkGA1UE\n" + "BhMCTkwxFjAUBgNVBAgTDU5vb3JkLUhvbGxhbmQxEjAQBgNVBAcTCUFtc3RlcmRhbTERMA8GA1UE\n" + "ChMIUklQRSBOQ0MxDDAKBgNVBAsTA09QUzEMMAoGA1UEAxMDQ0EyMRswGQYJKoZIhvcNAQkBFgxv\n" + "cHNAcmlwZS5uZXQCAgF8MAkGBSsOAwIaBQCgggGfMBgGCSqGSIb3DQEJAzELBgkqhkiG9w0BBwEw\n" + "HAYJKoZIhvcNAQkFMQ8XDTEzMDEwMzA4MzM0NFowIwYJKoZIhvcNAQkEMRYEFF8/6nTWJD4Fl2J0\n" + "sgOOpFsmJg/DMIGdBgkrBgEEAYI3EAQxgY8wgYwwgYUxCzAJBgNVBAYTAk5MMRYwFAYDVQQIEw1O\n" + "b29yZC1Ib2xsYW5kMRIwEAYDVQQHEwlBbXN0ZXJkYW0xETAPBgNVBAoTCFJJUEUgTkNDMQwwCgYD\n" + "VQQLEwNPUFMxDDAKBgNVBAMTA0NBMjEbMBkGCSqGSIb3DQEJARYMb3BzQHJpcGUubmV0AgIBfDCB\n" + "nwYLKoZIhvcNAQkQAgsxgY+ggYwwgYUxCzAJBgNVBAYTAk5MMRYwFAYDVQQIEw1Ob29yZC1Ib2xs\n" + "YW5kMRIwEAYDVQQHEwlBbXN0ZXJkYW0xETAPBgNVBAoTCFJJUEUgTkNDMQwwCgYDVQQLEwNPUFMx\n" + "DDAKBgNVBAMTA0NBMjEbMBkGCSqGSIb3DQEJARYMb3BzQHJpcGUubmV0AgIBfDANBgkqhkiG9w0B\n" + "AQEFAASBgJOTl3PkpLoOo5MRWaPs/2OHXOzg+Oj9OsNEB326bvl0e7ULuWq2SqVY44LKb6JM5nm9\n" + "6lHk5PJqv6xZq+m1pUYlCqJKFQTPsbnoA3zjrRCDghWc8CZdsK2F7OajTZ6WV98gPeoCdRhvgiU3\n" + "1jpwXyycrnAxekeLNqiX0/hldjkhAAAAAAAA\n"; final X509Certificate certificate = getCertificate( "-----BEGIN CERTIFICATE-----\n" + "MIIDsTCCAxqgAwIBAgICAXwwDQYJKoZIhvcNAQEEBQAwgYUxCzAJBgNVBAYTAk5M\n" + "MRYwFAYDVQQIEw1Ob29yZC1Ib2xsYW5kMRIwEAYDVQQHEwlBbXN0ZXJkYW0xETAP\n" + "BgNVBAoTCFJJUEUgTkNDMQwwCgYDVQQLEwNPUFMxDDAKBgNVBAMTA0NBMjEbMBkG\n" + "CSqGSIb3DQEJARYMb3BzQHJpcGUubmV0MB4XDTExMTIwMTEyMzcyM1oXDTIxMTEy\n" + "ODEyMzcyM1owgYAxCzAJBgNVBAYTAk5MMRYwFAYDVQQIEw1Ob29yZC1Ib2xsYW5k\n" + "MREwDwYDVQQKEwhSSVBFIE5DQzELMAkGA1UECxMCREIxFzAVBgNVBAMTDkVkd2Fy\n" + "ZCBTaHJ5YW5lMSAwHgYJKoZIhvcNAQkBFhFlc2hyeWFuZUByaXBlLm5ldDCBnzAN\n" + "BgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAw2zy4QciIZ1iaz3c9YDhvKxXchTCxptv\n" + "5/A/oAJL0lzw5pFCRP7WgrWx/D7JfRiWgLAle2cBgN4oeho82In52ujcY3oGKKON\n" + "XvYrIpOEfFaZnBd6o4pUJF5ERU02WS4lO/OJqeJxmGWv35vGHBGGjWaQS8GbETM9\n" + "lNgqXS9Cl3UCAwEAAaOCATEwggEtMAkGA1UdEwQCMAAwLAYJYIZIAYb4QgENBB8W\n" + "HU9wZW5TU0wgR2VuZXJhdGVkIENlcnRpZmljYXRlMB0GA1UdDgQWBBTBKJeV7er1\n" + "y5+EoNVQLGsQ+GP/1zCBsgYDVR0jBIGqMIGngBS+JFXUQVcXFWwDyKV0X07DIMpj\n" + "2KGBi6SBiDCBhTELMAkGA1UEBhMCTkwxFjAUBgNVBAgTDU5vb3JkLUhvbGxhbmQx\n" + "EjAQBgNVBAcTCUFtc3RlcmRhbTERMA8GA1UEChMIUklQRSBOQ0MxDDAKBgNVBAsT\n" + "A09QUzEMMAoGA1UEAxMDQ0EyMRswGQYJKoZIhvcNAQkBFgxvcHNAcmlwZS5uZXSC\n" + "AQAwHgYDVR0RBBcwFYITZTMtMi5zaW5ndy5yaXBlLm5ldDANBgkqhkiG9w0BAQQF\n" + "AAOBgQBTkPZ/lYrwA7mR5VV/X+SP7Bj+ZGKz0LudfKGZCCs1zHPGqr7RDtCYBiw1\n" + "YwoMtlF6aSzgV9MZOZVPZKixCe1dAFShHUUYPctBgsNnanV3sDp9qVQ27Q9HzICo\n" + "mlPZDYRpwo6Jz9TAdeFWisLWBspnl83R1tQepKTXObjVVCmhsA==\n" + "-----END CERTIFICATE-----"); final X509SignedMessage subject = new X509SignedMessage(signedData, signature); assertThat(subject.verify(certificate), is(true)); } | public boolean verify(final X509Certificate certificate) { try { CMSProcessable cmsProcessable = new CMSProcessableByteArray(signedData.getBytes()); CMSSignedData signedData = new CMSSignedData(cmsProcessable, Base64.decode(signature)); Iterator signersIterator = signedData.getSignerInfos().getSigners().iterator(); if (signersIterator.hasNext()) { SignerInformation signerInformation = (SignerInformation) signersIterator.next(); LOGGER.debug("Message is signed by certificate: {}", getFingerprint(signerInformation, signedData.getCertificates())); JcaSimpleSignerInfoVerifierBuilder verifierBuilder = new JcaSimpleSignerInfoVerifierBuilder(); verifierBuilder.setProvider(PROVIDER); return signerInformation.verify(verifierBuilder.build(certificate.getPublicKey())); } } catch (CMSSignerDigestMismatchException e) { throw new IllegalArgumentException("message-digest attribute value does not match calculated value", e); } catch (CMSException e) { throw new IllegalArgumentException("general exception verifying signed message", e); } catch (OperatorCreationException e) { throw new IllegalArgumentException("error creating verifier", e); } catch (Exception e) { throw new IllegalArgumentException(e); } return false; } | X509SignedMessage { public boolean verify(final X509Certificate certificate) { try { CMSProcessable cmsProcessable = new CMSProcessableByteArray(signedData.getBytes()); CMSSignedData signedData = new CMSSignedData(cmsProcessable, Base64.decode(signature)); Iterator signersIterator = signedData.getSignerInfos().getSigners().iterator(); if (signersIterator.hasNext()) { SignerInformation signerInformation = (SignerInformation) signersIterator.next(); LOGGER.debug("Message is signed by certificate: {}", getFingerprint(signerInformation, signedData.getCertificates())); JcaSimpleSignerInfoVerifierBuilder verifierBuilder = new JcaSimpleSignerInfoVerifierBuilder(); verifierBuilder.setProvider(PROVIDER); return signerInformation.verify(verifierBuilder.build(certificate.getPublicKey())); } } catch (CMSSignerDigestMismatchException e) { throw new IllegalArgumentException("message-digest attribute value does not match calculated value", e); } catch (CMSException e) { throw new IllegalArgumentException("general exception verifying signed message", e); } catch (OperatorCreationException e) { throw new IllegalArgumentException("error creating verifier", e); } catch (Exception e) { throw new IllegalArgumentException(e); } return false; } } | X509SignedMessage { public boolean verify(final X509Certificate certificate) { try { CMSProcessable cmsProcessable = new CMSProcessableByteArray(signedData.getBytes()); CMSSignedData signedData = new CMSSignedData(cmsProcessable, Base64.decode(signature)); Iterator signersIterator = signedData.getSignerInfos().getSigners().iterator(); if (signersIterator.hasNext()) { SignerInformation signerInformation = (SignerInformation) signersIterator.next(); LOGGER.debug("Message is signed by certificate: {}", getFingerprint(signerInformation, signedData.getCertificates())); JcaSimpleSignerInfoVerifierBuilder verifierBuilder = new JcaSimpleSignerInfoVerifierBuilder(); verifierBuilder.setProvider(PROVIDER); return signerInformation.verify(verifierBuilder.build(certificate.getPublicKey())); } } catch (CMSSignerDigestMismatchException e) { throw new IllegalArgumentException("message-digest attribute value does not match calculated value", e); } catch (CMSException e) { throw new IllegalArgumentException("general exception verifying signed message", e); } catch (OperatorCreationException e) { throw new IllegalArgumentException("error creating verifier", e); } catch (Exception e) { throw new IllegalArgumentException(e); } return false; } X509SignedMessage(final String signedData, final String signature); } | X509SignedMessage { public boolean verify(final X509Certificate certificate) { try { CMSProcessable cmsProcessable = new CMSProcessableByteArray(signedData.getBytes()); CMSSignedData signedData = new CMSSignedData(cmsProcessable, Base64.decode(signature)); Iterator signersIterator = signedData.getSignerInfos().getSigners().iterator(); if (signersIterator.hasNext()) { SignerInformation signerInformation = (SignerInformation) signersIterator.next(); LOGGER.debug("Message is signed by certificate: {}", getFingerprint(signerInformation, signedData.getCertificates())); JcaSimpleSignerInfoVerifierBuilder verifierBuilder = new JcaSimpleSignerInfoVerifierBuilder(); verifierBuilder.setProvider(PROVIDER); return signerInformation.verify(verifierBuilder.build(certificate.getPublicKey())); } } catch (CMSSignerDigestMismatchException e) { throw new IllegalArgumentException("message-digest attribute value does not match calculated value", e); } catch (CMSException e) { throw new IllegalArgumentException("general exception verifying signed message", e); } catch (OperatorCreationException e) { throw new IllegalArgumentException("error creating verifier", e); } catch (Exception e) { throw new IllegalArgumentException(e); } return false; } X509SignedMessage(final String signedData, final String signature); boolean verify(final X509Certificate certificate); boolean verifySigningTime(final DateTimeProvider dateTimeProvider); @Override boolean equals(final Object o); @Override int hashCode(); } | X509SignedMessage { public boolean verify(final X509Certificate certificate) { try { CMSProcessable cmsProcessable = new CMSProcessableByteArray(signedData.getBytes()); CMSSignedData signedData = new CMSSignedData(cmsProcessable, Base64.decode(signature)); Iterator signersIterator = signedData.getSignerInfos().getSigners().iterator(); if (signersIterator.hasNext()) { SignerInformation signerInformation = (SignerInformation) signersIterator.next(); LOGGER.debug("Message is signed by certificate: {}", getFingerprint(signerInformation, signedData.getCertificates())); JcaSimpleSignerInfoVerifierBuilder verifierBuilder = new JcaSimpleSignerInfoVerifierBuilder(); verifierBuilder.setProvider(PROVIDER); return signerInformation.verify(verifierBuilder.build(certificate.getPublicKey())); } } catch (CMSSignerDigestMismatchException e) { throw new IllegalArgumentException("message-digest attribute value does not match calculated value", e); } catch (CMSException e) { throw new IllegalArgumentException("general exception verifying signed message", e); } catch (OperatorCreationException e) { throw new IllegalArgumentException("error creating verifier", e); } catch (Exception e) { throw new IllegalArgumentException(e); } return false; } X509SignedMessage(final String signedData, final String signature); boolean verify(final X509Certificate certificate); boolean verifySigningTime(final DateTimeProvider dateTimeProvider); @Override boolean equals(final Object o); @Override int hashCode(); } |
@Test public void verify_smime_plaintext_multiple_paragraphs() throws Exception { final String signedData = ("Content-Type: text/plain; charset=\"iso-8859-1\"\n" + "Content-Transfer-Encoding: 7bit\n" + "Content-Language: de-DE\n" + "\n" + "inetnum: 193.0.0.0 - 193.0.0.255\n" + "netname: NETNAME\n" + "descr: Description\n" + "country: NL\n" + "admin-c: TEST-RIPE\n" + "tech-c: TEST-RIPE\n" + "status: ASSIGNED PA\n" + "mnt-by: TEST-MNT\n" + "changed: [email protected]\n" + "source: RIPE\n" + "\n" + "changed: [email protected]\n" + "\n").replaceAll("\\n", "\r\n"); final String signature = "MIIDsAYJKoZIhvcNAQcCoIIDoTCCA50CAQExCzAJBgUrDgMCGgUAMAsGCSqGSIb3\n" + "DQEHAaCCAd8wggHbMIIBRAIJAJrBRtmpa9a7MA0GCSqGSIb3DQEBBQUAMDIxCzAJ\n" + "BgNVBAYTAk5MMRMwEQYDVQQIEwpTb21lLVN0YXRlMQ4wDAYDVQQKEwVCT0dVUzAe\n" + "Fw0xMzA0MTgxNTQyMjBaFw0xNDA0MTgxNTQyMjBaMDIxCzAJBgNVBAYTAk5MMRMw\n" + "EQYDVQQIEwpTb21lLVN0YXRlMQ4wDAYDVQQKEwVCT0dVUzCBnzANBgkqhkiG9w0B\n" + "AQEFAAOBjQAwgYkCgYEAp9e053n54CuwZNjY0bgslBQDRSjN+f2wZ8ut0Xt5aj3j\n" + "RpjhWVUF4isUzqMm30E0HHev1meDOWQIgzyhnqDJF/+UUjzKBrZ47OvpBR/9W1WY\n" + "EI4xbUHEBd8LIxPuMrY8+l7xJcPw1D1W/MNs/wscUDTMBX63/qq+WkZcl+31idsC\n" + "AwEAATANBgkqhkiG9w0BAQUFAAOBgQBHLN6q1lPTRQ6+VLPc0dK5fQAaGI5C9d6L\n" + "Yb1fAn0vt1eBt6HnAK+H2PX19yaaCmItEh6KPNzX1uT9uBh12sAff47KMGwftGZU\n" + "cw7cVdulM2qr3UTL98AuF1O2XbRE2dtET+IWXCgjnqKID11NNCzksfgEaesrpdkr\n" + "TFrB+nHvuTGCAZkwggGVAgEBMD8wMjELMAkGA1UEBhMCTkwxEzARBgNVBAgTClNv\n" + "bWUtU3RhdGUxDjAMBgNVBAoTBUJPR1VTAgkAmsFG2alr1rswCQYFKw4DAhoFAKCB\n" + "sTAYBgkqhkiG9w0BCQMxCwYJKoZIhvcNAQcBMBwGCSqGSIb3DQEJBTEPFw0xMzA0\n" + "MTkwOTU5MDdaMCMGCSqGSIb3DQEJBDEWBBS/9gqYJMaWAm8sp2Rf99Oh06aRATBS\n" + "BgkqhkiG9w0BCQ8xRTBDMAoGCCqGSIb3DQMHMA4GCCqGSIb3DQMCAgIAgDANBggq\n" + "hkiG9w0DAgIBQDAHBgUrDgMCBzANBggqhkiG9w0DAgIBKDANBgkqhkiG9w0BAQEF\n" + "AASBgJ8sFkzA3mksoazwIc/eNpMy20wQh1CKtiGU+xTzErkurSg8Z+7pIkod1bbq\n" + "k6tiSWnWhRzmz/YFqgGuzk+O3MyRt3YqU9nZpdaZVZxepN/p/gjQI1gfTXK+7WJ/\n" + "OcKukh/onU6eXZOD50r1RdgFPL4+lXpe0VrWjUOT3CoglnU1"; final X509Certificate certificate = getCertificate( "-----BEGIN CERTIFICATE-----\n" + "MIIB2zCCAUQCCQCawUbZqWvWuzANBgkqhkiG9w0BAQUFADAyMQswCQYDVQQGEwJO\n" + "TDETMBEGA1UECBMKU29tZS1TdGF0ZTEOMAwGA1UEChMFQk9HVVMwHhcNMTMwNDE4\n" + "MTU0MjIwWhcNMTQwNDE4MTU0MjIwWjAyMQswCQYDVQQGEwJOTDETMBEGA1UECBMK\n" + "U29tZS1TdGF0ZTEOMAwGA1UEChMFQk9HVVMwgZ8wDQYJKoZIhvcNAQEBBQADgY0A\n" + "MIGJAoGBAKfXtOd5+eArsGTY2NG4LJQUA0Uozfn9sGfLrdF7eWo940aY4VlVBeIr\n" + "FM6jJt9BNBx3r9ZngzlkCIM8oZ6gyRf/lFI8yga2eOzr6QUf/VtVmBCOMW1BxAXf\n" + "CyMT7jK2PPpe8SXD8NQ9VvzDbP8LHFA0zAV+t/6qvlpGXJft9YnbAgMBAAEwDQYJ\n" + "KoZIhvcNAQEFBQADgYEARyzeqtZT00UOvlSz3NHSuX0AGhiOQvXei2G9XwJ9L7dX\n" + "gbeh5wCvh9j19fcmmgpiLRIeijzc19bk/bgYddrAH3+OyjBsH7RmVHMO3FXbpTNq\n" + "q91Ey/fALhdTtl20RNnbRE/iFlwoI56iiA9dTTQs5LH4BGnrK6XZK0xawfpx77k=\n" + "-----END CERTIFICATE-----"); final X509SignedMessage subject = new X509SignedMessage(signedData, signature); assertThat(subject.verify(certificate), is(true)); } | public boolean verify(final X509Certificate certificate) { try { CMSProcessable cmsProcessable = new CMSProcessableByteArray(signedData.getBytes()); CMSSignedData signedData = new CMSSignedData(cmsProcessable, Base64.decode(signature)); Iterator signersIterator = signedData.getSignerInfos().getSigners().iterator(); if (signersIterator.hasNext()) { SignerInformation signerInformation = (SignerInformation) signersIterator.next(); LOGGER.debug("Message is signed by certificate: {}", getFingerprint(signerInformation, signedData.getCertificates())); JcaSimpleSignerInfoVerifierBuilder verifierBuilder = new JcaSimpleSignerInfoVerifierBuilder(); verifierBuilder.setProvider(PROVIDER); return signerInformation.verify(verifierBuilder.build(certificate.getPublicKey())); } } catch (CMSSignerDigestMismatchException e) { throw new IllegalArgumentException("message-digest attribute value does not match calculated value", e); } catch (CMSException e) { throw new IllegalArgumentException("general exception verifying signed message", e); } catch (OperatorCreationException e) { throw new IllegalArgumentException("error creating verifier", e); } catch (Exception e) { throw new IllegalArgumentException(e); } return false; } | X509SignedMessage { public boolean verify(final X509Certificate certificate) { try { CMSProcessable cmsProcessable = new CMSProcessableByteArray(signedData.getBytes()); CMSSignedData signedData = new CMSSignedData(cmsProcessable, Base64.decode(signature)); Iterator signersIterator = signedData.getSignerInfos().getSigners().iterator(); if (signersIterator.hasNext()) { SignerInformation signerInformation = (SignerInformation) signersIterator.next(); LOGGER.debug("Message is signed by certificate: {}", getFingerprint(signerInformation, signedData.getCertificates())); JcaSimpleSignerInfoVerifierBuilder verifierBuilder = new JcaSimpleSignerInfoVerifierBuilder(); verifierBuilder.setProvider(PROVIDER); return signerInformation.verify(verifierBuilder.build(certificate.getPublicKey())); } } catch (CMSSignerDigestMismatchException e) { throw new IllegalArgumentException("message-digest attribute value does not match calculated value", e); } catch (CMSException e) { throw new IllegalArgumentException("general exception verifying signed message", e); } catch (OperatorCreationException e) { throw new IllegalArgumentException("error creating verifier", e); } catch (Exception e) { throw new IllegalArgumentException(e); } return false; } } | X509SignedMessage { public boolean verify(final X509Certificate certificate) { try { CMSProcessable cmsProcessable = new CMSProcessableByteArray(signedData.getBytes()); CMSSignedData signedData = new CMSSignedData(cmsProcessable, Base64.decode(signature)); Iterator signersIterator = signedData.getSignerInfos().getSigners().iterator(); if (signersIterator.hasNext()) { SignerInformation signerInformation = (SignerInformation) signersIterator.next(); LOGGER.debug("Message is signed by certificate: {}", getFingerprint(signerInformation, signedData.getCertificates())); JcaSimpleSignerInfoVerifierBuilder verifierBuilder = new JcaSimpleSignerInfoVerifierBuilder(); verifierBuilder.setProvider(PROVIDER); return signerInformation.verify(verifierBuilder.build(certificate.getPublicKey())); } } catch (CMSSignerDigestMismatchException e) { throw new IllegalArgumentException("message-digest attribute value does not match calculated value", e); } catch (CMSException e) { throw new IllegalArgumentException("general exception verifying signed message", e); } catch (OperatorCreationException e) { throw new IllegalArgumentException("error creating verifier", e); } catch (Exception e) { throw new IllegalArgumentException(e); } return false; } X509SignedMessage(final String signedData, final String signature); } | X509SignedMessage { public boolean verify(final X509Certificate certificate) { try { CMSProcessable cmsProcessable = new CMSProcessableByteArray(signedData.getBytes()); CMSSignedData signedData = new CMSSignedData(cmsProcessable, Base64.decode(signature)); Iterator signersIterator = signedData.getSignerInfos().getSigners().iterator(); if (signersIterator.hasNext()) { SignerInformation signerInformation = (SignerInformation) signersIterator.next(); LOGGER.debug("Message is signed by certificate: {}", getFingerprint(signerInformation, signedData.getCertificates())); JcaSimpleSignerInfoVerifierBuilder verifierBuilder = new JcaSimpleSignerInfoVerifierBuilder(); verifierBuilder.setProvider(PROVIDER); return signerInformation.verify(verifierBuilder.build(certificate.getPublicKey())); } } catch (CMSSignerDigestMismatchException e) { throw new IllegalArgumentException("message-digest attribute value does not match calculated value", e); } catch (CMSException e) { throw new IllegalArgumentException("general exception verifying signed message", e); } catch (OperatorCreationException e) { throw new IllegalArgumentException("error creating verifier", e); } catch (Exception e) { throw new IllegalArgumentException(e); } return false; } X509SignedMessage(final String signedData, final String signature); boolean verify(final X509Certificate certificate); boolean verifySigningTime(final DateTimeProvider dateTimeProvider); @Override boolean equals(final Object o); @Override int hashCode(); } | X509SignedMessage { public boolean verify(final X509Certificate certificate) { try { CMSProcessable cmsProcessable = new CMSProcessableByteArray(signedData.getBytes()); CMSSignedData signedData = new CMSSignedData(cmsProcessable, Base64.decode(signature)); Iterator signersIterator = signedData.getSignerInfos().getSigners().iterator(); if (signersIterator.hasNext()) { SignerInformation signerInformation = (SignerInformation) signersIterator.next(); LOGGER.debug("Message is signed by certificate: {}", getFingerprint(signerInformation, signedData.getCertificates())); JcaSimpleSignerInfoVerifierBuilder verifierBuilder = new JcaSimpleSignerInfoVerifierBuilder(); verifierBuilder.setProvider(PROVIDER); return signerInformation.verify(verifierBuilder.build(certificate.getPublicKey())); } } catch (CMSSignerDigestMismatchException e) { throw new IllegalArgumentException("message-digest attribute value does not match calculated value", e); } catch (CMSException e) { throw new IllegalArgumentException("general exception verifying signed message", e); } catch (OperatorCreationException e) { throw new IllegalArgumentException("error creating verifier", e); } catch (Exception e) { throw new IllegalArgumentException(e); } return false; } X509SignedMessage(final String signedData, final String signature); boolean verify(final X509Certificate certificate); boolean verifySigningTime(final DateTimeProvider dateTimeProvider); @Override boolean equals(final Object o); @Override int hashCode(); } |
@Test public void verify_smime_multipart_inetnum() throws Exception { final String signedData = ( "Content-Type: multipart/alternative;\n" + "boundary=\"_000_54F98DDECB052B4A98783EDEF1B77C4C30649470SG000708corproo_\"\n" + "Content-Language: de-DE\n" + "\n" + "--_000_54F98DDECB052B4A98783EDEF1B77C4C30649470SG000708corproo_\n" + "Content-Type: text/plain; charset=\"us-ascii\"\n" + "Content-Transfer-Encoding: quoted-printable\n" + "\n" + "inetnum: 193.0.0.0 - 193.0.0.255\n" + "netname: NETNAME\n" + "descr: Description\n" + "country: NL\n" + "admin-c: TEST-RIPE\n" + "tech-c: TEST-RIPE\n" + "status: ASSIGNED PA\n" + "mnt-by: TEST-MNT\n" + "changed: [email protected]\n" + "source: RIPE\n" + "\n" + "\n" + "--_000_54F98DDECB052B4A98783EDEF1B77C4C30649470SG000708corproo_\n" + "Content-Type: text/html; charset=\"us-ascii\"\n" + "Content-Transfer-Encoding: quoted-printable\n" + "\n" + "<html>\n" + "<head>\n" + "<meta http-equiv=3D\"Content-Type\" content=3D\"text/html; charset=3Dus-ascii\">\n" + "<meta name=3D\"Generator\" content=3D\"Microsoft Exchange Server\">\n" + "<!-- converted from rtf -->\n" + "<style><!-- .EmailQuote { margin-left: 1pt; padding-left: 4pt; border-left:#800000 2px solid; } --></style>\n" + "</head>\n" + "<body>\n" + "<font face=3D\"TheSans\" size=3D\"2\"><span style=3D\"font-size:10pt;\">\n" + "<div>inetnum: 193.0.0.0 - 193.0.0.255</div>\n" + "<div>netname: NETNAME</div>\n" + "<div>descr: Description</div>\n" + "<div>country: NL</div>\n" + "<div>admin-c: TEST-RIPE</div>\n" + "<div>tech-c: TEST-RIPE</div>\n" + "<div>status: ASSIGNED PA</div>\n" + "<div>mnt-by: TEST-MNT</div>\n" + "<div>changed: [email protected]</div>\n" + "<div>source: RIPE</div>\n" + "<div><font face=3D\"Calibri\" size=3D\"2\"><span style=3D\"font-size:11pt;\"> </span></font></div>\n" + "</span></font>\n" + "</body>\n" + "</html>\n" + "--_000_54F98DDECB052B4A98783EDEF1B77C4C30649470SG000708corproo_\n").replaceAll("\\n", "\r\n"); final String signature = "MIIDsAYJKoZIhvcNAQcCoIIDoTCCA50CAQExCzAJBgUrDgMCGgUAMAsGCSqGSIb3\n" + "DQEHAaCCAd8wggHbMIIBRAIJAJrBRtmpa9a7MA0GCSqGSIb3DQEBBQUAMDIxCzAJ\n" + "BgNVBAYTAk5MMRMwEQYDVQQIEwpTb21lLVN0YXRlMQ4wDAYDVQQKEwVCT0dVUzAe\n" + "Fw0xMzA0MTgxNTQyMjBaFw0xNDA0MTgxNTQyMjBaMDIxCzAJBgNVBAYTAk5MMRMw\n" + "EQYDVQQIEwpTb21lLVN0YXRlMQ4wDAYDVQQKEwVCT0dVUzCBnzANBgkqhkiG9w0B\n" + "AQEFAAOBjQAwgYkCgYEAp9e053n54CuwZNjY0bgslBQDRSjN+f2wZ8ut0Xt5aj3j\n" + "RpjhWVUF4isUzqMm30E0HHev1meDOWQIgzyhnqDJF/+UUjzKBrZ47OvpBR/9W1WY\n" + "EI4xbUHEBd8LIxPuMrY8+l7xJcPw1D1W/MNs/wscUDTMBX63/qq+WkZcl+31idsC\n" + "AwEAATANBgkqhkiG9w0BAQUFAAOBgQBHLN6q1lPTRQ6+VLPc0dK5fQAaGI5C9d6L\n" + "Yb1fAn0vt1eBt6HnAK+H2PX19yaaCmItEh6KPNzX1uT9uBh12sAff47KMGwftGZU\n" + "cw7cVdulM2qr3UTL98AuF1O2XbRE2dtET+IWXCgjnqKID11NNCzksfgEaesrpdkr\n" + "TFrB+nHvuTGCAZkwggGVAgEBMD8wMjELMAkGA1UEBhMCTkwxEzARBgNVBAgTClNv\n" + "bWUtU3RhdGUxDjAMBgNVBAoTBUJPR1VTAgkAmsFG2alr1rswCQYFKw4DAhoFAKCB\n" + "sTAYBgkqhkiG9w0BCQMxCwYJKoZIhvcNAQcBMBwGCSqGSIb3DQEJBTEPFw0xMzA0\n" + "MTkxMDI2MDhaMCMGCSqGSIb3DQEJBDEWBBQcYbZgEwjIMEBgIQW5vU9ZO2vyETBS\n" + "BgkqhkiG9w0BCQ8xRTBDMAoGCCqGSIb3DQMHMA4GCCqGSIb3DQMCAgIAgDANBggq\n" + "hkiG9w0DAgIBQDAHBgUrDgMCBzANBggqhkiG9w0DAgIBKDANBgkqhkiG9w0BAQEF\n" + "AASBgGh1N+W4rzQ6n9+dvLY4jfP4lavYdcaNKNVZf0Yhx14vW5LQ1iggqtB+ZYtM\n" + "Xzs8SdGSM9FtepvHkLSYtZId0odF/eB6rY7DN3O69TQN7GhmYeICtevT3bkzL950\n" + "P3FhHeI3vHvnW1Xb+fdg46213Ym1tVw3V0caqGdp5Cw5vry5"; final X509Certificate certificate = getCertificate( "-----BEGIN CERTIFICATE-----\n" + "MIIB2zCCAUQCCQCawUbZqWvWuzANBgkqhkiG9w0BAQUFADAyMQswCQYDVQQGEwJO\n" + "TDETMBEGA1UECBMKU29tZS1TdGF0ZTEOMAwGA1UEChMFQk9HVVMwHhcNMTMwNDE4\n" + "MTU0MjIwWhcNMTQwNDE4MTU0MjIwWjAyMQswCQYDVQQGEwJOTDETMBEGA1UECBMK\n" + "U29tZS1TdGF0ZTEOMAwGA1UEChMFQk9HVVMwgZ8wDQYJKoZIhvcNAQEBBQADgY0A\n" + "MIGJAoGBAKfXtOd5+eArsGTY2NG4LJQUA0Uozfn9sGfLrdF7eWo940aY4VlVBeIr\n" + "FM6jJt9BNBx3r9ZngzlkCIM8oZ6gyRf/lFI8yga2eOzr6QUf/VtVmBCOMW1BxAXf\n" + "CyMT7jK2PPpe8SXD8NQ9VvzDbP8LHFA0zAV+t/6qvlpGXJft9YnbAgMBAAEwDQYJ\n" + "KoZIhvcNAQEFBQADgYEARyzeqtZT00UOvlSz3NHSuX0AGhiOQvXei2G9XwJ9L7dX\n" + "gbeh5wCvh9j19fcmmgpiLRIeijzc19bk/bgYddrAH3+OyjBsH7RmVHMO3FXbpTNq\n" + "q91Ey/fALhdTtl20RNnbRE/iFlwoI56iiA9dTTQs5LH4BGnrK6XZK0xawfpx77k=\n" + "-----END CERTIFICATE-----"); final X509SignedMessage subject = new X509SignedMessage(signedData, signature); assertThat(subject.verify(certificate), is(true)); } | public boolean verify(final X509Certificate certificate) { try { CMSProcessable cmsProcessable = new CMSProcessableByteArray(signedData.getBytes()); CMSSignedData signedData = new CMSSignedData(cmsProcessable, Base64.decode(signature)); Iterator signersIterator = signedData.getSignerInfos().getSigners().iterator(); if (signersIterator.hasNext()) { SignerInformation signerInformation = (SignerInformation) signersIterator.next(); LOGGER.debug("Message is signed by certificate: {}", getFingerprint(signerInformation, signedData.getCertificates())); JcaSimpleSignerInfoVerifierBuilder verifierBuilder = new JcaSimpleSignerInfoVerifierBuilder(); verifierBuilder.setProvider(PROVIDER); return signerInformation.verify(verifierBuilder.build(certificate.getPublicKey())); } } catch (CMSSignerDigestMismatchException e) { throw new IllegalArgumentException("message-digest attribute value does not match calculated value", e); } catch (CMSException e) { throw new IllegalArgumentException("general exception verifying signed message", e); } catch (OperatorCreationException e) { throw new IllegalArgumentException("error creating verifier", e); } catch (Exception e) { throw new IllegalArgumentException(e); } return false; } | X509SignedMessage { public boolean verify(final X509Certificate certificate) { try { CMSProcessable cmsProcessable = new CMSProcessableByteArray(signedData.getBytes()); CMSSignedData signedData = new CMSSignedData(cmsProcessable, Base64.decode(signature)); Iterator signersIterator = signedData.getSignerInfos().getSigners().iterator(); if (signersIterator.hasNext()) { SignerInformation signerInformation = (SignerInformation) signersIterator.next(); LOGGER.debug("Message is signed by certificate: {}", getFingerprint(signerInformation, signedData.getCertificates())); JcaSimpleSignerInfoVerifierBuilder verifierBuilder = new JcaSimpleSignerInfoVerifierBuilder(); verifierBuilder.setProvider(PROVIDER); return signerInformation.verify(verifierBuilder.build(certificate.getPublicKey())); } } catch (CMSSignerDigestMismatchException e) { throw new IllegalArgumentException("message-digest attribute value does not match calculated value", e); } catch (CMSException e) { throw new IllegalArgumentException("general exception verifying signed message", e); } catch (OperatorCreationException e) { throw new IllegalArgumentException("error creating verifier", e); } catch (Exception e) { throw new IllegalArgumentException(e); } return false; } } | X509SignedMessage { public boolean verify(final X509Certificate certificate) { try { CMSProcessable cmsProcessable = new CMSProcessableByteArray(signedData.getBytes()); CMSSignedData signedData = new CMSSignedData(cmsProcessable, Base64.decode(signature)); Iterator signersIterator = signedData.getSignerInfos().getSigners().iterator(); if (signersIterator.hasNext()) { SignerInformation signerInformation = (SignerInformation) signersIterator.next(); LOGGER.debug("Message is signed by certificate: {}", getFingerprint(signerInformation, signedData.getCertificates())); JcaSimpleSignerInfoVerifierBuilder verifierBuilder = new JcaSimpleSignerInfoVerifierBuilder(); verifierBuilder.setProvider(PROVIDER); return signerInformation.verify(verifierBuilder.build(certificate.getPublicKey())); } } catch (CMSSignerDigestMismatchException e) { throw new IllegalArgumentException("message-digest attribute value does not match calculated value", e); } catch (CMSException e) { throw new IllegalArgumentException("general exception verifying signed message", e); } catch (OperatorCreationException e) { throw new IllegalArgumentException("error creating verifier", e); } catch (Exception e) { throw new IllegalArgumentException(e); } return false; } X509SignedMessage(final String signedData, final String signature); } | X509SignedMessage { public boolean verify(final X509Certificate certificate) { try { CMSProcessable cmsProcessable = new CMSProcessableByteArray(signedData.getBytes()); CMSSignedData signedData = new CMSSignedData(cmsProcessable, Base64.decode(signature)); Iterator signersIterator = signedData.getSignerInfos().getSigners().iterator(); if (signersIterator.hasNext()) { SignerInformation signerInformation = (SignerInformation) signersIterator.next(); LOGGER.debug("Message is signed by certificate: {}", getFingerprint(signerInformation, signedData.getCertificates())); JcaSimpleSignerInfoVerifierBuilder verifierBuilder = new JcaSimpleSignerInfoVerifierBuilder(); verifierBuilder.setProvider(PROVIDER); return signerInformation.verify(verifierBuilder.build(certificate.getPublicKey())); } } catch (CMSSignerDigestMismatchException e) { throw new IllegalArgumentException("message-digest attribute value does not match calculated value", e); } catch (CMSException e) { throw new IllegalArgumentException("general exception verifying signed message", e); } catch (OperatorCreationException e) { throw new IllegalArgumentException("error creating verifier", e); } catch (Exception e) { throw new IllegalArgumentException(e); } return false; } X509SignedMessage(final String signedData, final String signature); boolean verify(final X509Certificate certificate); boolean verifySigningTime(final DateTimeProvider dateTimeProvider); @Override boolean equals(final Object o); @Override int hashCode(); } | X509SignedMessage { public boolean verify(final X509Certificate certificate) { try { CMSProcessable cmsProcessable = new CMSProcessableByteArray(signedData.getBytes()); CMSSignedData signedData = new CMSSignedData(cmsProcessable, Base64.decode(signature)); Iterator signersIterator = signedData.getSignerInfos().getSigners().iterator(); if (signersIterator.hasNext()) { SignerInformation signerInformation = (SignerInformation) signersIterator.next(); LOGGER.debug("Message is signed by certificate: {}", getFingerprint(signerInformation, signedData.getCertificates())); JcaSimpleSignerInfoVerifierBuilder verifierBuilder = new JcaSimpleSignerInfoVerifierBuilder(); verifierBuilder.setProvider(PROVIDER); return signerInformation.verify(verifierBuilder.build(certificate.getPublicKey())); } } catch (CMSSignerDigestMismatchException e) { throw new IllegalArgumentException("message-digest attribute value does not match calculated value", e); } catch (CMSException e) { throw new IllegalArgumentException("general exception verifying signed message", e); } catch (OperatorCreationException e) { throw new IllegalArgumentException("error creating verifier", e); } catch (Exception e) { throw new IllegalArgumentException(e); } return false; } X509SignedMessage(final String signedData, final String signature); boolean verify(final X509Certificate certificate); boolean verifySigningTime(final DateTimeProvider dateTimeProvider); @Override boolean equals(final Object o); @Override int hashCode(); } |
@Test public void verify_smime_multipart_person() throws Exception { final String signedData = ( "Content-Type: multipart/alternative;\n" + "\tboundary=\"Apple-Mail=_C45B4ECE-1DB6-4DDE-8B6D-4DB0BB0CDC8E\"\n" + "\n" + "\n" + "--Apple-Mail=_C45B4ECE-1DB6-4DDE-8B6D-4DB0BB0CDC8E\n" + "Content-Transfer-Encoding: 7bit\n" + "Content-Type: text/plain;\n" + "\tcharset=us-ascii\n" + "\n" + "person: First Person\n" + "address: St James Street\n" + "address: Burnley\n" + "address: UK\n" + "phone: +44 282 420469\n" + "nic-hdl: FP1-TEST\n" + "mnt-by: OWNER-MNT\n" + "changed: [email protected] 20121016\n" + "source: TEST\n" + "\n" + "\n" + "--Apple-Mail=_C45B4ECE-1DB6-4DDE-8B6D-4DB0BB0CDC8E\n" + "Content-Transfer-Encoding: 7bit\n" + "Content-Type: text/html;\n" + "\tcharset=us-ascii\n" + "\n" + "<html><head></head><body style=\"word-wrap: break-word; -webkit-nbsp-mode: space; -webkit-line-break: after-white-space; \">" + "<div style=\"font-size: 13px; \">person: First Person</div><div style=\"font-size: 13px; \">address: St James Street</div>" + "<div style=\"font-size: 13px; \">address: Burnley</div><div style=\"font-size: 13px; \">address: UK</div><div style=\"font-size: 13px; \">" + "phone: +44 282 420469</div><div style=\"font-size: 13px; \">nic-hdl: FP1-TEST</div><div style=\"font-size: 13px; \">" + "mnt-by: OWNER-MNT</div><div style=\"font-size: 13px; \">changed: <a href=\"mailto:[email protected]\">[email protected]</a> 20121016</div>" + "<div style=\"font-size: 13px; \">source: TEST</div><div><br></div></body></html>\n" + "--Apple-Mail=_C45B4ECE-1DB6-4DDE-8B6D-4DB0BB0CDC8E--\n").replaceAll("\\n", "\r\n"); final String signature = "MIAGCSqGSIb3DQEHAqCAMIACAQExCzAJBgUrDgMCGgUAMIAGCSqGSIb3DQEHAQAAoIIDtTCCA7Ew\n" + "ggMaoAMCAQICAgF8MA0GCSqGSIb3DQEBBAUAMIGFMQswCQYDVQQGEwJOTDEWMBQGA1UECBMNTm9v\n" + "cmQtSG9sbGFuZDESMBAGA1UEBxMJQW1zdGVyZGFtMREwDwYDVQQKEwhSSVBFIE5DQzEMMAoGA1UE\n" + "CxMDT1BTMQwwCgYDVQQDEwNDQTIxGzAZBgkqhkiG9w0BCQEWDG9wc0ByaXBlLm5ldDAeFw0xMTEy\n" + "MDExMjM3MjNaFw0yMTExMjgxMjM3MjNaMIGAMQswCQYDVQQGEwJOTDEWMBQGA1UECBMNTm9vcmQt\n" + "SG9sbGFuZDERMA8GA1UEChMIUklQRSBOQ0MxCzAJBgNVBAsTAkRCMRcwFQYDVQQDEw5FZHdhcmQg\n" + "U2hyeWFuZTEgMB4GCSqGSIb3DQEJARYRZXNocnlhbmVAcmlwZS5uZXQwgZ8wDQYJKoZIhvcNAQEB\n" + "BQADgY0AMIGJAoGBAMNs8uEHIiGdYms93PWA4bysV3IUwsabb+fwP6ACS9Jc8OaRQkT+1oK1sfw+\n" + "yX0YloCwJXtnAYDeKHoaPNiJ+dro3GN6BiijjV72KyKThHxWmZwXeqOKVCReREVNNlkuJTvziani\n" + "cZhlr9+bxhwRho1mkEvBmxEzPZTYKl0vQpd1AgMBAAGjggExMIIBLTAJBgNVHRMEAjAAMCwGCWCG\n" + "SAGG+EIBDQQfFh1PcGVuU1NMIEdlbmVyYXRlZCBDZXJ0aWZpY2F0ZTAdBgNVHQ4EFgQUwSiXle3q\n" + "9cufhKDVUCxrEPhj/9cwgbIGA1UdIwSBqjCBp4AUviRV1EFXFxVsA8ildF9OwyDKY9ihgYukgYgw\n" + "gYUxCzAJBgNVBAYTAk5MMRYwFAYDVQQIEw1Ob29yZC1Ib2xsYW5kMRIwEAYDVQQHEwlBbXN0ZXJk\n" + "YW0xETAPBgNVBAoTCFJJUEUgTkNDMQwwCgYDVQQLEwNPUFMxDDAKBgNVBAMTA0NBMjEbMBkGCSqG\n" + "SIb3DQEJARYMb3BzQHJpcGUubmV0ggEAMB4GA1UdEQQXMBWCE2UzLTIuc2luZ3cucmlwZS5uZXQw\n" + "DQYJKoZIhvcNAQEEBQADgYEAU5D2f5WK8AO5keVVf1/kj+wY/mRis9C7nXyhmQgrNcxzxqq+0Q7Q\n" + "mAYsNWMKDLZRemks4FfTGTmVT2SosQntXQBUoR1FGD3LQYLDZ2p1d7A6falUNu0PR8yAqJpT2Q2E\n" + "acKOic/UwHXhVorC1gbKZ5fN0dbUHqSk1zm41VQpobAxggLWMIIC0gIBATCBjDCBhTELMAkGA1UE\n" + "BhMCTkwxFjAUBgNVBAgTDU5vb3JkLUhvbGxhbmQxEjAQBgNVBAcTCUFtc3RlcmRhbTERMA8GA1UE\n" + "ChMIUklQRSBOQ0MxDDAKBgNVBAsTA09QUzEMMAoGA1UEAxMDQ0EyMRswGQYJKoZIhvcNAQkBFgxv\n" + "cHNAcmlwZS5uZXQCAgF8MAkGBSsOAwIaBQCgggGfMBgGCSqGSIb3DQEJAzELBgkqhkiG9w0BBwEw\n" + "HAYJKoZIhvcNAQkFMQ8XDTEzMDEwMzA4MzIwMVowIwYJKoZIhvcNAQkEMRYEFD4JhAipdRLJoj18\n" + "lGrkGzK74L00MIGdBgkrBgEEAYI3EAQxgY8wgYwwgYUxCzAJBgNVBAYTAk5MMRYwFAYDVQQIEw1O\n" + "b29yZC1Ib2xsYW5kMRIwEAYDVQQHEwlBbXN0ZXJkYW0xETAPBgNVBAoTCFJJUEUgTkNDMQwwCgYD\n" + "VQQLEwNPUFMxDDAKBgNVBAMTA0NBMjEbMBkGCSqGSIb3DQEJARYMb3BzQHJpcGUubmV0AgIBfDCB\n" + "nwYLKoZIhvcNAQkQAgsxgY+ggYwwgYUxCzAJBgNVBAYTAk5MMRYwFAYDVQQIEw1Ob29yZC1Ib2xs\n" + "YW5kMRIwEAYDVQQHEwlBbXN0ZXJkYW0xETAPBgNVBAoTCFJJUEUgTkNDMQwwCgYDVQQLEwNPUFMx\n" + "DDAKBgNVBAMTA0NBMjEbMBkGCSqGSIb3DQEJARYMb3BzQHJpcGUubmV0AgIBfDANBgkqhkiG9w0B\n" + "AQEFAASBgGlxIaAcSIDw5PUw7JscCO7waLRubOusGlg7KaQOodLNAItiqU1xE8jTDmHXt97RTbRG\n" + "AXWPFW9ByXburQmxCSSxxOnIey5ta8qlP8wXQrp86aKVYO9iUWDRH8B7C1R/ApHWhRsIHadscpDn\n" + "0dZdWzSqRcNJzOJjna7eHLz8SEDFAAAAAAAA\n"; final X509Certificate certificate = getCertificate("-----BEGIN CERTIFICATE-----\n" + "MIIDsTCCAxqgAwIBAgICAXwwDQYJKoZIhvcNAQEEBQAwgYUxCzAJBgNVBAYTAk5M\n" + "MRYwFAYDVQQIEw1Ob29yZC1Ib2xsYW5kMRIwEAYDVQQHEwlBbXN0ZXJkYW0xETAP\n" + "BgNVBAoTCFJJUEUgTkNDMQwwCgYDVQQLEwNPUFMxDDAKBgNVBAMTA0NBMjEbMBkG\n" + "CSqGSIb3DQEJARYMb3BzQHJpcGUubmV0MB4XDTExMTIwMTEyMzcyM1oXDTIxMTEy\n" + "ODEyMzcyM1owgYAxCzAJBgNVBAYTAk5MMRYwFAYDVQQIEw1Ob29yZC1Ib2xsYW5k\n" + "MREwDwYDVQQKEwhSSVBFIE5DQzELMAkGA1UECxMCREIxFzAVBgNVBAMTDkVkd2Fy\n" + "ZCBTaHJ5YW5lMSAwHgYJKoZIhvcNAQkBFhFlc2hyeWFuZUByaXBlLm5ldDCBnzAN\n" + "BgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAw2zy4QciIZ1iaz3c9YDhvKxXchTCxptv\n" + "5/A/oAJL0lzw5pFCRP7WgrWx/D7JfRiWgLAle2cBgN4oeho82In52ujcY3oGKKON\n" + "XvYrIpOEfFaZnBd6o4pUJF5ERU02WS4lO/OJqeJxmGWv35vGHBGGjWaQS8GbETM9\n" + "lNgqXS9Cl3UCAwEAAaOCATEwggEtMAkGA1UdEwQCMAAwLAYJYIZIAYb4QgENBB8W\n" + "HU9wZW5TU0wgR2VuZXJhdGVkIENlcnRpZmljYXRlMB0GA1UdDgQWBBTBKJeV7er1\n" + "y5+EoNVQLGsQ+GP/1zCBsgYDVR0jBIGqMIGngBS+JFXUQVcXFWwDyKV0X07DIMpj\n" + "2KGBi6SBiDCBhTELMAkGA1UEBhMCTkwxFjAUBgNVBAgTDU5vb3JkLUhvbGxhbmQx\n" + "EjAQBgNVBAcTCUFtc3RlcmRhbTERMA8GA1UEChMIUklQRSBOQ0MxDDAKBgNVBAsT\n" + "A09QUzEMMAoGA1UEAxMDQ0EyMRswGQYJKoZIhvcNAQkBFgxvcHNAcmlwZS5uZXSC\n" + "AQAwHgYDVR0RBBcwFYITZTMtMi5zaW5ndy5yaXBlLm5ldDANBgkqhkiG9w0BAQQF\n" + "AAOBgQBTkPZ/lYrwA7mR5VV/X+SP7Bj+ZGKz0LudfKGZCCs1zHPGqr7RDtCYBiw1\n" + "YwoMtlF6aSzgV9MZOZVPZKixCe1dAFShHUUYPctBgsNnanV3sDp9qVQ27Q9HzICo\n" + "mlPZDYRpwo6Jz9TAdeFWisLWBspnl83R1tQepKTXObjVVCmhsA==\n" + "-----END CERTIFICATE-----"); X509SignedMessage subject = new X509SignedMessage(signedData, signature); assertThat(subject.verify(certificate), is(true)); } | public boolean verify(final X509Certificate certificate) { try { CMSProcessable cmsProcessable = new CMSProcessableByteArray(signedData.getBytes()); CMSSignedData signedData = new CMSSignedData(cmsProcessable, Base64.decode(signature)); Iterator signersIterator = signedData.getSignerInfos().getSigners().iterator(); if (signersIterator.hasNext()) { SignerInformation signerInformation = (SignerInformation) signersIterator.next(); LOGGER.debug("Message is signed by certificate: {}", getFingerprint(signerInformation, signedData.getCertificates())); JcaSimpleSignerInfoVerifierBuilder verifierBuilder = new JcaSimpleSignerInfoVerifierBuilder(); verifierBuilder.setProvider(PROVIDER); return signerInformation.verify(verifierBuilder.build(certificate.getPublicKey())); } } catch (CMSSignerDigestMismatchException e) { throw new IllegalArgumentException("message-digest attribute value does not match calculated value", e); } catch (CMSException e) { throw new IllegalArgumentException("general exception verifying signed message", e); } catch (OperatorCreationException e) { throw new IllegalArgumentException("error creating verifier", e); } catch (Exception e) { throw new IllegalArgumentException(e); } return false; } | X509SignedMessage { public boolean verify(final X509Certificate certificate) { try { CMSProcessable cmsProcessable = new CMSProcessableByteArray(signedData.getBytes()); CMSSignedData signedData = new CMSSignedData(cmsProcessable, Base64.decode(signature)); Iterator signersIterator = signedData.getSignerInfos().getSigners().iterator(); if (signersIterator.hasNext()) { SignerInformation signerInformation = (SignerInformation) signersIterator.next(); LOGGER.debug("Message is signed by certificate: {}", getFingerprint(signerInformation, signedData.getCertificates())); JcaSimpleSignerInfoVerifierBuilder verifierBuilder = new JcaSimpleSignerInfoVerifierBuilder(); verifierBuilder.setProvider(PROVIDER); return signerInformation.verify(verifierBuilder.build(certificate.getPublicKey())); } } catch (CMSSignerDigestMismatchException e) { throw new IllegalArgumentException("message-digest attribute value does not match calculated value", e); } catch (CMSException e) { throw new IllegalArgumentException("general exception verifying signed message", e); } catch (OperatorCreationException e) { throw new IllegalArgumentException("error creating verifier", e); } catch (Exception e) { throw new IllegalArgumentException(e); } return false; } } | X509SignedMessage { public boolean verify(final X509Certificate certificate) { try { CMSProcessable cmsProcessable = new CMSProcessableByteArray(signedData.getBytes()); CMSSignedData signedData = new CMSSignedData(cmsProcessable, Base64.decode(signature)); Iterator signersIterator = signedData.getSignerInfos().getSigners().iterator(); if (signersIterator.hasNext()) { SignerInformation signerInformation = (SignerInformation) signersIterator.next(); LOGGER.debug("Message is signed by certificate: {}", getFingerprint(signerInformation, signedData.getCertificates())); JcaSimpleSignerInfoVerifierBuilder verifierBuilder = new JcaSimpleSignerInfoVerifierBuilder(); verifierBuilder.setProvider(PROVIDER); return signerInformation.verify(verifierBuilder.build(certificate.getPublicKey())); } } catch (CMSSignerDigestMismatchException e) { throw new IllegalArgumentException("message-digest attribute value does not match calculated value", e); } catch (CMSException e) { throw new IllegalArgumentException("general exception verifying signed message", e); } catch (OperatorCreationException e) { throw new IllegalArgumentException("error creating verifier", e); } catch (Exception e) { throw new IllegalArgumentException(e); } return false; } X509SignedMessage(final String signedData, final String signature); } | X509SignedMessage { public boolean verify(final X509Certificate certificate) { try { CMSProcessable cmsProcessable = new CMSProcessableByteArray(signedData.getBytes()); CMSSignedData signedData = new CMSSignedData(cmsProcessable, Base64.decode(signature)); Iterator signersIterator = signedData.getSignerInfos().getSigners().iterator(); if (signersIterator.hasNext()) { SignerInformation signerInformation = (SignerInformation) signersIterator.next(); LOGGER.debug("Message is signed by certificate: {}", getFingerprint(signerInformation, signedData.getCertificates())); JcaSimpleSignerInfoVerifierBuilder verifierBuilder = new JcaSimpleSignerInfoVerifierBuilder(); verifierBuilder.setProvider(PROVIDER); return signerInformation.verify(verifierBuilder.build(certificate.getPublicKey())); } } catch (CMSSignerDigestMismatchException e) { throw new IllegalArgumentException("message-digest attribute value does not match calculated value", e); } catch (CMSException e) { throw new IllegalArgumentException("general exception verifying signed message", e); } catch (OperatorCreationException e) { throw new IllegalArgumentException("error creating verifier", e); } catch (Exception e) { throw new IllegalArgumentException(e); } return false; } X509SignedMessage(final String signedData, final String signature); boolean verify(final X509Certificate certificate); boolean verifySigningTime(final DateTimeProvider dateTimeProvider); @Override boolean equals(final Object o); @Override int hashCode(); } | X509SignedMessage { public boolean verify(final X509Certificate certificate) { try { CMSProcessable cmsProcessable = new CMSProcessableByteArray(signedData.getBytes()); CMSSignedData signedData = new CMSSignedData(cmsProcessable, Base64.decode(signature)); Iterator signersIterator = signedData.getSignerInfos().getSigners().iterator(); if (signersIterator.hasNext()) { SignerInformation signerInformation = (SignerInformation) signersIterator.next(); LOGGER.debug("Message is signed by certificate: {}", getFingerprint(signerInformation, signedData.getCertificates())); JcaSimpleSignerInfoVerifierBuilder verifierBuilder = new JcaSimpleSignerInfoVerifierBuilder(); verifierBuilder.setProvider(PROVIDER); return signerInformation.verify(verifierBuilder.build(certificate.getPublicKey())); } } catch (CMSSignerDigestMismatchException e) { throw new IllegalArgumentException("message-digest attribute value does not match calculated value", e); } catch (CMSException e) { throw new IllegalArgumentException("general exception verifying signed message", e); } catch (OperatorCreationException e) { throw new IllegalArgumentException("error creating verifier", e); } catch (Exception e) { throw new IllegalArgumentException(e); } return false; } X509SignedMessage(final String signedData, final String signature); boolean verify(final X509Certificate certificate); boolean verifySigningTime(final DateTimeProvider dateTimeProvider); @Override boolean equals(final Object o); @Override int hashCode(); } |
@Test public void isEquals() { X509SignedMessage first = new X509SignedMessage("First Test", "First Signature"); X509SignedMessage second = new X509SignedMessage("Second Test", "Second Signature"); assertThat(first.equals(first), is(true)); assertThat(first.equals(second), is(false)); } | @Override public boolean equals(final Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; final X509SignedMessage that = (X509SignedMessage) o; return Objects.equals(signature, that.signature); } | X509SignedMessage { @Override public boolean equals(final Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; final X509SignedMessage that = (X509SignedMessage) o; return Objects.equals(signature, that.signature); } } | X509SignedMessage { @Override public boolean equals(final Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; final X509SignedMessage that = (X509SignedMessage) o; return Objects.equals(signature, that.signature); } X509SignedMessage(final String signedData, final String signature); } | X509SignedMessage { @Override public boolean equals(final Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; final X509SignedMessage that = (X509SignedMessage) o; return Objects.equals(signature, that.signature); } X509SignedMessage(final String signedData, final String signature); boolean verify(final X509Certificate certificate); boolean verifySigningTime(final DateTimeProvider dateTimeProvider); @Override boolean equals(final Object o); @Override int hashCode(); } | X509SignedMessage { @Override public boolean equals(final Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; final X509SignedMessage that = (X509SignedMessage) o; return Objects.equals(signature, that.signature); } X509SignedMessage(final String signedData, final String signature); boolean verify(final X509Certificate certificate); boolean verifySigningTime(final DateTimeProvider dateTimeProvider); @Override boolean equals(final Object o); @Override int hashCode(); } |
@Test public void log() throws Exception { subject = new LoggingHandlerAdapter(loggerContext); subject.log(statementInfo, resultInfo); verify(loggerContext, times(1)).logQuery(statementInfo, resultInfo); } | @Override public void log(final StatementInfo statementInfo, final ResultInfo resultInfo) { loggerContext.logQuery(statementInfo, resultInfo); } | LoggingHandlerAdapter implements LoggingHandler { @Override public void log(final StatementInfo statementInfo, final ResultInfo resultInfo) { loggerContext.logQuery(statementInfo, resultInfo); } } | LoggingHandlerAdapter implements LoggingHandler { @Override public void log(final StatementInfo statementInfo, final ResultInfo resultInfo) { loggerContext.logQuery(statementInfo, resultInfo); } @Autowired LoggingHandlerAdapter(final LoggerContext loggerContext); } | LoggingHandlerAdapter implements LoggingHandler { @Override public void log(final StatementInfo statementInfo, final ResultInfo resultInfo) { loggerContext.logQuery(statementInfo, resultInfo); } @Autowired LoggingHandlerAdapter(final LoggerContext loggerContext); @Override void log(final StatementInfo statementInfo, final ResultInfo resultInfo); } | LoggingHandlerAdapter implements LoggingHandler { @Override public void log(final StatementInfo statementInfo, final ResultInfo resultInfo) { loggerContext.logQuery(statementInfo, resultInfo); } @Autowired LoggingHandlerAdapter(final LoggerContext loggerContext); @Override void log(final StatementInfo statementInfo, final ResultInfo resultInfo); } |
@Test public void logUpdateResult_create_success() { final RpslObject maintainer = RpslObject.parse("mntner: TST-MNT"); final UpdateResult updateResult = new UpdateResult(maintainer, maintainer, Action.CREATE, UpdateStatus.SUCCESS, new ObjectMessages(), 0, false); when(update.getCredentials()).thenReturn(new Credentials()); when(updateContext.createUpdateResult(update)).thenReturn(updateResult); subject.logUpdateResult(updateRequest, updateContext, update, stopwatch); verify(logger).info(matches("\\[\\s*0\\] 0[,.]000 ns UPD CREATE mntner TST-MNT \\(1\\) SUCCESS : <E0,W0,I0> AUTH - null")); } | public void logUpdateResult(final UpdateRequest updateRequest, final UpdateContext updateContext, final Update update, final Stopwatch stopwatch) { logger.info(formatMessage(updateRequest, updateContext, update, stopwatch)); } | UpdateLog { public void logUpdateResult(final UpdateRequest updateRequest, final UpdateContext updateContext, final Update update, final Stopwatch stopwatch) { logger.info(formatMessage(updateRequest, updateContext, update, stopwatch)); } } | UpdateLog { public void logUpdateResult(final UpdateRequest updateRequest, final UpdateContext updateContext, final Update update, final Stopwatch stopwatch) { logger.info(formatMessage(updateRequest, updateContext, update, stopwatch)); } UpdateLog(); UpdateLog(final Logger logger); } | UpdateLog { public void logUpdateResult(final UpdateRequest updateRequest, final UpdateContext updateContext, final Update update, final Stopwatch stopwatch) { logger.info(formatMessage(updateRequest, updateContext, update, stopwatch)); } UpdateLog(); UpdateLog(final Logger logger); void logUpdateResult(final UpdateRequest updateRequest, final UpdateContext updateContext, final Update update, final Stopwatch stopwatch); } | UpdateLog { public void logUpdateResult(final UpdateRequest updateRequest, final UpdateContext updateContext, final Update update, final Stopwatch stopwatch) { logger.info(formatMessage(updateRequest, updateContext, update, stopwatch)); } UpdateLog(); UpdateLog(final Logger logger); void logUpdateResult(final UpdateRequest updateRequest, final UpdateContext updateContext, final Update update, final Stopwatch stopwatch); } |
@Test public void logUpdateResult_create_success_dryRun() { final RpslObject maintainer = RpslObject.parse("mntner: TST-MNT"); final UpdateResult updateResult = new UpdateResult(maintainer, maintainer, Action.CREATE, UpdateStatus.SUCCESS, new ObjectMessages(), 0, true); when(update.getCredentials()).thenReturn(new Credentials()); when(updateContext.createUpdateResult(update)).thenReturn(updateResult); subject.logUpdateResult(updateRequest, updateContext, update, stopwatch); verify(logger).info(matches("\\[\\s*0\\] 0[,.]000 ns DRY CREATE mntner TST-MNT \\(1\\) SUCCESS : <E0,W0,I0> AUTH - null")); } | public void logUpdateResult(final UpdateRequest updateRequest, final UpdateContext updateContext, final Update update, final Stopwatch stopwatch) { logger.info(formatMessage(updateRequest, updateContext, update, stopwatch)); } | UpdateLog { public void logUpdateResult(final UpdateRequest updateRequest, final UpdateContext updateContext, final Update update, final Stopwatch stopwatch) { logger.info(formatMessage(updateRequest, updateContext, update, stopwatch)); } } | UpdateLog { public void logUpdateResult(final UpdateRequest updateRequest, final UpdateContext updateContext, final Update update, final Stopwatch stopwatch) { logger.info(formatMessage(updateRequest, updateContext, update, stopwatch)); } UpdateLog(); UpdateLog(final Logger logger); } | UpdateLog { public void logUpdateResult(final UpdateRequest updateRequest, final UpdateContext updateContext, final Update update, final Stopwatch stopwatch) { logger.info(formatMessage(updateRequest, updateContext, update, stopwatch)); } UpdateLog(); UpdateLog(final Logger logger); void logUpdateResult(final UpdateRequest updateRequest, final UpdateContext updateContext, final Update update, final Stopwatch stopwatch); } | UpdateLog { public void logUpdateResult(final UpdateRequest updateRequest, final UpdateContext updateContext, final Update update, final Stopwatch stopwatch) { logger.info(formatMessage(updateRequest, updateContext, update, stopwatch)); } UpdateLog(); UpdateLog(final Logger logger); void logUpdateResult(final UpdateRequest updateRequest, final UpdateContext updateContext, final Update update, final Stopwatch stopwatch); } |
@Test public void logException() throws Exception { subject.logUpdate(update); subject.logException(update, new NullPointerException()); subject.close(); final String log = outputStream.toString("UTF-8"); assertThat(log, containsString("" + "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n" + "<dbupdate created=\"2012-12-01 00:00:00\">\n" + " <messages/>\n" + " <updates>\n" + " <update attempt=\"1\" time=\"2012-12-01 00:00:00\">\n" + " <key>[mntner] DEV-ROOT-MNT</key>\n" + " <operation>DELETE</operation>\n" + " <reason>reason</reason>\n" + " <paragraph><![CDATA[paragraph]]></paragraph>\n" + " <object><![CDATA[mntner: DEV-ROOT-MNT\n" + "]]></object>\n" + " <exception>\n" + " <class>java.lang.NullPointerException</class>\n" + " <message><![CDATA[null]]></message>\n" + " <stacktrace><![CDATA[java.lang.NullPointerException\n")); } | public void logException(final Update update, final Throwable throwable) { final Element updateElement = createOrGetUpdateElement(update); final Element exceptionElement = doc.createElement("exception"); updateElement.appendChild(exceptionElement); exceptionElement.appendChild(keyValue("class", throwable.getClass().getName())); exceptionElement.appendChild(keyValue("message", throwable.getMessage())); final StringWriter stringWriter = new StringWriter(); final PrintWriter stackTraceWriter = new PrintWriter(stringWriter); throwable.printStackTrace(stackTraceWriter); exceptionElement.appendChild(keyValue("stacktrace", stringWriter.getBuffer().toString())); } | AuditLogger { public void logException(final Update update, final Throwable throwable) { final Element updateElement = createOrGetUpdateElement(update); final Element exceptionElement = doc.createElement("exception"); updateElement.appendChild(exceptionElement); exceptionElement.appendChild(keyValue("class", throwable.getClass().getName())); exceptionElement.appendChild(keyValue("message", throwable.getMessage())); final StringWriter stringWriter = new StringWriter(); final PrintWriter stackTraceWriter = new PrintWriter(stringWriter); throwable.printStackTrace(stackTraceWriter); exceptionElement.appendChild(keyValue("stacktrace", stringWriter.getBuffer().toString())); } } | AuditLogger { public void logException(final Update update, final Throwable throwable) { final Element updateElement = createOrGetUpdateElement(update); final Element exceptionElement = doc.createElement("exception"); updateElement.appendChild(exceptionElement); exceptionElement.appendChild(keyValue("class", throwable.getClass().getName())); exceptionElement.appendChild(keyValue("message", throwable.getMessage())); final StringWriter stringWriter = new StringWriter(); final PrintWriter stackTraceWriter = new PrintWriter(stringWriter); throwable.printStackTrace(stackTraceWriter); exceptionElement.appendChild(keyValue("stacktrace", stringWriter.getBuffer().toString())); } AuditLogger(final DateTimeProvider dateTimeProvider, final OutputStream outputStream); } | AuditLogger { public void logException(final Update update, final Throwable throwable) { final Element updateElement = createOrGetUpdateElement(update); final Element exceptionElement = doc.createElement("exception"); updateElement.appendChild(exceptionElement); exceptionElement.appendChild(keyValue("class", throwable.getClass().getName())); exceptionElement.appendChild(keyValue("message", throwable.getMessage())); final StringWriter stringWriter = new StringWriter(); final PrintWriter stackTraceWriter = new PrintWriter(stringWriter); throwable.printStackTrace(stackTraceWriter); exceptionElement.appendChild(keyValue("stacktrace", stringWriter.getBuffer().toString())); } AuditLogger(final DateTimeProvider dateTimeProvider, final OutputStream outputStream); @SuppressWarnings("ThrowableResultOfMethodCallIgnored" /* Throwable is logged */) void log(final Message message, @Nullable final Throwable t); void logDryRun(); void logBatchUpdate(); void logUpdate(final Update update); void logPreparedUpdate(final PreparedUpdate preparedUpdate); void logException(final Update update, final Throwable throwable); void logDuration(final Update update, final String duration); void logQuery(final Update update, final StatementInfo statementInfo, final ResultInfo resultInfo); void logString(Update update, String element, String auditMessage); void logAuthenticationStrategy(Update update, String authenticationStrategy, Collection<RpslObject> maintainers); void logCredentials(Update update); void logAction(final Update update, final Action action); void logStatus(final Update update, final UpdateStatus status); void logMessage(final Update update, final Message message); void logMessage(final Update update, final RpslAttribute attribute, final Message message); void close(); } | AuditLogger { public void logException(final Update update, final Throwable throwable) { final Element updateElement = createOrGetUpdateElement(update); final Element exceptionElement = doc.createElement("exception"); updateElement.appendChild(exceptionElement); exceptionElement.appendChild(keyValue("class", throwable.getClass().getName())); exceptionElement.appendChild(keyValue("message", throwable.getMessage())); final StringWriter stringWriter = new StringWriter(); final PrintWriter stackTraceWriter = new PrintWriter(stringWriter); throwable.printStackTrace(stackTraceWriter); exceptionElement.appendChild(keyValue("stacktrace", stringWriter.getBuffer().toString())); } AuditLogger(final DateTimeProvider dateTimeProvider, final OutputStream outputStream); @SuppressWarnings("ThrowableResultOfMethodCallIgnored" /* Throwable is logged */) void log(final Message message, @Nullable final Throwable t); void logDryRun(); void logBatchUpdate(); void logUpdate(final Update update); void logPreparedUpdate(final PreparedUpdate preparedUpdate); void logException(final Update update, final Throwable throwable); void logDuration(final Update update, final String duration); void logQuery(final Update update, final StatementInfo statementInfo, final ResultInfo resultInfo); void logString(Update update, String element, String auditMessage); void logAuthenticationStrategy(Update update, String authenticationStrategy, Collection<RpslObject> maintainers); void logCredentials(Update update); void logAction(final Update update, final Action action); void logStatus(final Update update, final UpdateStatus status); void logMessage(final Update update, final Message message); void logMessage(final Update update, final RpslAttribute attribute, final Message message); void close(); } |
@Test public void logDuration() throws Exception { subject.logUpdate(update); subject.logDuration(update, "1 ns"); subject.close(); final String log = outputStream.toString("UTF-8"); assertThat(log, containsString("" + "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n" + "<dbupdate created=\"2012-12-01 00:00:00\">\n" + " <messages/>\n" + " <updates>\n" + " <update attempt=\"1\" time=\"2012-12-01 00:00:00\">\n" + " <key>[mntner] DEV-ROOT-MNT</key>\n" + " <operation>DELETE</operation>\n" + " <reason>reason</reason>\n" + " <paragraph><![CDATA[paragraph]]></paragraph>\n" + " <object><![CDATA[mntner: DEV-ROOT-MNT\n" + "]]></object>\n" + " <duration>1 ns</duration>\n" + " </update>\n" + " </updates>\n" + "</dbupdate>")); } | public void logDuration(final Update update, final String duration) { final Element updateElement = createOrGetUpdateElement(update); updateElement.appendChild(keyValue("duration", duration)); } | AuditLogger { public void logDuration(final Update update, final String duration) { final Element updateElement = createOrGetUpdateElement(update); updateElement.appendChild(keyValue("duration", duration)); } } | AuditLogger { public void logDuration(final Update update, final String duration) { final Element updateElement = createOrGetUpdateElement(update); updateElement.appendChild(keyValue("duration", duration)); } AuditLogger(final DateTimeProvider dateTimeProvider, final OutputStream outputStream); } | AuditLogger { public void logDuration(final Update update, final String duration) { final Element updateElement = createOrGetUpdateElement(update); updateElement.appendChild(keyValue("duration", duration)); } AuditLogger(final DateTimeProvider dateTimeProvider, final OutputStream outputStream); @SuppressWarnings("ThrowableResultOfMethodCallIgnored" /* Throwable is logged */) void log(final Message message, @Nullable final Throwable t); void logDryRun(); void logBatchUpdate(); void logUpdate(final Update update); void logPreparedUpdate(final PreparedUpdate preparedUpdate); void logException(final Update update, final Throwable throwable); void logDuration(final Update update, final String duration); void logQuery(final Update update, final StatementInfo statementInfo, final ResultInfo resultInfo); void logString(Update update, String element, String auditMessage); void logAuthenticationStrategy(Update update, String authenticationStrategy, Collection<RpslObject> maintainers); void logCredentials(Update update); void logAction(final Update update, final Action action); void logStatus(final Update update, final UpdateStatus status); void logMessage(final Update update, final Message message); void logMessage(final Update update, final RpslAttribute attribute, final Message message); void close(); } | AuditLogger { public void logDuration(final Update update, final String duration) { final Element updateElement = createOrGetUpdateElement(update); updateElement.appendChild(keyValue("duration", duration)); } AuditLogger(final DateTimeProvider dateTimeProvider, final OutputStream outputStream); @SuppressWarnings("ThrowableResultOfMethodCallIgnored" /* Throwable is logged */) void log(final Message message, @Nullable final Throwable t); void logDryRun(); void logBatchUpdate(); void logUpdate(final Update update); void logPreparedUpdate(final PreparedUpdate preparedUpdate); void logException(final Update update, final Throwable throwable); void logDuration(final Update update, final String duration); void logQuery(final Update update, final StatementInfo statementInfo, final ResultInfo resultInfo); void logString(Update update, String element, String auditMessage); void logAuthenticationStrategy(Update update, String authenticationStrategy, Collection<RpslObject> maintainers); void logCredentials(Update update); void logAction(final Update update, final Action action); void logStatus(final Update update, final UpdateStatus status); void logMessage(final Update update, final Message message); void logMessage(final Update update, final RpslAttribute attribute, final Message message); void close(); } |
@Test public void testDateTimeToString_dateTime() throws Exception { assertThat(FormatHelper.dateTimeToString(LocalDateTime.of(2001, 10, 1, 12, 13, 14)), is("2001-10-01 12:13:14")); } | public static String dateTimeToString(final TemporalAccessor temporalAccessor) { if (temporalAccessor == null) { return null; } if (temporalAccessor.isSupported(ChronoField.HOUR_OF_DAY)) { return DATE_TIME_FORMAT.format(temporalAccessor); } return DATE_FORMAT.format(temporalAccessor); } | FormatHelper { public static String dateTimeToString(final TemporalAccessor temporalAccessor) { if (temporalAccessor == null) { return null; } if (temporalAccessor.isSupported(ChronoField.HOUR_OF_DAY)) { return DATE_TIME_FORMAT.format(temporalAccessor); } return DATE_FORMAT.format(temporalAccessor); } } | FormatHelper { public static String dateTimeToString(final TemporalAccessor temporalAccessor) { if (temporalAccessor == null) { return null; } if (temporalAccessor.isSupported(ChronoField.HOUR_OF_DAY)) { return DATE_TIME_FORMAT.format(temporalAccessor); } return DATE_FORMAT.format(temporalAccessor); } private FormatHelper(); } | FormatHelper { public static String dateTimeToString(final TemporalAccessor temporalAccessor) { if (temporalAccessor == null) { return null; } if (temporalAccessor.isSupported(ChronoField.HOUR_OF_DAY)) { return DATE_TIME_FORMAT.format(temporalAccessor); } return DATE_FORMAT.format(temporalAccessor); } private FormatHelper(); static String dateToString(final TemporalAccessor temporalAccessor); static String dateTimeToString(final TemporalAccessor temporalAccessor); static String dateTimeToUtcString(final TemporalAccessor temporalAccessor); static String prettyPrint(final String prefix, final String value, final int indentation, final int maxLineLength); static String prettyPrint(final String prefix, final String value, final int indentation, final int maxLineLength, boolean repeatPrefix); } | FormatHelper { public static String dateTimeToString(final TemporalAccessor temporalAccessor) { if (temporalAccessor == null) { return null; } if (temporalAccessor.isSupported(ChronoField.HOUR_OF_DAY)) { return DATE_TIME_FORMAT.format(temporalAccessor); } return DATE_FORMAT.format(temporalAccessor); } private FormatHelper(); static String dateToString(final TemporalAccessor temporalAccessor); static String dateTimeToString(final TemporalAccessor temporalAccessor); static String dateTimeToUtcString(final TemporalAccessor temporalAccessor); static String prettyPrint(final String prefix, final String value, final int indentation, final int maxLineLength); static String prettyPrint(final String prefix, final String value, final int indentation, final int maxLineLength, boolean repeatPrefix); } |
@Test public void logQuery() throws Exception { final Map<Integer, Object> params = Maps.newTreeMap(); params.put(1, "p1"); params.put(2, 22); final List<List<String>> rows = Arrays.asList( Arrays.asList("c1-1", "c1-2"), Arrays.asList("c2-1", "c2-2")); final StatementInfo statementInfo = new StatementInfo("sql", params); final ResultInfo resultInfo = new ResultInfo(rows); subject.logUpdate(update); subject.logQuery(update, statementInfo, resultInfo); subject.close(); final String log = outputStream.toString("UTF-8"); assertThat(log, containsString("" + "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n" + "<dbupdate created=\"2012-12-01 00:00:00\">\n" + " <messages/>\n" + " <updates>\n" + " <update attempt=\"1\" time=\"2012-12-01 00:00:00\">\n" + " <key>[mntner] DEV-ROOT-MNT</key>\n" + " <operation>DELETE</operation>\n" + " <reason>reason</reason>\n" + " <paragraph><![CDATA[paragraph]]></paragraph>\n" + " <object><![CDATA[mntner: DEV-ROOT-MNT\n" + "]]></object>\n" + " <query>\n" + " <sql><![CDATA[sql]]></sql>\n" + " <params>\n" + " <param idx=\"1\">p1</param>\n" + " <param idx=\"2\">22</param>\n" + " </params>\n" + " <results>\n" + " <row idx=\"1\">\n" + " <column idx=\"0\"><![CDATA[c1-1]]></column>\n" + " <column idx=\"1\"><![CDATA[c1-2]]></column>\n" + " </row>\n" + " <row idx=\"2\">\n" + " <column idx=\"0\"><![CDATA[c2-1]]></column>\n" + " <column idx=\"1\"><![CDATA[c2-2]]></column>\n" + " </row>\n" + " </results>\n" + " </query>\n" + " </update>\n" + " </updates>\n" + "</dbupdate>")); } | public void logQuery(final Update update, final StatementInfo statementInfo, final ResultInfo resultInfo) { final Element updateElement = createOrGetUpdateElement(update); final Element queryElement = doc.createElement("query"); updateElement.appendChild(queryElement); queryElement.appendChild(keyValue("sql", statementInfo.getSql())); final Element paramsElement = doc.createElement("params"); queryElement.appendChild(paramsElement); for (final Map.Entry<Integer, Object> entry : statementInfo.getParameters().entrySet()) { final Element param = keyValue("param", entry.getValue()); param.setAttribute("idx", String.valueOf(entry.getKey())); paramsElement.appendChild(param); } final Element resultsElement = doc.createElement("results"); queryElement.appendChild(resultsElement); int rowNum = 1; for (final List<String> row : resultInfo.getRows()) { final Element rowElement = doc.createElement("row"); rowElement.setAttribute("idx", String.valueOf(rowNum++)); resultsElement.appendChild(rowElement); int colNum = 0; for (final String column : row) { final Element columnElement = keyValue("column", column); columnElement.setAttribute("idx", String.valueOf(colNum++)); rowElement.appendChild(columnElement); } } } | AuditLogger { public void logQuery(final Update update, final StatementInfo statementInfo, final ResultInfo resultInfo) { final Element updateElement = createOrGetUpdateElement(update); final Element queryElement = doc.createElement("query"); updateElement.appendChild(queryElement); queryElement.appendChild(keyValue("sql", statementInfo.getSql())); final Element paramsElement = doc.createElement("params"); queryElement.appendChild(paramsElement); for (final Map.Entry<Integer, Object> entry : statementInfo.getParameters().entrySet()) { final Element param = keyValue("param", entry.getValue()); param.setAttribute("idx", String.valueOf(entry.getKey())); paramsElement.appendChild(param); } final Element resultsElement = doc.createElement("results"); queryElement.appendChild(resultsElement); int rowNum = 1; for (final List<String> row : resultInfo.getRows()) { final Element rowElement = doc.createElement("row"); rowElement.setAttribute("idx", String.valueOf(rowNum++)); resultsElement.appendChild(rowElement); int colNum = 0; for (final String column : row) { final Element columnElement = keyValue("column", column); columnElement.setAttribute("idx", String.valueOf(colNum++)); rowElement.appendChild(columnElement); } } } } | AuditLogger { public void logQuery(final Update update, final StatementInfo statementInfo, final ResultInfo resultInfo) { final Element updateElement = createOrGetUpdateElement(update); final Element queryElement = doc.createElement("query"); updateElement.appendChild(queryElement); queryElement.appendChild(keyValue("sql", statementInfo.getSql())); final Element paramsElement = doc.createElement("params"); queryElement.appendChild(paramsElement); for (final Map.Entry<Integer, Object> entry : statementInfo.getParameters().entrySet()) { final Element param = keyValue("param", entry.getValue()); param.setAttribute("idx", String.valueOf(entry.getKey())); paramsElement.appendChild(param); } final Element resultsElement = doc.createElement("results"); queryElement.appendChild(resultsElement); int rowNum = 1; for (final List<String> row : resultInfo.getRows()) { final Element rowElement = doc.createElement("row"); rowElement.setAttribute("idx", String.valueOf(rowNum++)); resultsElement.appendChild(rowElement); int colNum = 0; for (final String column : row) { final Element columnElement = keyValue("column", column); columnElement.setAttribute("idx", String.valueOf(colNum++)); rowElement.appendChild(columnElement); } } } AuditLogger(final DateTimeProvider dateTimeProvider, final OutputStream outputStream); } | AuditLogger { public void logQuery(final Update update, final StatementInfo statementInfo, final ResultInfo resultInfo) { final Element updateElement = createOrGetUpdateElement(update); final Element queryElement = doc.createElement("query"); updateElement.appendChild(queryElement); queryElement.appendChild(keyValue("sql", statementInfo.getSql())); final Element paramsElement = doc.createElement("params"); queryElement.appendChild(paramsElement); for (final Map.Entry<Integer, Object> entry : statementInfo.getParameters().entrySet()) { final Element param = keyValue("param", entry.getValue()); param.setAttribute("idx", String.valueOf(entry.getKey())); paramsElement.appendChild(param); } final Element resultsElement = doc.createElement("results"); queryElement.appendChild(resultsElement); int rowNum = 1; for (final List<String> row : resultInfo.getRows()) { final Element rowElement = doc.createElement("row"); rowElement.setAttribute("idx", String.valueOf(rowNum++)); resultsElement.appendChild(rowElement); int colNum = 0; for (final String column : row) { final Element columnElement = keyValue("column", column); columnElement.setAttribute("idx", String.valueOf(colNum++)); rowElement.appendChild(columnElement); } } } AuditLogger(final DateTimeProvider dateTimeProvider, final OutputStream outputStream); @SuppressWarnings("ThrowableResultOfMethodCallIgnored" /* Throwable is logged */) void log(final Message message, @Nullable final Throwable t); void logDryRun(); void logBatchUpdate(); void logUpdate(final Update update); void logPreparedUpdate(final PreparedUpdate preparedUpdate); void logException(final Update update, final Throwable throwable); void logDuration(final Update update, final String duration); void logQuery(final Update update, final StatementInfo statementInfo, final ResultInfo resultInfo); void logString(Update update, String element, String auditMessage); void logAuthenticationStrategy(Update update, String authenticationStrategy, Collection<RpslObject> maintainers); void logCredentials(Update update); void logAction(final Update update, final Action action); void logStatus(final Update update, final UpdateStatus status); void logMessage(final Update update, final Message message); void logMessage(final Update update, final RpslAttribute attribute, final Message message); void close(); } | AuditLogger { public void logQuery(final Update update, final StatementInfo statementInfo, final ResultInfo resultInfo) { final Element updateElement = createOrGetUpdateElement(update); final Element queryElement = doc.createElement("query"); updateElement.appendChild(queryElement); queryElement.appendChild(keyValue("sql", statementInfo.getSql())); final Element paramsElement = doc.createElement("params"); queryElement.appendChild(paramsElement); for (final Map.Entry<Integer, Object> entry : statementInfo.getParameters().entrySet()) { final Element param = keyValue("param", entry.getValue()); param.setAttribute("idx", String.valueOf(entry.getKey())); paramsElement.appendChild(param); } final Element resultsElement = doc.createElement("results"); queryElement.appendChild(resultsElement); int rowNum = 1; for (final List<String> row : resultInfo.getRows()) { final Element rowElement = doc.createElement("row"); rowElement.setAttribute("idx", String.valueOf(rowNum++)); resultsElement.appendChild(rowElement); int colNum = 0; for (final String column : row) { final Element columnElement = keyValue("column", column); columnElement.setAttribute("idx", String.valueOf(colNum++)); rowElement.appendChild(columnElement); } } } AuditLogger(final DateTimeProvider dateTimeProvider, final OutputStream outputStream); @SuppressWarnings("ThrowableResultOfMethodCallIgnored" /* Throwable is logged */) void log(final Message message, @Nullable final Throwable t); void logDryRun(); void logBatchUpdate(); void logUpdate(final Update update); void logPreparedUpdate(final PreparedUpdate preparedUpdate); void logException(final Update update, final Throwable throwable); void logDuration(final Update update, final String duration); void logQuery(final Update update, final StatementInfo statementInfo, final ResultInfo resultInfo); void logString(Update update, String element, String auditMessage); void logAuthenticationStrategy(Update update, String authenticationStrategy, Collection<RpslObject> maintainers); void logCredentials(Update update); void logAction(final Update update, final Action action); void logStatus(final Update update, final UpdateStatus status); void logMessage(final Update update, final Message message); void logMessage(final Update update, final RpslAttribute attribute, final Message message); void close(); } |
@Test public void empty() throws Exception { subject.close(); assertThat(outputStream.toString("UTF-8"), is("" + "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n" + "<dbupdate created=\"2012-12-01 00:00:00\">\n" + " <messages/>\n" + " <updates/>\n" + "</dbupdate>\n" )); verify(outputStream, times(1)).close(); } | public void close() { try { writeAndClose(); } catch (IOException e) { LOGGER.error("IO Exception", e); } } | AuditLogger { public void close() { try { writeAndClose(); } catch (IOException e) { LOGGER.error("IO Exception", e); } } } | AuditLogger { public void close() { try { writeAndClose(); } catch (IOException e) { LOGGER.error("IO Exception", e); } } AuditLogger(final DateTimeProvider dateTimeProvider, final OutputStream outputStream); } | AuditLogger { public void close() { try { writeAndClose(); } catch (IOException e) { LOGGER.error("IO Exception", e); } } AuditLogger(final DateTimeProvider dateTimeProvider, final OutputStream outputStream); @SuppressWarnings("ThrowableResultOfMethodCallIgnored" /* Throwable is logged */) void log(final Message message, @Nullable final Throwable t); void logDryRun(); void logBatchUpdate(); void logUpdate(final Update update); void logPreparedUpdate(final PreparedUpdate preparedUpdate); void logException(final Update update, final Throwable throwable); void logDuration(final Update update, final String duration); void logQuery(final Update update, final StatementInfo statementInfo, final ResultInfo resultInfo); void logString(Update update, String element, String auditMessage); void logAuthenticationStrategy(Update update, String authenticationStrategy, Collection<RpslObject> maintainers); void logCredentials(Update update); void logAction(final Update update, final Action action); void logStatus(final Update update, final UpdateStatus status); void logMessage(final Update update, final Message message); void logMessage(final Update update, final RpslAttribute attribute, final Message message); void close(); } | AuditLogger { public void close() { try { writeAndClose(); } catch (IOException e) { LOGGER.error("IO Exception", e); } } AuditLogger(final DateTimeProvider dateTimeProvider, final OutputStream outputStream); @SuppressWarnings("ThrowableResultOfMethodCallIgnored" /* Throwable is logged */) void log(final Message message, @Nullable final Throwable t); void logDryRun(); void logBatchUpdate(); void logUpdate(final Update update); void logPreparedUpdate(final PreparedUpdate preparedUpdate); void logException(final Update update, final Throwable throwable); void logDuration(final Update update, final String duration); void logQuery(final Update update, final StatementInfo statementInfo, final ResultInfo resultInfo); void logString(Update update, String element, String auditMessage); void logAuthenticationStrategy(Update update, String authenticationStrategy, Collection<RpslObject> maintainers); void logCredentials(Update update); void logAction(final Update update, final Action action); void logStatus(final Update update, final UpdateStatus status); void logMessage(final Update update, final Message message); void logMessage(final Update update, final RpslAttribute attribute, final Message message); void close(); } |
@Test public void checkDirs() { subject.remove(); final File f = new File(folder.getRoot(), "test/"); subject.setBaseDir(f.getAbsolutePath()); subject.checkDirs(); subject.init("folder"); assertThat(f.exists(), is(true)); } | public void checkDirs() { getCreatedDir(baseDir); } | LoggerContext { public void checkDirs() { getCreatedDir(baseDir); } } | LoggerContext { public void checkDirs() { getCreatedDir(baseDir); } @Autowired LoggerContext(final DateTimeProvider dateTimeProvider); } | LoggerContext { public void checkDirs() { getCreatedDir(baseDir); } @Autowired LoggerContext(final DateTimeProvider dateTimeProvider); void setBaseDir(final String baseDir); @PostConstruct void start(); void checkDirs(); void init(final String folderName); void remove(); File getFile(final String filename); File log(final String name, final LogCallback callback); void log(final Message message); void log(final Message message, final Throwable t); void logUpdateStarted(final Update update); void logUpdateCompleted(final UpdateContainer updateContainer); void logUpdateFailed(final UpdateContainer updateContainer, final Throwable throwable); void logPreparedUpdate(PreparedUpdate preparedUpdate); void logQuery(final StatementInfo statementInfo, final ResultInfo resultInfo); void logDryRun(); void logBatchUpdate(); void logAction(final UpdateContainer updateContainer, final Action action); void logAuthenticationStrategy(Update update, String authenticationStrategy, Collection<RpslObject> maintainers); void logCredentials(Update update); void logString(final Update update, final String element, final String auditMessage); void logStatus(final UpdateContainer updateContainer, final UpdateStatus action); void logMessage(final UpdateContainer updateContainer, final Message message); void logMessage(final UpdateContainer updateContainer, final RpslAttribute attribute, final Message message); void logException(final UpdateContainer updateContainer, final Throwable throwable); void logMessages(final UpdateContainer updateContainer, ObjectMessages objectMessages); } | LoggerContext { public void checkDirs() { getCreatedDir(baseDir); } @Autowired LoggerContext(final DateTimeProvider dateTimeProvider); void setBaseDir(final String baseDir); @PostConstruct void start(); void checkDirs(); void init(final String folderName); void remove(); File getFile(final String filename); File log(final String name, final LogCallback callback); void log(final Message message); void log(final Message message, final Throwable t); void logUpdateStarted(final Update update); void logUpdateCompleted(final UpdateContainer updateContainer); void logUpdateFailed(final UpdateContainer updateContainer, final Throwable throwable); void logPreparedUpdate(PreparedUpdate preparedUpdate); void logQuery(final StatementInfo statementInfo, final ResultInfo resultInfo); void logDryRun(); void logBatchUpdate(); void logAction(final UpdateContainer updateContainer, final Action action); void logAuthenticationStrategy(Update update, String authenticationStrategy, Collection<RpslObject> maintainers); void logCredentials(Update update); void logString(final Update update, final String element, final String auditMessage); void logStatus(final UpdateContainer updateContainer, final UpdateStatus action); void logMessage(final UpdateContainer updateContainer, final Message message); void logMessage(final UpdateContainer updateContainer, final RpslAttribute attribute, final Message message); void logException(final UpdateContainer updateContainer, final Throwable throwable); void logMessages(final UpdateContainer updateContainer, ObjectMessages objectMessages); } |
@Test public void getFile() throws Exception { assertThat(subject.getFile("test.txt").getName(), is("001.test.txt.gz")); assertThat(subject.getFile("test.txt").getName(), is("002.test.txt.gz")); assertThat(subject.getFile("test.txt").getName(), is("003.test.txt.gz")); } | public File getFile(final String filename) { final Context tempContext = getContext(); return getFile(tempContext.baseDir, tempContext.nextFileNumber(), filename); } | LoggerContext { public File getFile(final String filename) { final Context tempContext = getContext(); return getFile(tempContext.baseDir, tempContext.nextFileNumber(), filename); } } | LoggerContext { public File getFile(final String filename) { final Context tempContext = getContext(); return getFile(tempContext.baseDir, tempContext.nextFileNumber(), filename); } @Autowired LoggerContext(final DateTimeProvider dateTimeProvider); } | LoggerContext { public File getFile(final String filename) { final Context tempContext = getContext(); return getFile(tempContext.baseDir, tempContext.nextFileNumber(), filename); } @Autowired LoggerContext(final DateTimeProvider dateTimeProvider); void setBaseDir(final String baseDir); @PostConstruct void start(); void checkDirs(); void init(final String folderName); void remove(); File getFile(final String filename); File log(final String name, final LogCallback callback); void log(final Message message); void log(final Message message, final Throwable t); void logUpdateStarted(final Update update); void logUpdateCompleted(final UpdateContainer updateContainer); void logUpdateFailed(final UpdateContainer updateContainer, final Throwable throwable); void logPreparedUpdate(PreparedUpdate preparedUpdate); void logQuery(final StatementInfo statementInfo, final ResultInfo resultInfo); void logDryRun(); void logBatchUpdate(); void logAction(final UpdateContainer updateContainer, final Action action); void logAuthenticationStrategy(Update update, String authenticationStrategy, Collection<RpslObject> maintainers); void logCredentials(Update update); void logString(final Update update, final String element, final String auditMessage); void logStatus(final UpdateContainer updateContainer, final UpdateStatus action); void logMessage(final UpdateContainer updateContainer, final Message message); void logMessage(final UpdateContainer updateContainer, final RpslAttribute attribute, final Message message); void logException(final UpdateContainer updateContainer, final Throwable throwable); void logMessages(final UpdateContainer updateContainer, ObjectMessages objectMessages); } | LoggerContext { public File getFile(final String filename) { final Context tempContext = getContext(); return getFile(tempContext.baseDir, tempContext.nextFileNumber(), filename); } @Autowired LoggerContext(final DateTimeProvider dateTimeProvider); void setBaseDir(final String baseDir); @PostConstruct void start(); void checkDirs(); void init(final String folderName); void remove(); File getFile(final String filename); File log(final String name, final LogCallback callback); void log(final Message message); void log(final Message message, final Throwable t); void logUpdateStarted(final Update update); void logUpdateCompleted(final UpdateContainer updateContainer); void logUpdateFailed(final UpdateContainer updateContainer, final Throwable throwable); void logPreparedUpdate(PreparedUpdate preparedUpdate); void logQuery(final StatementInfo statementInfo, final ResultInfo resultInfo); void logDryRun(); void logBatchUpdate(); void logAction(final UpdateContainer updateContainer, final Action action); void logAuthenticationStrategy(Update update, String authenticationStrategy, Collection<RpslObject> maintainers); void logCredentials(Update update); void logString(final Update update, final String element, final String auditMessage); void logStatus(final UpdateContainer updateContainer, final UpdateStatus action); void logMessage(final UpdateContainer updateContainer, final Message message); void logMessage(final UpdateContainer updateContainer, final RpslAttribute attribute, final Message message); void logException(final UpdateContainer updateContainer, final Throwable throwable); void logMessages(final UpdateContainer updateContainer, ObjectMessages objectMessages); } |
@Test public void log() throws Exception { final File file = subject.log("test.txt", new LogCallback() { @Override public void log(final OutputStream outputStream) throws IOException { outputStream.write("test".getBytes()); } }); final InputStream is = new GZIPInputStream(new BufferedInputStream(new FileInputStream(new File(folder.getRoot(), "001.test.txt.gz")))); final String contents = new String(FileCopyUtils.copyToByteArray(is), StandardCharsets.UTF_8); assertThat(file.getName(), is("001.test.txt.gz")); assertThat(contents, is("test")); } | public File log(final String name, final LogCallback callback) { final File file = getFile(name); OutputStream os = null; try { os = getOutputstream(file); callback.log(os); } catch (IOException e) { throw new IllegalStateException("Unable to write to " + file.getAbsolutePath(), e); } finally { closeOutputStream(os); } return file; } | LoggerContext { public File log(final String name, final LogCallback callback) { final File file = getFile(name); OutputStream os = null; try { os = getOutputstream(file); callback.log(os); } catch (IOException e) { throw new IllegalStateException("Unable to write to " + file.getAbsolutePath(), e); } finally { closeOutputStream(os); } return file; } } | LoggerContext { public File log(final String name, final LogCallback callback) { final File file = getFile(name); OutputStream os = null; try { os = getOutputstream(file); callback.log(os); } catch (IOException e) { throw new IllegalStateException("Unable to write to " + file.getAbsolutePath(), e); } finally { closeOutputStream(os); } return file; } @Autowired LoggerContext(final DateTimeProvider dateTimeProvider); } | LoggerContext { public File log(final String name, final LogCallback callback) { final File file = getFile(name); OutputStream os = null; try { os = getOutputstream(file); callback.log(os); } catch (IOException e) { throw new IllegalStateException("Unable to write to " + file.getAbsolutePath(), e); } finally { closeOutputStream(os); } return file; } @Autowired LoggerContext(final DateTimeProvider dateTimeProvider); void setBaseDir(final String baseDir); @PostConstruct void start(); void checkDirs(); void init(final String folderName); void remove(); File getFile(final String filename); File log(final String name, final LogCallback callback); void log(final Message message); void log(final Message message, final Throwable t); void logUpdateStarted(final Update update); void logUpdateCompleted(final UpdateContainer updateContainer); void logUpdateFailed(final UpdateContainer updateContainer, final Throwable throwable); void logPreparedUpdate(PreparedUpdate preparedUpdate); void logQuery(final StatementInfo statementInfo, final ResultInfo resultInfo); void logDryRun(); void logBatchUpdate(); void logAction(final UpdateContainer updateContainer, final Action action); void logAuthenticationStrategy(Update update, String authenticationStrategy, Collection<RpslObject> maintainers); void logCredentials(Update update); void logString(final Update update, final String element, final String auditMessage); void logStatus(final UpdateContainer updateContainer, final UpdateStatus action); void logMessage(final UpdateContainer updateContainer, final Message message); void logMessage(final UpdateContainer updateContainer, final RpslAttribute attribute, final Message message); void logException(final UpdateContainer updateContainer, final Throwable throwable); void logMessages(final UpdateContainer updateContainer, ObjectMessages objectMessages); } | LoggerContext { public File log(final String name, final LogCallback callback) { final File file = getFile(name); OutputStream os = null; try { os = getOutputstream(file); callback.log(os); } catch (IOException e) { throw new IllegalStateException("Unable to write to " + file.getAbsolutePath(), e); } finally { closeOutputStream(os); } return file; } @Autowired LoggerContext(final DateTimeProvider dateTimeProvider); void setBaseDir(final String baseDir); @PostConstruct void start(); void checkDirs(); void init(final String folderName); void remove(); File getFile(final String filename); File log(final String name, final LogCallback callback); void log(final Message message); void log(final Message message, final Throwable t); void logUpdateStarted(final Update update); void logUpdateCompleted(final UpdateContainer updateContainer); void logUpdateFailed(final UpdateContainer updateContainer, final Throwable throwable); void logPreparedUpdate(PreparedUpdate preparedUpdate); void logQuery(final StatementInfo statementInfo, final ResultInfo resultInfo); void logDryRun(); void logBatchUpdate(); void logAction(final UpdateContainer updateContainer, final Action action); void logAuthenticationStrategy(Update update, String authenticationStrategy, Collection<RpslObject> maintainers); void logCredentials(Update update); void logString(final Update update, final String element, final String auditMessage); void logStatus(final UpdateContainer updateContainer, final UpdateStatus action); void logMessage(final UpdateContainer updateContainer, final Message message); void logMessage(final UpdateContainer updateContainer, final RpslAttribute attribute, final Message message); void logException(final UpdateContainer updateContainer, final Throwable throwable); void logMessages(final UpdateContainer updateContainer, ObjectMessages objectMessages); } |
@Test(expected = IllegalStateException.class) public void log_throws_exception() { subject.log("filename", new LogCallback() { @Override public void log(final OutputStream outputStream) throws IOException { throw new IOException(); } }); } | public File log(final String name, final LogCallback callback) { final File file = getFile(name); OutputStream os = null; try { os = getOutputstream(file); callback.log(os); } catch (IOException e) { throw new IllegalStateException("Unable to write to " + file.getAbsolutePath(), e); } finally { closeOutputStream(os); } return file; } | LoggerContext { public File log(final String name, final LogCallback callback) { final File file = getFile(name); OutputStream os = null; try { os = getOutputstream(file); callback.log(os); } catch (IOException e) { throw new IllegalStateException("Unable to write to " + file.getAbsolutePath(), e); } finally { closeOutputStream(os); } return file; } } | LoggerContext { public File log(final String name, final LogCallback callback) { final File file = getFile(name); OutputStream os = null; try { os = getOutputstream(file); callback.log(os); } catch (IOException e) { throw new IllegalStateException("Unable to write to " + file.getAbsolutePath(), e); } finally { closeOutputStream(os); } return file; } @Autowired LoggerContext(final DateTimeProvider dateTimeProvider); } | LoggerContext { public File log(final String name, final LogCallback callback) { final File file = getFile(name); OutputStream os = null; try { os = getOutputstream(file); callback.log(os); } catch (IOException e) { throw new IllegalStateException("Unable to write to " + file.getAbsolutePath(), e); } finally { closeOutputStream(os); } return file; } @Autowired LoggerContext(final DateTimeProvider dateTimeProvider); void setBaseDir(final String baseDir); @PostConstruct void start(); void checkDirs(); void init(final String folderName); void remove(); File getFile(final String filename); File log(final String name, final LogCallback callback); void log(final Message message); void log(final Message message, final Throwable t); void logUpdateStarted(final Update update); void logUpdateCompleted(final UpdateContainer updateContainer); void logUpdateFailed(final UpdateContainer updateContainer, final Throwable throwable); void logPreparedUpdate(PreparedUpdate preparedUpdate); void logQuery(final StatementInfo statementInfo, final ResultInfo resultInfo); void logDryRun(); void logBatchUpdate(); void logAction(final UpdateContainer updateContainer, final Action action); void logAuthenticationStrategy(Update update, String authenticationStrategy, Collection<RpslObject> maintainers); void logCredentials(Update update); void logString(final Update update, final String element, final String auditMessage); void logStatus(final UpdateContainer updateContainer, final UpdateStatus action); void logMessage(final UpdateContainer updateContainer, final Message message); void logMessage(final UpdateContainer updateContainer, final RpslAttribute attribute, final Message message); void logException(final UpdateContainer updateContainer, final Throwable throwable); void logMessages(final UpdateContainer updateContainer, ObjectMessages objectMessages); } | LoggerContext { public File log(final String name, final LogCallback callback) { final File file = getFile(name); OutputStream os = null; try { os = getOutputstream(file); callback.log(os); } catch (IOException e) { throw new IllegalStateException("Unable to write to " + file.getAbsolutePath(), e); } finally { closeOutputStream(os); } return file; } @Autowired LoggerContext(final DateTimeProvider dateTimeProvider); void setBaseDir(final String baseDir); @PostConstruct void start(); void checkDirs(); void init(final String folderName); void remove(); File getFile(final String filename); File log(final String name, final LogCallback callback); void log(final Message message); void log(final Message message, final Throwable t); void logUpdateStarted(final Update update); void logUpdateCompleted(final UpdateContainer updateContainer); void logUpdateFailed(final UpdateContainer updateContainer, final Throwable throwable); void logPreparedUpdate(PreparedUpdate preparedUpdate); void logQuery(final StatementInfo statementInfo, final ResultInfo resultInfo); void logDryRun(); void logBatchUpdate(); void logAction(final UpdateContainer updateContainer, final Action action); void logAuthenticationStrategy(Update update, String authenticationStrategy, Collection<RpslObject> maintainers); void logCredentials(Update update); void logString(final Update update, final String element, final String auditMessage); void logStatus(final UpdateContainer updateContainer, final UpdateStatus action); void logMessage(final UpdateContainer updateContainer, final Message message); void logMessage(final UpdateContainer updateContainer, final RpslAttribute attribute, final Message message); void logException(final UpdateContainer updateContainer, final Throwable throwable); void logMessages(final UpdateContainer updateContainer, ObjectMessages objectMessages); } |
@Test public void log_query_no_context_should_not_fail() { subject.logQuery(new StatementInfo("sql"), new ResultInfo(Collections.<List<String>>emptyList())); } | public void logQuery(final StatementInfo statementInfo, final ResultInfo resultInfo) { final Context ctx = context.get(); if (ctx != null && ctx.currentUpdate != null) { ctx.auditLogger.logQuery(ctx.currentUpdate, statementInfo, resultInfo); } } | LoggerContext { public void logQuery(final StatementInfo statementInfo, final ResultInfo resultInfo) { final Context ctx = context.get(); if (ctx != null && ctx.currentUpdate != null) { ctx.auditLogger.logQuery(ctx.currentUpdate, statementInfo, resultInfo); } } } | LoggerContext { public void logQuery(final StatementInfo statementInfo, final ResultInfo resultInfo) { final Context ctx = context.get(); if (ctx != null && ctx.currentUpdate != null) { ctx.auditLogger.logQuery(ctx.currentUpdate, statementInfo, resultInfo); } } @Autowired LoggerContext(final DateTimeProvider dateTimeProvider); } | LoggerContext { public void logQuery(final StatementInfo statementInfo, final ResultInfo resultInfo) { final Context ctx = context.get(); if (ctx != null && ctx.currentUpdate != null) { ctx.auditLogger.logQuery(ctx.currentUpdate, statementInfo, resultInfo); } } @Autowired LoggerContext(final DateTimeProvider dateTimeProvider); void setBaseDir(final String baseDir); @PostConstruct void start(); void checkDirs(); void init(final String folderName); void remove(); File getFile(final String filename); File log(final String name, final LogCallback callback); void log(final Message message); void log(final Message message, final Throwable t); void logUpdateStarted(final Update update); void logUpdateCompleted(final UpdateContainer updateContainer); void logUpdateFailed(final UpdateContainer updateContainer, final Throwable throwable); void logPreparedUpdate(PreparedUpdate preparedUpdate); void logQuery(final StatementInfo statementInfo, final ResultInfo resultInfo); void logDryRun(); void logBatchUpdate(); void logAction(final UpdateContainer updateContainer, final Action action); void logAuthenticationStrategy(Update update, String authenticationStrategy, Collection<RpslObject> maintainers); void logCredentials(Update update); void logString(final Update update, final String element, final String auditMessage); void logStatus(final UpdateContainer updateContainer, final UpdateStatus action); void logMessage(final UpdateContainer updateContainer, final Message message); void logMessage(final UpdateContainer updateContainer, final RpslAttribute attribute, final Message message); void logException(final UpdateContainer updateContainer, final Throwable throwable); void logMessages(final UpdateContainer updateContainer, ObjectMessages objectMessages); } | LoggerContext { public void logQuery(final StatementInfo statementInfo, final ResultInfo resultInfo) { final Context ctx = context.get(); if (ctx != null && ctx.currentUpdate != null) { ctx.auditLogger.logQuery(ctx.currentUpdate, statementInfo, resultInfo); } } @Autowired LoggerContext(final DateTimeProvider dateTimeProvider); void setBaseDir(final String baseDir); @PostConstruct void start(); void checkDirs(); void init(final String folderName); void remove(); File getFile(final String filename); File log(final String name, final LogCallback callback); void log(final Message message); void log(final Message message, final Throwable t); void logUpdateStarted(final Update update); void logUpdateCompleted(final UpdateContainer updateContainer); void logUpdateFailed(final UpdateContainer updateContainer, final Throwable throwable); void logPreparedUpdate(PreparedUpdate preparedUpdate); void logQuery(final StatementInfo statementInfo, final ResultInfo resultInfo); void logDryRun(); void logBatchUpdate(); void logAction(final UpdateContainer updateContainer, final Action action); void logAuthenticationStrategy(Update update, String authenticationStrategy, Collection<RpslObject> maintainers); void logCredentials(Update update); void logString(final Update update, final String element, final String auditMessage); void logStatus(final UpdateContainer updateContainer, final UpdateStatus action); void logMessage(final UpdateContainer updateContainer, final Message message); void logMessage(final UpdateContainer updateContainer, final RpslAttribute attribute, final Message message); void logException(final UpdateContainer updateContainer, final Throwable throwable); void logMessages(final UpdateContainer updateContainer, ObjectMessages objectMessages); } |
@Test(expected = IllegalStateException.class) public void logUpdateComplete_no_context_should_fail() { subject.logUpdateCompleted(update); } | public void logUpdateCompleted(final UpdateContainer updateContainer) { logUpdateComplete(updateContainer, null); } | LoggerContext { public void logUpdateCompleted(final UpdateContainer updateContainer) { logUpdateComplete(updateContainer, null); } } | LoggerContext { public void logUpdateCompleted(final UpdateContainer updateContainer) { logUpdateComplete(updateContainer, null); } @Autowired LoggerContext(final DateTimeProvider dateTimeProvider); } | LoggerContext { public void logUpdateCompleted(final UpdateContainer updateContainer) { logUpdateComplete(updateContainer, null); } @Autowired LoggerContext(final DateTimeProvider dateTimeProvider); void setBaseDir(final String baseDir); @PostConstruct void start(); void checkDirs(); void init(final String folderName); void remove(); File getFile(final String filename); File log(final String name, final LogCallback callback); void log(final Message message); void log(final Message message, final Throwable t); void logUpdateStarted(final Update update); void logUpdateCompleted(final UpdateContainer updateContainer); void logUpdateFailed(final UpdateContainer updateContainer, final Throwable throwable); void logPreparedUpdate(PreparedUpdate preparedUpdate); void logQuery(final StatementInfo statementInfo, final ResultInfo resultInfo); void logDryRun(); void logBatchUpdate(); void logAction(final UpdateContainer updateContainer, final Action action); void logAuthenticationStrategy(Update update, String authenticationStrategy, Collection<RpslObject> maintainers); void logCredentials(Update update); void logString(final Update update, final String element, final String auditMessage); void logStatus(final UpdateContainer updateContainer, final UpdateStatus action); void logMessage(final UpdateContainer updateContainer, final Message message); void logMessage(final UpdateContainer updateContainer, final RpslAttribute attribute, final Message message); void logException(final UpdateContainer updateContainer, final Throwable throwable); void logMessages(final UpdateContainer updateContainer, ObjectMessages objectMessages); } | LoggerContext { public void logUpdateCompleted(final UpdateContainer updateContainer) { logUpdateComplete(updateContainer, null); } @Autowired LoggerContext(final DateTimeProvider dateTimeProvider); void setBaseDir(final String baseDir); @PostConstruct void start(); void checkDirs(); void init(final String folderName); void remove(); File getFile(final String filename); File log(final String name, final LogCallback callback); void log(final Message message); void log(final Message message, final Throwable t); void logUpdateStarted(final Update update); void logUpdateCompleted(final UpdateContainer updateContainer); void logUpdateFailed(final UpdateContainer updateContainer, final Throwable throwable); void logPreparedUpdate(PreparedUpdate preparedUpdate); void logQuery(final StatementInfo statementInfo, final ResultInfo resultInfo); void logDryRun(); void logBatchUpdate(); void logAction(final UpdateContainer updateContainer, final Action action); void logAuthenticationStrategy(Update update, String authenticationStrategy, Collection<RpslObject> maintainers); void logCredentials(Update update); void logString(final Update update, final String element, final String auditMessage); void logStatus(final UpdateContainer updateContainer, final UpdateStatus action); void logMessage(final UpdateContainer updateContainer, final Message message); void logMessage(final UpdateContainer updateContainer, final RpslAttribute attribute, final Message message); void logException(final UpdateContainer updateContainer, final Throwable throwable); void logMessages(final UpdateContainer updateContainer, ObjectMessages objectMessages); } |
@Test public void logException() throws IOException { final String content = "mntner: DEV-ROOT-MNT"; final RpslObject object = RpslObject.parse(content); when(update.getOperation()).thenReturn(Operation.DELETE); when(update.getParagraph()).thenReturn(new Paragraph(content)); when(update.getSubmittedObject()).thenReturn(object); subject.logUpdateStarted(update); subject.logUpdateFailed(update, new NullPointerException()); subject.remove(); final InputStream is = new GZIPInputStream(new BufferedInputStream(new FileInputStream(new File(folder.getRoot(), "000.audit.xml.gz")))); final String contents = new String(FileCopyUtils.copyToByteArray(is), StandardCharsets.UTF_8); assertThat(contents, containsString("" + " <exception>\n" + " <class>java.lang.NullPointerException</class>\n" + " <message><![CDATA[null]]></message>\n" + " <stacktrace><![CDATA[java.lang.NullPointerException\n")); } | public void logException(final UpdateContainer updateContainer, final Throwable throwable) { getContext().auditLogger.logException(updateContainer.getUpdate(), throwable); } | LoggerContext { public void logException(final UpdateContainer updateContainer, final Throwable throwable) { getContext().auditLogger.logException(updateContainer.getUpdate(), throwable); } } | LoggerContext { public void logException(final UpdateContainer updateContainer, final Throwable throwable) { getContext().auditLogger.logException(updateContainer.getUpdate(), throwable); } @Autowired LoggerContext(final DateTimeProvider dateTimeProvider); } | LoggerContext { public void logException(final UpdateContainer updateContainer, final Throwable throwable) { getContext().auditLogger.logException(updateContainer.getUpdate(), throwable); } @Autowired LoggerContext(final DateTimeProvider dateTimeProvider); void setBaseDir(final String baseDir); @PostConstruct void start(); void checkDirs(); void init(final String folderName); void remove(); File getFile(final String filename); File log(final String name, final LogCallback callback); void log(final Message message); void log(final Message message, final Throwable t); void logUpdateStarted(final Update update); void logUpdateCompleted(final UpdateContainer updateContainer); void logUpdateFailed(final UpdateContainer updateContainer, final Throwable throwable); void logPreparedUpdate(PreparedUpdate preparedUpdate); void logQuery(final StatementInfo statementInfo, final ResultInfo resultInfo); void logDryRun(); void logBatchUpdate(); void logAction(final UpdateContainer updateContainer, final Action action); void logAuthenticationStrategy(Update update, String authenticationStrategy, Collection<RpslObject> maintainers); void logCredentials(Update update); void logString(final Update update, final String element, final String auditMessage); void logStatus(final UpdateContainer updateContainer, final UpdateStatus action); void logMessage(final UpdateContainer updateContainer, final Message message); void logMessage(final UpdateContainer updateContainer, final RpslAttribute attribute, final Message message); void logException(final UpdateContainer updateContainer, final Throwable throwable); void logMessages(final UpdateContainer updateContainer, ObjectMessages objectMessages); } | LoggerContext { public void logException(final UpdateContainer updateContainer, final Throwable throwable) { getContext().auditLogger.logException(updateContainer.getUpdate(), throwable); } @Autowired LoggerContext(final DateTimeProvider dateTimeProvider); void setBaseDir(final String baseDir); @PostConstruct void start(); void checkDirs(); void init(final String folderName); void remove(); File getFile(final String filename); File log(final String name, final LogCallback callback); void log(final Message message); void log(final Message message, final Throwable t); void logUpdateStarted(final Update update); void logUpdateCompleted(final UpdateContainer updateContainer); void logUpdateFailed(final UpdateContainer updateContainer, final Throwable throwable); void logPreparedUpdate(PreparedUpdate preparedUpdate); void logQuery(final StatementInfo statementInfo, final ResultInfo resultInfo); void logDryRun(); void logBatchUpdate(); void logAction(final UpdateContainer updateContainer, final Action action); void logAuthenticationStrategy(Update update, String authenticationStrategy, Collection<RpslObject> maintainers); void logCredentials(Update update); void logString(final Update update, final String element, final String auditMessage); void logStatus(final UpdateContainer updateContainer, final UpdateStatus action); void logMessage(final UpdateContainer updateContainer, final Message message); void logMessage(final UpdateContainer updateContainer, final RpslAttribute attribute, final Message message); void logException(final UpdateContainer updateContainer, final Throwable throwable); void logMessages(final UpdateContainer updateContainer, ObjectMessages objectMessages); } |
@Test public void log() throws IOException, MessagingException { final MailMessageLogCallback subject = new MailMessageLogCallback(message); subject.log(outputStream); verify(outputStream).write("".getBytes()); } | @Override public void log(final OutputStream outputStream) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { message.writeTo(baos); String messageData = new String( baos.toByteArray(), "UTF-8" ); String filtered = PasswordFilter.filterPasswordsInContents(messageData); outputStream.write(filtered.getBytes("UTF-8")); } catch (MessagingException e) { LOGGER.warn("Writing message", e); } } | MailMessageLogCallback implements LogCallback { @Override public void log(final OutputStream outputStream) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { message.writeTo(baos); String messageData = new String( baos.toByteArray(), "UTF-8" ); String filtered = PasswordFilter.filterPasswordsInContents(messageData); outputStream.write(filtered.getBytes("UTF-8")); } catch (MessagingException e) { LOGGER.warn("Writing message", e); } } } | MailMessageLogCallback implements LogCallback { @Override public void log(final OutputStream outputStream) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { message.writeTo(baos); String messageData = new String( baos.toByteArray(), "UTF-8" ); String filtered = PasswordFilter.filterPasswordsInContents(messageData); outputStream.write(filtered.getBytes("UTF-8")); } catch (MessagingException e) { LOGGER.warn("Writing message", e); } } MailMessageLogCallback(final Message message); } | MailMessageLogCallback implements LogCallback { @Override public void log(final OutputStream outputStream) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { message.writeTo(baos); String messageData = new String( baos.toByteArray(), "UTF-8" ); String filtered = PasswordFilter.filterPasswordsInContents(messageData); outputStream.write(filtered.getBytes("UTF-8")); } catch (MessagingException e) { LOGGER.warn("Writing message", e); } } MailMessageLogCallback(final Message message); @Override void log(final OutputStream outputStream); } | MailMessageLogCallback implements LogCallback { @Override public void log(final OutputStream outputStream) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { message.writeTo(baos); String messageData = new String( baos.toByteArray(), "UTF-8" ); String filtered = PasswordFilter.filterPasswordsInContents(messageData); outputStream.write(filtered.getBytes("UTF-8")); } catch (MessagingException e) { LOGGER.warn("Writing message", e); } } MailMessageLogCallback(final Message message); @Override void log(final OutputStream outputStream); } |
@Test public void empty_input_test() { final Iterable subject = getSimpleIterable(); final Iterator<Integer> iterator = subject.iterator(); assertFalse(iterator.hasNext()); } | @Override public Iterator<T> iterator() { return new IteratorTransformer(head); } | IterableTransformer implements Iterable<T> { @Override public Iterator<T> iterator() { return new IteratorTransformer(head); } } | IterableTransformer implements Iterable<T> { @Override public Iterator<T> iterator() { return new IteratorTransformer(head); } IterableTransformer(final Iterable<? extends T> wrap); } | IterableTransformer implements Iterable<T> { @Override public Iterator<T> iterator() { return new IteratorTransformer(head); } IterableTransformer(final Iterable<? extends T> wrap); IterableTransformer<T> setHeader(T... header); IterableTransformer<T> setHeader(Collection<T> header); abstract void apply(final T input, final Deque<T> result); @Override Iterator<T> iterator(); } | IterableTransformer implements Iterable<T> { @Override public Iterator<T> iterator() { return new IteratorTransformer(head); } IterableTransformer(final Iterable<? extends T> wrap); IterableTransformer<T> setHeader(T... header); IterableTransformer<T> setHeader(Collection<T> header); abstract void apply(final T input, final Deque<T> result); @Override Iterator<T> iterator(); } |
@Test public void run() { subject = spy(subject); subject.setGrsImportEnabled(false); subject.run(); verify(subject, times(0)).grsImport(anyString(), anyBoolean()); } | @Override @Scheduled(cron = "0 0 0 * * *") @SchedulerLock(name = "GrsImporter") public void run() { if (!grsImportEnabled) { LOGGER.info("GRS import is not enabled"); return; } List<Future> futures = grsImport(defaultSources, false); for (Future future : futures) { try { future.get(); } catch (InterruptedException | ExecutionException e) { LOGGER.error(e.getMessage(), e); } } } | GrsImporter implements DailyScheduledTask { @Override @Scheduled(cron = "0 0 0 * * *") @SchedulerLock(name = "GrsImporter") public void run() { if (!grsImportEnabled) { LOGGER.info("GRS import is not enabled"); return; } List<Future> futures = grsImport(defaultSources, false); for (Future future : futures) { try { future.get(); } catch (InterruptedException | ExecutionException e) { LOGGER.error(e.getMessage(), e); } } } } | GrsImporter implements DailyScheduledTask { @Override @Scheduled(cron = "0 0 0 * * *") @SchedulerLock(name = "GrsImporter") public void run() { if (!grsImportEnabled) { LOGGER.info("GRS import is not enabled"); return; } List<Future> futures = grsImport(defaultSources, false); for (Future future : futures) { try { future.get(); } catch (InterruptedException | ExecutionException e) { LOGGER.error(e.getMessage(), e); } } } @Autowired GrsImporter(final GrsSourceImporter grsSourceImporter, final GrsSource[] grsSources); } | GrsImporter implements DailyScheduledTask { @Override @Scheduled(cron = "0 0 0 * * *") @SchedulerLock(name = "GrsImporter") public void run() { if (!grsImportEnabled) { LOGGER.info("GRS import is not enabled"); return; } List<Future> futures = grsImport(defaultSources, false); for (Future future : futures) { try { future.get(); } catch (InterruptedException | ExecutionException e) { LOGGER.error(e.getMessage(), e); } } } @Autowired GrsImporter(final GrsSourceImporter grsSourceImporter, final GrsSource[] grsSources); @Value("${grs.import.enabled}") void setGrsImportEnabled(final boolean grsImportEnabled); @Value("${grs.import.sources}") void setDefaultSources(final String defaultSources); @Override @Scheduled(cron = "0 0 0 * * *") @SchedulerLock(name = "GrsImporter") void run(); List<Future> grsImport(String sources, final boolean rebuild); } | GrsImporter implements DailyScheduledTask { @Override @Scheduled(cron = "0 0 0 * * *") @SchedulerLock(name = "GrsImporter") public void run() { if (!grsImportEnabled) { LOGGER.info("GRS import is not enabled"); return; } List<Future> futures = grsImport(defaultSources, false); for (Future future : futures) { try { future.get(); } catch (InterruptedException | ExecutionException e) { LOGGER.error(e.getMessage(), e); } } } @Autowired GrsImporter(final GrsSourceImporter grsSourceImporter, final GrsSource[] grsSources); @Value("${grs.import.enabled}") void setGrsImportEnabled(final boolean grsImportEnabled); @Value("${grs.import.sources}") void setDefaultSources(final String defaultSources); @Override @Scheduled(cron = "0 0 0 * * *") @SchedulerLock(name = "GrsImporter") void run(); List<Future> grsImport(String sources, final boolean rebuild); } |
@Test public void log_never_throws_exception() throws IOException, MessagingException { final MailMessageLogCallback subject = new MailMessageLogCallback(message); doThrow(MessagingException.class).when(message).writeTo(outputStream); subject.log(outputStream); verify(outputStream).write("".getBytes()); } | @Override public void log(final OutputStream outputStream) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { message.writeTo(baos); String messageData = new String( baos.toByteArray(), "UTF-8" ); String filtered = PasswordFilter.filterPasswordsInContents(messageData); outputStream.write(filtered.getBytes("UTF-8")); } catch (MessagingException e) { LOGGER.warn("Writing message", e); } } | MailMessageLogCallback implements LogCallback { @Override public void log(final OutputStream outputStream) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { message.writeTo(baos); String messageData = new String( baos.toByteArray(), "UTF-8" ); String filtered = PasswordFilter.filterPasswordsInContents(messageData); outputStream.write(filtered.getBytes("UTF-8")); } catch (MessagingException e) { LOGGER.warn("Writing message", e); } } } | MailMessageLogCallback implements LogCallback { @Override public void log(final OutputStream outputStream) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { message.writeTo(baos); String messageData = new String( baos.toByteArray(), "UTF-8" ); String filtered = PasswordFilter.filterPasswordsInContents(messageData); outputStream.write(filtered.getBytes("UTF-8")); } catch (MessagingException e) { LOGGER.warn("Writing message", e); } } MailMessageLogCallback(final Message message); } | MailMessageLogCallback implements LogCallback { @Override public void log(final OutputStream outputStream) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { message.writeTo(baos); String messageData = new String( baos.toByteArray(), "UTF-8" ); String filtered = PasswordFilter.filterPasswordsInContents(messageData); outputStream.write(filtered.getBytes("UTF-8")); } catch (MessagingException e) { LOGGER.warn("Writing message", e); } } MailMessageLogCallback(final Message message); @Override void log(final OutputStream outputStream); } | MailMessageLogCallback implements LogCallback { @Override public void log(final OutputStream outputStream) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { message.writeTo(baos); String messageData = new String( baos.toByteArray(), "UTF-8" ); String filtered = PasswordFilter.filterPasswordsInContents(messageData); outputStream.write(filtered.getBytes("UTF-8")); } catch (MessagingException e) { LOGGER.warn("Writing message", e); } } MailMessageLogCallback(final Message message); @Override void log(final OutputStream outputStream); } |
@Test public void sendResponse() throws Exception { subject.sendEmail("to", "subject", "test", ""); verify(mailSender, times(1)).send(any(MimeMessagePreparator.class)); } | @Override public void sendEmail(final String to, final ResponseMessage responseMessage) { sendEmail(to, responseMessage.getSubject(), responseMessage.getMessage(), responseMessage.getReplyTo()); } | MailGatewaySmtp implements MailGateway { @Override public void sendEmail(final String to, final ResponseMessage responseMessage) { sendEmail(to, responseMessage.getSubject(), responseMessage.getMessage(), responseMessage.getReplyTo()); } } | MailGatewaySmtp implements MailGateway { @Override public void sendEmail(final String to, final ResponseMessage responseMessage) { sendEmail(to, responseMessage.getSubject(), responseMessage.getMessage(), responseMessage.getReplyTo()); } @Autowired MailGatewaySmtp(final LoggerContext loggerContext, final MailConfiguration mailConfiguration, final JavaMailSender mailSender); } | MailGatewaySmtp implements MailGateway { @Override public void sendEmail(final String to, final ResponseMessage responseMessage) { sendEmail(to, responseMessage.getSubject(), responseMessage.getMessage(), responseMessage.getReplyTo()); } @Autowired MailGatewaySmtp(final LoggerContext loggerContext, final MailConfiguration mailConfiguration, final JavaMailSender mailSender); @Override void sendEmail(final String to, final ResponseMessage responseMessage); @Override void sendEmail(final String to, final String subject, final String text, @Nullable final String replyTo); } | MailGatewaySmtp implements MailGateway { @Override public void sendEmail(final String to, final ResponseMessage responseMessage) { sendEmail(to, responseMessage.getSubject(), responseMessage.getMessage(), responseMessage.getReplyTo()); } @Autowired MailGatewaySmtp(final LoggerContext loggerContext, final MailConfiguration mailConfiguration, final JavaMailSender mailSender); @Override void sendEmail(final String to, final ResponseMessage responseMessage); @Override void sendEmail(final String to, final String subject, final String text, @Nullable final String replyTo); } |
@Test public void sendResponse_disabled() throws Exception { ReflectionTestUtils.setField(subject, "outgoingMailEnabled", false); subject.sendEmail("to", "subject", "test", ""); verifyZeroInteractions(mailSender); } | @Override public void sendEmail(final String to, final ResponseMessage responseMessage) { sendEmail(to, responseMessage.getSubject(), responseMessage.getMessage(), responseMessage.getReplyTo()); } | MailGatewaySmtp implements MailGateway { @Override public void sendEmail(final String to, final ResponseMessage responseMessage) { sendEmail(to, responseMessage.getSubject(), responseMessage.getMessage(), responseMessage.getReplyTo()); } } | MailGatewaySmtp implements MailGateway { @Override public void sendEmail(final String to, final ResponseMessage responseMessage) { sendEmail(to, responseMessage.getSubject(), responseMessage.getMessage(), responseMessage.getReplyTo()); } @Autowired MailGatewaySmtp(final LoggerContext loggerContext, final MailConfiguration mailConfiguration, final JavaMailSender mailSender); } | MailGatewaySmtp implements MailGateway { @Override public void sendEmail(final String to, final ResponseMessage responseMessage) { sendEmail(to, responseMessage.getSubject(), responseMessage.getMessage(), responseMessage.getReplyTo()); } @Autowired MailGatewaySmtp(final LoggerContext loggerContext, final MailConfiguration mailConfiguration, final JavaMailSender mailSender); @Override void sendEmail(final String to, final ResponseMessage responseMessage); @Override void sendEmail(final String to, final String subject, final String text, @Nullable final String replyTo); } | MailGatewaySmtp implements MailGateway { @Override public void sendEmail(final String to, final ResponseMessage responseMessage) { sendEmail(to, responseMessage.getSubject(), responseMessage.getMessage(), responseMessage.getReplyTo()); } @Autowired MailGatewaySmtp(final LoggerContext loggerContext, final MailConfiguration mailConfiguration, final JavaMailSender mailSender); @Override void sendEmail(final String to, final ResponseMessage responseMessage); @Override void sendEmail(final String to, final String subject, final String text, @Nullable final String replyTo); } |
@Test public void send_invoked_only_once_on_permanent_negative_response() { Mockito.doAnswer(invocation -> { throw new SendFailedException("550 rejected: mail rejected for policy reasons"); }).when(mailSender).send(any(MimeMessagePreparator.class)); try { subject.sendEmail("to", "subject", "test", ""); fail(); } catch (Exception e) { assertThat(e, instanceOf(SendFailedException.class)); verify(mailSender, times(1)).send(any(MimeMessagePreparator.class)); } } | @Override public void sendEmail(final String to, final ResponseMessage responseMessage) { sendEmail(to, responseMessage.getSubject(), responseMessage.getMessage(), responseMessage.getReplyTo()); } | MailGatewaySmtp implements MailGateway { @Override public void sendEmail(final String to, final ResponseMessage responseMessage) { sendEmail(to, responseMessage.getSubject(), responseMessage.getMessage(), responseMessage.getReplyTo()); } } | MailGatewaySmtp implements MailGateway { @Override public void sendEmail(final String to, final ResponseMessage responseMessage) { sendEmail(to, responseMessage.getSubject(), responseMessage.getMessage(), responseMessage.getReplyTo()); } @Autowired MailGatewaySmtp(final LoggerContext loggerContext, final MailConfiguration mailConfiguration, final JavaMailSender mailSender); } | MailGatewaySmtp implements MailGateway { @Override public void sendEmail(final String to, final ResponseMessage responseMessage) { sendEmail(to, responseMessage.getSubject(), responseMessage.getMessage(), responseMessage.getReplyTo()); } @Autowired MailGatewaySmtp(final LoggerContext loggerContext, final MailConfiguration mailConfiguration, final JavaMailSender mailSender); @Override void sendEmail(final String to, final ResponseMessage responseMessage); @Override void sendEmail(final String to, final String subject, final String text, @Nullable final String replyTo); } | MailGatewaySmtp implements MailGateway { @Override public void sendEmail(final String to, final ResponseMessage responseMessage) { sendEmail(to, responseMessage.getSubject(), responseMessage.getMessage(), responseMessage.getReplyTo()); } @Autowired MailGatewaySmtp(final LoggerContext loggerContext, final MailConfiguration mailConfiguration, final JavaMailSender mailSender); @Override void sendEmail(final String to, final ResponseMessage responseMessage); @Override void sendEmail(final String to, final String subject, final String text, @Nullable final String replyTo); } |
@Test public void sendResponseAndCheckForReplyTo() throws Exception { final String replyToAddress = "[email protected]"; setExpectReplyToField(replyToAddress); subject.sendEmail("to", "subject", "test", replyToAddress); } | @Override public void sendEmail(final String to, final ResponseMessage responseMessage) { sendEmail(to, responseMessage.getSubject(), responseMessage.getMessage(), responseMessage.getReplyTo()); } | MailGatewaySmtp implements MailGateway { @Override public void sendEmail(final String to, final ResponseMessage responseMessage) { sendEmail(to, responseMessage.getSubject(), responseMessage.getMessage(), responseMessage.getReplyTo()); } } | MailGatewaySmtp implements MailGateway { @Override public void sendEmail(final String to, final ResponseMessage responseMessage) { sendEmail(to, responseMessage.getSubject(), responseMessage.getMessage(), responseMessage.getReplyTo()); } @Autowired MailGatewaySmtp(final LoggerContext loggerContext, final MailConfiguration mailConfiguration, final JavaMailSender mailSender); } | MailGatewaySmtp implements MailGateway { @Override public void sendEmail(final String to, final ResponseMessage responseMessage) { sendEmail(to, responseMessage.getSubject(), responseMessage.getMessage(), responseMessage.getReplyTo()); } @Autowired MailGatewaySmtp(final LoggerContext loggerContext, final MailConfiguration mailConfiguration, final JavaMailSender mailSender); @Override void sendEmail(final String to, final ResponseMessage responseMessage); @Override void sendEmail(final String to, final String subject, final String text, @Nullable final String replyTo); } | MailGatewaySmtp implements MailGateway { @Override public void sendEmail(final String to, final ResponseMessage responseMessage) { sendEmail(to, responseMessage.getSubject(), responseMessage.getMessage(), responseMessage.getReplyTo()); } @Autowired MailGatewaySmtp(final LoggerContext loggerContext, final MailConfiguration mailConfiguration, final JavaMailSender mailSender); @Override void sendEmail(final String to, final ResponseMessage responseMessage); @Override void sendEmail(final String to, final String subject, final String text, @Nullable final String replyTo); } |
@Test public void sendResponseAndCheckForEmptyReplyTo() throws Exception { final String replyToAddress = ""; setExpectReplyToField(replyToAddress); subject.sendEmail("to", "subject", "test", ""); } | @Override public void sendEmail(final String to, final ResponseMessage responseMessage) { sendEmail(to, responseMessage.getSubject(), responseMessage.getMessage(), responseMessage.getReplyTo()); } | MailGatewaySmtp implements MailGateway { @Override public void sendEmail(final String to, final ResponseMessage responseMessage) { sendEmail(to, responseMessage.getSubject(), responseMessage.getMessage(), responseMessage.getReplyTo()); } } | MailGatewaySmtp implements MailGateway { @Override public void sendEmail(final String to, final ResponseMessage responseMessage) { sendEmail(to, responseMessage.getSubject(), responseMessage.getMessage(), responseMessage.getReplyTo()); } @Autowired MailGatewaySmtp(final LoggerContext loggerContext, final MailConfiguration mailConfiguration, final JavaMailSender mailSender); } | MailGatewaySmtp implements MailGateway { @Override public void sendEmail(final String to, final ResponseMessage responseMessage) { sendEmail(to, responseMessage.getSubject(), responseMessage.getMessage(), responseMessage.getReplyTo()); } @Autowired MailGatewaySmtp(final LoggerContext loggerContext, final MailConfiguration mailConfiguration, final JavaMailSender mailSender); @Override void sendEmail(final String to, final ResponseMessage responseMessage); @Override void sendEmail(final String to, final String subject, final String text, @Nullable final String replyTo); } | MailGatewaySmtp implements MailGateway { @Override public void sendEmail(final String to, final ResponseMessage responseMessage) { sendEmail(to, responseMessage.getSubject(), responseMessage.getMessage(), responseMessage.getReplyTo()); } @Autowired MailGatewaySmtp(final LoggerContext loggerContext, final MailConfiguration mailConfiguration, final JavaMailSender mailSender); @Override void sendEmail(final String to, final ResponseMessage responseMessage); @Override void sendEmail(final String to, final String subject, final String text, @Nullable final String replyTo); } |
@Test public void testToString() { assertThat(OverrideCredential.parse("").toString(), is("OverrideCredential{NOT_VALID}")); assertThat(OverrideCredential.parse("user").toString(), is("OverrideCredential{NOT_VALID}")); assertThat(OverrideCredential.parse("user,password").toString(), is("OverrideCredential{user,FILTERED}")); assertThat(OverrideCredential.parse("user, password").toString(), is("OverrideCredential{user,FILTERED}")); assertThat(OverrideCredential.parse("user, password, remarks").toString(), is("OverrideCredential{user,FILTERED,remarks}")); assertThat(OverrideCredential.parse("user,password,remarks,more remarks").toString(), is("OverrideCredential{user,FILTERED,remarks,more remarks}")); } | @Override public String toString() { if (!overrideValues.isPresent()){ return "OverrideCredential{NOT_VALID}"; } if (StringUtils.isBlank(overrideValues.get().getRemarks())){ return String.format("OverrideCredential{%s,FILTERED}", overrideValues.get().getUsername()); } return String.format("OverrideCredential{%s,FILTERED,%s}", overrideValues.get().getUsername(), overrideValues.get().getRemarks()); } | OverrideCredential implements Credential { @Override public String toString() { if (!overrideValues.isPresent()){ return "OverrideCredential{NOT_VALID}"; } if (StringUtils.isBlank(overrideValues.get().getRemarks())){ return String.format("OverrideCredential{%s,FILTERED}", overrideValues.get().getUsername()); } return String.format("OverrideCredential{%s,FILTERED,%s}", overrideValues.get().getUsername(), overrideValues.get().getRemarks()); } } | OverrideCredential implements Credential { @Override public String toString() { if (!overrideValues.isPresent()){ return "OverrideCredential{NOT_VALID}"; } if (StringUtils.isBlank(overrideValues.get().getRemarks())){ return String.format("OverrideCredential{%s,FILTERED}", overrideValues.get().getUsername()); } return String.format("OverrideCredential{%s,FILTERED,%s}", overrideValues.get().getUsername(), overrideValues.get().getRemarks()); } private OverrideCredential(final String value, final Optional<OverrideValues> overrideValues); } | OverrideCredential implements Credential { @Override public String toString() { if (!overrideValues.isPresent()){ return "OverrideCredential{NOT_VALID}"; } if (StringUtils.isBlank(overrideValues.get().getRemarks())){ return String.format("OverrideCredential{%s,FILTERED}", overrideValues.get().getUsername()); } return String.format("OverrideCredential{%s,FILTERED,%s}", overrideValues.get().getUsername(), overrideValues.get().getRemarks()); } private OverrideCredential(final String value, final Optional<OverrideValues> overrideValues); Optional<OverrideValues> getOverrideValues(); @Override boolean equals(final Object o); @Override int hashCode(); @Override String toString(); static OverrideCredential parse(final String value); } | OverrideCredential implements Credential { @Override public String toString() { if (!overrideValues.isPresent()){ return "OverrideCredential{NOT_VALID}"; } if (StringUtils.isBlank(overrideValues.get().getRemarks())){ return String.format("OverrideCredential{%s,FILTERED}", overrideValues.get().getUsername()); } return String.format("OverrideCredential{%s,FILTERED,%s}", overrideValues.get().getUsername(), overrideValues.get().getRemarks()); } private OverrideCredential(final String value, final Optional<OverrideValues> overrideValues); Optional<OverrideValues> getOverrideValues(); @Override boolean equals(final Object o); @Override int hashCode(); @Override String toString(); static OverrideCredential parse(final String value); } |
@Test public void contains() { assertThat(subject.contains(ciString("AS100")), is(false)); assertThat(subject.contains(ciString("AS102")), is(true)); } | public boolean contains(final CIString autnum) { return cachedLegacyAutnums.contains(autnum); } | LegacyAutnum { public boolean contains(final CIString autnum) { return cachedLegacyAutnums.contains(autnum); } } | LegacyAutnum { public boolean contains(final CIString autnum) { return cachedLegacyAutnums.contains(autnum); } @Autowired LegacyAutnum(final LegacyAutnumDao legacyAutnumDao); } | LegacyAutnum { public boolean contains(final CIString autnum) { return cachedLegacyAutnums.contains(autnum); } @Autowired LegacyAutnum(final LegacyAutnumDao legacyAutnumDao); @PostConstruct synchronized void init(); boolean contains(final CIString autnum); int getTotal(); } | LegacyAutnum { public boolean contains(final CIString autnum) { return cachedLegacyAutnums.contains(autnum); } @Autowired LegacyAutnum(final LegacyAutnumDao legacyAutnumDao); @PostConstruct synchronized void init(); boolean contains(final CIString autnum); int getTotal(); } |
@Test public void string() { final OrganisationId subject = new OrganisationId("SAT", 1, "RIPE"); assertThat(subject.toString(), is("ORG-SAT1-RIPE")); } | @Override public String toString() { return new StringBuilder() .append("ORG-") .append(getSpace().toUpperCase()) .append(getIndex()) .append("-") .append(getSuffix()) .toString(); } | OrganisationId extends AutoKey { @Override public String toString() { return new StringBuilder() .append("ORG-") .append(getSpace().toUpperCase()) .append(getIndex()) .append("-") .append(getSuffix()) .toString(); } } | OrganisationId extends AutoKey { @Override public String toString() { return new StringBuilder() .append("ORG-") .append(getSpace().toUpperCase()) .append(getIndex()) .append("-") .append(getSuffix()) .toString(); } OrganisationId(final String space, final int index, final String suffix); } | OrganisationId extends AutoKey { @Override public String toString() { return new StringBuilder() .append("ORG-") .append(getSpace().toUpperCase()) .append(getIndex()) .append("-") .append(getSuffix()) .toString(); } OrganisationId(final String space, final int index, final String suffix); @Override String toString(); } | OrganisationId extends AutoKey { @Override public String toString() { return new StringBuilder() .append("ORG-") .append(getSpace().toUpperCase()) .append(getIndex()) .append("-") .append(getSuffix()) .toString(); } OrganisationId(final String space, final int index, final String suffix); @Override String toString(); } |
@Test public void parse_auto() { try { NicHandle.parse("AUTO-1", source, countryCodes); fail("AUTO- should not be supported as NIC-HDL"); } catch (NicHandleParseException e) { assertThat(e.getMessage(), is("Primary key generation request cannot be parsed as NIC-HDL: AUTO-1")); } } | public static NicHandle parse(final String nicHdl, final CIString source, final Set<CIString> countryCodes) { if (StringUtils.startsWithIgnoreCase(nicHdl, "AUTO-")) { throw new NicHandleParseException("Primary key generation request cannot be parsed as NIC-HDL: " + nicHdl); } final Matcher matcher = NIC_HDL_PATTERN.matcher(nicHdl.trim()); if (!matcher.matches()) { throw new NicHandleParseException("Invalid NIC-HDL: " + nicHdl); } final String characterSpace = matcher.group(1); final int index = getIndex(matcher.group(2)); final String suffix = getSuffix(matcher.group(3), source, countryCodes); return new NicHandle(characterSpace, index, suffix); } | NicHandle extends AutoKey { public static NicHandle parse(final String nicHdl, final CIString source, final Set<CIString> countryCodes) { if (StringUtils.startsWithIgnoreCase(nicHdl, "AUTO-")) { throw new NicHandleParseException("Primary key generation request cannot be parsed as NIC-HDL: " + nicHdl); } final Matcher matcher = NIC_HDL_PATTERN.matcher(nicHdl.trim()); if (!matcher.matches()) { throw new NicHandleParseException("Invalid NIC-HDL: " + nicHdl); } final String characterSpace = matcher.group(1); final int index = getIndex(matcher.group(2)); final String suffix = getSuffix(matcher.group(3), source, countryCodes); return new NicHandle(characterSpace, index, suffix); } } | NicHandle extends AutoKey { public static NicHandle parse(final String nicHdl, final CIString source, final Set<CIString> countryCodes) { if (StringUtils.startsWithIgnoreCase(nicHdl, "AUTO-")) { throw new NicHandleParseException("Primary key generation request cannot be parsed as NIC-HDL: " + nicHdl); } final Matcher matcher = NIC_HDL_PATTERN.matcher(nicHdl.trim()); if (!matcher.matches()) { throw new NicHandleParseException("Invalid NIC-HDL: " + nicHdl); } final String characterSpace = matcher.group(1); final int index = getIndex(matcher.group(2)); final String suffix = getSuffix(matcher.group(3), source, countryCodes); return new NicHandle(characterSpace, index, suffix); } NicHandle(final String space, final Integer index, final String suffix); } | NicHandle extends AutoKey { public static NicHandle parse(final String nicHdl, final CIString source, final Set<CIString> countryCodes) { if (StringUtils.startsWithIgnoreCase(nicHdl, "AUTO-")) { throw new NicHandleParseException("Primary key generation request cannot be parsed as NIC-HDL: " + nicHdl); } final Matcher matcher = NIC_HDL_PATTERN.matcher(nicHdl.trim()); if (!matcher.matches()) { throw new NicHandleParseException("Invalid NIC-HDL: " + nicHdl); } final String characterSpace = matcher.group(1); final int index = getIndex(matcher.group(2)); final String suffix = getSuffix(matcher.group(3), source, countryCodes); return new NicHandle(characterSpace, index, suffix); } NicHandle(final String space, final Integer index, final String suffix); static NicHandle parse(final String nicHdl, final CIString source, final Set<CIString> countryCodes); @Override String toString(); } | NicHandle extends AutoKey { public static NicHandle parse(final String nicHdl, final CIString source, final Set<CIString> countryCodes) { if (StringUtils.startsWithIgnoreCase(nicHdl, "AUTO-")) { throw new NicHandleParseException("Primary key generation request cannot be parsed as NIC-HDL: " + nicHdl); } final Matcher matcher = NIC_HDL_PATTERN.matcher(nicHdl.trim()); if (!matcher.matches()) { throw new NicHandleParseException("Invalid NIC-HDL: " + nicHdl); } final String characterSpace = matcher.group(1); final int index = getIndex(matcher.group(2)); final String suffix = getSuffix(matcher.group(3), source, countryCodes); return new NicHandle(characterSpace, index, suffix); } NicHandle(final String space, final Integer index, final String suffix); static NicHandle parse(final String nicHdl, final CIString source, final Set<CIString> countryCodes); @Override String toString(); } |
@Test(expected = NullPointerException.class) public void null_test() { final Iterable<Integer> subject = getSimpleIterable(1, null, 2, null); final Iterator<Integer> iterator = subject.iterator(); assertTrue(iterator.hasNext()); assertThat(iterator.next(), is(1)); assertTrue(iterator.hasNext()); assertNull(iterator.next()); assertTrue(iterator.hasNext()); assertThat(iterator.next(), is(2)); assertTrue(iterator.hasNext()); assertNull(iterator.next()); assertFalse(iterator.hasNext()); } | @Override public Iterator<T> iterator() { return new IteratorTransformer(head); } | IterableTransformer implements Iterable<T> { @Override public Iterator<T> iterator() { return new IteratorTransformer(head); } } | IterableTransformer implements Iterable<T> { @Override public Iterator<T> iterator() { return new IteratorTransformer(head); } IterableTransformer(final Iterable<? extends T> wrap); } | IterableTransformer implements Iterable<T> { @Override public Iterator<T> iterator() { return new IteratorTransformer(head); } IterableTransformer(final Iterable<? extends T> wrap); IterableTransformer<T> setHeader(T... header); IterableTransformer<T> setHeader(Collection<T> header); abstract void apply(final T input, final Deque<T> result); @Override Iterator<T> iterator(); } | IterableTransformer implements Iterable<T> { @Override public Iterator<T> iterator() { return new IteratorTransformer(head); } IterableTransformer(final Iterable<? extends T> wrap); IterableTransformer<T> setHeader(T... header); IterableTransformer<T> setHeader(Collection<T> header); abstract void apply(final T input, final Deque<T> result); @Override Iterator<T> iterator(); } |
@Test public void parse_auto_lowercase() { try { NicHandle.parse("auto-1", source, countryCodes); fail("AUTO- should not be supported as NIC-HDL"); } catch (NicHandleParseException e) { assertThat(e.getMessage(), is("Primary key generation request cannot be parsed as NIC-HDL: auto-1")); } } | public static NicHandle parse(final String nicHdl, final CIString source, final Set<CIString> countryCodes) { if (StringUtils.startsWithIgnoreCase(nicHdl, "AUTO-")) { throw new NicHandleParseException("Primary key generation request cannot be parsed as NIC-HDL: " + nicHdl); } final Matcher matcher = NIC_HDL_PATTERN.matcher(nicHdl.trim()); if (!matcher.matches()) { throw new NicHandleParseException("Invalid NIC-HDL: " + nicHdl); } final String characterSpace = matcher.group(1); final int index = getIndex(matcher.group(2)); final String suffix = getSuffix(matcher.group(3), source, countryCodes); return new NicHandle(characterSpace, index, suffix); } | NicHandle extends AutoKey { public static NicHandle parse(final String nicHdl, final CIString source, final Set<CIString> countryCodes) { if (StringUtils.startsWithIgnoreCase(nicHdl, "AUTO-")) { throw new NicHandleParseException("Primary key generation request cannot be parsed as NIC-HDL: " + nicHdl); } final Matcher matcher = NIC_HDL_PATTERN.matcher(nicHdl.trim()); if (!matcher.matches()) { throw new NicHandleParseException("Invalid NIC-HDL: " + nicHdl); } final String characterSpace = matcher.group(1); final int index = getIndex(matcher.group(2)); final String suffix = getSuffix(matcher.group(3), source, countryCodes); return new NicHandle(characterSpace, index, suffix); } } | NicHandle extends AutoKey { public static NicHandle parse(final String nicHdl, final CIString source, final Set<CIString> countryCodes) { if (StringUtils.startsWithIgnoreCase(nicHdl, "AUTO-")) { throw new NicHandleParseException("Primary key generation request cannot be parsed as NIC-HDL: " + nicHdl); } final Matcher matcher = NIC_HDL_PATTERN.matcher(nicHdl.trim()); if (!matcher.matches()) { throw new NicHandleParseException("Invalid NIC-HDL: " + nicHdl); } final String characterSpace = matcher.group(1); final int index = getIndex(matcher.group(2)); final String suffix = getSuffix(matcher.group(3), source, countryCodes); return new NicHandle(characterSpace, index, suffix); } NicHandle(final String space, final Integer index, final String suffix); } | NicHandle extends AutoKey { public static NicHandle parse(final String nicHdl, final CIString source, final Set<CIString> countryCodes) { if (StringUtils.startsWithIgnoreCase(nicHdl, "AUTO-")) { throw new NicHandleParseException("Primary key generation request cannot be parsed as NIC-HDL: " + nicHdl); } final Matcher matcher = NIC_HDL_PATTERN.matcher(nicHdl.trim()); if (!matcher.matches()) { throw new NicHandleParseException("Invalid NIC-HDL: " + nicHdl); } final String characterSpace = matcher.group(1); final int index = getIndex(matcher.group(2)); final String suffix = getSuffix(matcher.group(3), source, countryCodes); return new NicHandle(characterSpace, index, suffix); } NicHandle(final String space, final Integer index, final String suffix); static NicHandle parse(final String nicHdl, final CIString source, final Set<CIString> countryCodes); @Override String toString(); } | NicHandle extends AutoKey { public static NicHandle parse(final String nicHdl, final CIString source, final Set<CIString> countryCodes) { if (StringUtils.startsWithIgnoreCase(nicHdl, "AUTO-")) { throw new NicHandleParseException("Primary key generation request cannot be parsed as NIC-HDL: " + nicHdl); } final Matcher matcher = NIC_HDL_PATTERN.matcher(nicHdl.trim()); if (!matcher.matches()) { throw new NicHandleParseException("Invalid NIC-HDL: " + nicHdl); } final String characterSpace = matcher.group(1); final int index = getIndex(matcher.group(2)); final String suffix = getSuffix(matcher.group(3), source, countryCodes); return new NicHandle(characterSpace, index, suffix); } NicHandle(final String space, final Integer index, final String suffix); static NicHandle parse(final String nicHdl, final CIString source, final Set<CIString> countryCodes); @Override String toString(); } |
@Test public void parse_empty() { try { NicHandle.parse("", source, countryCodes); fail("Empty should not be supported as NIC-HDL"); } catch (NicHandleParseException e) { assertThat(e.getMessage(), is("Invalid NIC-HDL: ")); } } | public static NicHandle parse(final String nicHdl, final CIString source, final Set<CIString> countryCodes) { if (StringUtils.startsWithIgnoreCase(nicHdl, "AUTO-")) { throw new NicHandleParseException("Primary key generation request cannot be parsed as NIC-HDL: " + nicHdl); } final Matcher matcher = NIC_HDL_PATTERN.matcher(nicHdl.trim()); if (!matcher.matches()) { throw new NicHandleParseException("Invalid NIC-HDL: " + nicHdl); } final String characterSpace = matcher.group(1); final int index = getIndex(matcher.group(2)); final String suffix = getSuffix(matcher.group(3), source, countryCodes); return new NicHandle(characterSpace, index, suffix); } | NicHandle extends AutoKey { public static NicHandle parse(final String nicHdl, final CIString source, final Set<CIString> countryCodes) { if (StringUtils.startsWithIgnoreCase(nicHdl, "AUTO-")) { throw new NicHandleParseException("Primary key generation request cannot be parsed as NIC-HDL: " + nicHdl); } final Matcher matcher = NIC_HDL_PATTERN.matcher(nicHdl.trim()); if (!matcher.matches()) { throw new NicHandleParseException("Invalid NIC-HDL: " + nicHdl); } final String characterSpace = matcher.group(1); final int index = getIndex(matcher.group(2)); final String suffix = getSuffix(matcher.group(3), source, countryCodes); return new NicHandle(characterSpace, index, suffix); } } | NicHandle extends AutoKey { public static NicHandle parse(final String nicHdl, final CIString source, final Set<CIString> countryCodes) { if (StringUtils.startsWithIgnoreCase(nicHdl, "AUTO-")) { throw new NicHandleParseException("Primary key generation request cannot be parsed as NIC-HDL: " + nicHdl); } final Matcher matcher = NIC_HDL_PATTERN.matcher(nicHdl.trim()); if (!matcher.matches()) { throw new NicHandleParseException("Invalid NIC-HDL: " + nicHdl); } final String characterSpace = matcher.group(1); final int index = getIndex(matcher.group(2)); final String suffix = getSuffix(matcher.group(3), source, countryCodes); return new NicHandle(characterSpace, index, suffix); } NicHandle(final String space, final Integer index, final String suffix); } | NicHandle extends AutoKey { public static NicHandle parse(final String nicHdl, final CIString source, final Set<CIString> countryCodes) { if (StringUtils.startsWithIgnoreCase(nicHdl, "AUTO-")) { throw new NicHandleParseException("Primary key generation request cannot be parsed as NIC-HDL: " + nicHdl); } final Matcher matcher = NIC_HDL_PATTERN.matcher(nicHdl.trim()); if (!matcher.matches()) { throw new NicHandleParseException("Invalid NIC-HDL: " + nicHdl); } final String characterSpace = matcher.group(1); final int index = getIndex(matcher.group(2)); final String suffix = getSuffix(matcher.group(3), source, countryCodes); return new NicHandle(characterSpace, index, suffix); } NicHandle(final String space, final Integer index, final String suffix); static NicHandle parse(final String nicHdl, final CIString source, final Set<CIString> countryCodes); @Override String toString(); } | NicHandle extends AutoKey { public static NicHandle parse(final String nicHdl, final CIString source, final Set<CIString> countryCodes) { if (StringUtils.startsWithIgnoreCase(nicHdl, "AUTO-")) { throw new NicHandleParseException("Primary key generation request cannot be parsed as NIC-HDL: " + nicHdl); } final Matcher matcher = NIC_HDL_PATTERN.matcher(nicHdl.trim()); if (!matcher.matches()) { throw new NicHandleParseException("Invalid NIC-HDL: " + nicHdl); } final String characterSpace = matcher.group(1); final int index = getIndex(matcher.group(2)); final String suffix = getSuffix(matcher.group(3), source, countryCodes); return new NicHandle(characterSpace, index, suffix); } NicHandle(final String space, final Integer index, final String suffix); static NicHandle parse(final String nicHdl, final CIString source, final Set<CIString> countryCodes); @Override String toString(); } |
@Test(expected = NicHandleParseException.class) public void parse_space_too_long() { NicHandle.parse("SPACE", source, countryCodes); } | public static NicHandle parse(final String nicHdl, final CIString source, final Set<CIString> countryCodes) { if (StringUtils.startsWithIgnoreCase(nicHdl, "AUTO-")) { throw new NicHandleParseException("Primary key generation request cannot be parsed as NIC-HDL: " + nicHdl); } final Matcher matcher = NIC_HDL_PATTERN.matcher(nicHdl.trim()); if (!matcher.matches()) { throw new NicHandleParseException("Invalid NIC-HDL: " + nicHdl); } final String characterSpace = matcher.group(1); final int index = getIndex(matcher.group(2)); final String suffix = getSuffix(matcher.group(3), source, countryCodes); return new NicHandle(characterSpace, index, suffix); } | NicHandle extends AutoKey { public static NicHandle parse(final String nicHdl, final CIString source, final Set<CIString> countryCodes) { if (StringUtils.startsWithIgnoreCase(nicHdl, "AUTO-")) { throw new NicHandleParseException("Primary key generation request cannot be parsed as NIC-HDL: " + nicHdl); } final Matcher matcher = NIC_HDL_PATTERN.matcher(nicHdl.trim()); if (!matcher.matches()) { throw new NicHandleParseException("Invalid NIC-HDL: " + nicHdl); } final String characterSpace = matcher.group(1); final int index = getIndex(matcher.group(2)); final String suffix = getSuffix(matcher.group(3), source, countryCodes); return new NicHandle(characterSpace, index, suffix); } } | NicHandle extends AutoKey { public static NicHandle parse(final String nicHdl, final CIString source, final Set<CIString> countryCodes) { if (StringUtils.startsWithIgnoreCase(nicHdl, "AUTO-")) { throw new NicHandleParseException("Primary key generation request cannot be parsed as NIC-HDL: " + nicHdl); } final Matcher matcher = NIC_HDL_PATTERN.matcher(nicHdl.trim()); if (!matcher.matches()) { throw new NicHandleParseException("Invalid NIC-HDL: " + nicHdl); } final String characterSpace = matcher.group(1); final int index = getIndex(matcher.group(2)); final String suffix = getSuffix(matcher.group(3), source, countryCodes); return new NicHandle(characterSpace, index, suffix); } NicHandle(final String space, final Integer index, final String suffix); } | NicHandle extends AutoKey { public static NicHandle parse(final String nicHdl, final CIString source, final Set<CIString> countryCodes) { if (StringUtils.startsWithIgnoreCase(nicHdl, "AUTO-")) { throw new NicHandleParseException("Primary key generation request cannot be parsed as NIC-HDL: " + nicHdl); } final Matcher matcher = NIC_HDL_PATTERN.matcher(nicHdl.trim()); if (!matcher.matches()) { throw new NicHandleParseException("Invalid NIC-HDL: " + nicHdl); } final String characterSpace = matcher.group(1); final int index = getIndex(matcher.group(2)); final String suffix = getSuffix(matcher.group(3), source, countryCodes); return new NicHandle(characterSpace, index, suffix); } NicHandle(final String space, final Integer index, final String suffix); static NicHandle parse(final String nicHdl, final CIString source, final Set<CIString> countryCodes); @Override String toString(); } | NicHandle extends AutoKey { public static NicHandle parse(final String nicHdl, final CIString source, final Set<CIString> countryCodes) { if (StringUtils.startsWithIgnoreCase(nicHdl, "AUTO-")) { throw new NicHandleParseException("Primary key generation request cannot be parsed as NIC-HDL: " + nicHdl); } final Matcher matcher = NIC_HDL_PATTERN.matcher(nicHdl.trim()); if (!matcher.matches()) { throw new NicHandleParseException("Invalid NIC-HDL: " + nicHdl); } final String characterSpace = matcher.group(1); final int index = getIndex(matcher.group(2)); final String suffix = getSuffix(matcher.group(3), source, countryCodes); return new NicHandle(characterSpace, index, suffix); } NicHandle(final String space, final Integer index, final String suffix); static NicHandle parse(final String nicHdl, final CIString source, final Set<CIString> countryCodes); @Override String toString(); } |
@Test(expected = NicHandleParseException.class) public void parse_suffix_too_long() { NicHandle.parse("DW-VERYLONGSUFFIX", source, countryCodes); } | public static NicHandle parse(final String nicHdl, final CIString source, final Set<CIString> countryCodes) { if (StringUtils.startsWithIgnoreCase(nicHdl, "AUTO-")) { throw new NicHandleParseException("Primary key generation request cannot be parsed as NIC-HDL: " + nicHdl); } final Matcher matcher = NIC_HDL_PATTERN.matcher(nicHdl.trim()); if (!matcher.matches()) { throw new NicHandleParseException("Invalid NIC-HDL: " + nicHdl); } final String characterSpace = matcher.group(1); final int index = getIndex(matcher.group(2)); final String suffix = getSuffix(matcher.group(3), source, countryCodes); return new NicHandle(characterSpace, index, suffix); } | NicHandle extends AutoKey { public static NicHandle parse(final String nicHdl, final CIString source, final Set<CIString> countryCodes) { if (StringUtils.startsWithIgnoreCase(nicHdl, "AUTO-")) { throw new NicHandleParseException("Primary key generation request cannot be parsed as NIC-HDL: " + nicHdl); } final Matcher matcher = NIC_HDL_PATTERN.matcher(nicHdl.trim()); if (!matcher.matches()) { throw new NicHandleParseException("Invalid NIC-HDL: " + nicHdl); } final String characterSpace = matcher.group(1); final int index = getIndex(matcher.group(2)); final String suffix = getSuffix(matcher.group(3), source, countryCodes); return new NicHandle(characterSpace, index, suffix); } } | NicHandle extends AutoKey { public static NicHandle parse(final String nicHdl, final CIString source, final Set<CIString> countryCodes) { if (StringUtils.startsWithIgnoreCase(nicHdl, "AUTO-")) { throw new NicHandleParseException("Primary key generation request cannot be parsed as NIC-HDL: " + nicHdl); } final Matcher matcher = NIC_HDL_PATTERN.matcher(nicHdl.trim()); if (!matcher.matches()) { throw new NicHandleParseException("Invalid NIC-HDL: " + nicHdl); } final String characterSpace = matcher.group(1); final int index = getIndex(matcher.group(2)); final String suffix = getSuffix(matcher.group(3), source, countryCodes); return new NicHandle(characterSpace, index, suffix); } NicHandle(final String space, final Integer index, final String suffix); } | NicHandle extends AutoKey { public static NicHandle parse(final String nicHdl, final CIString source, final Set<CIString> countryCodes) { if (StringUtils.startsWithIgnoreCase(nicHdl, "AUTO-")) { throw new NicHandleParseException("Primary key generation request cannot be parsed as NIC-HDL: " + nicHdl); } final Matcher matcher = NIC_HDL_PATTERN.matcher(nicHdl.trim()); if (!matcher.matches()) { throw new NicHandleParseException("Invalid NIC-HDL: " + nicHdl); } final String characterSpace = matcher.group(1); final int index = getIndex(matcher.group(2)); final String suffix = getSuffix(matcher.group(3), source, countryCodes); return new NicHandle(characterSpace, index, suffix); } NicHandle(final String space, final Integer index, final String suffix); static NicHandle parse(final String nicHdl, final CIString source, final Set<CIString> countryCodes); @Override String toString(); } | NicHandle extends AutoKey { public static NicHandle parse(final String nicHdl, final CIString source, final Set<CIString> countryCodes) { if (StringUtils.startsWithIgnoreCase(nicHdl, "AUTO-")) { throw new NicHandleParseException("Primary key generation request cannot be parsed as NIC-HDL: " + nicHdl); } final Matcher matcher = NIC_HDL_PATTERN.matcher(nicHdl.trim()); if (!matcher.matches()) { throw new NicHandleParseException("Invalid NIC-HDL: " + nicHdl); } final String characterSpace = matcher.group(1); final int index = getIndex(matcher.group(2)); final String suffix = getSuffix(matcher.group(3), source, countryCodes); return new NicHandle(characterSpace, index, suffix); } NicHandle(final String space, final Integer index, final String suffix); static NicHandle parse(final String nicHdl, final CIString source, final Set<CIString> countryCodes); @Override String toString(); } |
@Test(expected = NicHandleParseException.class) public void parse_suffix_invalid() { NicHandle.parse("DW-SOMETHING", source, countryCodes); } | public static NicHandle parse(final String nicHdl, final CIString source, final Set<CIString> countryCodes) { if (StringUtils.startsWithIgnoreCase(nicHdl, "AUTO-")) { throw new NicHandleParseException("Primary key generation request cannot be parsed as NIC-HDL: " + nicHdl); } final Matcher matcher = NIC_HDL_PATTERN.matcher(nicHdl.trim()); if (!matcher.matches()) { throw new NicHandleParseException("Invalid NIC-HDL: " + nicHdl); } final String characterSpace = matcher.group(1); final int index = getIndex(matcher.group(2)); final String suffix = getSuffix(matcher.group(3), source, countryCodes); return new NicHandle(characterSpace, index, suffix); } | NicHandle extends AutoKey { public static NicHandle parse(final String nicHdl, final CIString source, final Set<CIString> countryCodes) { if (StringUtils.startsWithIgnoreCase(nicHdl, "AUTO-")) { throw new NicHandleParseException("Primary key generation request cannot be parsed as NIC-HDL: " + nicHdl); } final Matcher matcher = NIC_HDL_PATTERN.matcher(nicHdl.trim()); if (!matcher.matches()) { throw new NicHandleParseException("Invalid NIC-HDL: " + nicHdl); } final String characterSpace = matcher.group(1); final int index = getIndex(matcher.group(2)); final String suffix = getSuffix(matcher.group(3), source, countryCodes); return new NicHandle(characterSpace, index, suffix); } } | NicHandle extends AutoKey { public static NicHandle parse(final String nicHdl, final CIString source, final Set<CIString> countryCodes) { if (StringUtils.startsWithIgnoreCase(nicHdl, "AUTO-")) { throw new NicHandleParseException("Primary key generation request cannot be parsed as NIC-HDL: " + nicHdl); } final Matcher matcher = NIC_HDL_PATTERN.matcher(nicHdl.trim()); if (!matcher.matches()) { throw new NicHandleParseException("Invalid NIC-HDL: " + nicHdl); } final String characterSpace = matcher.group(1); final int index = getIndex(matcher.group(2)); final String suffix = getSuffix(matcher.group(3), source, countryCodes); return new NicHandle(characterSpace, index, suffix); } NicHandle(final String space, final Integer index, final String suffix); } | NicHandle extends AutoKey { public static NicHandle parse(final String nicHdl, final CIString source, final Set<CIString> countryCodes) { if (StringUtils.startsWithIgnoreCase(nicHdl, "AUTO-")) { throw new NicHandleParseException("Primary key generation request cannot be parsed as NIC-HDL: " + nicHdl); } final Matcher matcher = NIC_HDL_PATTERN.matcher(nicHdl.trim()); if (!matcher.matches()) { throw new NicHandleParseException("Invalid NIC-HDL: " + nicHdl); } final String characterSpace = matcher.group(1); final int index = getIndex(matcher.group(2)); final String suffix = getSuffix(matcher.group(3), source, countryCodes); return new NicHandle(characterSpace, index, suffix); } NicHandle(final String space, final Integer index, final String suffix); static NicHandle parse(final String nicHdl, final CIString source, final Set<CIString> countryCodes); @Override String toString(); } | NicHandle extends AutoKey { public static NicHandle parse(final String nicHdl, final CIString source, final Set<CIString> countryCodes) { if (StringUtils.startsWithIgnoreCase(nicHdl, "AUTO-")) { throw new NicHandleParseException("Primary key generation request cannot be parsed as NIC-HDL: " + nicHdl); } final Matcher matcher = NIC_HDL_PATTERN.matcher(nicHdl.trim()); if (!matcher.matches()) { throw new NicHandleParseException("Invalid NIC-HDL: " + nicHdl); } final String characterSpace = matcher.group(1); final int index = getIndex(matcher.group(2)); final String suffix = getSuffix(matcher.group(3), source, countryCodes); return new NicHandle(characterSpace, index, suffix); } NicHandle(final String space, final Integer index, final String suffix); static NicHandle parse(final String nicHdl, final CIString source, final Set<CIString> countryCodes); @Override String toString(); } |
@Test public void equal_null() { final NicHandle nicHandle = NicHandle.parse("DW", source, countryCodes); assertFalse(nicHandle.equals(null)); } | public static NicHandle parse(final String nicHdl, final CIString source, final Set<CIString> countryCodes) { if (StringUtils.startsWithIgnoreCase(nicHdl, "AUTO-")) { throw new NicHandleParseException("Primary key generation request cannot be parsed as NIC-HDL: " + nicHdl); } final Matcher matcher = NIC_HDL_PATTERN.matcher(nicHdl.trim()); if (!matcher.matches()) { throw new NicHandleParseException("Invalid NIC-HDL: " + nicHdl); } final String characterSpace = matcher.group(1); final int index = getIndex(matcher.group(2)); final String suffix = getSuffix(matcher.group(3), source, countryCodes); return new NicHandle(characterSpace, index, suffix); } | NicHandle extends AutoKey { public static NicHandle parse(final String nicHdl, final CIString source, final Set<CIString> countryCodes) { if (StringUtils.startsWithIgnoreCase(nicHdl, "AUTO-")) { throw new NicHandleParseException("Primary key generation request cannot be parsed as NIC-HDL: " + nicHdl); } final Matcher matcher = NIC_HDL_PATTERN.matcher(nicHdl.trim()); if (!matcher.matches()) { throw new NicHandleParseException("Invalid NIC-HDL: " + nicHdl); } final String characterSpace = matcher.group(1); final int index = getIndex(matcher.group(2)); final String suffix = getSuffix(matcher.group(3), source, countryCodes); return new NicHandle(characterSpace, index, suffix); } } | NicHandle extends AutoKey { public static NicHandle parse(final String nicHdl, final CIString source, final Set<CIString> countryCodes) { if (StringUtils.startsWithIgnoreCase(nicHdl, "AUTO-")) { throw new NicHandleParseException("Primary key generation request cannot be parsed as NIC-HDL: " + nicHdl); } final Matcher matcher = NIC_HDL_PATTERN.matcher(nicHdl.trim()); if (!matcher.matches()) { throw new NicHandleParseException("Invalid NIC-HDL: " + nicHdl); } final String characterSpace = matcher.group(1); final int index = getIndex(matcher.group(2)); final String suffix = getSuffix(matcher.group(3), source, countryCodes); return new NicHandle(characterSpace, index, suffix); } NicHandle(final String space, final Integer index, final String suffix); } | NicHandle extends AutoKey { public static NicHandle parse(final String nicHdl, final CIString source, final Set<CIString> countryCodes) { if (StringUtils.startsWithIgnoreCase(nicHdl, "AUTO-")) { throw new NicHandleParseException("Primary key generation request cannot be parsed as NIC-HDL: " + nicHdl); } final Matcher matcher = NIC_HDL_PATTERN.matcher(nicHdl.trim()); if (!matcher.matches()) { throw new NicHandleParseException("Invalid NIC-HDL: " + nicHdl); } final String characterSpace = matcher.group(1); final int index = getIndex(matcher.group(2)); final String suffix = getSuffix(matcher.group(3), source, countryCodes); return new NicHandle(characterSpace, index, suffix); } NicHandle(final String space, final Integer index, final String suffix); static NicHandle parse(final String nicHdl, final CIString source, final Set<CIString> countryCodes); @Override String toString(); } | NicHandle extends AutoKey { public static NicHandle parse(final String nicHdl, final CIString source, final Set<CIString> countryCodes) { if (StringUtils.startsWithIgnoreCase(nicHdl, "AUTO-")) { throw new NicHandleParseException("Primary key generation request cannot be parsed as NIC-HDL: " + nicHdl); } final Matcher matcher = NIC_HDL_PATTERN.matcher(nicHdl.trim()); if (!matcher.matches()) { throw new NicHandleParseException("Invalid NIC-HDL: " + nicHdl); } final String characterSpace = matcher.group(1); final int index = getIndex(matcher.group(2)); final String suffix = getSuffix(matcher.group(3), source, countryCodes); return new NicHandle(characterSpace, index, suffix); } NicHandle(final String space, final Integer index, final String suffix); static NicHandle parse(final String nicHdl, final CIString source, final Set<CIString> countryCodes); @Override String toString(); } |
@Test public void equal_otherClass() { final NicHandle nicHandle = NicHandle.parse("DW", source, countryCodes); assertFalse(nicHandle.equals("")); } | public static NicHandle parse(final String nicHdl, final CIString source, final Set<CIString> countryCodes) { if (StringUtils.startsWithIgnoreCase(nicHdl, "AUTO-")) { throw new NicHandleParseException("Primary key generation request cannot be parsed as NIC-HDL: " + nicHdl); } final Matcher matcher = NIC_HDL_PATTERN.matcher(nicHdl.trim()); if (!matcher.matches()) { throw new NicHandleParseException("Invalid NIC-HDL: " + nicHdl); } final String characterSpace = matcher.group(1); final int index = getIndex(matcher.group(2)); final String suffix = getSuffix(matcher.group(3), source, countryCodes); return new NicHandle(characterSpace, index, suffix); } | NicHandle extends AutoKey { public static NicHandle parse(final String nicHdl, final CIString source, final Set<CIString> countryCodes) { if (StringUtils.startsWithIgnoreCase(nicHdl, "AUTO-")) { throw new NicHandleParseException("Primary key generation request cannot be parsed as NIC-HDL: " + nicHdl); } final Matcher matcher = NIC_HDL_PATTERN.matcher(nicHdl.trim()); if (!matcher.matches()) { throw new NicHandleParseException("Invalid NIC-HDL: " + nicHdl); } final String characterSpace = matcher.group(1); final int index = getIndex(matcher.group(2)); final String suffix = getSuffix(matcher.group(3), source, countryCodes); return new NicHandle(characterSpace, index, suffix); } } | NicHandle extends AutoKey { public static NicHandle parse(final String nicHdl, final CIString source, final Set<CIString> countryCodes) { if (StringUtils.startsWithIgnoreCase(nicHdl, "AUTO-")) { throw new NicHandleParseException("Primary key generation request cannot be parsed as NIC-HDL: " + nicHdl); } final Matcher matcher = NIC_HDL_PATTERN.matcher(nicHdl.trim()); if (!matcher.matches()) { throw new NicHandleParseException("Invalid NIC-HDL: " + nicHdl); } final String characterSpace = matcher.group(1); final int index = getIndex(matcher.group(2)); final String suffix = getSuffix(matcher.group(3), source, countryCodes); return new NicHandle(characterSpace, index, suffix); } NicHandle(final String space, final Integer index, final String suffix); } | NicHandle extends AutoKey { public static NicHandle parse(final String nicHdl, final CIString source, final Set<CIString> countryCodes) { if (StringUtils.startsWithIgnoreCase(nicHdl, "AUTO-")) { throw new NicHandleParseException("Primary key generation request cannot be parsed as NIC-HDL: " + nicHdl); } final Matcher matcher = NIC_HDL_PATTERN.matcher(nicHdl.trim()); if (!matcher.matches()) { throw new NicHandleParseException("Invalid NIC-HDL: " + nicHdl); } final String characterSpace = matcher.group(1); final int index = getIndex(matcher.group(2)); final String suffix = getSuffix(matcher.group(3), source, countryCodes); return new NicHandle(characterSpace, index, suffix); } NicHandle(final String space, final Integer index, final String suffix); static NicHandle parse(final String nicHdl, final CIString source, final Set<CIString> countryCodes); @Override String toString(); } | NicHandle extends AutoKey { public static NicHandle parse(final String nicHdl, final CIString source, final Set<CIString> countryCodes) { if (StringUtils.startsWithIgnoreCase(nicHdl, "AUTO-")) { throw new NicHandleParseException("Primary key generation request cannot be parsed as NIC-HDL: " + nicHdl); } final Matcher matcher = NIC_HDL_PATTERN.matcher(nicHdl.trim()); if (!matcher.matches()) { throw new NicHandleParseException("Invalid NIC-HDL: " + nicHdl); } final String characterSpace = matcher.group(1); final int index = getIndex(matcher.group(2)); final String suffix = getSuffix(matcher.group(3), source, countryCodes); return new NicHandle(characterSpace, index, suffix); } NicHandle(final String space, final Integer index, final String suffix); static NicHandle parse(final String nicHdl, final CIString source, final Set<CIString> countryCodes); @Override String toString(); } |
@Test public void equal_self() { final NicHandle nicHandle = NicHandle.parse("DW", source, countryCodes); assertTrue(nicHandle.equals(nicHandle)); } | public static NicHandle parse(final String nicHdl, final CIString source, final Set<CIString> countryCodes) { if (StringUtils.startsWithIgnoreCase(nicHdl, "AUTO-")) { throw new NicHandleParseException("Primary key generation request cannot be parsed as NIC-HDL: " + nicHdl); } final Matcher matcher = NIC_HDL_PATTERN.matcher(nicHdl.trim()); if (!matcher.matches()) { throw new NicHandleParseException("Invalid NIC-HDL: " + nicHdl); } final String characterSpace = matcher.group(1); final int index = getIndex(matcher.group(2)); final String suffix = getSuffix(matcher.group(3), source, countryCodes); return new NicHandle(characterSpace, index, suffix); } | NicHandle extends AutoKey { public static NicHandle parse(final String nicHdl, final CIString source, final Set<CIString> countryCodes) { if (StringUtils.startsWithIgnoreCase(nicHdl, "AUTO-")) { throw new NicHandleParseException("Primary key generation request cannot be parsed as NIC-HDL: " + nicHdl); } final Matcher matcher = NIC_HDL_PATTERN.matcher(nicHdl.trim()); if (!matcher.matches()) { throw new NicHandleParseException("Invalid NIC-HDL: " + nicHdl); } final String characterSpace = matcher.group(1); final int index = getIndex(matcher.group(2)); final String suffix = getSuffix(matcher.group(3), source, countryCodes); return new NicHandle(characterSpace, index, suffix); } } | NicHandle extends AutoKey { public static NicHandle parse(final String nicHdl, final CIString source, final Set<CIString> countryCodes) { if (StringUtils.startsWithIgnoreCase(nicHdl, "AUTO-")) { throw new NicHandleParseException("Primary key generation request cannot be parsed as NIC-HDL: " + nicHdl); } final Matcher matcher = NIC_HDL_PATTERN.matcher(nicHdl.trim()); if (!matcher.matches()) { throw new NicHandleParseException("Invalid NIC-HDL: " + nicHdl); } final String characterSpace = matcher.group(1); final int index = getIndex(matcher.group(2)); final String suffix = getSuffix(matcher.group(3), source, countryCodes); return new NicHandle(characterSpace, index, suffix); } NicHandle(final String space, final Integer index, final String suffix); } | NicHandle extends AutoKey { public static NicHandle parse(final String nicHdl, final CIString source, final Set<CIString> countryCodes) { if (StringUtils.startsWithIgnoreCase(nicHdl, "AUTO-")) { throw new NicHandleParseException("Primary key generation request cannot be parsed as NIC-HDL: " + nicHdl); } final Matcher matcher = NIC_HDL_PATTERN.matcher(nicHdl.trim()); if (!matcher.matches()) { throw new NicHandleParseException("Invalid NIC-HDL: " + nicHdl); } final String characterSpace = matcher.group(1); final int index = getIndex(matcher.group(2)); final String suffix = getSuffix(matcher.group(3), source, countryCodes); return new NicHandle(characterSpace, index, suffix); } NicHandle(final String space, final Integer index, final String suffix); static NicHandle parse(final String nicHdl, final CIString source, final Set<CIString> countryCodes); @Override String toString(); } | NicHandle extends AutoKey { public static NicHandle parse(final String nicHdl, final CIString source, final Set<CIString> countryCodes) { if (StringUtils.startsWithIgnoreCase(nicHdl, "AUTO-")) { throw new NicHandleParseException("Primary key generation request cannot be parsed as NIC-HDL: " + nicHdl); } final Matcher matcher = NIC_HDL_PATTERN.matcher(nicHdl.trim()); if (!matcher.matches()) { throw new NicHandleParseException("Invalid NIC-HDL: " + nicHdl); } final String characterSpace = matcher.group(1); final int index = getIndex(matcher.group(2)); final String suffix = getSuffix(matcher.group(3), source, countryCodes); return new NicHandle(characterSpace, index, suffix); } NicHandle(final String space, final Integer index, final String suffix); static NicHandle parse(final String nicHdl, final CIString source, final Set<CIString> countryCodes); @Override String toString(); } |
@Test public void equal_same() { final NicHandle nicHandle = NicHandle.parse("DW", source, countryCodes); assertTrue(nicHandle.equals(NicHandle.parse("DW", source, countryCodes))); } | public static NicHandle parse(final String nicHdl, final CIString source, final Set<CIString> countryCodes) { if (StringUtils.startsWithIgnoreCase(nicHdl, "AUTO-")) { throw new NicHandleParseException("Primary key generation request cannot be parsed as NIC-HDL: " + nicHdl); } final Matcher matcher = NIC_HDL_PATTERN.matcher(nicHdl.trim()); if (!matcher.matches()) { throw new NicHandleParseException("Invalid NIC-HDL: " + nicHdl); } final String characterSpace = matcher.group(1); final int index = getIndex(matcher.group(2)); final String suffix = getSuffix(matcher.group(3), source, countryCodes); return new NicHandle(characterSpace, index, suffix); } | NicHandle extends AutoKey { public static NicHandle parse(final String nicHdl, final CIString source, final Set<CIString> countryCodes) { if (StringUtils.startsWithIgnoreCase(nicHdl, "AUTO-")) { throw new NicHandleParseException("Primary key generation request cannot be parsed as NIC-HDL: " + nicHdl); } final Matcher matcher = NIC_HDL_PATTERN.matcher(nicHdl.trim()); if (!matcher.matches()) { throw new NicHandleParseException("Invalid NIC-HDL: " + nicHdl); } final String characterSpace = matcher.group(1); final int index = getIndex(matcher.group(2)); final String suffix = getSuffix(matcher.group(3), source, countryCodes); return new NicHandle(characterSpace, index, suffix); } } | NicHandle extends AutoKey { public static NicHandle parse(final String nicHdl, final CIString source, final Set<CIString> countryCodes) { if (StringUtils.startsWithIgnoreCase(nicHdl, "AUTO-")) { throw new NicHandleParseException("Primary key generation request cannot be parsed as NIC-HDL: " + nicHdl); } final Matcher matcher = NIC_HDL_PATTERN.matcher(nicHdl.trim()); if (!matcher.matches()) { throw new NicHandleParseException("Invalid NIC-HDL: " + nicHdl); } final String characterSpace = matcher.group(1); final int index = getIndex(matcher.group(2)); final String suffix = getSuffix(matcher.group(3), source, countryCodes); return new NicHandle(characterSpace, index, suffix); } NicHandle(final String space, final Integer index, final String suffix); } | NicHandle extends AutoKey { public static NicHandle parse(final String nicHdl, final CIString source, final Set<CIString> countryCodes) { if (StringUtils.startsWithIgnoreCase(nicHdl, "AUTO-")) { throw new NicHandleParseException("Primary key generation request cannot be parsed as NIC-HDL: " + nicHdl); } final Matcher matcher = NIC_HDL_PATTERN.matcher(nicHdl.trim()); if (!matcher.matches()) { throw new NicHandleParseException("Invalid NIC-HDL: " + nicHdl); } final String characterSpace = matcher.group(1); final int index = getIndex(matcher.group(2)); final String suffix = getSuffix(matcher.group(3), source, countryCodes); return new NicHandle(characterSpace, index, suffix); } NicHandle(final String space, final Integer index, final String suffix); static NicHandle parse(final String nicHdl, final CIString source, final Set<CIString> countryCodes); @Override String toString(); } | NicHandle extends AutoKey { public static NicHandle parse(final String nicHdl, final CIString source, final Set<CIString> countryCodes) { if (StringUtils.startsWithIgnoreCase(nicHdl, "AUTO-")) { throw new NicHandleParseException("Primary key generation request cannot be parsed as NIC-HDL: " + nicHdl); } final Matcher matcher = NIC_HDL_PATTERN.matcher(nicHdl.trim()); if (!matcher.matches()) { throw new NicHandleParseException("Invalid NIC-HDL: " + nicHdl); } final String characterSpace = matcher.group(1); final int index = getIndex(matcher.group(2)); final String suffix = getSuffix(matcher.group(3), source, countryCodes); return new NicHandle(characterSpace, index, suffix); } NicHandle(final String space, final Integer index, final String suffix); static NicHandle parse(final String nicHdl, final CIString source, final Set<CIString> countryCodes); @Override String toString(); } |
@Test public void equal_different() { final NicHandle nicHandle = NicHandle.parse("DW", source, countryCodes); assertFalse(nicHandle.equals(NicHandle.parse("AB", source, countryCodes))); } | public static NicHandle parse(final String nicHdl, final CIString source, final Set<CIString> countryCodes) { if (StringUtils.startsWithIgnoreCase(nicHdl, "AUTO-")) { throw new NicHandleParseException("Primary key generation request cannot be parsed as NIC-HDL: " + nicHdl); } final Matcher matcher = NIC_HDL_PATTERN.matcher(nicHdl.trim()); if (!matcher.matches()) { throw new NicHandleParseException("Invalid NIC-HDL: " + nicHdl); } final String characterSpace = matcher.group(1); final int index = getIndex(matcher.group(2)); final String suffix = getSuffix(matcher.group(3), source, countryCodes); return new NicHandle(characterSpace, index, suffix); } | NicHandle extends AutoKey { public static NicHandle parse(final String nicHdl, final CIString source, final Set<CIString> countryCodes) { if (StringUtils.startsWithIgnoreCase(nicHdl, "AUTO-")) { throw new NicHandleParseException("Primary key generation request cannot be parsed as NIC-HDL: " + nicHdl); } final Matcher matcher = NIC_HDL_PATTERN.matcher(nicHdl.trim()); if (!matcher.matches()) { throw new NicHandleParseException("Invalid NIC-HDL: " + nicHdl); } final String characterSpace = matcher.group(1); final int index = getIndex(matcher.group(2)); final String suffix = getSuffix(matcher.group(3), source, countryCodes); return new NicHandle(characterSpace, index, suffix); } } | NicHandle extends AutoKey { public static NicHandle parse(final String nicHdl, final CIString source, final Set<CIString> countryCodes) { if (StringUtils.startsWithIgnoreCase(nicHdl, "AUTO-")) { throw new NicHandleParseException("Primary key generation request cannot be parsed as NIC-HDL: " + nicHdl); } final Matcher matcher = NIC_HDL_PATTERN.matcher(nicHdl.trim()); if (!matcher.matches()) { throw new NicHandleParseException("Invalid NIC-HDL: " + nicHdl); } final String characterSpace = matcher.group(1); final int index = getIndex(matcher.group(2)); final String suffix = getSuffix(matcher.group(3), source, countryCodes); return new NicHandle(characterSpace, index, suffix); } NicHandle(final String space, final Integer index, final String suffix); } | NicHandle extends AutoKey { public static NicHandle parse(final String nicHdl, final CIString source, final Set<CIString> countryCodes) { if (StringUtils.startsWithIgnoreCase(nicHdl, "AUTO-")) { throw new NicHandleParseException("Primary key generation request cannot be parsed as NIC-HDL: " + nicHdl); } final Matcher matcher = NIC_HDL_PATTERN.matcher(nicHdl.trim()); if (!matcher.matches()) { throw new NicHandleParseException("Invalid NIC-HDL: " + nicHdl); } final String characterSpace = matcher.group(1); final int index = getIndex(matcher.group(2)); final String suffix = getSuffix(matcher.group(3), source, countryCodes); return new NicHandle(characterSpace, index, suffix); } NicHandle(final String space, final Integer index, final String suffix); static NicHandle parse(final String nicHdl, final CIString source, final Set<CIString> countryCodes); @Override String toString(); } | NicHandle extends AutoKey { public static NicHandle parse(final String nicHdl, final CIString source, final Set<CIString> countryCodes) { if (StringUtils.startsWithIgnoreCase(nicHdl, "AUTO-")) { throw new NicHandleParseException("Primary key generation request cannot be parsed as NIC-HDL: " + nicHdl); } final Matcher matcher = NIC_HDL_PATTERN.matcher(nicHdl.trim()); if (!matcher.matches()) { throw new NicHandleParseException("Invalid NIC-HDL: " + nicHdl); } final String characterSpace = matcher.group(1); final int index = getIndex(matcher.group(2)); final String suffix = getSuffix(matcher.group(3), source, countryCodes); return new NicHandle(characterSpace, index, suffix); } NicHandle(final String space, final Integer index, final String suffix); static NicHandle parse(final String nicHdl, final CIString source, final Set<CIString> countryCodes); @Override String toString(); } |
@Test public void simple_test() { final Iterable<Integer> subject = getSimpleIterable(1,2,3); final Iterator<Integer> iterator = subject.iterator(); assertTrue(iterator.hasNext()); assertThat(iterator.next(), is(1)); assertTrue(iterator.hasNext()); assertThat(iterator.next(), is(2)); assertTrue(iterator.hasNext()); assertThat(iterator.next(), is(3)); assertFalse(iterator.hasNext()); } | @Override public Iterator<T> iterator() { return new IteratorTransformer(head); } | IterableTransformer implements Iterable<T> { @Override public Iterator<T> iterator() { return new IteratorTransformer(head); } } | IterableTransformer implements Iterable<T> { @Override public Iterator<T> iterator() { return new IteratorTransformer(head); } IterableTransformer(final Iterable<? extends T> wrap); } | IterableTransformer implements Iterable<T> { @Override public Iterator<T> iterator() { return new IteratorTransformer(head); } IterableTransformer(final Iterable<? extends T> wrap); IterableTransformer<T> setHeader(T... header); IterableTransformer<T> setHeader(Collection<T> header); abstract void apply(final T input, final Deque<T> result); @Override Iterator<T> iterator(); } | IterableTransformer implements Iterable<T> { @Override public Iterator<T> iterator() { return new IteratorTransformer(head); } IterableTransformer(final Iterable<? extends T> wrap); IterableTransformer<T> setHeader(T... header); IterableTransformer<T> setHeader(Collection<T> header); abstract void apply(final T input, final Deque<T> result); @Override Iterator<T> iterator(); } |
@Test public void hashCode_check() { NicHandle.parse("DW", source, countryCodes).hashCode(); } | public static NicHandle parse(final String nicHdl, final CIString source, final Set<CIString> countryCodes) { if (StringUtils.startsWithIgnoreCase(nicHdl, "AUTO-")) { throw new NicHandleParseException("Primary key generation request cannot be parsed as NIC-HDL: " + nicHdl); } final Matcher matcher = NIC_HDL_PATTERN.matcher(nicHdl.trim()); if (!matcher.matches()) { throw new NicHandleParseException("Invalid NIC-HDL: " + nicHdl); } final String characterSpace = matcher.group(1); final int index = getIndex(matcher.group(2)); final String suffix = getSuffix(matcher.group(3), source, countryCodes); return new NicHandle(characterSpace, index, suffix); } | NicHandle extends AutoKey { public static NicHandle parse(final String nicHdl, final CIString source, final Set<CIString> countryCodes) { if (StringUtils.startsWithIgnoreCase(nicHdl, "AUTO-")) { throw new NicHandleParseException("Primary key generation request cannot be parsed as NIC-HDL: " + nicHdl); } final Matcher matcher = NIC_HDL_PATTERN.matcher(nicHdl.trim()); if (!matcher.matches()) { throw new NicHandleParseException("Invalid NIC-HDL: " + nicHdl); } final String characterSpace = matcher.group(1); final int index = getIndex(matcher.group(2)); final String suffix = getSuffix(matcher.group(3), source, countryCodes); return new NicHandle(characterSpace, index, suffix); } } | NicHandle extends AutoKey { public static NicHandle parse(final String nicHdl, final CIString source, final Set<CIString> countryCodes) { if (StringUtils.startsWithIgnoreCase(nicHdl, "AUTO-")) { throw new NicHandleParseException("Primary key generation request cannot be parsed as NIC-HDL: " + nicHdl); } final Matcher matcher = NIC_HDL_PATTERN.matcher(nicHdl.trim()); if (!matcher.matches()) { throw new NicHandleParseException("Invalid NIC-HDL: " + nicHdl); } final String characterSpace = matcher.group(1); final int index = getIndex(matcher.group(2)); final String suffix = getSuffix(matcher.group(3), source, countryCodes); return new NicHandle(characterSpace, index, suffix); } NicHandle(final String space, final Integer index, final String suffix); } | NicHandle extends AutoKey { public static NicHandle parse(final String nicHdl, final CIString source, final Set<CIString> countryCodes) { if (StringUtils.startsWithIgnoreCase(nicHdl, "AUTO-")) { throw new NicHandleParseException("Primary key generation request cannot be parsed as NIC-HDL: " + nicHdl); } final Matcher matcher = NIC_HDL_PATTERN.matcher(nicHdl.trim()); if (!matcher.matches()) { throw new NicHandleParseException("Invalid NIC-HDL: " + nicHdl); } final String characterSpace = matcher.group(1); final int index = getIndex(matcher.group(2)); final String suffix = getSuffix(matcher.group(3), source, countryCodes); return new NicHandle(characterSpace, index, suffix); } NicHandle(final String space, final Integer index, final String suffix); static NicHandle parse(final String nicHdl, final CIString source, final Set<CIString> countryCodes); @Override String toString(); } | NicHandle extends AutoKey { public static NicHandle parse(final String nicHdl, final CIString source, final Set<CIString> countryCodes) { if (StringUtils.startsWithIgnoreCase(nicHdl, "AUTO-")) { throw new NicHandleParseException("Primary key generation request cannot be parsed as NIC-HDL: " + nicHdl); } final Matcher matcher = NIC_HDL_PATTERN.matcher(nicHdl.trim()); if (!matcher.matches()) { throw new NicHandleParseException("Invalid NIC-HDL: " + nicHdl); } final String characterSpace = matcher.group(1); final int index = getIndex(matcher.group(2)); final String suffix = getSuffix(matcher.group(3), source, countryCodes); return new NicHandle(characterSpace, index, suffix); } NicHandle(final String space, final Integer index, final String suffix); static NicHandle parse(final String nicHdl, final CIString source, final Set<CIString> countryCodes); @Override String toString(); } |
@Test public void no_warnings() { assertThat(subject.getGlobalMessages().getAllMessages(), hasSize(0)); } | public Messages getGlobalMessages() { return globalMessages; } | UpdateContext { public Messages getGlobalMessages() { return globalMessages; } } | UpdateContext { public Messages getGlobalMessages() { return globalMessages; } UpdateContext(final LoggerContext loggerContext); } | UpdateContext { public Messages getGlobalMessages() { return globalMessages; } UpdateContext(final LoggerContext loggerContext); boolean isDryRun(); void dryRun(); int getNrSinceRestart(); boolean isBatchUpdate(); void setBatchUpdate(); void addDnsCheckResponse(final DnsCheckRequest request, final DnsCheckResponse response); void addSsoTranslationResult(final String username, final String uuid); boolean hasSsoTranslationResult(String usernameOrUuid); @CheckForNull String getSsoTranslationResult(final String usernameOrUuid); @CheckForNull DnsCheckResponse getCachedDnsCheckResponse(final DnsCheckRequest dnsCheckRequest); void addMessage(final UpdateContainer updateContainer, final Message message); void addMessage(final UpdateContainer updateContainer, final RpslAttribute attribute, final Message message); ObjectMessages getMessages(final UpdateContainer updateContainer); void setAction(final UpdateContainer updateContainer, final Action action); Action getAction(final UpdateContainer updateContainer); void setOrigin(final UpdateContainer updateContainer, final Origin origin); Origin getOrigin(final UpdateContainer updateContainer); PreparedUpdate getPreparedUpdate(final UpdateContainer updateContainer); boolean hasErrors(final UpdateContainer updateContainer); int getErrorCount(final UpdateContainer updateContainer); void status(final UpdateContainer updateContainer, final UpdateStatus status); UpdateStatus getStatus(final UpdateContainer updateContainer); void subject(final UpdateContainer updateContainer, final Subject subject); Subject getSubject(final UpdateContainer updateContainer); void updateInfo(final UpdateContainer updateContainer, final RpslObjectUpdateInfo updateInfo); RpslObjectUpdateInfo getUpdateInfo(final UpdateContainer updateContainer); void versionId(final UpdateContainer updateContainer, final int versionId); int getVersionId(final UpdateContainer updateContainer); void setPreparedUpdate(final PreparedUpdate preparedUpdate); void ignore(final Paragraph paragraph); void addGlobalMessage(final Message message); Messages getGlobalMessages(); String printGlobalMessages(); void addGeneratedKey(final UpdateContainer updateContainer, final CIString keyPlaceholder, final GeneratedKey generatedKey); void failedUpdate(final UpdateContainer updateContainer, final Message... messages); @CheckForNull GeneratedKey getGeneratedKey(final CIString keyPlaceholder); Ack createAck(); UpdateResult createUpdateResult(final UpdateContainer updateContainer); void prepareForReattempt(final UpdateContainer update); void setUserSession(final UserSession userSession); UserSession getUserSession(); void setClientCertificate(final Optional<X509CertificateWrapper> clientCertificate); Optional<X509CertificateWrapper> getClientCertificate(); } | UpdateContext { public Messages getGlobalMessages() { return globalMessages; } UpdateContext(final LoggerContext loggerContext); boolean isDryRun(); void dryRun(); int getNrSinceRestart(); boolean isBatchUpdate(); void setBatchUpdate(); void addDnsCheckResponse(final DnsCheckRequest request, final DnsCheckResponse response); void addSsoTranslationResult(final String username, final String uuid); boolean hasSsoTranslationResult(String usernameOrUuid); @CheckForNull String getSsoTranslationResult(final String usernameOrUuid); @CheckForNull DnsCheckResponse getCachedDnsCheckResponse(final DnsCheckRequest dnsCheckRequest); void addMessage(final UpdateContainer updateContainer, final Message message); void addMessage(final UpdateContainer updateContainer, final RpslAttribute attribute, final Message message); ObjectMessages getMessages(final UpdateContainer updateContainer); void setAction(final UpdateContainer updateContainer, final Action action); Action getAction(final UpdateContainer updateContainer); void setOrigin(final UpdateContainer updateContainer, final Origin origin); Origin getOrigin(final UpdateContainer updateContainer); PreparedUpdate getPreparedUpdate(final UpdateContainer updateContainer); boolean hasErrors(final UpdateContainer updateContainer); int getErrorCount(final UpdateContainer updateContainer); void status(final UpdateContainer updateContainer, final UpdateStatus status); UpdateStatus getStatus(final UpdateContainer updateContainer); void subject(final UpdateContainer updateContainer, final Subject subject); Subject getSubject(final UpdateContainer updateContainer); void updateInfo(final UpdateContainer updateContainer, final RpslObjectUpdateInfo updateInfo); RpslObjectUpdateInfo getUpdateInfo(final UpdateContainer updateContainer); void versionId(final UpdateContainer updateContainer, final int versionId); int getVersionId(final UpdateContainer updateContainer); void setPreparedUpdate(final PreparedUpdate preparedUpdate); void ignore(final Paragraph paragraph); void addGlobalMessage(final Message message); Messages getGlobalMessages(); String printGlobalMessages(); void addGeneratedKey(final UpdateContainer updateContainer, final CIString keyPlaceholder, final GeneratedKey generatedKey); void failedUpdate(final UpdateContainer updateContainer, final Message... messages); @CheckForNull GeneratedKey getGeneratedKey(final CIString keyPlaceholder); Ack createAck(); UpdateResult createUpdateResult(final UpdateContainer updateContainer); void prepareForReattempt(final UpdateContainer update); void setUserSession(final UserSession userSession); UserSession getUserSession(); void setClientCertificate(final Optional<X509CertificateWrapper> clientCertificate); Optional<X509CertificateWrapper> getClientCertificate(); } |
@Test public void no_errors() { final RpslObject mntner = RpslObject.parse(MAINTAINER); final Update update = new Update(new Paragraph(MAINTAINER), Operation.DELETE, Lists.<String>newArrayList(), mntner); final PreparedUpdate preparedUpdate = new PreparedUpdate(update, null, mntner, Action.DELETE); assertThat(subject.hasErrors(preparedUpdate), is(false)); } | public boolean hasErrors(final UpdateContainer updateContainer) { return getOrCreateContext(updateContainer).objectMessages.hasErrors(); } | UpdateContext { public boolean hasErrors(final UpdateContainer updateContainer) { return getOrCreateContext(updateContainer).objectMessages.hasErrors(); } } | UpdateContext { public boolean hasErrors(final UpdateContainer updateContainer) { return getOrCreateContext(updateContainer).objectMessages.hasErrors(); } UpdateContext(final LoggerContext loggerContext); } | UpdateContext { public boolean hasErrors(final UpdateContainer updateContainer) { return getOrCreateContext(updateContainer).objectMessages.hasErrors(); } UpdateContext(final LoggerContext loggerContext); boolean isDryRun(); void dryRun(); int getNrSinceRestart(); boolean isBatchUpdate(); void setBatchUpdate(); void addDnsCheckResponse(final DnsCheckRequest request, final DnsCheckResponse response); void addSsoTranslationResult(final String username, final String uuid); boolean hasSsoTranslationResult(String usernameOrUuid); @CheckForNull String getSsoTranslationResult(final String usernameOrUuid); @CheckForNull DnsCheckResponse getCachedDnsCheckResponse(final DnsCheckRequest dnsCheckRequest); void addMessage(final UpdateContainer updateContainer, final Message message); void addMessage(final UpdateContainer updateContainer, final RpslAttribute attribute, final Message message); ObjectMessages getMessages(final UpdateContainer updateContainer); void setAction(final UpdateContainer updateContainer, final Action action); Action getAction(final UpdateContainer updateContainer); void setOrigin(final UpdateContainer updateContainer, final Origin origin); Origin getOrigin(final UpdateContainer updateContainer); PreparedUpdate getPreparedUpdate(final UpdateContainer updateContainer); boolean hasErrors(final UpdateContainer updateContainer); int getErrorCount(final UpdateContainer updateContainer); void status(final UpdateContainer updateContainer, final UpdateStatus status); UpdateStatus getStatus(final UpdateContainer updateContainer); void subject(final UpdateContainer updateContainer, final Subject subject); Subject getSubject(final UpdateContainer updateContainer); void updateInfo(final UpdateContainer updateContainer, final RpslObjectUpdateInfo updateInfo); RpslObjectUpdateInfo getUpdateInfo(final UpdateContainer updateContainer); void versionId(final UpdateContainer updateContainer, final int versionId); int getVersionId(final UpdateContainer updateContainer); void setPreparedUpdate(final PreparedUpdate preparedUpdate); void ignore(final Paragraph paragraph); void addGlobalMessage(final Message message); Messages getGlobalMessages(); String printGlobalMessages(); void addGeneratedKey(final UpdateContainer updateContainer, final CIString keyPlaceholder, final GeneratedKey generatedKey); void failedUpdate(final UpdateContainer updateContainer, final Message... messages); @CheckForNull GeneratedKey getGeneratedKey(final CIString keyPlaceholder); Ack createAck(); UpdateResult createUpdateResult(final UpdateContainer updateContainer); void prepareForReattempt(final UpdateContainer update); void setUserSession(final UserSession userSession); UserSession getUserSession(); void setClientCertificate(final Optional<X509CertificateWrapper> clientCertificate); Optional<X509CertificateWrapper> getClientCertificate(); } | UpdateContext { public boolean hasErrors(final UpdateContainer updateContainer) { return getOrCreateContext(updateContainer).objectMessages.hasErrors(); } UpdateContext(final LoggerContext loggerContext); boolean isDryRun(); void dryRun(); int getNrSinceRestart(); boolean isBatchUpdate(); void setBatchUpdate(); void addDnsCheckResponse(final DnsCheckRequest request, final DnsCheckResponse response); void addSsoTranslationResult(final String username, final String uuid); boolean hasSsoTranslationResult(String usernameOrUuid); @CheckForNull String getSsoTranslationResult(final String usernameOrUuid); @CheckForNull DnsCheckResponse getCachedDnsCheckResponse(final DnsCheckRequest dnsCheckRequest); void addMessage(final UpdateContainer updateContainer, final Message message); void addMessage(final UpdateContainer updateContainer, final RpslAttribute attribute, final Message message); ObjectMessages getMessages(final UpdateContainer updateContainer); void setAction(final UpdateContainer updateContainer, final Action action); Action getAction(final UpdateContainer updateContainer); void setOrigin(final UpdateContainer updateContainer, final Origin origin); Origin getOrigin(final UpdateContainer updateContainer); PreparedUpdate getPreparedUpdate(final UpdateContainer updateContainer); boolean hasErrors(final UpdateContainer updateContainer); int getErrorCount(final UpdateContainer updateContainer); void status(final UpdateContainer updateContainer, final UpdateStatus status); UpdateStatus getStatus(final UpdateContainer updateContainer); void subject(final UpdateContainer updateContainer, final Subject subject); Subject getSubject(final UpdateContainer updateContainer); void updateInfo(final UpdateContainer updateContainer, final RpslObjectUpdateInfo updateInfo); RpslObjectUpdateInfo getUpdateInfo(final UpdateContainer updateContainer); void versionId(final UpdateContainer updateContainer, final int versionId); int getVersionId(final UpdateContainer updateContainer); void setPreparedUpdate(final PreparedUpdate preparedUpdate); void ignore(final Paragraph paragraph); void addGlobalMessage(final Message message); Messages getGlobalMessages(); String printGlobalMessages(); void addGeneratedKey(final UpdateContainer updateContainer, final CIString keyPlaceholder, final GeneratedKey generatedKey); void failedUpdate(final UpdateContainer updateContainer, final Message... messages); @CheckForNull GeneratedKey getGeneratedKey(final CIString keyPlaceholder); Ack createAck(); UpdateResult createUpdateResult(final UpdateContainer updateContainer); void prepareForReattempt(final UpdateContainer update); void setUserSession(final UserSession userSession); UserSession getUserSession(); void setClientCertificate(final Optional<X509CertificateWrapper> clientCertificate); Optional<X509CertificateWrapper> getClientCertificate(); } |
@Test public void status() { final String content = "mntner: DEV-ROOT-MNT"; final RpslObject mntner = RpslObject.parse(content); final Update update = new Update(new Paragraph(content), Operation.DELETE, Lists.<String>newArrayList(), mntner); final PreparedUpdate preparedUpdate = new PreparedUpdate(update, null, mntner, Action.DELETE); subject.status(preparedUpdate, UpdateStatus.FAILED_AUTHENTICATION); assertThat(subject.getStatus(preparedUpdate), is(UpdateStatus.FAILED_AUTHENTICATION)); } | public void status(final UpdateContainer updateContainer, final UpdateStatus status) { getOrCreateContext(updateContainer).status = status; loggerContext.logStatus(updateContainer, status); } | UpdateContext { public void status(final UpdateContainer updateContainer, final UpdateStatus status) { getOrCreateContext(updateContainer).status = status; loggerContext.logStatus(updateContainer, status); } } | UpdateContext { public void status(final UpdateContainer updateContainer, final UpdateStatus status) { getOrCreateContext(updateContainer).status = status; loggerContext.logStatus(updateContainer, status); } UpdateContext(final LoggerContext loggerContext); } | UpdateContext { public void status(final UpdateContainer updateContainer, final UpdateStatus status) { getOrCreateContext(updateContainer).status = status; loggerContext.logStatus(updateContainer, status); } UpdateContext(final LoggerContext loggerContext); boolean isDryRun(); void dryRun(); int getNrSinceRestart(); boolean isBatchUpdate(); void setBatchUpdate(); void addDnsCheckResponse(final DnsCheckRequest request, final DnsCheckResponse response); void addSsoTranslationResult(final String username, final String uuid); boolean hasSsoTranslationResult(String usernameOrUuid); @CheckForNull String getSsoTranslationResult(final String usernameOrUuid); @CheckForNull DnsCheckResponse getCachedDnsCheckResponse(final DnsCheckRequest dnsCheckRequest); void addMessage(final UpdateContainer updateContainer, final Message message); void addMessage(final UpdateContainer updateContainer, final RpslAttribute attribute, final Message message); ObjectMessages getMessages(final UpdateContainer updateContainer); void setAction(final UpdateContainer updateContainer, final Action action); Action getAction(final UpdateContainer updateContainer); void setOrigin(final UpdateContainer updateContainer, final Origin origin); Origin getOrigin(final UpdateContainer updateContainer); PreparedUpdate getPreparedUpdate(final UpdateContainer updateContainer); boolean hasErrors(final UpdateContainer updateContainer); int getErrorCount(final UpdateContainer updateContainer); void status(final UpdateContainer updateContainer, final UpdateStatus status); UpdateStatus getStatus(final UpdateContainer updateContainer); void subject(final UpdateContainer updateContainer, final Subject subject); Subject getSubject(final UpdateContainer updateContainer); void updateInfo(final UpdateContainer updateContainer, final RpslObjectUpdateInfo updateInfo); RpslObjectUpdateInfo getUpdateInfo(final UpdateContainer updateContainer); void versionId(final UpdateContainer updateContainer, final int versionId); int getVersionId(final UpdateContainer updateContainer); void setPreparedUpdate(final PreparedUpdate preparedUpdate); void ignore(final Paragraph paragraph); void addGlobalMessage(final Message message); Messages getGlobalMessages(); String printGlobalMessages(); void addGeneratedKey(final UpdateContainer updateContainer, final CIString keyPlaceholder, final GeneratedKey generatedKey); void failedUpdate(final UpdateContainer updateContainer, final Message... messages); @CheckForNull GeneratedKey getGeneratedKey(final CIString keyPlaceholder); Ack createAck(); UpdateResult createUpdateResult(final UpdateContainer updateContainer); void prepareForReattempt(final UpdateContainer update); void setUserSession(final UserSession userSession); UserSession getUserSession(); void setClientCertificate(final Optional<X509CertificateWrapper> clientCertificate); Optional<X509CertificateWrapper> getClientCertificate(); } | UpdateContext { public void status(final UpdateContainer updateContainer, final UpdateStatus status) { getOrCreateContext(updateContainer).status = status; loggerContext.logStatus(updateContainer, status); } UpdateContext(final LoggerContext loggerContext); boolean isDryRun(); void dryRun(); int getNrSinceRestart(); boolean isBatchUpdate(); void setBatchUpdate(); void addDnsCheckResponse(final DnsCheckRequest request, final DnsCheckResponse response); void addSsoTranslationResult(final String username, final String uuid); boolean hasSsoTranslationResult(String usernameOrUuid); @CheckForNull String getSsoTranslationResult(final String usernameOrUuid); @CheckForNull DnsCheckResponse getCachedDnsCheckResponse(final DnsCheckRequest dnsCheckRequest); void addMessage(final UpdateContainer updateContainer, final Message message); void addMessage(final UpdateContainer updateContainer, final RpslAttribute attribute, final Message message); ObjectMessages getMessages(final UpdateContainer updateContainer); void setAction(final UpdateContainer updateContainer, final Action action); Action getAction(final UpdateContainer updateContainer); void setOrigin(final UpdateContainer updateContainer, final Origin origin); Origin getOrigin(final UpdateContainer updateContainer); PreparedUpdate getPreparedUpdate(final UpdateContainer updateContainer); boolean hasErrors(final UpdateContainer updateContainer); int getErrorCount(final UpdateContainer updateContainer); void status(final UpdateContainer updateContainer, final UpdateStatus status); UpdateStatus getStatus(final UpdateContainer updateContainer); void subject(final UpdateContainer updateContainer, final Subject subject); Subject getSubject(final UpdateContainer updateContainer); void updateInfo(final UpdateContainer updateContainer, final RpslObjectUpdateInfo updateInfo); RpslObjectUpdateInfo getUpdateInfo(final UpdateContainer updateContainer); void versionId(final UpdateContainer updateContainer, final int versionId); int getVersionId(final UpdateContainer updateContainer); void setPreparedUpdate(final PreparedUpdate preparedUpdate); void ignore(final Paragraph paragraph); void addGlobalMessage(final Message message); Messages getGlobalMessages(); String printGlobalMessages(); void addGeneratedKey(final UpdateContainer updateContainer, final CIString keyPlaceholder, final GeneratedKey generatedKey); void failedUpdate(final UpdateContainer updateContainer, final Message... messages); @CheckForNull GeneratedKey getGeneratedKey(final CIString keyPlaceholder); Ack createAck(); UpdateResult createUpdateResult(final UpdateContainer updateContainer); void prepareForReattempt(final UpdateContainer update); void setUserSession(final UserSession userSession); UserSession getUserSession(); void setClientCertificate(final Optional<X509CertificateWrapper> clientCertificate); Optional<X509CertificateWrapper> getClientCertificate(); } |
@Test public void createAck() { final RpslObject object = RpslObject.parse(MAINTAINER); final Update delete = new Update(new Paragraph(MAINTAINER), Operation.DELETE, Lists.<String>newArrayList(), object); subject.setAction(delete, Action.DELETE); final Update deleteWithError = new Update(new Paragraph(MAINTAINER), Operation.DELETE, Lists.<String>newArrayList(), object); subject.setAction(deleteWithError, Action.DELETE); subject.addMessage(deleteWithError, UpdateMessages.objectInUse(object)); subject.addMessage(deleteWithError, UpdateMessages.filteredNotAllowed()); subject.status(deleteWithError, UpdateStatus.FAILED); final Update update = new Update(new Paragraph(MAINTAINER), Operation.UNSPECIFIED, Lists.<String>newArrayList(), object); subject.setAction(update, Action.MODIFY); final Update updateWithError = new Update(new Paragraph(MAINTAINER), Operation.UNSPECIFIED, Lists.<String>newArrayList(), object); subject.setAction(updateWithError, Action.MODIFY); subject.addMessage(updateWithError, UpdateMessages.filteredNotAllowed()); subject.status(updateWithError, UpdateStatus.FAILED); final String updateMessage = "ignore"; final Paragraph paragraphIgnore = new Paragraph(updateMessage); subject.ignore(paragraphIgnore); final Ack ack = subject.createAck(); assertThat(ack.getNrFound(), is(4)); assertThat(ack.getNrProcessedsuccessfully(), is(2)); assertThat(ack.getNrDelete(), is(1)); assertThat(ack.getNrProcessedErrrors(), is(2)); assertThat(ack.getNrDeleteErrors(), is(1)); assertThat(ack.getIgnoredParagraphs(), contains(paragraphIgnore)); assertThat(ack.getUpdateStatus(), is(UpdateStatus.FAILED)); final List<UpdateResult> failedUpdates = ack.getFailedUpdates(); assertThat(failedUpdates, hasSize(2)); final Iterable<Message> errors = failedUpdates.get(0).getErrors(); assertThat(errors, contains(UpdateMessages.objectInUse(object), UpdateMessages.filteredNotAllowed())); } | public Ack createAck() { final List<UpdateResult> updateResults = Lists.newArrayList(); for (final Update update : contexts.keySet()) { updateResults.add(createUpdateResult(update)); } final List<Paragraph> ignoredParagraphs = getIgnoredParagraphs(); return new Ack(updateResults, ignoredParagraphs); } | UpdateContext { public Ack createAck() { final List<UpdateResult> updateResults = Lists.newArrayList(); for (final Update update : contexts.keySet()) { updateResults.add(createUpdateResult(update)); } final List<Paragraph> ignoredParagraphs = getIgnoredParagraphs(); return new Ack(updateResults, ignoredParagraphs); } } | UpdateContext { public Ack createAck() { final List<UpdateResult> updateResults = Lists.newArrayList(); for (final Update update : contexts.keySet()) { updateResults.add(createUpdateResult(update)); } final List<Paragraph> ignoredParagraphs = getIgnoredParagraphs(); return new Ack(updateResults, ignoredParagraphs); } UpdateContext(final LoggerContext loggerContext); } | UpdateContext { public Ack createAck() { final List<UpdateResult> updateResults = Lists.newArrayList(); for (final Update update : contexts.keySet()) { updateResults.add(createUpdateResult(update)); } final List<Paragraph> ignoredParagraphs = getIgnoredParagraphs(); return new Ack(updateResults, ignoredParagraphs); } UpdateContext(final LoggerContext loggerContext); boolean isDryRun(); void dryRun(); int getNrSinceRestart(); boolean isBatchUpdate(); void setBatchUpdate(); void addDnsCheckResponse(final DnsCheckRequest request, final DnsCheckResponse response); void addSsoTranslationResult(final String username, final String uuid); boolean hasSsoTranslationResult(String usernameOrUuid); @CheckForNull String getSsoTranslationResult(final String usernameOrUuid); @CheckForNull DnsCheckResponse getCachedDnsCheckResponse(final DnsCheckRequest dnsCheckRequest); void addMessage(final UpdateContainer updateContainer, final Message message); void addMessage(final UpdateContainer updateContainer, final RpslAttribute attribute, final Message message); ObjectMessages getMessages(final UpdateContainer updateContainer); void setAction(final UpdateContainer updateContainer, final Action action); Action getAction(final UpdateContainer updateContainer); void setOrigin(final UpdateContainer updateContainer, final Origin origin); Origin getOrigin(final UpdateContainer updateContainer); PreparedUpdate getPreparedUpdate(final UpdateContainer updateContainer); boolean hasErrors(final UpdateContainer updateContainer); int getErrorCount(final UpdateContainer updateContainer); void status(final UpdateContainer updateContainer, final UpdateStatus status); UpdateStatus getStatus(final UpdateContainer updateContainer); void subject(final UpdateContainer updateContainer, final Subject subject); Subject getSubject(final UpdateContainer updateContainer); void updateInfo(final UpdateContainer updateContainer, final RpslObjectUpdateInfo updateInfo); RpslObjectUpdateInfo getUpdateInfo(final UpdateContainer updateContainer); void versionId(final UpdateContainer updateContainer, final int versionId); int getVersionId(final UpdateContainer updateContainer); void setPreparedUpdate(final PreparedUpdate preparedUpdate); void ignore(final Paragraph paragraph); void addGlobalMessage(final Message message); Messages getGlobalMessages(); String printGlobalMessages(); void addGeneratedKey(final UpdateContainer updateContainer, final CIString keyPlaceholder, final GeneratedKey generatedKey); void failedUpdate(final UpdateContainer updateContainer, final Message... messages); @CheckForNull GeneratedKey getGeneratedKey(final CIString keyPlaceholder); Ack createAck(); UpdateResult createUpdateResult(final UpdateContainer updateContainer); void prepareForReattempt(final UpdateContainer update); void setUserSession(final UserSession userSession); UserSession getUserSession(); void setClientCertificate(final Optional<X509CertificateWrapper> clientCertificate); Optional<X509CertificateWrapper> getClientCertificate(); } | UpdateContext { public Ack createAck() { final List<UpdateResult> updateResults = Lists.newArrayList(); for (final Update update : contexts.keySet()) { updateResults.add(createUpdateResult(update)); } final List<Paragraph> ignoredParagraphs = getIgnoredParagraphs(); return new Ack(updateResults, ignoredParagraphs); } UpdateContext(final LoggerContext loggerContext); boolean isDryRun(); void dryRun(); int getNrSinceRestart(); boolean isBatchUpdate(); void setBatchUpdate(); void addDnsCheckResponse(final DnsCheckRequest request, final DnsCheckResponse response); void addSsoTranslationResult(final String username, final String uuid); boolean hasSsoTranslationResult(String usernameOrUuid); @CheckForNull String getSsoTranslationResult(final String usernameOrUuid); @CheckForNull DnsCheckResponse getCachedDnsCheckResponse(final DnsCheckRequest dnsCheckRequest); void addMessage(final UpdateContainer updateContainer, final Message message); void addMessage(final UpdateContainer updateContainer, final RpslAttribute attribute, final Message message); ObjectMessages getMessages(final UpdateContainer updateContainer); void setAction(final UpdateContainer updateContainer, final Action action); Action getAction(final UpdateContainer updateContainer); void setOrigin(final UpdateContainer updateContainer, final Origin origin); Origin getOrigin(final UpdateContainer updateContainer); PreparedUpdate getPreparedUpdate(final UpdateContainer updateContainer); boolean hasErrors(final UpdateContainer updateContainer); int getErrorCount(final UpdateContainer updateContainer); void status(final UpdateContainer updateContainer, final UpdateStatus status); UpdateStatus getStatus(final UpdateContainer updateContainer); void subject(final UpdateContainer updateContainer, final Subject subject); Subject getSubject(final UpdateContainer updateContainer); void updateInfo(final UpdateContainer updateContainer, final RpslObjectUpdateInfo updateInfo); RpslObjectUpdateInfo getUpdateInfo(final UpdateContainer updateContainer); void versionId(final UpdateContainer updateContainer, final int versionId); int getVersionId(final UpdateContainer updateContainer); void setPreparedUpdate(final PreparedUpdate preparedUpdate); void ignore(final Paragraph paragraph); void addGlobalMessage(final Message message); Messages getGlobalMessages(); String printGlobalMessages(); void addGeneratedKey(final UpdateContainer updateContainer, final CIString keyPlaceholder, final GeneratedKey generatedKey); void failedUpdate(final UpdateContainer updateContainer, final Message... messages); @CheckForNull GeneratedKey getGeneratedKey(final CIString keyPlaceholder); Ack createAck(); UpdateResult createUpdateResult(final UpdateContainer updateContainer); void prepareForReattempt(final UpdateContainer update); void setUserSession(final UserSession userSession); UserSession getUserSession(); void setClientCertificate(final Optional<X509CertificateWrapper> clientCertificate); Optional<X509CertificateWrapper> getClientCertificate(); } |
@Test(expected = UnsupportedOperationException.class) public void credentials_are_immutable() { final ContentWithCredentials subject = new ContentWithCredentials("test", Lists.newArrayList(credential)); subject.getCredentials().add(mock(Credential.class)); } | public List<Credential> getCredentials() { return credentials; } | ContentWithCredentials { public List<Credential> getCredentials() { return credentials; } } | ContentWithCredentials { public List<Credential> getCredentials() { return credentials; } ContentWithCredentials(final String content); ContentWithCredentials(final String content, final Charset charset); ContentWithCredentials(final String content, final List<Credential> credentials); ContentWithCredentials(final String content, final List<Credential> credentials, final Charset charset); } | ContentWithCredentials { public List<Credential> getCredentials() { return credentials; } ContentWithCredentials(final String content); ContentWithCredentials(final String content, final Charset charset); ContentWithCredentials(final String content, final List<Credential> credentials); ContentWithCredentials(final String content, final List<Credential> credentials, final Charset charset); String getContent(); List<Credential> getCredentials(); Charset getCharset(); } | ContentWithCredentials { public List<Credential> getCredentials() { return credentials; } ContentWithCredentials(final String content); ContentWithCredentials(final String content, final Charset charset); ContentWithCredentials(final String content, final List<Credential> credentials); ContentWithCredentials(final String content, final List<Credential> credentials, final Charset charset); String getContent(); List<Credential> getCredentials(); Charset getCharset(); } |
@Test public void getUpdate() { assertThat(subject.getUpdate(), is(update)); } | @Override public Update getUpdate() { return update; } | PreparedUpdate implements UpdateContainer { @Override public Update getUpdate() { return update; } } | PreparedUpdate implements UpdateContainer { @Override public Update getUpdate() { return update; } PreparedUpdate(final Update update, @Nullable final RpslObject originalObject, @Nullable final RpslObject updatedObject, final Action action); PreparedUpdate(final Update update, @Nullable final RpslObject originalObject, @Nullable final RpslObject updatedObject, final Action action, final OverrideOptions overrideOptions); } | PreparedUpdate implements UpdateContainer { @Override public Update getUpdate() { return update; } PreparedUpdate(final Update update, @Nullable final RpslObject originalObject, @Nullable final RpslObject updatedObject, final Action action); PreparedUpdate(final Update update, @Nullable final RpslObject originalObject, @Nullable final RpslObject updatedObject, final Action action, final OverrideOptions overrideOptions); @Override Update getUpdate(); Paragraph getParagraph(); boolean hasOriginalObject(); @Nullable RpslObject getReferenceObject(); @Nullable RpslObject getUpdatedObject(); RpslObject getSubmittedObject(); Action getAction(); Credentials getCredentials(); boolean isOverride(); OverrideOptions getOverrideOptions(); ObjectType getType(); String getKey(); String getFormattedKey(); Set<CIString> getNewValues(final AttributeType attributeType); Set<CIString> getDifferences(final AttributeType attributeType); @Override String toString(); } | PreparedUpdate implements UpdateContainer { @Override public Update getUpdate() { return update; } PreparedUpdate(final Update update, @Nullable final RpslObject originalObject, @Nullable final RpslObject updatedObject, final Action action); PreparedUpdate(final Update update, @Nullable final RpslObject originalObject, @Nullable final RpslObject updatedObject, final Action action, final OverrideOptions overrideOptions); @Override Update getUpdate(); Paragraph getParagraph(); boolean hasOriginalObject(); @Nullable RpslObject getReferenceObject(); @Nullable RpslObject getUpdatedObject(); RpslObject getSubmittedObject(); Action getAction(); Credentials getCredentials(); boolean isOverride(); OverrideOptions getOverrideOptions(); ObjectType getType(); String getKey(); String getFormattedKey(); Set<CIString> getNewValues(final AttributeType attributeType); Set<CIString> getDifferences(final AttributeType attributeType); @Override String toString(); } |
@Test public void getParagraph() { subject.getParagraph(); verify(update).getParagraph(); } | public Paragraph getParagraph() { return update.getParagraph(); } | PreparedUpdate implements UpdateContainer { public Paragraph getParagraph() { return update.getParagraph(); } } | PreparedUpdate implements UpdateContainer { public Paragraph getParagraph() { return update.getParagraph(); } PreparedUpdate(final Update update, @Nullable final RpslObject originalObject, @Nullable final RpslObject updatedObject, final Action action); PreparedUpdate(final Update update, @Nullable final RpslObject originalObject, @Nullable final RpslObject updatedObject, final Action action, final OverrideOptions overrideOptions); } | PreparedUpdate implements UpdateContainer { public Paragraph getParagraph() { return update.getParagraph(); } PreparedUpdate(final Update update, @Nullable final RpslObject originalObject, @Nullable final RpslObject updatedObject, final Action action); PreparedUpdate(final Update update, @Nullable final RpslObject originalObject, @Nullable final RpslObject updatedObject, final Action action, final OverrideOptions overrideOptions); @Override Update getUpdate(); Paragraph getParagraph(); boolean hasOriginalObject(); @Nullable RpslObject getReferenceObject(); @Nullable RpslObject getUpdatedObject(); RpslObject getSubmittedObject(); Action getAction(); Credentials getCredentials(); boolean isOverride(); OverrideOptions getOverrideOptions(); ObjectType getType(); String getKey(); String getFormattedKey(); Set<CIString> getNewValues(final AttributeType attributeType); Set<CIString> getDifferences(final AttributeType attributeType); @Override String toString(); } | PreparedUpdate implements UpdateContainer { public Paragraph getParagraph() { return update.getParagraph(); } PreparedUpdate(final Update update, @Nullable final RpslObject originalObject, @Nullable final RpslObject updatedObject, final Action action); PreparedUpdate(final Update update, @Nullable final RpslObject originalObject, @Nullable final RpslObject updatedObject, final Action action, final OverrideOptions overrideOptions); @Override Update getUpdate(); Paragraph getParagraph(); boolean hasOriginalObject(); @Nullable RpslObject getReferenceObject(); @Nullable RpslObject getUpdatedObject(); RpslObject getSubmittedObject(); Action getAction(); Credentials getCredentials(); boolean isOverride(); OverrideOptions getOverrideOptions(); ObjectType getType(); String getKey(); String getFormattedKey(); Set<CIString> getNewValues(final AttributeType attributeType); Set<CIString> getDifferences(final AttributeType attributeType); @Override String toString(); } |
@Test public void getOriginalObject() { assertThat(subject.getReferenceObject(), is(originalObject)); } | @Nullable public RpslObject getReferenceObject() { if (originalObject != null) { return originalObject; } return updatedObject; } | PreparedUpdate implements UpdateContainer { @Nullable public RpslObject getReferenceObject() { if (originalObject != null) { return originalObject; } return updatedObject; } } | PreparedUpdate implements UpdateContainer { @Nullable public RpslObject getReferenceObject() { if (originalObject != null) { return originalObject; } return updatedObject; } PreparedUpdate(final Update update, @Nullable final RpslObject originalObject, @Nullable final RpslObject updatedObject, final Action action); PreparedUpdate(final Update update, @Nullable final RpslObject originalObject, @Nullable final RpslObject updatedObject, final Action action, final OverrideOptions overrideOptions); } | PreparedUpdate implements UpdateContainer { @Nullable public RpslObject getReferenceObject() { if (originalObject != null) { return originalObject; } return updatedObject; } PreparedUpdate(final Update update, @Nullable final RpslObject originalObject, @Nullable final RpslObject updatedObject, final Action action); PreparedUpdate(final Update update, @Nullable final RpslObject originalObject, @Nullable final RpslObject updatedObject, final Action action, final OverrideOptions overrideOptions); @Override Update getUpdate(); Paragraph getParagraph(); boolean hasOriginalObject(); @Nullable RpslObject getReferenceObject(); @Nullable RpslObject getUpdatedObject(); RpslObject getSubmittedObject(); Action getAction(); Credentials getCredentials(); boolean isOverride(); OverrideOptions getOverrideOptions(); ObjectType getType(); String getKey(); String getFormattedKey(); Set<CIString> getNewValues(final AttributeType attributeType); Set<CIString> getDifferences(final AttributeType attributeType); @Override String toString(); } | PreparedUpdate implements UpdateContainer { @Nullable public RpslObject getReferenceObject() { if (originalObject != null) { return originalObject; } return updatedObject; } PreparedUpdate(final Update update, @Nullable final RpslObject originalObject, @Nullable final RpslObject updatedObject, final Action action); PreparedUpdate(final Update update, @Nullable final RpslObject originalObject, @Nullable final RpslObject updatedObject, final Action action, final OverrideOptions overrideOptions); @Override Update getUpdate(); Paragraph getParagraph(); boolean hasOriginalObject(); @Nullable RpslObject getReferenceObject(); @Nullable RpslObject getUpdatedObject(); RpslObject getSubmittedObject(); Action getAction(); Credentials getCredentials(); boolean isOverride(); OverrideOptions getOverrideOptions(); ObjectType getType(); String getKey(); String getFormattedKey(); Set<CIString> getNewValues(final AttributeType attributeType); Set<CIString> getDifferences(final AttributeType attributeType); @Override String toString(); } |
@Test public void getUpdatedObject() { assertThat(subject.getUpdatedObject(), is(updatedObject)); } | @Nullable public RpslObject getUpdatedObject() { return updatedObject; } | PreparedUpdate implements UpdateContainer { @Nullable public RpslObject getUpdatedObject() { return updatedObject; } } | PreparedUpdate implements UpdateContainer { @Nullable public RpslObject getUpdatedObject() { return updatedObject; } PreparedUpdate(final Update update, @Nullable final RpslObject originalObject, @Nullable final RpslObject updatedObject, final Action action); PreparedUpdate(final Update update, @Nullable final RpslObject originalObject, @Nullable final RpslObject updatedObject, final Action action, final OverrideOptions overrideOptions); } | PreparedUpdate implements UpdateContainer { @Nullable public RpslObject getUpdatedObject() { return updatedObject; } PreparedUpdate(final Update update, @Nullable final RpslObject originalObject, @Nullable final RpslObject updatedObject, final Action action); PreparedUpdate(final Update update, @Nullable final RpslObject originalObject, @Nullable final RpslObject updatedObject, final Action action, final OverrideOptions overrideOptions); @Override Update getUpdate(); Paragraph getParagraph(); boolean hasOriginalObject(); @Nullable RpslObject getReferenceObject(); @Nullable RpslObject getUpdatedObject(); RpslObject getSubmittedObject(); Action getAction(); Credentials getCredentials(); boolean isOverride(); OverrideOptions getOverrideOptions(); ObjectType getType(); String getKey(); String getFormattedKey(); Set<CIString> getNewValues(final AttributeType attributeType); Set<CIString> getDifferences(final AttributeType attributeType); @Override String toString(); } | PreparedUpdate implements UpdateContainer { @Nullable public RpslObject getUpdatedObject() { return updatedObject; } PreparedUpdate(final Update update, @Nullable final RpslObject originalObject, @Nullable final RpslObject updatedObject, final Action action); PreparedUpdate(final Update update, @Nullable final RpslObject originalObject, @Nullable final RpslObject updatedObject, final Action action, final OverrideOptions overrideOptions); @Override Update getUpdate(); Paragraph getParagraph(); boolean hasOriginalObject(); @Nullable RpslObject getReferenceObject(); @Nullable RpslObject getUpdatedObject(); RpslObject getSubmittedObject(); Action getAction(); Credentials getCredentials(); boolean isOverride(); OverrideOptions getOverrideOptions(); ObjectType getType(); String getKey(); String getFormattedKey(); Set<CIString> getNewValues(final AttributeType attributeType); Set<CIString> getDifferences(final AttributeType attributeType); @Override String toString(); } |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.