src_fm_fc_ms_ff
stringlengths 43
86.8k
| target
stringlengths 20
276k
|
---|---|
MessageDequeue implements ApplicationService { @Override public void start() { if (handlerExecutor != null || pollerExecutor != null) { throw new IllegalStateException("Already started"); } if (nrThreads > 0) { freeThreads.set(nrThreads); handlerExecutor = Executors.newFixedThreadPool(nrThreads); pollerExecutor = Executors.newSingleThreadScheduledExecutor(); pollerExecutor.scheduleWithFixedDelay(new MessagePoller(), intervalMs, intervalMs, TimeUnit.MILLISECONDS); LOGGER.info("Message dequeue started"); } } @Autowired MessageDequeue(final MaintenanceMode maintenanceMode,
final MailGateway mailGateway,
final MailMessageDao mailMessageDao,
final MessageFilter messageFilter,
final MessageParser messageParser,
final UpdatesParser updatesParser,
final UpdateRequestHandler messageHandler,
final LoggerContext loggerContext,
final DateTimeProvider dateTimeProvider); @Override void start(); @Override void stop(final boolean force); } | @Test(expected = IllegalStateException.class) public void start_twice() { when(mailMessageDao.claimMessage()).thenReturn(null); subject.start(); subject.start(); }
@Test public void noMessages() { when(mailMessageDao.claimMessage()).thenReturn(null); subject.start(); verifyZeroInteractions(messageHandler); }
@Test public void handleMessage_filtered() throws Exception { final MimeMessage message = MimeMessageProvider.getMessageSimpleTextUnsigned(); when(messageFilter.shouldProcess(any(MailMessage.class))).thenReturn(false); when(mailMessageDao.getMessage("1")).thenReturn(message); when(mailMessageDao.claimMessage()).thenReturn("1").thenReturn(null); subject.start(); verify(mailMessageDao, timeout(TIMEOUT)).deleteMessage("1"); verify(loggerContext, timeout(TIMEOUT)).init("20120527220444.GA6565"); verify(loggerContext, timeout(TIMEOUT)).log(eq("msg-in.txt"), any(MailMessageLogCallback.class)); verify(mailMessageDao, timeout(TIMEOUT)).setStatus("1", DequeueStatus.LOGGED); verify(mailMessageDao, timeout(TIMEOUT)).setStatus("1", DequeueStatus.PARSED); verifyZeroInteractions(messageHandler); }
@Test public void handleMessage_exception() throws Exception { final MimeMessage message = MimeMessageProvider.getMessageSimpleTextUnsigned(); when(messageFilter.shouldProcess(any(MailMessage.class))).thenReturn(true); when(messageParser.parse(eq(message), any(UpdateContext.class))).thenReturn( new MailMessage("", "", "", "", "", "", Keyword.NONE, Lists.<ContentWithCredentials>newArrayList())); when(updatesParser.parse(any(UpdateContext.class), anyListOf(ContentWithCredentials.class))).thenReturn(Lists.<Update>newArrayList()); when(messageHandler.handle(any(UpdateRequest.class), any(UpdateContext.class))).thenThrow(RuntimeException.class); when(mailMessageDao.getMessage("1")).thenReturn(message); when(mailMessageDao.claimMessage()).thenReturn("1").thenReturn(null); subject.start(); verify(mailMessageDao, timeout(TIMEOUT)).setStatus("1", DequeueStatus.LOGGED); verify(mailMessageDao, timeout(TIMEOUT)).setStatus("1", DequeueStatus.PARSED); verify(mailMessageDao, timeout(TIMEOUT)).setStatus("1", DequeueStatus.FAILED); verify(loggerContext, timeout(TIMEOUT)).init("20120527220444.GA6565"); verify(loggerContext, timeout(TIMEOUT)).log(eq("msg-in.txt"), any(MailMessageLogCallback.class)); verifyZeroInteractions(mailGateway); verify(mailMessageDao, never()).deleteMessage("1"); }
@Test public void handleMessage_invalidReplyTo() throws Exception { final MimeMessage message = new MimeMessage(null, new ByteArrayInputStream("Reply-To: <respondera: [email protected]>".getBytes())); when(messageFilter.shouldProcess(any(MailMessage.class))).thenReturn(false); when(messageParser.parse(eq(message), any(UpdateContext.class))).thenReturn( new MailMessage("", null, "", "", null, "", Keyword.NONE, Lists.<ContentWithCredentials>newArrayList())); when(mailMessageDao.getMessage("1")).thenReturn(message); when(mailMessageDao.claimMessage()).thenReturn("1").thenReturn(null); subject.start(); verify(mailMessageDao, timeout(TIMEOUT)).deleteMessage("1"); }
@Test public void malformed_from_header_is_detected() throws Exception { final MimeMessage message = new MimeMessage(null, new ByteArrayInputStream(("From: <\"[email protected]\">\n" + "Subject: blabla\n" + "To: [email protected]\n" + "\n" + "body\n").getBytes())); when(mailMessageDao.getMessage("1")).thenReturn(message); when(mailMessageDao.claimMessage()).thenReturn("1").thenReturn(null); when(messageParser.parse(eq(message), any(UpdateContext.class))).thenAnswer(new Answer<MailMessage>() { @Override public MailMessage answer(InvocationOnMock invocation) throws Throwable { final Object[] arguments = invocation.getArguments(); return new MessageParser(loggerContext).parse(((MimeMessage) arguments[0]), ((UpdateContext) arguments[1])); } }); when(messageFilter.shouldProcess(any(MailMessage.class))).thenAnswer(new Answer<Boolean>() { @Override public Boolean answer(InvocationOnMock invocation) throws Throwable { final Object[] arguments = invocation.getArguments(); return new MessageFilter(loggerContext).shouldProcess((MailMessage)arguments[0]); } }); subject.start(); verify(mailMessageDao, timeout(TIMEOUT)).deleteMessage("1"); verify(updatesParser, never()).parse(any(UpdateContext.class), anyList()); verify(messageHandler, never()).handle(any(UpdateRequest.class), any(UpdateContext.class)); verify(loggerContext).log(any(net.ripe.db.whois.common.Message.class)); } |
MessageDequeue implements ApplicationService { @Override public void stop(final boolean force) { LOGGER.info("Message dequeue stopping"); if (stopExecutor(pollerExecutor)) { pollerExecutor = null; } if (stopExecutor(handlerExecutor)) { handlerExecutor = null; } LOGGER.info("Message dequeue stopped"); } @Autowired MessageDequeue(final MaintenanceMode maintenanceMode,
final MailGateway mailGateway,
final MailMessageDao mailMessageDao,
final MessageFilter messageFilter,
final MessageParser messageParser,
final UpdatesParser updatesParser,
final UpdateRequestHandler messageHandler,
final LoggerContext loggerContext,
final DateTimeProvider dateTimeProvider); @Override void start(); @Override void stop(final boolean force); } | @Test public void stop_not_running() throws InterruptedException { subject.stop(true); } |
MessageDequeue implements ApplicationService { private void handleMessage(final String messageId) { final MimeMessage message = mailMessageDao.getMessage(messageId); try { loggerContext.init(getMessageIdLocalPart(message)); try { handleMessageInContext(messageId, message); } finally { loggerContext.remove(); } } catch (MessagingException e) { LOGGER.error("Handle message", e); } catch (IOException e) { LOGGER.error("Handle message", e); } } @Autowired MessageDequeue(final MaintenanceMode maintenanceMode,
final MailGateway mailGateway,
final MailMessageDao mailMessageDao,
final MessageFilter messageFilter,
final MessageParser messageParser,
final UpdatesParser updatesParser,
final UpdateRequestHandler messageHandler,
final LoggerContext loggerContext,
final DateTimeProvider dateTimeProvider); @Override void start(); @Override void stop(final boolean force); } | @Test public void handleMessage() throws Exception { final MimeMessage message = MimeMessageProvider.getMessageSimpleTextUnsigned(); when(messageFilter.shouldProcess(any(MailMessage.class))).thenReturn(true); when(messageParser.parse(eq(message), any(UpdateContext.class))).thenReturn( new MailMessage("", "", "", "", "", "", Keyword.NONE, Lists.<ContentWithCredentials>newArrayList())); when(updatesParser.parse(any(UpdateContext.class), anyListOf(ContentWithCredentials.class))).thenReturn(Lists.<Update>newArrayList()); when(messageHandler.handle(any(UpdateRequest.class), any(UpdateContext.class))).thenReturn(new UpdateResponse(UpdateStatus.SUCCESS, "")); when(mailMessageDao.getMessage("1")).thenReturn(message); when(mailMessageDao.claimMessage()).thenReturn("1").thenReturn(null); subject.start(); verify(mailMessageDao, timeout(TIMEOUT)).deleteMessage("1"); verify(loggerContext, timeout(TIMEOUT)).init("20120527220444.GA6565"); verify(loggerContext, timeout(TIMEOUT)).log(eq("msg-in.txt"), any(MailMessageLogCallback.class)); verify(mailMessageDao, timeout(TIMEOUT)).setStatus("1", DequeueStatus.LOGGED); verify(mailMessageDao, timeout(TIMEOUT)).setStatus("1", DequeueStatus.PARSED); verify(messageHandler, timeout(TIMEOUT)).handle(any(UpdateRequest.class), any(UpdateContext.class)); verify(mailGateway, timeout(TIMEOUT)).sendEmail(anyString(), anyString(), anyString(), any()); } |
MessageDequeue implements ApplicationService { String getMessageIdLocalPart(final Message message) throws MessagingException { final String[] headers = message.getHeader("Message-Id"); if (headers != null && headers.length > 0) { Matcher matcher = MESSAGE_ID_PATTERN.matcher(headers[0]); if (matcher.matches()) { return matcher.group(1); } LOGGER.debug("Unable to parse Message-Id: {}", headers[0]); } return "No-Message-Id." + dateTimeProvider.getElapsedTime(); } @Autowired MessageDequeue(final MaintenanceMode maintenanceMode,
final MailGateway mailGateway,
final MailMessageDao mailMessageDao,
final MessageFilter messageFilter,
final MessageParser messageParser,
final UpdatesParser updatesParser,
final UpdateRequestHandler messageHandler,
final LoggerContext loggerContext,
final DateTimeProvider dateTimeProvider); @Override void start(); @Override void stop(final boolean force); } | @Test public void getMessageIdLocalPart_local_and_domain_parts() throws Exception { Message message = mock(Message.class); when(message.getHeader("Message-Id")).thenReturn(new String[]{"<[email protected]>"}); final String messageIdLocalPart = subject.getMessageIdLocalPart(message); assertThat(messageIdLocalPart, is("20120527220444.GA6565")); }
@Test public void getMessageIdLocalPart_local_part_only() throws Exception { Message message = mock(Message.class); when(message.getHeader("Message-Id")).thenReturn(new String[]{"<20120527220444.GA6565>"}); final String messageIdLocalPart = subject.getMessageIdLocalPart(message); assertThat(messageIdLocalPart, is("20120527220444.GA6565")); }
@Test public void getMessageIdLocalPart_emptyMessageId() throws Exception { Message message = mock(Message.class); final String messageIdLocalPart = subject.getMessageIdLocalPart(message); assertThat(messageIdLocalPart, containsString("No-Message-Id.")); }
@Test public void getMessageIdLocalPart_messageId_doesnt_match() throws Exception { Message message = mock(Message.class); when(message.getHeader("Message-Id")).thenReturn(new String[]{"<W[20"}); final String messageIdLocalPart = subject.getMessageIdLocalPart(message); assertThat(messageIdLocalPart, containsString("No-Message-Id.")); } |
MessageParser { public MailMessage parse(final MimeMessage message, final UpdateContext updateContext) throws MessagingException { final MailMessageBuilder messageBuilder = new MailMessageBuilder(); messageBuilder.id(message.getMessageID()); parseSubject(messageBuilder, message, updateContext); String[] deliveryDate = message.getHeader("Delivery-date"); if (deliveryDate != null && deliveryDate.length > 0 && deliveryDate[0].length() > 0) { messageBuilder.date(deliveryDate[0]); } else { messageBuilder.date(DATE_FORMAT.format(ZonedDateTime.now())); } parseReplyTo(messageBuilder, message); try { parseContents(messageBuilder, message); final MailMessage mailMessage = messageBuilder.build(); if (!mailMessage.getKeyword().isContentExpected() || !mailMessage.getContentWithCredentials().isEmpty()) { return mailMessage; } } catch (ParseException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message"), e); } catch (MessagingException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Unable to parse message using java mail"), e); } catch (IOException e) { loggerContext.log(new Message(Messages.Type.ERROR, "Exception parsing message"), e); } catch (RuntimeException e) { LOGGER.error("Unexpected error parsing message: {}", message.getMessageID(), e); } updateContext.addGlobalMessage(UpdateMessages.noValidUpdateFound()); return messageBuilder.build(); } @Autowired MessageParser(final LoggerContext loggerContext); MailMessage parse(final MimeMessage message, final UpdateContext updateContext); } | @Test public void parseKeywords_validOnes() throws Exception { final Keyword[] validKeywords = new Keyword[]{Keyword.HELP, Keyword.HOWTO, Keyword.NEW, Keyword.NONE}; for (Keyword keyword : validKeywords) { final String keywordKeyword = keyword.getKeyword(); if (keywordKeyword == null) { continue; } when(mimeMessage.getSubject()).thenReturn(keywordKeyword); final MailMessage message = subject.parse(mimeMessage, updateContext); assertThat(keyword.toString(), message.getKeyword(), is(keyword)); verify(updateContext, never()).addGlobalMessage(any(Message.class)); } }
@Test public void parseKeywords_diff() throws Exception { final Keyword keyword = Keyword.DIFF; when(mimeMessage.getSubject()).thenReturn(keyword.getKeyword()); final MailMessage message = subject.parse(mimeMessage, updateContext); assertThat(keyword.toString(), message.getKeyword(), is(keyword)); verify(updateContext, times(1)).addGlobalMessage(UpdateMessages.diffNotSupported()); }
@Test public void parse_set_delivery_date() throws Exception { MimeMessage simpleTextUnsignedMessage = MimeMessageProvider.getMessageSimpleTextUnsigned(); final MailMessage result = subject.parse(simpleTextUnsignedMessage, updateContext); assertThat(result.getDate(), is("Mon, 28 May 2012 00:04:45 +0200")); }
@Test public void parse_set_default_date() throws Exception { when(mimeMessage.getSubject()).thenReturn("NEW"); final MailMessage message = subject.parse(mimeMessage, updateContext); assertThat(message.getDate().length(), not(is(0))); final String timezone = DateTimeFormatter.ofPattern("zzz").format(ZonedDateTime.now()); assertThat(message.getDate(), containsString(timezone)); final String year = DateTimeFormatter.ofPattern("yyyy").format(ZonedDateTime.now()); assertThat(message.getDate(), containsString(year)); }
@Test public void parseKeywords_mixedCaps() throws Exception { when(mimeMessage.getSubject()).thenReturn("nEw"); final MailMessage message = subject.parse(mimeMessage, updateContext); assertThat(message.getKeyword(), is(Keyword.NEW)); verify(updateContext, never()).addGlobalMessage(any(Message.class)); }
@Test public void parseSending_stringWithKeyword() throws Exception { final String keywordString = "sending my new objects"; when(mimeMessage.getSubject()).thenReturn(keywordString); final MailMessage message = subject.parse(mimeMessage, updateContext); assertThat(message.getKeyword(), is(Keyword.NONE)); verify(updateContext, times(1)).addGlobalMessage(UpdateMessages.invalidKeywordsFound(keywordString)); verify(updateContext, times(1)).addGlobalMessage(UpdateMessages.allKeywordsIgnored()); }
@Test public void parseKeywords_keyWords() throws Exception { final String keywordString = "KEYWORDS:"; when(mimeMessage.getSubject()).thenReturn(keywordString); final MailMessage message = subject.parse(mimeMessage, updateContext); assertThat(message.getKeyword(), is(Keyword.NONE)); verify(updateContext, times(1)).addGlobalMessage(UpdateMessages.invalidKeywordsFound(keywordString)); verify(updateContext, times(1)).addGlobalMessage(UpdateMessages.allKeywordsIgnored()); }
@Test public void parseKeywords_keyWordsAndNew() throws Exception { final String keywordString = "KEYWORDS: new"; when(mimeMessage.getSubject()).thenReturn(keywordString); final MailMessage message = subject.parse(mimeMessage, updateContext); assertThat(message.getKeyword(), is(Keyword.NONE)); verify(updateContext, times(1)).addGlobalMessage(UpdateMessages.invalidKeywordsFound(keywordString)); verify(updateContext, times(1)).addGlobalMessage(UpdateMessages.allKeywordsIgnored()); }
@Test public void parse_invalid_reply_to() throws Exception { MimeMessage messageWithInvalidReplyTo = new MimeMessage(null, new ByteArrayInputStream("Reply-To: <respondera: [email protected]>".getBytes())); MailMessage result = subject.parse(messageWithInvalidReplyTo, updateContext); assertThat(result.getReplyTo(), isEmptyString()); }
@Test public void parse_missing_reply_to() throws Exception { MimeMessage messageWithoutReplyTo = new MimeMessage(null, new ByteArrayInputStream("From: [email protected]".getBytes())); MailMessage result = subject.parse(messageWithoutReplyTo, updateContext); assertThat(result.getReplyTo(), is("[email protected]")); assertThat(result.getFrom(), is("[email protected]")); }
@Test public void parse_text_html_message() throws Exception { final MailMessage message = subject.parse(MimeMessageProvider.getUpdateMessage("simpleHtmlTextUnsigned.mail"), updateContext); assertThat(message.getId(), is("<[email protected]>")); assertThat(message.getReplyTo(), is("[email protected]")); assertThat(message.getKeyword(), is(Keyword.NONE)); assertThat(message.getContentWithCredentials(), hasSize(0)); }
@Test public void parse_signed_message_missing_crc_check() throws Exception { final MailMessage message = subject.parse( getMessage( "To: [email protected]\n" + "From: No Reply <[email protected]>\n" + "Date: Thu, 30 Mar 2017 09:00:00 +0100\n" + "MIME-Version: 1.0\n" + "Content-Type: text/plain; charset=windows-1252\n" + "Content-Transfer-Encoding: 7bit\n" + "\n" + "\n" + "-----BEGIN PGP SIGNED MESSAGE-----\n" + "Hash: SHA1\n" + "\n" + "aut-num: AS3333\n" + "remarks: +---------------------\n" + "----------------------+\n" + "mnt-by: TEST-MNT\n" + "source: TEST\n" + "\n" + "\n" + "-----BEGIN PGP SIGNATURE-----\n" + "Version: GnuPG v2\n" + " \n" + "iEYEARECAAYFAljcrkEACgkQYAnVsDBumXz9bwCfZQAm+4e7bbXztKzgwjGpjBQs\n" + "cYEAn3pN9uN9zhFrph7Co4tZ00aw/7TG\n" + "=NjUf\n" + "-----END PGP SIGNATURE-----\n" + "\n" + "\n" + "\n"), updateContext); assertThat(message.getContentWithCredentials(), hasSize(1)); final ContentWithCredentials contentWithCredentials = message.getContentWithCredentials().get(0); assertThat(contentWithCredentials.getCredentials(), hasSize(0)); } |
MessageParser { Charset getCharset(final ContentType contentType) { final String charset = contentType.getParameter("charset"); if (charset != null) { try { return Charset.forName(MimeUtility.javaCharset(charset)); } catch (UnsupportedCharsetException e) { loggerContext.log(new Message(Messages.Type.WARNING, "Unsupported charset: %s in contentType: %s", charset, contentType)); } catch (IllegalCharsetNameException e) { loggerContext.log(new Message(Messages.Type.WARNING, "Illegal charset: %s in contentType: %s", charset, contentType)); } } return StandardCharsets.ISO_8859_1; } @Autowired MessageParser(final LoggerContext loggerContext); MailMessage parse(final MimeMessage message, final UpdateContext updateContext); } | @Test public void illegal_charset() throws Exception { assertThat(subject.getCharset(new ContentType("text/plain;\n\tcharset=\"_iso-2022-jp$ESC\"")), is(StandardCharsets.ISO_8859_1)); } |
DnsCheckRequest { @Override public boolean equals(final Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; final DnsCheckRequest that = (DnsCheckRequest) o; return Objects.equals(domain, that.domain) && Objects.equals(glue, that.glue); } DnsCheckRequest(final Update update, final String domain, final String glue); Update getUpdate(); String getDomain(); String getGlue(); @Override boolean equals(final Object o); @Override int hashCode(); @Override String toString(); } | @Test public void equals_null() { assertThat(new DnsCheckRequest(update, "domain", "glue").equals(null), is(false)); }
@Test public void equals_other_class() { assertThat(new DnsCheckRequest(update, "domain", "glue").equals(""), is(false)); }
@Test public void equals_same_instance() { final DnsCheckRequest dnsCheckRequest = new DnsCheckRequest(update, "domain", "glue"); assertThat(dnsCheckRequest.equals(dnsCheckRequest), is(true)); }
@Test public void equals_not_equal_domain() { final DnsCheckRequest dnsCheckRequest1 = new DnsCheckRequest(update, "domain", "glue"); final DnsCheckRequest dnsCheckRequest2 = new DnsCheckRequest(update, "DOMAIN", "glue"); assertThat(dnsCheckRequest1.equals(dnsCheckRequest2), is(false)); }
@Test public void equals_not_equal_glue() { final DnsCheckRequest dnsCheckRequest1 = new DnsCheckRequest(update, "domain", "glue"); final DnsCheckRequest dnsCheckRequest2 = new DnsCheckRequest(update, "domain", "GLUE"); assertThat(dnsCheckRequest1.equals(dnsCheckRequest2), is(false)); } |
ZonemasterDnsGateway implements DnsGateway { @Override public Map<DnsCheckRequest, DnsCheckResponse> performDnsChecks(final Set<DnsCheckRequest> dnsCheckRequests) { return dnsCheckRequests .parallelStream() .collect(Collectors.toMap( dnsCheckRequest -> dnsCheckRequest, new ZonemasterFunction())); } ZonemasterDnsGateway(final ZonemasterRestClient zonemasterRestClient); @Override Map<DnsCheckRequest, DnsCheckResponse> performDnsChecks(final Set<DnsCheckRequest> dnsCheckRequests); } | @Test public void single_record_with_error_message() { mock(RpslObject.parse("domain: 22.0.193.in-addr.arpa")); when(startDomainTestResponse.getResult()).thenReturn("1"); when(testProgressResponse.getResult()).thenReturn("50").thenReturn("100"); when(result.getResults()).thenReturn(Lists.newArrayList(message)); when(message.getMessage()).thenReturn("check failed"); when(message.getLevel()).thenReturn("ERROR"); final Map<DnsCheckRequest, DnsCheckResponse> response = subject.performDnsChecks( Sets.newHashSet(new DnsCheckRequest(update, "1.ripe.net", null)) ); assertThat(response.size(), is(1)); assertThat(response.values(), hasSize(1)); final List<Message> messages = response.values().iterator().next().getMessages(); assertThat(messages, contains(new Message(Messages.Type.ERROR, "check failed"))); }
@Test public void odd_number_of_domain_objects_above_threshold() { mock(RpslObject.parse("domain: 22.0.193.in-addr.arpa")); when(startDomainTestResponse.getResult()).thenReturn("1"); when(testProgressResponse.getResult()).thenReturn("100"); final Map<DnsCheckRequest, DnsCheckResponse> response = subject.performDnsChecks(Sets.newHashSet( new DnsCheckRequest(update, "1.ripe.net", null), new DnsCheckRequest(update, "2.ripe.net", null), new DnsCheckRequest(update, "3.ripe.net", null), new DnsCheckRequest(update, "4.ripe.net", null), new DnsCheckRequest(update, "5.ripe.net", null), new DnsCheckRequest(update, "6.ripe.net", null), new DnsCheckRequest(update, "7.ripe.net", null), new DnsCheckRequest(update, "8.ripe.net", null), new DnsCheckRequest(update, "9.ripe.net", null), new DnsCheckRequest(update, "10.ripe.net", null), new DnsCheckRequest(update, "11.ripe.net", null) )); assertThat(response.values(), hasSize(11)); }
@Test public void even_number_of_domain_objects_above_threshold() { mock(RpslObject.parse("domain: 22.0.193.in-addr.arpa")); when(startDomainTestResponse.getResult()).thenReturn("1"); when(testProgressResponse.getResult()).thenReturn("100"); final Map<DnsCheckRequest, DnsCheckResponse> response = subject.performDnsChecks(Sets.newHashSet( new DnsCheckRequest(update, "1.ripe.net", null), new DnsCheckRequest(update, "2.ripe.net", null), new DnsCheckRequest(update, "3.ripe.net", null), new DnsCheckRequest(update, "4.ripe.net", null), new DnsCheckRequest(update, "5.ripe.net", null), new DnsCheckRequest(update, "6.ripe.net", null), new DnsCheckRequest(update, "7.ripe.net", null), new DnsCheckRequest(update, "8.ripe.net", null), new DnsCheckRequest(update, "9.ripe.net", null), new DnsCheckRequest(update, "10.ripe.net", null), new DnsCheckRequest(update, "11.ripe.net", null), new DnsCheckRequest(update, "12.ripe.net", null) )); assertThat(response.values(), hasSize(12)); } |
DnsChecker { public void checkAll(final UpdateRequest updateRequest, final UpdateContext updateContext) { if (!dnsCheckEnabled) { return; } Set<DnsCheckRequest> dnsCheckRequestSet = Sets.newLinkedHashSet(); for (Update update : updateRequest.getUpdates()) { if (isDnsCheckRequired(update)) { dnsCheckRequestSet.add(createDnsCheckRequest(update)); } } if (dnsCheckRequestSet.isEmpty()) { return; } final Stopwatch stopwatch = Stopwatch.createStarted(); final Map<DnsCheckRequest, DnsCheckResponse> dnsCheckResponseMap = dnsGateway.performDnsChecks(dnsCheckRequestSet); loggerContext.log(new Message(Messages.Type.INFO, "Called dnsGateway with %d requests and processed in %s", dnsCheckRequestSet.size(), stopwatch.stop().toString())); for (Map.Entry<DnsCheckRequest, DnsCheckResponse> entry : dnsCheckResponseMap.entrySet()) { final DnsCheckRequest dnsCheckRequest = entry.getKey(); final DnsCheckResponse dnsCheckResponse = entry.getValue(); updateContext.addDnsCheckResponse(dnsCheckRequest, dnsCheckResponse); for (final Message message : dnsCheckResponse.getMessages()) { updateContext.addMessage(dnsCheckRequest.getUpdate(), message); } } } @Autowired DnsChecker(final DnsGateway dnsGateway,
final LoggerContext loggerContext,
@Value("${whois.zonemaster.baseUrl:}") final String baseUrl); void checkAll(final UpdateRequest updateRequest, final UpdateContext updateContext); } | @Test public void check_delete() { when(update.getOperation()).thenReturn(Operation.DELETE); subject.checkAll(updateRequest, updateContext); verifyZeroInteractions(dnsGateway); }
@Test public void check_not_domain() { when(update.getType()).thenReturn(ObjectType.INETNUM); subject.checkAll(updateRequest, updateContext); verifyZeroInteractions(dnsGateway); }
@Test public void check_override() { when(update.isOverride()).thenReturn(true); subject.checkAll(updateRequest, updateContext); verifyZeroInteractions(dnsGateway); }
@Test public void checkAll() { when(update.getOperation()).thenReturn(Operation.UNSPECIFIED); when(update.getType()).thenReturn(ObjectType.DOMAIN); when(update.isOverride()).thenReturn(false); when(update.getSubmittedObject()).thenReturn(RpslObject.parse("" + "domain: 36.84.80.in-addr.arpa\n" + "descr: Description\n" + "descr: Description\n" + "admin-c: DUMY-RIPE\n" + "tech-c: DUMY-RIPE\n" + "zone-c: DUMY-RIPE\n" + "notify: [email protected]\n" + "nserver: ns1.test.se 80.84.32.12\n" + "nserver: ns2.test.se 80.84.32.10\n" + "source: RIPE\n" + "mnt-by: TEST-MNT" )); List<Update> updateList = Lists.newArrayList(); Set<DnsCheckRequest> dnsCheckRequests = Sets.newLinkedHashSet(); Map<DnsCheckRequest, DnsCheckResponse> dnsResults = Maps.newHashMap(); DnsCheckRequest dnsCheckRequest = new DnsCheckRequest(update, "36.84.80.in-addr.arpa", "ns1.test.se/80.84.32.12 ns2.test.se/80.84.32.10"); dnsCheckRequests.add(dnsCheckRequest); DnsCheckResponse dnsCheckResponse = new DnsCheckResponse(); updateList.add(update); dnsResults.put(dnsCheckRequest, dnsCheckResponse); when(updateRequest.getUpdates()).thenReturn(updateList); when(updateContext.getCachedDnsCheckResponse(any(DnsCheckRequest.class))).thenReturn(null); when(dnsGateway.performDnsChecks(dnsCheckRequests)).thenReturn(dnsResults); subject.checkAll(updateRequest, updateContext); verify(dnsGateway).performDnsChecks(dnsCheckRequests); assertThat(dnsCheckRequest.getDomain(), is("36.84.80.in-addr.arpa")); assertThat(dnsCheckRequest.getGlue(), is("ns1.test.se/80.84.32.12 ns2.test.se/80.84.32.10")); verify(updateContext, never()).addMessage(any(UpdateContainer.class), any(Message.class)); }
@Test public void check_errors() { when(update.getOperation()).thenReturn(Operation.UNSPECIFIED); when(update.getType()).thenReturn(ObjectType.DOMAIN); when(update.isOverride()).thenReturn(false); when(update.getSubmittedObject()).thenReturn(RpslObject.parse("" + "domain: 36.84.80.in-addr.arpa\n" )); when(dnsGateway.performDnsChecks(any(Set.class))).thenAnswer((Answer<Map<DnsCheckRequest, DnsCheckResponse>>) invocation -> { DnsCheckRequest arg = (DnsCheckRequest)(((Set)invocation.getArguments()[0]).iterator().next()); return Collections.singletonMap(arg, new DnsCheckResponse(UpdateMessages.dnsCheckTimeout())); }); subject.checkAll(updateRequest, updateContext); verify(updateContext).addMessage(update, UpdateMessages.dnsCheckTimeout()); }
@Test public void check_disabled() { subject = new DnsChecker(dnsGateway, loggerContext, ""); when(update.getOperation()).thenReturn(Operation.UNSPECIFIED); when(update.getType()).thenReturn(ObjectType.DOMAIN); when(update.isOverride()).thenReturn(false); when(update.getSubmittedObject()).thenReturn(RpslObject.parse("" + "domain: 36.84.80.in-addr.arpa\n" )); subject.checkAll(updateRequest, updateContext); verifyZeroInteractions(dnsGateway); } |
AutnumAuthentication extends AuthenticationStrategyBase { @Override public boolean supports(final PreparedUpdate update) { return update.getType().equals(ObjectType.AUT_NUM) && update.getAction().equals(Action.CREATE); } @Autowired AutnumAuthentication(final RpslObjectDao objectDao, final AuthenticationModule authenticationModule); @Override boolean supports(final PreparedUpdate update); @Override List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext); } | @Test public void supports_autnum_create() { when(update.getAction()).thenReturn(Action.CREATE); when(update.getType()).thenReturn(ObjectType.AUT_NUM); final boolean supported = subject.supports(update); assertThat(supported, is(true)); }
@Test public void supports_other_than_autnum_create() { for (final ObjectType objectType : ObjectType.values()) { if (ObjectType.AUT_NUM.equals(objectType)) { continue; } when(update.getAction()).thenReturn(Action.CREATE); when(update.getType()).thenReturn(ObjectType.AS_BLOCK); final boolean supported = subject.supports(update); assertThat(supported, is(false)); reset(update); } }
@Test public void supports_autnum_modify() { when(update.getAction()).thenReturn(Action.MODIFY); when(update.getType()).thenReturn(ObjectType.AUT_NUM); final boolean supported = subject.supports(update); assertThat(supported, is(false)); }
@Test public void supports_autnum_delete() { when(update.getAction()).thenReturn(Action.DELETE); when(update.getType()).thenReturn(ObjectType.AUT_NUM); final boolean supported = subject.supports(update); assertThat(supported, is(false)); } |
AutnumAuthentication extends AuthenticationStrategyBase { @Override public List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext) { final RpslObject object = update.getUpdatedObject(); final CIString pkey = object.getKey(); final long number = Long.parseLong(pkey.toString().substring("AS".length())); final RpslObject asBlock = objectDao.findAsBlock(number, number); if (asBlock == null) { throw new AuthenticationFailedException(UpdateMessages.noParentAsBlockFound(pkey), Collections.<RpslObject>emptyList()); } AttributeType attributeType = AttributeType.MNT_LOWER; Collection<CIString> parentMnts = asBlock.getValuesForAttribute(attributeType); if (parentMnts.isEmpty()) { attributeType = AttributeType.MNT_BY; parentMnts = asBlock.getValuesForAttribute(attributeType); } final List<RpslObject> maintainers = objectDao.getByKeys(ObjectType.MNTNER, parentMnts); final List<RpslObject> authenticatedBy = authenticationModule.authenticate(update, updateContext, maintainers); if (authenticatedBy.isEmpty()) { throw new AuthenticationFailedException(UpdateMessages.authenticationFailed(asBlock, attributeType, maintainers), maintainers); } return authenticatedBy; } @Autowired AutnumAuthentication(final RpslObjectDao objectDao, final AuthenticationModule authenticationModule); @Override boolean supports(final PreparedUpdate update); @Override List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext); } | @Test public void authenticated_by_mntlower_succeeds() { when(update.getUpdatedObject()).thenReturn(RpslObject.parse("aut-num: AS3333")); when(objectDao.findAsBlock(3333, 3333)).thenReturn(RpslObject.parse("as-block: AS3209 - AS3353\nmnt-lower: LOW-MNT")); final ArrayList<RpslObject> parentMaintainers = Lists.newArrayList(RpslObject.parse("mntner: LOW-MNT")); when(objectDao.getByKeys(eq(ObjectType.MNTNER), anyCollection())).thenReturn(parentMaintainers); when(authenticationModule.authenticate(update, updateContext, parentMaintainers)).thenReturn(parentMaintainers); final List<RpslObject> authenticatedBy = subject.authenticate(update, updateContext); assertThat(authenticatedBy.equals(parentMaintainers), is(true)); verifyZeroInteractions(updateContext); }
@Test(expected = AuthenticationFailedException.class) public void authenticated_by_mntlower_fails() { when(update.getUpdatedObject()).thenReturn(RpslObject.parse("aut-num: AS3333")); when(objectDao.findAsBlock(3333, 3333)).thenReturn(RpslObject.parse("as-block: AS3209 - AS3353\nmnt-by: TEST-MNT\nmnt-lower: LOW-MNT")); final ArrayList<RpslObject> parentMaintainers = Lists.newArrayList(RpslObject.parse("mntner: LOW-MNT")); when(objectDao.getByKeys(eq(ObjectType.MNTNER), anyCollection())).thenReturn(parentMaintainers); when(authenticationModule.authenticate(update, updateContext, parentMaintainers)).thenReturn(Lists.<RpslObject>newArrayList()); subject.authenticate(update, updateContext); }
@Test(expected = AuthenticationFailedException.class) public void cant_find_asblock() { when(update.getUpdatedObject()).thenReturn(RpslObject.parse("aut-num: AS3333")); when(objectDao.findAsBlock(3333, 3333)).thenReturn(null); subject.authenticate(update, updateContext); }
@Test public void authenticated_by_mntby_succeeds() { when(update.getUpdatedObject()).thenReturn(RpslObject.parse("aut-num: AS3333")); when(objectDao.findAsBlock(3333, 3333)).thenReturn(RpslObject.parse("as-block: AS3209 - AS3353\nmnt-by: TEST-MNT")); final ArrayList<RpslObject> parentMaintainers = Lists.newArrayList(RpslObject.parse("mntner: TEST-MNT")); when(objectDao.getByKeys(eq(ObjectType.MNTNER), anyCollection())).thenReturn(parentMaintainers); when(authenticationModule.authenticate(update, updateContext, parentMaintainers)).thenReturn(parentMaintainers); final List<RpslObject> authenticatedBy = subject.authenticate(update, updateContext); assertThat(authenticatedBy.equals(parentMaintainers), is(true)); verifyZeroInteractions(updateContext); }
@Test(expected = AuthenticationFailedException.class) public void authenticated_by_mntby_fails() { when(update.getUpdatedObject()).thenReturn(RpslObject.parse("aut-num: AS3333")); when(objectDao.findAsBlock(3333, 3333)).thenReturn(RpslObject.parse("as-block: AS3209 - AS3353\nmnt-by: TEST-MNT")); final ArrayList<RpslObject> parentMaintainers = Lists.newArrayList(RpslObject.parse("mntner: TEST-MNT")); when(objectDao.getByKeys(eq(ObjectType.MNTNER), anyCollection())).thenReturn(parentMaintainers); when(authenticationModule.authenticate(update, updateContext, parentMaintainers)).thenReturn(Lists.<RpslObject>newArrayList()); subject.authenticate(update, updateContext); }
@Test public void max_value() { final long maxValue = (1L << 32) - 1; final RpslObject autNum = RpslObject.parse("aut-num: AS" + maxValue); final RpslObject asBlock = RpslObject.parse("as-block: AS" + (maxValue - 1) + " - AS" + maxValue + "\nmnt-by: TEST-MNT"); when(update.getUpdatedObject()).thenReturn(autNum); when(objectDao.findAsBlock(maxValue, maxValue)).thenReturn(asBlock); final ArrayList<RpslObject> parentMaintainers = Lists.newArrayList(RpslObject.parse("mntner: TEST-MNT")); when(objectDao.getByKeys(eq(ObjectType.MNTNER), anyCollection())).thenReturn(parentMaintainers); when(authenticationModule.authenticate(update, updateContext, parentMaintainers)).thenReturn(parentMaintainers); subject.authenticate(update, updateContext); verifyZeroInteractions(updateContext); } |
MntIrtAuthentication extends AuthenticationStrategyBase { @Override public boolean supports(final PreparedUpdate update) { return !update.getNewValues(AttributeType.MNT_IRT).isEmpty(); } @Autowired MntIrtAuthentication(final AuthenticationModule credentialValidators, final RpslObjectDao rpslObjectDao); @Override boolean supports(final PreparedUpdate update); @Override List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext); } | @Test public void operates_on_updates_with_new_mntirts() { when(update.getNewValues(AttributeType.MNT_IRT)).thenReturn(ciSet("IRT-MNT")); assertThat(subject.supports(update), is(true)); }
@Test public void does_not_support_updates_with_same_mntirts() { when(update.getNewValues(AttributeType.MNT_IRT)).thenReturn(Sets.<CIString>newHashSet()); assertThat(subject.supports(update), is(false)); } |
MntIrtAuthentication extends AuthenticationStrategyBase { @Override public List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext) { final Collection<CIString> keys = update.getNewValues(AttributeType.MNT_IRT); final List<RpslObject> candidates = rpslObjectDao.getByKeys(ObjectType.IRT, keys); if (isSelfReference(update, keys)) { candidates.add(update.getUpdatedObject()); } final List<RpslObject> authenticatedBy = credentialValidators.authenticate(update, updateContext, candidates); if (authenticatedBy.isEmpty()) { throw new AuthenticationFailedException(UpdateMessages.authenticationFailed(update.getReferenceObject(), AttributeType.MNT_IRT, candidates), candidates); } return authenticatedBy; } @Autowired MntIrtAuthentication(final AuthenticationModule credentialValidators, final RpslObjectDao rpslObjectDao); @Override boolean supports(final PreparedUpdate update); @Override List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext); } | @Test public void authentication_succeeds() { when(update.getType()).thenReturn(ObjectType.INETNUM); when(update.getNewValues(AttributeType.MNT_IRT)).thenReturn(ciSet("IRT-MNT")); when(update.getReferenceObject()).thenReturn(RpslObject.parse("inetnum: 192.0/24")); when(update.getUpdatedObject()).thenReturn(RpslObject.parse("inetnum: 192.0/24\nmnt-irt: IRT-MNT")); final RpslObject irt = RpslObject.parse("irt: IRT-MNT"); final ArrayList<RpslObject> irts = Lists.newArrayList(irt); when(rpslObjectDao.getByKeys(ObjectType.IRT, ciSet("IRT-MNT"))).thenReturn(irts); when(credentialValidators.authenticate(eq(update), eq(updateContext), anyCollection())).thenReturn(irts); final List<RpslObject> result = subject.authenticate(update, updateContext); assertThat(result.size(), is(1)); assertThat(result.get(0), is(irt)); verifyZeroInteractions(updateContext); }
@Test(expected = AuthenticationFailedException.class) public void authentication_fails() { when(update.getType()).thenReturn(ObjectType.INETNUM); when(update.getReferenceObject()).thenReturn(RpslObject.parse("inetnum: 192.0/24\nmnt-irt: IRT-MNT")); final RpslObject irt = RpslObject.parse("irt: IRT-MNT"); final ArrayList<RpslObject> irts = Lists.newArrayList(irt); when(rpslObjectDao.getByKeys(ObjectType.IRT, ciSet("IRT-MNT"))).thenReturn(irts); when(credentialValidators.authenticate(eq(update), eq(updateContext), anyCollection())).thenReturn(Lists.<RpslObject>newArrayList()); subject.authenticate(update, updateContext); } |
MntByAuthentication extends AuthenticationStrategyBase { @Override public boolean supports(final PreparedUpdate update) { return ObjectTemplate.getTemplate(update.getType()).hasAttribute(AttributeType.MNT_BY); } @Autowired MntByAuthentication(final Maintainers maintainers,
final AuthenticationModule authenticationModule,
final RpslObjectDao rpslObjectDao,
final SsoTranslator ssoTranslator,
final Ipv4Tree ipv4Tree,
final Ipv6Tree ipv6Tree); @Override boolean supports(final PreparedUpdate update); @Override List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext); } | @Test public void supports_every_object_with_a_mntby_attribute() { when(update.getType()).thenReturn(ObjectType.POEM); assertThat(subject.supports(update), is(true)); when(update.getType()).thenReturn(ObjectType.INETNUM); assertThat(subject.supports(update), is(true)); verifyZeroInteractions(maintainers); } |
MntByAuthentication extends AuthenticationStrategyBase { @Override public List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext) { try { return authenticateMntBy(update, updateContext); } catch (AuthenticationFailedException e) { return authenticateByAddressSpaceHolder(update, updateContext, e); } } @Autowired MntByAuthentication(final Maintainers maintainers,
final AuthenticationModule authenticationModule,
final RpslObjectDao rpslObjectDao,
final SsoTranslator ssoTranslator,
final Ipv4Tree ipv4Tree,
final Ipv6Tree ipv6Tree); @Override boolean supports(final PreparedUpdate update); @Override List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext); } | @Test public void authenticate_succeeds() { final RpslObject org = RpslObject.parse("organisation: ORG1\nmnt-by: TEST-MNT"); when(update.getReferenceObject()).thenReturn(org); when(update.getType()).thenReturn(ObjectType.ORGANISATION); when(update.getUpdatedObject()).thenReturn(RpslObject.parse("organisation: ORG1\nmnt-by: TEST-MNT\nnotify: TEST-MNT")); final RpslObject maintainer = RpslObject.parse("mntner: TEST-MNT"); final ArrayList<RpslObject> candidates = Lists.newArrayList(maintainer); when(rpslObjectDao.getByKeys(ObjectType.MNTNER, org.getValuesForAttribute(AttributeType.MNT_BY))).thenReturn(candidates); when(credentialValidators.authenticate(update, updateContext, candidates)).thenReturn(candidates); final List<RpslObject> result = subject.authenticate(update, updateContext); assertThat(result.size(), is(1)); assertThat(result.get(0), is(maintainer)); verifyZeroInteractions(updateContext); verifyZeroInteractions(maintainers); }
@Test(expected = AuthenticationFailedException.class) public void authenticate_fails() { final RpslObject person = RpslObject.parse("person: Some One\nnic-hdl: TEST-NIC\nmnt-by: TEST-MNT"); when(update.getAction()).thenReturn(Action.MODIFY); when(update.getReferenceObject()).thenReturn(person); when(update.getType()).thenReturn(person.getType()); when(update.getUpdatedObject()).thenReturn(person); final RpslObject maintainer = RpslObject.parse("mntner: TEST-MNT"); final ArrayList<RpslObject> candidates = Lists.newArrayList(maintainer); when(rpslObjectDao.getByKeys(ObjectType.MNTNER, person.getValuesForAttribute(AttributeType.MNT_BY))).thenReturn(candidates); when(credentialValidators.authenticate(update, updateContext, candidates)).thenReturn(Lists.<RpslObject>newArrayList()); subject.authenticate(update, updateContext); verify(maintainers).isRsMaintainer(ciSet("RS-MNT")); verifyNoMoreInteractions(maintainers); }
@Test public void authenticate_create_self_reference_succeeds() { final RpslObject mntner = RpslObject.parse("mntner: TEST-MNT\nmnt-by: TEST-MNT"); when(update.getType()).thenReturn(mntner.getType()); when(update.getReferenceObject()).thenReturn(mntner); when(update.getUpdatedObject()).thenReturn(mntner); when(update.getAction()).thenReturn(Action.CREATE); final ArrayList<RpslObject> candidates = Lists.newArrayList(mntner); when(rpslObjectDao.getByKeys(ObjectType.MNTNER, mntner.getValuesForAttribute(AttributeType.MNT_BY))).thenReturn(Lists.<RpslObject>newArrayList()); when(credentialValidators.authenticate(update, updateContext, candidates)).thenReturn(candidates); when(ssoTranslator.translateFromCacheAuthToUuid(updateContext, mntner)).thenReturn(mntner); final List<RpslObject> result = subject.authenticate(update, updateContext); assertThat(result.size(), is(1)); assertThat(result.get(0), is(mntner)); verifyZeroInteractions(updateContext); verifyZeroInteractions(maintainers); }
@Test public void authenticate_modify_original_object_has_no_mntby_update() { when(update.getAction()).thenReturn(Action.MODIFY); final RpslObject original = RpslObject.parse("person: Mr Hubbard\nnic-hdl: TEST-NIC"); when(update.getReferenceObject()).thenReturn(original); final RpslObject updated = RpslObject.parse("person: Mr Hubbard\nnic-hdl: TEST-NIC\nmnt-by: TEST-MNT"); when(update.getUpdatedObject()).thenReturn(updated); when(update.getType()).thenReturn(ObjectType.PERSON); final List<RpslObject> candidates = Lists.newArrayList(RpslObject.parse("mntner: TEST-MNT")); when(rpslObjectDao.getByKeys(eq(ObjectType.MNTNER), anyCollection())).thenReturn(candidates); when(credentialValidators.authenticate(update, updateContext, candidates)).thenReturn(candidates); final List<RpslObject> authenticate = subject.authenticate(update, updateContext); assertThat(authenticate, is(candidates)); verifyZeroInteractions(maintainers); }
@Test public void authenticate_modify_original_object_has_no_mntby_delete() { final RpslObject original = RpslObject.parse("person: Mr Hubbard\nnic-hdl: TEST-NIC"); final RpslObject updated = RpslObject.parse("person: Mr Hubbard\nnic-hdl: TEST-NIC\nmnt-by: TEST-MNT"); when(update.getAction()).thenReturn(Action.DELETE); when(update.getReferenceObject()).thenReturn(original); when(update.getUpdatedObject()).thenReturn(updated); when(update.getType()).thenReturn(ObjectType.PERSON); verifyZeroInteractions(rpslObjectDao, credentialValidators); final List<RpslObject> authenticate = subject.authenticate(update, updateContext); assertThat(authenticate, hasSize(0)); verifyZeroInteractions(maintainers); }
@Test public void authenticate_mnt_by_fails_delete_with_rs_maintainer() { final RpslObject inetnum = RpslObject.parse("" + "inetnum: 193.0.0.0\n" + "mnt-by: DEV1-MNT\n" + "mnt-by: RS-MNT\n"); when(update.getAction()).thenReturn(Action.DELETE); when(update.getReferenceObject()).thenReturn(inetnum); when(update.getUpdatedObject()).thenReturn(inetnum); when(update.getType()).thenReturn(inetnum.getType()); final RpslObject maintainer = RpslObject.parse("mntner: DEV1-MNT\n"); final ArrayList<RpslObject> mntByCandidates = Lists.newArrayList(maintainer); when(rpslObjectDao.getByKeys(ObjectType.MNTNER, ciSet("DEV1-MNT", "RS-MNT"))).thenReturn(mntByCandidates); when(credentialValidators.authenticate(update, updateContext, mntByCandidates)).thenReturn(Lists.<RpslObject>newArrayList()); try { subject.authenticate(update, updateContext); fail("Expected exception"); } catch (AuthenticationFailedException e) { assertThat(e.getAuthenticationMessages(), contains(UpdateMessages.authenticationFailed(inetnum, AttributeType.MNT_BY, Lists.newArrayList(maintainer)))); } verifyZeroInteractions(maintainers); } |
RouteIpAddressAuthentication extends RouteAuthentication { @Override public List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext) { final RpslObject updatedObject = update.getUpdatedObject(); final RpslAttribute typeAttribute = updatedObject.getTypeAttribute(); final IpInterval addressPrefix = IpInterval.parse(typeAttribute.getCleanValue()); final List<RpslObject> ipObjects = getIpObjects(addressPrefix); if (ipObjects.isEmpty()) { throw new AuthenticationFailedException(UpdateMessages.authenticationFailed(updatedObject, typeAttribute.getType(), Collections.<RpslObject>emptyList()), Collections.<RpslObject>emptyList()); } final Set<RpslObject> allCandidates = Sets.newLinkedHashSet(); final List<Message> authenticationMessages = Lists.newArrayList(); for (final RpslObject ipObject : ipObjects) { if (ipObject.containsAttribute(AttributeType.MNT_ROUTES)) { final List<RpslObject> candidates = getCandidatesForMntRoutesAuthentication(ipObject, update); allCandidates.addAll(candidates); final List<RpslObject> authenticated = authenticationModule.authenticate(update, updateContext, candidates); if (authenticated.isEmpty()) { authenticationMessages.add(UpdateMessages.authenticationFailed(ipObject, AttributeType.MNT_ROUTES, candidates)); } else { return authenticated; } } } if (!authenticationMessages.isEmpty()) { throw new AuthenticationFailedException(authenticationMessages, allCandidates); } for (final RpslObject ipObject : ipObjects) { final IpInterval ipInterval = IpInterval.parse(ipObject.getTypeAttribute().getCleanValue()); if (!addressPrefix.equals(ipInterval) && ipObject.containsAttribute(AttributeType.MNT_LOWER)) { final List<RpslObject> candidates = objectDao.getByKeys(ObjectType.MNTNER, ipObject.getValuesForAttribute(AttributeType.MNT_LOWER)); allCandidates.addAll(candidates); final List<RpslObject> authenticated = authenticationModule.authenticate(update, updateContext, candidates); if (authenticated.isEmpty()) { authenticationMessages.add(UpdateMessages.authenticationFailed(ipObject, AttributeType.MNT_LOWER, candidates)); } else { return authenticated; } } } if (!authenticationMessages.isEmpty()) { throw new AuthenticationFailedException(authenticationMessages, allCandidates); } for (final RpslObject ipObject : ipObjects) { if (ipObject.containsAttribute(AttributeType.MNT_BY)) { final List<RpslObject> candidates = objectDao.getByKeys(ObjectType.MNTNER, ipObject.getValuesForAttribute(AttributeType.MNT_BY)); allCandidates.addAll(candidates); final List<RpslObject> authenticated = authenticationModule.authenticate(update, updateContext, candidates); if (authenticated.isEmpty()) { authenticationMessages.add(UpdateMessages.authenticationFailed(ipObject, AttributeType.MNT_BY, candidates)); } else { return authenticated; } } } if (!authenticationMessages.isEmpty()) { throw new AuthenticationFailedException(authenticationMessages, allCandidates); } throw new AuthenticationFailedException(UpdateMessages.authenticationFailed(updatedObject, typeAttribute.getType(), Collections.<RpslObject>emptyList()), allCandidates); } @Autowired RouteIpAddressAuthentication(final AuthenticationModule authenticationModule, final RpslObjectDao objectDao, final Ipv4RouteTree ipv4RouteTree, final Ipv4Tree ipv4Tree, final Ipv6RouteTree ipv6RouteTree, final Ipv6Tree ipv6Tree); @Override List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext); } | @Test public void exact_match_route_without_mntRoutes_succeeds() { final RpslObject existingRoute = RpslObject.parse("" + "route: 192.91.244.0/23\n" + "origin: AS12\n" + "mnt-by: TEST-MNT"); final Ipv4Resource existingRouteResource = Ipv4Resource.parse(existingRoute.getTypeAttribute().getCleanValue()); final Ipv4RouteEntry existingRouteEntry = new Ipv4RouteEntry(existingRouteResource, 1, "AS12"); when(routeTree.findExactOrFirstLessSpecific(routeResource)).thenReturn(Lists.newArrayList(existingRouteEntry)); when(objectDao.getById(1)).thenReturn(existingRoute); final RpslObject maintainer = RpslObject.parse("mntner: TEST-MNT\n"); final ArrayList<RpslObject> candidates = Lists.newArrayList(maintainer); when(objectDao.getByKeys(ObjectType.MNTNER, ciSet("TEST-MNT"))).thenReturn(candidates); when(authenticationModule.authenticate(update, updateContext, candidates)).thenReturn(candidates); final List<RpslObject> authenticatedMaintainers = subject.authenticate(update, updateContext); assertThat(authenticatedMaintainers, contains(maintainer)); }
@Test public void exact_match_route_without_mntRoutes_fails() { final RpslObject existingRoute = RpslObject.parse("" + "route: 192.91.244.0/23\n" + "origin: AS12\n" + "mnt-by: TEST-MNT"); final Ipv4Resource existingRouteResource = Ipv4Resource.parse(existingRoute.getTypeAttribute().getCleanValue()); final Ipv4RouteEntry existingRouteEntry = new Ipv4RouteEntry(existingRouteResource, 1, "AS12"); when(routeTree.findExactOrFirstLessSpecific(routeResource)).thenReturn(Lists.newArrayList(existingRouteEntry)); when(objectDao.getById(1)).thenReturn(existingRoute); final RpslObject maintainer = RpslObject.parse("mntner: TEST-MNT\n"); final ArrayList<RpslObject> candidates = Lists.newArrayList(maintainer); when(objectDao.getByKeys(ObjectType.MNTNER, ciSet("TEST-MNT"))).thenReturn(candidates); when(authenticationModule.authenticate(update, updateContext, candidates)).thenReturn(Collections.<RpslObject>emptyList()); try { subject.authenticate(update, updateContext); fail("Expected authentication exception"); } catch (AuthenticationFailedException e) { assertThat(e.getAuthenticationMessages(), contains(UpdateMessages.authenticationFailed(existingRoute, AttributeType.MNT_BY, candidates))); } }
@Test public void exact_match_route_with_mntRoutes_succeeds() { final RpslObject existingRoute = RpslObject.parse("" + "route: 192.91.244.0/23\n" + "origin: AS12\n" + "mnt-routes: ROUTES-MNT\n" + "mnt-by: TEST-MNT"); final Ipv4Resource existingRouteResource = Ipv4Resource.parse(existingRoute.getTypeAttribute().getCleanValue()); final Ipv4RouteEntry existingRouteEntry = new Ipv4RouteEntry(existingRouteResource, 1, "AS12"); when(routeTree.findExactOrFirstLessSpecific(routeResource)).thenReturn(Lists.newArrayList(existingRouteEntry)); when(objectDao.getById(1)).thenReturn(existingRoute); final RpslObject maintainer = RpslObject.parse("mntner: ROUTES-MNT\n"); final ArrayList<RpslObject> candidates = Lists.newArrayList(maintainer); when(objectDao.getByKeys(ObjectType.MNTNER, ciSet("ROUTES-MNT"))).thenReturn(candidates); when(authenticationModule.authenticate(update, updateContext, candidates)).thenReturn(candidates); final List<RpslObject> authenticatedMaintainers = subject.authenticate(update, updateContext); assertThat(authenticatedMaintainers, contains(maintainer)); verify(objectDao, never()).getByKeys(ObjectType.MNTNER, ciSet("TEST-MNT")); }
@Test public void exact_match_route_with_mntRoutes_fails() { final RpslObject existingRoute = RpslObject.parse("" + "route: 192.91.244.0/23\n" + "origin: AS12\n" + "mnt-routes: ROUTES-MNT\n" + "mnt-by: TEST-MNT"); final Ipv4Resource existingRouteResource = Ipv4Resource.parse(existingRoute.getTypeAttribute().getCleanValue()); final Ipv4RouteEntry existingRouteEntry = new Ipv4RouteEntry(existingRouteResource, 1, "AS12"); when(routeTree.findExactOrFirstLessSpecific(routeResource)).thenReturn(Lists.newArrayList(existingRouteEntry)); when(objectDao.getById(1)).thenReturn(existingRoute); final RpslObject maintainer = RpslObject.parse("mntner: ROUTES-MNT\n"); final ArrayList<RpslObject> candidates = Lists.newArrayList(maintainer); when(objectDao.getByKeys(ObjectType.MNTNER, ciSet("ROUTES-MNT"))).thenReturn(candidates); when(authenticationModule.authenticate(update, updateContext, candidates)).thenReturn(Collections.<RpslObject>emptyList()); try { subject.authenticate(update, updateContext); fail("Expected authentication exception"); } catch (AuthenticationFailedException e) { assertThat(e.getAuthenticationMessages(), contains(UpdateMessages.authenticationFailed(existingRoute, AttributeType.MNT_ROUTES, candidates))); } }
@Test public void less_specific_match_route_with_mntRoutes_fails() { final RpslObject existingRoute = RpslObject.parse("" + "route: 192.91/16\n" + "origin: AS12\n" + "mnt-lower: LOWER-MNT\n" + "mnt-by: TEST-MNT"); final Ipv4Resource existingRouteResource = Ipv4Resource.parse(existingRoute.getTypeAttribute().getCleanValue()); final Ipv4RouteEntry existingRouteEntry = new Ipv4RouteEntry(existingRouteResource, 1, "AS12"); when(routeTree.findExactOrFirstLessSpecific(routeResource)).thenReturn(Lists.newArrayList(existingRouteEntry)); when(objectDao.getById(1)).thenReturn(existingRoute); final RpslObject maintainer = RpslObject.parse("mntner: LOWER-MNT\n"); final ArrayList<RpslObject> candidates = Lists.newArrayList(maintainer); when(objectDao.getByKeys(ObjectType.MNTNER, ciSet("LOWER-MNT"))).thenReturn(candidates); when(authenticationModule.authenticate(update, updateContext, candidates)).thenReturn(Collections.<RpslObject>emptyList()); try { subject.authenticate(update, updateContext); fail("Expected authentication exception"); } catch (AuthenticationFailedException e) { assertThat(e.getAuthenticationMessages(), contains(UpdateMessages.authenticationFailed(existingRoute, AttributeType.MNT_LOWER, candidates))); } }
@Test public void less_specific_match_inetnum_with_mntRoutes_fails() { final RpslObject existingRoute = RpslObject.parse("" + "route: 192.91/16\n" + "origin: AS12\n" + "mnt-lower: LOWER-MNT\n" + "mnt-by: TEST-MNT"); final Ipv4Resource existingRouteResource = Ipv4Resource.parse(existingRoute.getTypeAttribute().getCleanValue()); when(routeTree.findExactOrFirstLessSpecific(routeResource)).thenReturn(Collections.<Ipv4RouteEntry>emptyList()); when(ipv4Tree.findExactOrFirstLessSpecific(routeResource)).thenReturn(Lists.newArrayList(new Ipv4Entry(existingRouteResource, 1))); when(objectDao.getById(1)).thenReturn(existingRoute); final RpslObject maintainer = RpslObject.parse("mntner: LOWER-MNT\n"); final ArrayList<RpslObject> candidates = Lists.newArrayList(maintainer); when(objectDao.getByKeys(ObjectType.MNTNER, ciSet("LOWER-MNT"))).thenReturn(candidates); when(authenticationModule.authenticate(update, updateContext, candidates)).thenReturn(Collections.<RpslObject>emptyList()); try { subject.authenticate(update, updateContext); fail("Expected authentication exception"); } catch (AuthenticationFailedException e) { assertThat(e.getAuthenticationMessages(), contains(UpdateMessages.authenticationFailed(existingRoute, AttributeType.MNT_LOWER, candidates))); } }
@Test public void no_match_ipObject() { when(routeTree.findExactOrFirstLessSpecific(routeResource)).thenReturn(Collections.<Ipv4RouteEntry>emptyList()); when(ipv4Tree.findExactOrFirstLessSpecific(routeResource)).thenReturn(Collections.<Ipv4Entry>emptyList()); when(authenticationModule.authenticate(eq(update), eq(updateContext), anyListOf(RpslObject.class))).thenReturn(Collections.<RpslObject>emptyList()); try { subject.authenticate(update, updateContext); fail("Expected authentication exception"); } catch (AuthenticationFailedException e) { assertThat(e.getAuthenticationMessages(), contains(UpdateMessages.authenticationFailed(routeObject, AttributeType.ROUTE, Collections.<RpslObject>emptyList()))); } }
@Test public void less_specific_match_route6_without_mntRoutes_fails() { final RpslObject route6Object = RpslObject.parse("" + "route6: acac::0/32\n" + "origin: AS12\n" + "mnt-routes: ROUTE-MNT"); final Ipv6Resource route6Resource = Ipv6Resource.parse(route6Object.getTypeAttribute().getCleanValue()); when(update.getUpdatedObject()).thenReturn(route6Object); final RpslObject existingRoute = RpslObject.parse("" + "route6: acac::0/16\n" + "origin: AS12\n" + "mnt-lower: LOWER-MNT\n" + "mnt-by: TEST-MNT"); final Ipv6Resource existingRouteResource = Ipv6Resource.parse(existingRoute.getTypeAttribute().getCleanValue()); final Ipv6RouteEntry existingRouteEntry = new Ipv6RouteEntry(existingRouteResource, 1, "AS12"); when(route6Tree.findExactOrFirstLessSpecific(route6Resource)).thenReturn(Lists.newArrayList(existingRouteEntry)); when(objectDao.getById(1)).thenReturn(existingRoute); final RpslObject maintainer = RpslObject.parse("mntner: LOWER-MNT\n"); final ArrayList<RpslObject> candidates = Lists.newArrayList(maintainer); when(objectDao.getByKeys(ObjectType.MNTNER, ciSet("LOWER-MNT"))).thenReturn(candidates); when(authenticationModule.authenticate(update, updateContext, candidates)).thenReturn(Collections.<RpslObject>emptyList()); try { subject.authenticate(update, updateContext); fail("Expected authentication exception"); } catch (AuthenticationFailedException e) { assertThat(e.getAuthenticationMessages(), contains(UpdateMessages.authenticationFailed(existingRoute, AttributeType.MNT_LOWER, candidates))); } } |
DomainAuthentication extends AuthenticationStrategyBase { @Override public boolean supports(final PreparedUpdate update) { return update.getAction().equals(Action.CREATE) && (update.getType().equals(ObjectType.DOMAIN)); } @Autowired DomainAuthentication(final Ipv4Tree ipv4Tree,
final Ipv6Tree ipv6Tree,
final RpslObjectDao objectDao,
final AuthenticationModule authenticationModule); @Override boolean supports(final PreparedUpdate update); @Override List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext); } | @Test public void supports_create_domain() { when(update.getAction()).thenReturn(Action.CREATE); when(update.getType()).thenReturn(ObjectType.DOMAIN); assertThat(subject.supports(update), is(true)); }
@Test public void supports_modify_domain() { when(update.getAction()).thenReturn(Action.MODIFY); when(update.getType()).thenReturn(ObjectType.DOMAIN); assertThat(subject.supports(update), is(false)); }
@Test public void supports_create_inetnum() { when(update.getAction()).thenReturn(Action.CREATE); when(update.getType()).thenReturn(ObjectType.INETNUM); assertThat(subject.supports(update), is(false)); } |
DomainAuthentication extends AuthenticationStrategyBase { @Override public List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext) { final RpslObject rpslObject = update.getUpdatedObject(); final CIString domainString = rpslObject.getKey(); final Domain domain = Domain.parse(domainString); if (domain.getType() == Domain.Type.E164) { return Collections.emptyList(); } final IpInterval<?> reverseIp = domain.getReverseIp(); if (reverseIp instanceof Ipv4Resource) { return authenticate(update, updateContext, reverseIp, ipv4Tree); } else if (reverseIp instanceof Ipv6Resource) { return authenticate(update, updateContext, reverseIp, ipv6Tree); } throw new IllegalArgumentException("Unexpected reverse ip: " + reverseIp); } @Autowired DomainAuthentication(final Ipv4Tree ipv4Tree,
final Ipv6Tree ipv6Tree,
final RpslObjectDao objectDao,
final AuthenticationModule authenticationModule); @Override boolean supports(final PreparedUpdate update); @Override List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext); } | @Test public void authenticate_enum_domain() { final RpslObject rpslObject = RpslObject.parse("domain: 2.1.2.1.5.5.5.2.0.2.1.e164.arpa"); when(update.getUpdatedObject()).thenReturn(rpslObject); final List<RpslObject> authenticated = subject.authenticate(update, updateContext); assertThat(authenticated, hasSize(0)); verifyZeroInteractions(ipv4Tree, ipv6Tree, objectDao); }
@Test public void authenticate_ipv4_domain_no_parent() { final RpslObject rpslObject = RpslObject.parse("domain: 255.255.193.in-addr.arpa"); when(update.getUpdatedObject()).thenReturn(rpslObject); when(ipv4Tree.findExactOrFirstLessSpecific(Ipv4Resource.parse("193.255.255.0/24"))).thenReturn(Collections.<Ipv4Entry>emptyList()); try { subject.authenticate(update, updateContext); fail("Expected exception"); } catch (AuthenticationFailedException ignored) { assertThat(ignored.getAuthenticationMessages(), contains(UpdateMessages.authenticationFailed(rpslObject, AttributeType.DOMAIN, Collections.<RpslObject>emptySet()))); } verify(ipv4Tree).findExactOrFirstLessSpecific(any(Ipv4Resource.class)); verifyZeroInteractions(ipv6Tree, objectDao); }
@Test public void authenticate_ipv6_domain_no_parent() { final RpslObject rpslObject = RpslObject.parse("domain: 0.0.0.0.8.f.7.0.1.0.0.2.ip6.arpa"); when(update.getUpdatedObject()).thenReturn(rpslObject); when(ipv6Tree.findExactOrFirstLessSpecific(Ipv6Resource.parse("2001:7f8::/48"))).thenReturn(Collections.<Ipv6Entry>emptyList()); try { subject.authenticate(update, updateContext); fail("Expected exception"); } catch (AuthenticationFailedException ignored) { assertThat(ignored.getAuthenticationMessages(), contains(UpdateMessages.authenticationFailed(rpslObject, AttributeType.DOMAIN, Collections.<RpslObject>emptySet()))); } verify(ipv6Tree).findExactOrFirstLessSpecific(any(Ipv6Resource.class)); verifyZeroInteractions(ipv4Tree, objectDao); }
@Test public void authenticate_ipv6_domain_multiple_parents() { final RpslObject rpslObject = RpslObject.parse("domain: 0.0.0.0.8.f.7.0.1.0.0.2.ip6.arpa"); when(update.getUpdatedObject()).thenReturn(rpslObject); when(ipv6Tree.findExactOrFirstLessSpecific(Ipv6Resource.parse("2001:7f8::/48"))).thenReturn(Lists.newArrayList( new Ipv6Entry(Ipv6Resource.parse("2001:7f8::/32"), 1), new Ipv6Entry(Ipv6Resource.parse("2001:7f8::/32"), 2))); try { subject.authenticate(update, updateContext); fail("Expected exception"); } catch (AuthenticationFailedException ignored) { assertThat(ignored.getAuthenticationMessages(), contains(UpdateMessages.authenticationFailed(rpslObject, AttributeType.DOMAIN, Collections.<RpslObject>emptySet()))); } verify(ipv6Tree).findExactOrFirstLessSpecific(any(Ipv6Resource.class)); verifyZeroInteractions(ipv4Tree, objectDao); } |
OrgRefAuthentication extends AuthenticationStrategyBase { @Override public boolean supports(final PreparedUpdate update) { return !update.getNewValues(AttributeType.ORG).isEmpty(); } @Autowired OrgRefAuthentication(final AuthenticationModule credentialValidators, final RpslObjectDao rpslObjectDao); @Override boolean supports(final PreparedUpdate update); @Override List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext); } | @Test public void supports_update_with_new_org_references() { when(update.getNewValues(AttributeType.ORG)).thenReturn(ciSet("ORG2")); when(update.getUpdatedObject()).thenReturn(RpslObject.parse("organisation: ORG1\norg: ORG1")); assertThat(subject.supports(update), is(true)); }
@Test public void no_difference_in_org_refs_is_not_supported() { when(update.getUpdatedObject()).thenReturn(RpslObject.parse("organisation: ORG1\norg: ORG1")); when(update.getReferenceObject()).thenReturn(RpslObject.parse("organisation: ORG1\norg: ORG1")); assertThat(subject.supports(update), is(false)); } |
OrgRefAuthentication extends AuthenticationStrategyBase { @Override public List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext) { final List<Message> authenticationMessages = Lists.newArrayList(); final Map<RpslObject, List<RpslObject>> candidatesForOrganisations = getCandidatesForOrganisations(update, updateContext); final Set<RpslObject> authenticatedOrganisations = Sets.newLinkedHashSet(); for (final Map.Entry<RpslObject, List<RpslObject>> organisationEntry : candidatesForOrganisations.entrySet()) { final List<RpslObject> candidates = organisationEntry.getValue(); final List<RpslObject> authenticatedBy = credentialValidators.authenticate(update, updateContext, candidates); if (authenticatedBy.isEmpty()) { final RpslObject organisation = organisationEntry.getKey(); authenticationMessages.add(UpdateMessages.authenticationFailed(organisation, AttributeType.MNT_REF, candidates)); } else { authenticatedOrganisations.addAll(authenticatedBy); } } if (!authenticationMessages.isEmpty()) { throw new AuthenticationFailedException(authenticationMessages, Sets.newLinkedHashSet(Iterables.concat(candidatesForOrganisations.values()))); } return Lists.newArrayList(authenticatedOrganisations); } @Autowired OrgRefAuthentication(final AuthenticationModule credentialValidators, final RpslObjectDao rpslObjectDao); @Override boolean supports(final PreparedUpdate update); @Override List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext); } | @Test public void authentication_succeeds() { when(update.getType()).thenReturn(ObjectType.INETNUM); when(update.getReferenceObject()).thenReturn(RpslObject.parse("inetnum: 192.0/24\norg: ORG1")); when(update.getUpdatedObject()).thenReturn(RpslObject.parse("inetnum: 192.0/24\norg: ORG2")); final RpslObject organisation = RpslObject.parse("organisation: ORG1\nmnt-ref: REF-MNT"); final List<RpslObject> organisations = Lists.newArrayList(organisation); when(rpslObjectDao.getByKeys(eq(ObjectType.ORGANISATION), anyList())).thenReturn(organisations); final RpslObject maintainer = RpslObject.parse("mntner: REF-MNT"); when(rpslObjectDao.getByKey(ObjectType.MNTNER, "REF-MNT")).thenReturn(maintainer); final ArrayList<RpslObject> candidates = Lists.newArrayList(maintainer); when(credentialValidators.authenticate(eq(update), eq(updateContext), anyList())).thenReturn(candidates); final List<RpslObject> result = subject.authenticate(update, updateContext); assertThat(result.size(), is(1)); assertThat(result.get(0), is(maintainer)); verifyZeroInteractions(updateContext); }
@Test(expected = AuthenticationFailedException.class) public void no_mntnerref_found() { when(update.getType()).thenReturn(ObjectType.PERSON); when(update.getReferenceObject()).thenReturn(RpslObject.parse("person: Some One\nnetname: NETNAME\nnic-hdl: TEST-NIC\norg: ORG1")); when(update.getUpdatedObject()).thenReturn(RpslObject.parse("person: Some One\nnetname: NETNAME\nnic-hdl: TEST-NIC\norg: ORG2")); final RpslObject organisation = RpslObject.parse("organisation: ORG2"); final List<RpslObject> organisations = Lists.newArrayList(organisation); when(rpslObjectDao.getByKeys(eq(ObjectType.ORGANISATION), anyList())).thenReturn(organisations); when(credentialValidators.authenticate(eq(update), eq(updateContext), anyList())).thenReturn(Lists.<RpslObject>newArrayList()); subject.authenticate(update, updateContext); }
@Test(expected = AuthenticationFailedException.class) public void mntnerref_does_not_exist() { when(update.getType()).thenReturn(ObjectType.INETNUM); when(update.getReferenceObject()).thenReturn(RpslObject.parse("inetnum: 192.0/24\norg: ORG1")); when(update.getUpdatedObject()).thenReturn(RpslObject.parse("inetnum: 192.0/24\norg: ORG2")); final RpslObject organisation = RpslObject.parse("organisation: ORG1\nmnt-ref: REF-MNT"); final List<RpslObject> organisations = Lists.newArrayList(organisation); when(rpslObjectDao.getByKeys(eq(ObjectType.ORGANISATION), anyList())).thenReturn(organisations); final RpslObject maintainer = RpslObject.parse("mntner: REF-MNT"); when(rpslObjectDao.getByKey(ObjectType.MNTNER, "REF-MNT")).thenThrow(EmptyResultDataAccessException.class); when(credentialValidators.authenticate(eq(update), eq(updateContext), anyList())).thenReturn(Lists.<RpslObject>newArrayList()); subject.authenticate(update, updateContext); verify(updateContext).addMessage(eq(update), UpdateMessages.nonexistantMntRef("ORG1", "REF-MNT")); } |
InetnumAuthentication extends AuthenticationStrategyBase { @Override public boolean supports(final PreparedUpdate update) { return update.getAction().equals(Action.CREATE) && (update.getType().equals(ObjectType.INETNUM) || update.getType().equals(ObjectType.INET6NUM)); } @Autowired InetnumAuthentication(final AuthenticationModule authenticationModule,
final Ipv4Tree ipv4Tree,
final Ipv6Tree ipv6Tree,
final RpslObjectDao rpslObjectDao); @Override boolean supports(final PreparedUpdate update); @Override List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext); } | @Test public void supports_creating_inetnum() { when(update.getAction()).thenReturn(Action.CREATE); when(update.getType()).thenReturn(ObjectType.INETNUM); assertThat(subject.supports(update), is(true)); }
@Test public void supports_creating_inet6num() { when(update.getAction()).thenReturn(Action.CREATE); when(update.getType()).thenReturn(ObjectType.INET6NUM); assertThat(subject.supports(update), is(true)); }
@Test public void does_not_support_modifying() { when(update.getAction()).thenReturn(Action.MODIFY); when(update.getType()).thenReturn(ObjectType.INETNUM); assertThat(subject.supports(update), is(false)); } |
InetnumAuthentication extends AuthenticationStrategyBase { @Override public List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext) { final IpInterval ipInterval = IpInterval.parse(update.getUpdatedObject().getKey()); IpEntry ipEntry; try { ipEntry = getParentEntry(ipInterval); } catch (IllegalArgumentException e) { return Collections.emptyList(); } final RpslObject parentObject = rpslObjectDao.getById(ipEntry.getObjectId()); AttributeType attributeType = AttributeType.MNT_LOWER; Collection<CIString> maintainerKeys = parentObject.getValuesForAttribute(attributeType); if (maintainerKeys.isEmpty()) { attributeType = AttributeType.MNT_BY; maintainerKeys = parentObject.getValuesForAttribute(attributeType); } final List<RpslObject> maintainers = rpslObjectDao.getByKeys(ObjectType.MNTNER, maintainerKeys); final List<RpslObject> authenticatedBy = authenticationModule.authenticate(update, updateContext, maintainers); if (authenticatedBy.isEmpty()) { throw new AuthenticationFailedException(UpdateMessages.parentAuthenticationFailed(parentObject, attributeType, maintainers), maintainers); } return authenticatedBy; } @Autowired InetnumAuthentication(final AuthenticationModule authenticationModule,
final Ipv4Tree ipv4Tree,
final Ipv6Tree ipv6Tree,
final RpslObjectDao rpslObjectDao); @Override boolean supports(final PreparedUpdate update); @Override List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext); } | @Test public void authenticate_mntlower_inetnum_succeeds() { when(update.getUpdatedObject()).thenReturn(RpslObject.parse("inetnum: 192.0/24")); final RpslObject parent = RpslObject.parse("inetnum: 192.0/16\nmnt-lower: LWR-MNT"); when(rpslObjectDao.getById(anyInt())).thenReturn(parent); when(ipv4Tree.findFirstLessSpecific(any(Ipv4Resource.class))).thenReturn(Lists.newArrayList(ipv4Entry)); final RpslObject lowerMaintainer = RpslObject.parse("mntner: LWR-MNT"); final ArrayList<RpslObject> lowerMaintainers = Lists.newArrayList(lowerMaintainer); when(rpslObjectDao.getByKeys(ObjectType.MNTNER, parent.getValuesForAttribute(AttributeType.MNT_LOWER))).thenReturn(lowerMaintainers); when(authenticationModule.authenticate(update, updateContext, lowerMaintainers)).thenReturn(lowerMaintainers); final List<RpslObject> result = subject.authenticate(update, updateContext); assertThat(result.size(), is(1)); assertThat(result.get(0), is(lowerMaintainer)); verifyZeroInteractions(updateContext); }
@Test public void authenticate_mntby_inetnum_succeeds() { when(update.getUpdatedObject()).thenReturn(RpslObject.parse("inetnum: 192.0/24")); final RpslObject parent = RpslObject.parse("inetnum: 192.0/16\nmnt-by: TEST-MNT"); when(rpslObjectDao.getById(anyInt())).thenReturn(parent); when(ipv4Tree.findFirstLessSpecific(any(Ipv4Resource.class))).thenReturn(Lists.newArrayList(ipv4Entry)); final RpslObject maintainer = RpslObject.parse("mntner: TEST-MNT"); final ArrayList<RpslObject> maintainers = Lists.newArrayList(maintainer); when(rpslObjectDao.getByKeys(ObjectType.MNTNER, parent.getValuesForAttribute(AttributeType.MNT_BY))).thenReturn(maintainers); when(authenticationModule.authenticate(update, updateContext, maintainers)).thenReturn(maintainers); final List<RpslObject> result = subject.authenticate(update, updateContext); assertThat(result.size(), is(1)); assertThat(result.get(0), is(maintainer)); verifyZeroInteractions(updateContext); }
@Test(expected = AuthenticationFailedException.class) public void authenticate_mntlower_inetnum_fails() { when(update.getUpdatedObject()).thenReturn(RpslObject.parse("inetnum: 192.0/24")); final RpslObject parent = RpslObject.parse("inetnum: 192.0/16\nmnt-lower: LWR-MNT"); when(rpslObjectDao.getById(anyInt())).thenReturn(parent); when(ipv4Tree.findFirstLessSpecific(any(Ipv4Resource.class))).thenReturn(Lists.newArrayList(ipv4Entry)); final RpslObject maintainer = RpslObject.parse("mntner: LWR-MNT"); final ArrayList<RpslObject> maintainers = Lists.newArrayList(maintainer); when(rpslObjectDao.getByKeys(ObjectType.MNTNER, parent.getValuesForAttribute(AttributeType.MNT_LOWER))).thenReturn(maintainers); when(authenticationModule.authenticate(update, updateContext, maintainers)).thenReturn(Lists.<RpslObject>newArrayList()); subject.authenticate(update, updateContext); }
@Test public void authenticate_mntlower_inet6num_succeeds() { when(update.getUpdatedObject()).thenReturn(RpslObject.parse("inetnum: fe80::/32")); final RpslObject parent = RpslObject.parse("inetnum: fe80::/16\nmnt-lower: LWR-MNT"); when(rpslObjectDao.getById(anyInt())).thenReturn(parent); when(ipv6Tree.findFirstLessSpecific(any(Ipv6Resource.class))).thenReturn(Lists.newArrayList(ipv6Entry)); final RpslObject maintainer = RpslObject.parse("mntner: LWR-MNT"); final ArrayList<RpslObject> maintainers = Lists.newArrayList(maintainer); when(rpslObjectDao.getByKeys(ObjectType.MNTNER, parent.getValuesForAttribute(AttributeType.MNT_LOWER))).thenReturn(maintainers); when(authenticationModule.authenticate(update, updateContext, maintainers)).thenReturn(Lists.<RpslObject>newArrayList(maintainer)); final List<RpslObject> result = subject.authenticate(update, updateContext); assertThat(result.size(), is(1)); assertThat(result.get(0), is(maintainer)); verifyZeroInteractions(updateContext); }
@Test public void parent_not_found() { when(update.getUpdatedObject()).thenReturn(RpslObject.parse("inetnum: fe80::/32")); when(ipv6Tree.findFirstLessSpecific(any(Ipv6Resource.class))).thenReturn(Lists.<Ipv6Entry>newArrayList()); List<RpslObject> rpslObjects = subject.authenticate(update, updateContext); assertThat(rpslObjects, is(empty())); }
@Test public void more_than_one_parent_found() { when(update.getUpdatedObject()).thenReturn(RpslObject.parse("inetnum: fe80::/32")); when(ipv6Tree.findFirstLessSpecific(any(Ipv6Resource.class))).thenReturn(Lists.<Ipv6Entry>newArrayList(ipv6Entry, ipv6Entry)); List<RpslObject> rpslObjects = subject.authenticate(update, updateContext); assertThat(rpslObjects, is(empty())); } |
X509CredentialValidator implements CredentialValidator<X509Credential, X509Credential> { @Override public boolean hasValidCredential(final PreparedUpdate update, final UpdateContext updateContext, final Collection<X509Credential> offeredCredentials, final X509Credential knownCredential) { for (final X509Credential offeredCredential : offeredCredentials) { if (verifySignedMessage(update, updateContext, offeredCredential, knownCredential)) { log(update, String.format("Successfully validated with keycert: %s", knownCredential.getKeyId())); return true; } } return false; } @Autowired X509CredentialValidator(final RpslObjectDao rpslObjectDao, final DateTimeProvider dateTimeProvider, final LoggerContext loggerContext); @Override Class<X509Credential> getSupportedCredentials(); @Override Class<X509Credential> getSupportedOfferedCredentialType(); @Override boolean hasValidCredential(final PreparedUpdate update, final UpdateContext updateContext, final Collection<X509Credential> offeredCredentials, final X509Credential knownCredential); } | @Test public void authentication_success() { boolean result = subject.hasValidCredential(update, updateContext, Sets.newHashSet(offeredCredential), knownCredential); assertThat(result, is(true)); }
@Test public void authentication_keycert_not_found() throws Exception { when(rpslObjectDao.getByKey(ObjectType.KEY_CERT, "X509-1")).thenThrow(new EmptyResultDataAccessException(1)); boolean result = subject.hasValidCredential(update, updateContext, Sets.newHashSet(offeredCredential), knownCredential); assertThat(result, is(false)); }
@Test public void authentication_keycert_is_invalid() throws Exception { when(rpslObjectDao.getByKey(ObjectType.KEY_CERT, "X509-1")).thenAnswer(new Answer<RpslObject>() { @Override public RpslObject answer(InvocationOnMock invocation) throws Throwable { return RpslObject.parse( "key-cert: AUTO-1\n" + "method: X509\n" + "mnt-by: OWNER-MNT\n" + "source: TEST\n"); } }); boolean result = subject.hasValidCredential(update, updateContext, Sets.newHashSet(offeredCredential), knownCredential); assertThat(result, is(false)); } |
SsoCredentialValidator implements CredentialValidator<SsoCredential, SsoCredential> { @Override public Class<SsoCredential> getSupportedCredentials() { return SsoCredential.class; } @Autowired SsoCredentialValidator(final LoggerContext loggerContext); @Override Class<SsoCredential> getSupportedCredentials(); @Override Class<SsoCredential> getSupportedOfferedCredentialType(); @Override boolean hasValidCredential(final PreparedUpdate update, final UpdateContext updateContext, final Collection<SsoCredential> offeredCredentials, final SsoCredential knownCredential); } | @Test public void supportedCredentials() { assertThat(subject.getSupportedCredentials(), Is.<Class<SsoCredential>>is(SsoCredential.class)); } |
SsoCredentialValidator implements CredentialValidator<SsoCredential, SsoCredential> { @Override public boolean hasValidCredential(final PreparedUpdate update, final UpdateContext updateContext, final Collection<SsoCredential> offeredCredentials, final SsoCredential knownCredential) { for (SsoCredential offered : offeredCredentials) { if (offered.getOfferedUserSession().getUuid().equals(knownCredential.getKnownUuid())) { log(update, String.format("Validated %s with RIPE NCC Access for user: %s.", update.getFormattedKey(), offered.getOfferedUserSession().getUsername())); update.getUpdate().setEffectiveCredential(offered.getOfferedUserSession().getUsername(), Update.EffectiveCredentialType.SSO); return true; } } return false; } @Autowired SsoCredentialValidator(final LoggerContext loggerContext); @Override Class<SsoCredential> getSupportedCredentials(); @Override Class<SsoCredential> getSupportedOfferedCredentialType(); @Override boolean hasValidCredential(final PreparedUpdate update, final UpdateContext updateContext, final Collection<SsoCredential> offeredCredentials, final SsoCredential knownCredential); } | @Test public void hasValidCredential() { final UserSession offered = new UserSession("[email protected]", "Test User", true, "2033-01-30T16:38:27.369+11:00"); offered.setUuid("testuuid"); final SsoCredential offeredCredential = (SsoCredential)SsoCredential.createOfferedCredential(offered); final SsoCredential knownCredential = SsoCredential.createKnownCredential("testuuid"); final boolean hasValidCredential = subject.hasValidCredential( preparedUpdate, updateContext, Collections.singletonList(offeredCredential), knownCredential); assertThat(hasValidCredential, is(true)); }
@Test public void setsEffectiveCredential() { final UserSession offered = new UserSession("[email protected]", "Test User", true, "2033-01-30T16:38:27.369+11:00"); offered.setUuid("testuuid"); final SsoCredential offeredCredential = (SsoCredential)SsoCredential.createOfferedCredential(offered); final SsoCredential knownCredential = SsoCredential.createKnownCredential("testuuid"); subject.hasValidCredential( preparedUpdate, updateContext, Collections.singletonList(offeredCredential), knownCredential); assertThat(update.getEffectiveCredential(), is("[email protected]" )); assertThat(update.getEffectiveCredentialType(), is(Update.EffectiveCredentialType.SSO)); }
@Test public void hasNoOfferedCredentials() { final UserSession offered = new UserSession("[email protected]", "Test User", true, "2033-01-30T16:38:27.369+11:00"); offered.setUuid("testuuid"); final SsoCredential knownCredential = SsoCredential.createKnownCredential("testuuid"); final boolean hasValidCredential = subject.hasValidCredential( preparedUpdate, updateContext, Collections.<SsoCredential>emptyList(), knownCredential); assertThat(hasValidCredential, is(false)); }
@Test public void noCheckForUserInactivity() { final UserSession offered = new UserSession("[email protected]", "Test User", false, "2033-01-30T16:38:27.369+11:00"); offered.setUuid("testuuid"); final SsoCredential offeredCredential = (SsoCredential)SsoCredential.createOfferedCredential(offered); final SsoCredential knownCredential = SsoCredential.createKnownCredential("testuuid"); final boolean hasValidCredential = subject.hasValidCredential( preparedUpdate, updateContext, Collections.singletonList(offeredCredential), knownCredential); assertThat(hasValidCredential, is(true)); }
@Test public void noCorrectCredential() { final UserSession offered = new UserSession("[email protected]", "Test User", false, "2033-01-30T16:38:27.369+11:00"); offered.setUuid("offereduuid"); final SsoCredential offeredCredential = (SsoCredential)SsoCredential.createOfferedCredential(offered); final SsoCredential knownCredential = SsoCredential.createKnownCredential("testuuid"); final boolean hasValidCredential = subject.hasValidCredential( preparedUpdate, updateContext, Collections.singletonList(offeredCredential), knownCredential); assertThat(hasValidCredential, is(false)); } |
AuthenticationModule { @CallerSensitive public List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext, final Collection<RpslObject> maintainers) { final Credentials offered = update.getCredentials(); boolean passwordRemovedRemark = false; loggerContext.logAuthenticationStrategy(update.getUpdate(), getCaller(), maintainers); final List<RpslObject> authenticatedCandidates = Lists.newArrayList(); for (final RpslObject maintainer : maintainers) { if (hasValidCredentialForCandidate(update, updateContext, offered, maintainer)) { authenticatedCandidates.add(maintainer); } else { if (hasPasswordRemovedRemark(maintainer)) { passwordRemovedRemark = true; } } } if (authenticatedCandidates.isEmpty() && passwordRemovedRemark) { updateContext.addMessage(update, UpdateMessages.oldPasswordsRemoved()); } return authenticatedCandidates; } @Autowired AuthenticationModule(final LoggerContext loggerContext,
final CredentialValidator<? extends Credential, ? extends Credential>... credentialValidators); @CallerSensitive List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext, final Collection<RpslObject> maintainers); } | @Test public void authenticate_finds_all_candidates() { when(credentialValidator.hasValidCredential(any(PreparedUpdate.class), any(UpdateContext.class), anyCollection(), any(PasswordCredential.class))).thenReturn(true); final RpslObject mntner1 = RpslObject.parse("mntner: TEST-MNT\nauth: MD5-PWsomething"); final RpslObject mntner2 = RpslObject.parse("mntner: TEST2-MNT\nauth: MD5-PWsomethingElse"); final RpslObject mntner3 = RpslObject.parse("mntner: TEST3-MNT"); final List<RpslObject> result = subject.authenticate(update, updateContext, Lists.newArrayList(mntner1, mntner2, mntner3)); assertThat(result.size(), is(2)); assertThat(result.contains(mntner1), is(true)); assertThat(result.contains(mntner2), is(true)); assertThat(result.contains(mntner3), is(false)); }
@Test public void authenticate_mixed_case_auth_line() { when(credentialValidator.hasValidCredential(any(PreparedUpdate.class), any(UpdateContext.class), anyCollection(), any(PasswordCredential.class))).thenReturn(true); final RpslObject mntner = RpslObject.parse("mntner: TEST-MNT\nauth: Md5-pW something"); final List<RpslObject> result = subject.authenticate(update, updateContext, Lists.newArrayList(mntner)); assertThat(result, hasSize(1)); assertThat(result.contains(mntner), is(true)); }
@Test public void authenticate_fails() { when(credentialValidator.hasValidCredential(any(PreparedUpdate.class), any(UpdateContext.class), anyCollection(), any(PasswordCredential.class))).thenReturn(false); final RpslObject mntner = RpslObject.parse("mntner: TEST-MNT\nauth: MD5-PW $1$d9fKeTr2$Si7YudNf4rUGmR71n/cqk/"); final List<RpslObject> result = subject.authenticate(update, updateContext, Lists.newArrayList(mntner)); assertThat(result, hasSize(0)); }
@Test public void authenticate_sso_credential_checked_first() { when(credentialValidator.hasValidCredential(any(PreparedUpdate.class), any(UpdateContext.class), anyCollection(), any(PasswordCredential.class))).thenReturn(false); when(ssoCredentialValidator.hasValidCredential(any(PreparedUpdate.class), any(UpdateContext.class), anyCollection(), any(SsoCredential.class))).thenAnswer( new Answer<Boolean>() { @Override public Boolean answer(InvocationOnMock invocation) throws Throwable { verify(credentialValidator, never()).hasValidCredential(any(PreparedUpdate.class), any(UpdateContext.class), anyCollection(), any(PasswordCredential.class)); return false; } }); final RpslObject maintainer = RpslObject.parse( "mntner: OWNER-MNT\n" + "descr: Owner Maintainer\n" + "admin-c: TP1-TEST\n" + "upd-to: [email protected]\n" + "auth: MD5-PW $1$d9fKeTr2$Si7YudNf4rUGmR71n/cqk/ #test\n" + "auth: SSO [email protected]\n" + "mnt-by: OWNER-MNT\n" + "source: TEST"); subject.authenticate(update, updateContext, Collections.singletonList(maintainer)); } |
PasswordCredentialValidator implements CredentialValidator<PasswordCredential, PasswordCredential> { @Override public Class<PasswordCredential> getSupportedCredentials() { return PasswordCredential.class; } @Autowired PasswordCredentialValidator(LoggerContext loggerContext); @Override Class<PasswordCredential> getSupportedCredentials(); @Override Class<PasswordCredential> getSupportedOfferedCredentialType(); @Override boolean hasValidCredential(final PreparedUpdate update,
final UpdateContext updateContext,
final Collection<PasswordCredential> offeredCredentials,
final PasswordCredential knownCredential); } | @Test public void supports() { assertEquals(PasswordCredential.class, subject.getSupportedCredentials()); } |
PgpCredentialValidator implements CredentialValidator<PgpCredential, PgpCredential> { @Override public boolean hasValidCredential(final PreparedUpdate update, final UpdateContext updateContext, final Collection<PgpCredential> offeredCredentials, final PgpCredential knownCredential) { for (final PgpCredential offeredCredential : offeredCredentials) { if (verifySignedMessage(update, updateContext, offeredCredential, knownCredential)) { update.getUpdate().setEffectiveCredential(knownCredential.getKeyId(), Update.EffectiveCredentialType.PGP); return true; } } return false; } @Autowired PgpCredentialValidator(final RpslObjectDao rpslObjectDao, final DateTimeProvider dateTimeProvider, LoggerContext loggerContext); @Override Class<PgpCredential> getSupportedCredentials(); @Override Class<PgpCredential> getSupportedOfferedCredentialType(); @Override boolean hasValidCredential(final PreparedUpdate update, final UpdateContext updateContext, final Collection<PgpCredential> offeredCredentials, final PgpCredential knownCredential); } | @Test public void setsEffectiveCredential() { final String message = "-----BEGIN PGP SIGNED MESSAGE-----\n" + "Hash: SHA1\n" + "\n" + "inetnum: 213.168.127.96 - 213.168.127.10\n" + "netname: NETNAME\n" + "descr: Description\n" + "country: DE\n" + "admin-c: TEST-RIPE\n" + "tech-c: TEST-RIPE\n" + "status: ASSIGNED PA\n" + "mnt-by: TEST-MNT\n" + "mnt-lower: TEST-MNT\n" + "source: RIPE\n" + "delete: reason\n" + "-----BEGIN PGP SIGNATURE-----\n" + "Version: GnuPG v1\n" + "Comment: GPGTools - http: "\n" + "iQEcBAEBAgAGBQJWTc5TAAoJELvMuy1XY5UNorkIAJsWhjbTcPBLCtug50Hkp0ty\n" + "6hMMVWfIS92fGFzpUKkS3fTnUXkTwsaF0+KQRSHEa6pobMXsP5MCl0SPJaVY4FTz\n" + "CtlpTHQ1avld/o281Y44wGmN/JFcGml8cnpY9/wseNS2OogemJ1ZQdd9Y4zNuCNX\n" + "YS5y2jXLQyuLEzmhg423+b4IqeVZBHdWX43tituzk5phy9U2ZuVAnxLQWvNt0QZC\n" + "v6g0Rig345U3rn0aRCAAFz6C/Al1QbRt5dsH3vQ/lQfiCBoR0A1x9ttsUkB7oCdJ\n" + "P4eeAXVVIZIqCPKBmNo2fRoDJW5Ly1YEAIASp1pjh0h/kDfJwPQc+mqOQ1CRwgQ=\n" + "=KPdC\n" + "-----END PGP SIGNATURE-----"; final PgpCredential offeredCredential = PgpCredential.createOfferedCredential(message, Charset.forName("ISO-8859-7")); final PgpCredential knownCredential = PgpCredential.createKnownCredential("PGPKEY-5763950D"); final Update update = createUpdate(); when(preparedUpdate.getUpdate()).thenReturn(update); when(rpslObjectDao.getByKey(ObjectType.KEY_CERT, KEYCERT_OBJECT.getKey().toString())).thenReturn(KEYCERT_OBJECT); subject.hasValidCredential(preparedUpdate, updateContext, Sets.newHashSet(offeredCredential), knownCredential); MatcherAssert.assertThat(update.getEffectiveCredential(), Is.is(knownCredential.getKeyId())); MatcherAssert.assertThat(update.getEffectiveCredentialType(), Is.is(Update.EffectiveCredentialType.PGP)); }
@Test public void authenticateSignatureVerifyFailed() throws Exception { final PgpCredential offeredCredential = PgpCredential.createOfferedCredential("" + "-----BEGIN PGP SIGNED MESSAGE-----\n" + "Hash: SHA1\n\n" + "inetnum: 213.168.127.96 - 213.168.127.103\n" + "-----BEGIN PGP SIGNATURE-----\n" + "Version: GnuPG v1.4.11 (MingW32) - WinPT 1.4.3\n" + "Charset: UTF-8\n" + "Comment: GnuPT 2.7.2\n\n" + "iEYEARECAAYFAk+r2BgACgkQesVNFxdpXQoLPQCgq4dt/+PymmQZ8/AX+0HJfbGL\n" + "LEwAn2zxSKmMKSLZVbRLxwgVhDQGn+5o\n" + "=g9vN\n" + "-----END PGP SIGNATURE-----\n"); final PgpCredential knownCredential = PgpCredential.createKnownCredential("PGPKEY-5763950D"); when(rpslObjectDao.getByKey(ObjectType.KEY_CERT, KEYCERT_OBJECT.getKey().toString())).thenReturn(KEYCERT_OBJECT); assertThat(subject.hasValidCredential(preparedUpdate, updateContext, Sets.newHashSet(offeredCredential), knownCredential), is(false)); }
@Test public void authenticateKeycertNotFound() throws Exception { final String message = "-----BEGIN PGP SIGNED MESSAGE-----\n" + "Hash: SHA1\n" + "\n" + "inetnum: 213.168.127.96 - 213.168.127.10\n" + "netname: NETNAME\n" + "descr: Description\n" + "country: DE\n" + "admin-c: TEST-RIPE\n" + "tech-c: TEST-RIPE\n" + "status: ASSIGNED PA\n" + "mnt-by: TEST-MNT\n" + "mnt-lower: TEST-MNT\n" + "source: RIPE\n" + "delete: reason\n" + "-----BEGIN PGP SIGNATURE-----\n" + "Version: GnuPG v1\n" + "Comment: GPGTools - http: "\n" + "iQEcBAEBAgAGBQJWTc9CAAoJELvMuy1XY5UNl2oH/2i2JeUvWsrOF/FAxJsvCUMG\n" + "4KqGWJKb1/Sdgp3NJbtrqoZo54+vdI3f0Oqb6q5nspTQJntfA0uq08GFbwcOHA5T\n" + "9fgyh0BVE/OFNUY336r+Gr8Sf9sfLWVgAIUNhe5hyUeoqSD+zcp0buYE/HFLp4Yh\n" + "EVoOSHSGdSpRtkErE3eMYEjYCle7zJhC3MDnauWYYHQzZVJEvQ8mnEi3fZd+OetL\n" + "XnngoRCUa3z3J8tFx0GYNNxP+YA24+gJf+BuJqxX86N0Nua8ZZqzR+AkbAffvXwv\n" + "HR3C5Mn2WOXspKRfdevzV34k4x/SzqFa1qGoF62AKmY5pLMX8XSvU4WV4zjOEDU=\n" + "=UgWC\n" + "-----END PGP SIGNATURE-----"; final PgpCredential offeredCredential = PgpCredential.createOfferedCredential(message); final PgpCredential knownCredential = PgpCredential.createKnownCredential("PGPKEY-5763950D"); when(rpslObjectDao.getByKey(ObjectType.KEY_CERT, KEYCERT_OBJECT.getKey().toString())).thenThrow(new EmptyResultDataAccessException(1)); assertThat(subject.hasValidCredential(preparedUpdate, updateContext, Sets.newHashSet(offeredCredential), knownCredential), is(false)); }
@Test public void authenticateKnownCredentialIsInvalid() { final String message = "-----BEGIN PGP SIGNED MESSAGE-----\n" + "Hash: SHA1\n" + "\n" + "inetnum: 213.168.127.96 - 213.168.127.10\n" + "netname: NETNAME\n" + "descr: Description\n" + "country: DE\n" + "admin-c: TEST-RIPE\n" + "tech-c: TEST-RIPE\n" + "status: ASSIGNED PA\n" + "mnt-by: TEST-MNT\n" + "mnt-lower: TEST-MNT\n" + "source: RIPE\n" + "delete: reason\n" + "-----BEGIN PGP SIGNATURE-----\n" + "Version: GnuPG v1\n" + "Comment: GPGTools - http: "\n" + "iQEcBAEBAgAGBQJWTdB6AAoJELvMuy1XY5UN96QIAJjssbJrKuJvWmgq/iTYjHYz\n" + "iq3qJGprdxM0G+OErsydLmG5R7BhW6aLmV/H07Ap84T9KUniGm+sWgAHJdC0Eb/n\n" + "cf+8sC7hy5Fkmwabam52Ncr+c4mEuR7Tt2s0bfm2x+IgFb/doMoJjCydYk5FQKL/\n" + "QzhgR3whwhftsrSgj2MAD2VDVo7HsvD1Otp/hVLISdnPQuR6i9wRp7gipn+QSdp/\n" + "PBK/UzdvUGItTM/wCoekEcwh41plq7VepL6rbA2NXe9x65rvMprEhL0ulQVP8YXZ\n" + "9LF/bGg8YGezpktt8iFnLKsOCek74mSdVi70xTNsc4sq9mNfdBXrsZstNHvDJ+E=\n" + "=Pr87\n" + "-----END PGP SIGNATURE-----"; final PgpCredential offeredCredential = PgpCredential.createOfferedCredential(message); final PgpCredential knownCredential = PgpCredential.createKnownCredential("PGPKEY-5763950D"); final RpslObject emptyKeycertObject = new RpslObjectBuilder(KEYCERT_OBJECT).removeAttributeType(AttributeType.CERTIF).get(); when(rpslObjectDao.getByKey(ObjectType.KEY_CERT, emptyKeycertObject.getKey().toString())).thenReturn(emptyKeycertObject); assertThat(subject.hasValidCredential(preparedUpdate, updateContext, Sets.newHashSet(offeredCredential), knownCredential), is(false)); } |
TimestampAttributeGenerator extends AttributeGenerator { @Override public RpslObject generateAttributes(final RpslObject originalObject, final RpslObject updatedObject, final Update update, final UpdateContext updateContext) { final Action action = updateContext.getAction(update); if (action == Action.CREATE || action == Action.MODIFY || action == Action.DELETE) { final RpslObjectBuilder builder = new RpslObjectBuilder(updatedObject); boolean addWarningsFlag = !updateContext.getPreparedUpdate(update).getOverrideOptions().isSkipLastModified(); generateTimestampAttributes(builder, originalObject, updatedObject, update, updateContext, addWarningsFlag); return builder.get(); } return updatedObject; } @Autowired TimestampAttributeGenerator(final DateTimeProvider dateTimeProvider); @Override RpslObject generateAttributes(final RpslObject originalObject, final RpslObject updatedObject, final Update update, final UpdateContext updateContext); } | @Test public void create_input_has_no_timestamps() { testDateTimeProvider.setTime(actionTime()); when(updateContext.getAction(update)).thenReturn(Action.CREATE); final RpslObject input = TEMPLATE; final RpslObject updatedObject = subject.generateAttributes(null, input, update, updateContext); assertThat(updatedObject.findAttribute(AttributeType.CREATED).getValue(), is(TIMESTAMP_STRING_ACTION)); assertThat(updatedObject.findAttribute(AttributeType.LAST_MODIFIED).getValue(), is(TIMESTAMP_STRING_ACTION)); testHelper.assertNoMessages(); }
@Test public void create_input_has_wrong_timestamps() { testDateTimeProvider.setTime(actionTime()); when(updateContext.getAction(update)).thenReturn(Action.CREATE); when(overrideOptions.isSkipLastModified()).thenReturn(false); final RpslObject input = new RpslObjectBuilder(TEMPLATE) .addAttributeSorted(new RpslAttribute(AttributeType.CREATED, TIMESTAMP_STRING_PAST)) .addAttributeSorted(new RpslAttribute(AttributeType.LAST_MODIFIED, TIMESTAMP_STRING_PAST)) .get(); final RpslObject updatedObject = subject.generateAttributes(null, input, update, updateContext); assertThat(updatedObject.findAttribute(AttributeType.CREATED).getValue(), is(TIMESTAMP_STRING_ACTION)); assertThat(updatedObject.findAttribute(AttributeType.LAST_MODIFIED).getValue(), is(TIMESTAMP_STRING_ACTION)); testHelper.assertAttributeMessage(updatedObject.findAttribute(AttributeType.CREATED), ValidationMessages.suppliedAttributeReplacedWithGeneratedValue(AttributeType.CREATED)); testHelper.assertAttributeMessage(updatedObject.findAttribute(AttributeType.LAST_MODIFIED), ValidationMessages.suppliedAttributeReplacedWithGeneratedValue(AttributeType.LAST_MODIFIED)); }
@Test public void create_input_has_double_timestamps() { testDateTimeProvider.setTime(actionTime()); when(updateContext.getAction(update)).thenReturn(Action.CREATE); when(overrideOptions.isSkipLastModified()).thenReturn(false); final RpslObject input = new RpslObjectBuilder(TEMPLATE) .addAttributeSorted(new RpslAttribute(AttributeType.CREATED, TIMESTAMP_STRING_PAST)) .addAttributeSorted(new RpslAttribute(AttributeType.CREATED, TIMESTAMP_STRING_PAST)) .addAttributeSorted(new RpslAttribute(AttributeType.LAST_MODIFIED, TIMESTAMP_STRING_PAST)) .addAttributeSorted(new RpslAttribute(AttributeType.LAST_MODIFIED, TIMESTAMP_STRING_PAST)) .get(); final RpslObject updatedObject = subject.generateAttributes(null, input, update, updateContext); assertThat(updatedObject.findAttribute(AttributeType.CREATED).getValue(), is(TIMESTAMP_STRING_ACTION)); assertThat(updatedObject.findAttribute(AttributeType.LAST_MODIFIED).getValue(), is(TIMESTAMP_STRING_ACTION)); testHelper.assertAttributeMessage(updatedObject.findAttribute(AttributeType.CREATED), ValidationMessages.suppliedAttributeReplacedWithGeneratedValue(AttributeType.CREATED), 2); testHelper.assertAttributeMessage(updatedObject.findAttribute(AttributeType.LAST_MODIFIED), ValidationMessages.suppliedAttributeReplacedWithGeneratedValue(AttributeType.LAST_MODIFIED), 2); }
@Test public void create_input_has_right_timestamps() { testDateTimeProvider.setTime(actionTime()); when(updateContext.getAction(update)).thenReturn(Action.CREATE); when(overrideOptions.isSkipLastModified()).thenReturn(false); final RpslObject input = new RpslObjectBuilder(TEMPLATE) .addAttributeSorted(new RpslAttribute(AttributeType.CREATED, TIMESTAMP_STRING_ACTION)) .addAttributeSorted(new RpslAttribute(AttributeType.LAST_MODIFIED, TIMESTAMP_STRING_ACTION)) .get(); final RpslObject updatedObject = subject.generateAttributes(null, input, update, updateContext); assertThat(updatedObject.findAttribute(AttributeType.CREATED).getValue(), is(TIMESTAMP_STRING_ACTION)); assertThat(updatedObject.findAttribute(AttributeType.LAST_MODIFIED).getValue(), is(TIMESTAMP_STRING_ACTION)); testHelper.assertNoMessages(); }
@Test public void modify_original_has_no_timestamps_input_has_no_timestamps() { testDateTimeProvider.setTime(actionTime()); when(updateContext.getAction(update)).thenReturn(Action.MODIFY); when(overrideOptions.isSkipLastModified()).thenReturn(false); final RpslObject original = TEMPLATE; final RpslObject input = TEMPLATE; final RpslObject updatedObject = subject.generateAttributes(original, input, update, updateContext); assertThat(updatedObject.containsAttribute(AttributeType.CREATED), is(false)); assertThat(updatedObject.findAttribute(AttributeType.LAST_MODIFIED).getValue(), is(TIMESTAMP_STRING_ACTION)); testHelper.assertNoMessages(); }
@Test public void modify_original_has_timestamps_input_has_no_timestamps() { testDateTimeProvider.setTime(actionTime()); when(updateContext.getAction(update)).thenReturn(Action.MODIFY); when(overrideOptions.isSkipLastModified()).thenReturn(false); final RpslObject original = new RpslObjectBuilder(TEMPLATE) .addAttributeSorted(new RpslAttribute(AttributeType.CREATED, TIMESTAMP_STRING_PAST)) .addAttributeSorted(new RpslAttribute(AttributeType.LAST_MODIFIED, TIMESTAMP_STRING_PAST)) .get(); final RpslObject input = TEMPLATE; final RpslObject updatedObject = subject.generateAttributes(original, input, update, updateContext); assertThat(updatedObject.findAttribute(AttributeType.CREATED).getValue(), is(TIMESTAMP_STRING_PAST)); assertThat(updatedObject.findAttribute(AttributeType.LAST_MODIFIED).getValue(), is(TIMESTAMP_STRING_ACTION)); testHelper.assertNoMessages(); }
@Ignore("TP: remove defensive code. all attributes have timestamps") @Test public void modify_original_has_no_timestamps_input_has_wrong_timestamps() { testDateTimeProvider.setTime(actionTime()); when(updateContext.getAction(update)).thenReturn(Action.MODIFY); when(overrideOptions.isSkipLastModified()).thenReturn(false); final RpslObject input = new RpslObjectBuilder(TEMPLATE) .addAttributeSorted(new RpslAttribute(AttributeType.CREATED, TIMESTAMP_STRING_OTHER)) .addAttributeSorted(new RpslAttribute(AttributeType.LAST_MODIFIED, TIMESTAMP_STRING_OTHER)) .get(); final RpslObject updatedObject = subject.generateAttributes(TEMPLATE, input, update, updateContext); assertThat(updatedObject.containsAttribute(AttributeType.CREATED), is(false)); assertThat(updatedObject.findAttribute(AttributeType.LAST_MODIFIED).getValue(), is(TIMESTAMP_STRING_ACTION)); testHelper.assertAttributeMessage( ValidationMessages.suppliedAttributeReplacedWithGeneratedValue(AttributeType.CREATED)); testHelper.assertAttributeMessage(updatedObject.findAttribute(AttributeType.LAST_MODIFIED), ValidationMessages.suppliedAttributeReplacedWithGeneratedValue(AttributeType.LAST_MODIFIED)); }
@Test public void modify_original_has_no_timestamps_input_has_right_timestamps() { testDateTimeProvider.setTime(actionTime()); when(updateContext.getAction(update)).thenReturn(Action.MODIFY); when(overrideOptions.isSkipLastModified()).thenReturn(false); final RpslObject original = TEMPLATE; final RpslObject input = new RpslObjectBuilder(TEMPLATE) .addAttributeSorted(new RpslAttribute(AttributeType.LAST_MODIFIED, TIMESTAMP_STRING_ACTION)) .get(); final RpslObject updatedObject = subject.generateAttributes(original, input, update, updateContext); assertThat(updatedObject.containsAttribute(AttributeType.CREATED), is(false)); assertThat(updatedObject.findAttribute(AttributeType.LAST_MODIFIED).getValue(), is(TIMESTAMP_STRING_ACTION)); testHelper.assertNoMessages(); }
@Test public void modify_original_has_timestamps_input_has_wrong_timestamps() { testDateTimeProvider.setTime(actionTime()); when(updateContext.getAction(update)).thenReturn(Action.MODIFY); when(overrideOptions.isSkipLastModified()).thenReturn(false); final RpslObject original = new RpslObjectBuilder(TEMPLATE) .addAttributeSorted(new RpslAttribute(AttributeType.CREATED, TIMESTAMP_STRING_PAST)) .addAttributeSorted(new RpslAttribute(AttributeType.LAST_MODIFIED, TIMESTAMP_STRING_PAST)) .get(); final RpslObject input = new RpslObjectBuilder(TEMPLATE) .addAttributeSorted(new RpslAttribute(AttributeType.CREATED, TIMESTAMP_STRING_OTHER)) .addAttributeSorted(new RpslAttribute(AttributeType.LAST_MODIFIED, TIMESTAMP_STRING_OTHER)) .get(); final RpslObject updatedObject = subject.generateAttributes(original, input, update, updateContext); assertThat(updatedObject.findAttribute(AttributeType.CREATED).getValue(), is(TIMESTAMP_STRING_PAST)); assertThat(updatedObject.findAttribute(AttributeType.LAST_MODIFIED).getValue(), is(TIMESTAMP_STRING_ACTION)); testHelper.assertAttributeMessage(updatedObject.findAttribute(AttributeType.CREATED), ValidationMessages.suppliedAttributeReplacedWithGeneratedValue(AttributeType.CREATED)); testHelper.assertAttributeMessage(updatedObject.findAttribute(AttributeType.LAST_MODIFIED), ValidationMessages.suppliedAttributeReplacedWithGeneratedValue(AttributeType.LAST_MODIFIED)); }
@Test public void modify_original_has_timestamps_input_has_right_timestamps() { testDateTimeProvider.setTime(actionTime()); when(updateContext.getAction(update)).thenReturn(Action.MODIFY); when(overrideOptions.isSkipLastModified()).thenReturn(false); final RpslObject original = new RpslObjectBuilder(TEMPLATE) .addAttributeSorted(new RpslAttribute(AttributeType.CREATED, TIMESTAMP_STRING_PAST)) .addAttributeSorted(new RpslAttribute(AttributeType.LAST_MODIFIED, TIMESTAMP_STRING_PAST)) .get(); final RpslObject input = new RpslObjectBuilder(TEMPLATE) .addAttributeSorted(new RpslAttribute(AttributeType.CREATED, TIMESTAMP_STRING_PAST)) .addAttributeSorted(new RpslAttribute(AttributeType.LAST_MODIFIED, TIMESTAMP_STRING_ACTION)) .get(); final RpslObject updatedObject = subject.generateAttributes(original, input, update, updateContext); assertThat(updatedObject.findAttribute(AttributeType.CREATED).getValue(), is(TIMESTAMP_STRING_PAST)); assertThat(updatedObject.findAttribute(AttributeType.LAST_MODIFIED).getValue(), is(TIMESTAMP_STRING_ACTION)); testHelper.assertNoMessages(); }
@Test public void delete_original_has_no_timestamps_input_has_no_timestamps() { testDateTimeProvider.setTime(actionTime()); when(updateContext.getAction(update)).thenReturn(Action.DELETE); final RpslObject original = TEMPLATE; final RpslObject input = TEMPLATE; final RpslObject updatedObject = subject.generateAttributes(original, input, update, updateContext); assertThat(updatedObject.containsAttribute(AttributeType.CREATED), is(false)); assertThat(updatedObject.containsAttribute(AttributeType.LAST_MODIFIED), is(false)); testHelper.assertNoMessages(); }
@Test public void delete_original_has_timestamps_input_has_no_timestamps() { testDateTimeProvider.setTime(actionTime()); when(updateContext.getAction(update)).thenReturn(Action.DELETE); final RpslObject original = new RpslObjectBuilder(TEMPLATE) .addAttributeSorted(new RpslAttribute(AttributeType.CREATED, TIMESTAMP_STRING_PAST)) .addAttributeSorted(new RpslAttribute(AttributeType.LAST_MODIFIED, TIMESTAMP_STRING_PAST)) .get(); final RpslObject input = TEMPLATE; final RpslObject updatedObject = subject.generateAttributes(original, input, update, updateContext); assertThat(updatedObject.findAttribute(AttributeType.CREATED).getValue(), is(TIMESTAMP_STRING_PAST)); assertThat(updatedObject.findAttribute(AttributeType.LAST_MODIFIED).getValue(), is(TIMESTAMP_STRING_PAST)); testHelper.assertNoMessages(); }
@Test public void delete_original_has_timestamps_input_has_wrong_timestamps() { testDateTimeProvider.setTime(actionTime()); when(updateContext.getAction(update)).thenReturn(Action.DELETE); final RpslObject original = new RpslObjectBuilder(TEMPLATE) .addAttributeSorted(new RpslAttribute(AttributeType.CREATED, TIMESTAMP_STRING_PAST)) .addAttributeSorted(new RpslAttribute(AttributeType.LAST_MODIFIED, TIMESTAMP_STRING_PAST)) .get(); final RpslObject input = new RpslObjectBuilder(TEMPLATE) .addAttributeSorted(new RpslAttribute(AttributeType.CREATED, TIMESTAMP_STRING_OTHER)) .addAttributeSorted(new RpslAttribute(AttributeType.LAST_MODIFIED, TIMESTAMP_STRING_OTHER)) .get(); final RpslObject updatedObject = subject.generateAttributes(original, input, update, updateContext); assertThat(updatedObject.findAttribute(AttributeType.CREATED).getValue(), is(TIMESTAMP_STRING_PAST)); assertThat(updatedObject.findAttribute(AttributeType.LAST_MODIFIED).getValue(), is(TIMESTAMP_STRING_PAST)); testHelper.assertAttributeMessage(updatedObject.findAttribute(AttributeType.CREATED), ValidationMessages.suppliedAttributeReplacedWithGeneratedValue(AttributeType.CREATED)); testHelper.assertAttributeMessage(updatedObject.findAttribute(AttributeType.LAST_MODIFIED), ValidationMessages.suppliedAttributeReplacedWithGeneratedValue(AttributeType.LAST_MODIFIED)); }
@Test public void delete_original_has_timestamps_input_has_right_timestamps() { testDateTimeProvider.setTime(actionTime()); when(updateContext.getAction(update)).thenReturn(Action.DELETE); final RpslObject original = new RpslObjectBuilder(TEMPLATE) .addAttributeSorted(new RpslAttribute(AttributeType.CREATED, TIMESTAMP_STRING_PAST)) .addAttributeSorted(new RpslAttribute(AttributeType.LAST_MODIFIED, TIMESTAMP_STRING_PAST)) .get(); final RpslObject input = new RpslObjectBuilder(TEMPLATE) .addAttributeSorted(new RpslAttribute(AttributeType.CREATED, TIMESTAMP_STRING_PAST)) .addAttributeSorted(new RpslAttribute(AttributeType.LAST_MODIFIED, TIMESTAMP_STRING_PAST)) .get(); final RpslObject updatedObject = subject.generateAttributes(original, input, update, updateContext); assertThat(updatedObject.findAttribute(AttributeType.CREATED).getValue(), is(TIMESTAMP_STRING_PAST)); assertThat(updatedObject.findAttribute(AttributeType.LAST_MODIFIED).getValue(), is(TIMESTAMP_STRING_PAST)); testHelper.assertNoMessages(); }
@Ignore("TP: remove defensive code. all attributes have timestamps") @Test public void delete_original_no_timestamps_input_has_wrong_timestamps() { testDateTimeProvider.setTime(actionTime()); when(updateContext.getAction(update)).thenReturn(Action.DELETE); final RpslObject original = TEMPLATE; final RpslObject input = new RpslObjectBuilder(TEMPLATE) .addAttributeSorted(new RpslAttribute(AttributeType.CREATED, TIMESTAMP_STRING_OTHER)) .addAttributeSorted(new RpslAttribute(AttributeType.LAST_MODIFIED, TIMESTAMP_STRING_OTHER)) .get(); final RpslObject updatedObject = subject.generateAttributes(original, input, update, updateContext); assertThat(updatedObject.containsAttribute(AttributeType.CREATED), is(false)); assertThat(updatedObject.containsAttribute(AttributeType.LAST_MODIFIED), is(false)); testHelper.assertAttributeMessage( ValidationMessages.suppliedAttributeReplacedWithGeneratedValue(AttributeType.CREATED)); testHelper.assertAttributeMessage( ValidationMessages.suppliedAttributeReplacedWithGeneratedValue(AttributeType.LAST_MODIFIED)); }
@Ignore("TP: remove defensive code. all attributes have timestamps") @Test public void delete_original_no_timestamps_input_has_right_timestamps() { testDateTimeProvider.setTime(actionTime()); when(updateContext.getAction(update)).thenReturn(Action.DELETE); final RpslObject input = new RpslObjectBuilder(TEMPLATE) .addAttributeSorted(new RpslAttribute(AttributeType.CREATED, TIMESTAMP_STRING_PAST)) .addAttributeSorted(new RpslAttribute(AttributeType.LAST_MODIFIED, TIMESTAMP_STRING_PAST)) .get(); final RpslObject updatedObject = subject.generateAttributes(TEMPLATE, input, update, updateContext); assertThat(updatedObject.containsAttribute(AttributeType.CREATED), is(false)); assertThat(updatedObject.containsAttribute(AttributeType.LAST_MODIFIED), is(false)); testHelper.assertAttributeMessage( ValidationMessages.suppliedAttributeReplacedWithGeneratedValue(AttributeType.CREATED)); testHelper.assertAttributeMessage( ValidationMessages.suppliedAttributeReplacedWithGeneratedValue(AttributeType.LAST_MODIFIED)); }
@Test public void create_input_has_no_timestamps_skipLastModified() { testDateTimeProvider.setTime(actionTime()); when(overrideOptions.isSkipLastModified()).thenReturn(true); when(updateContext.getAction(update)).thenReturn(Action.CREATE); final RpslObject input = new RpslObjectBuilder(TEMPLATE) .addAttributeSorted(new RpslAttribute(AttributeType.CREATED, TIMESTAMP_STRING_PAST)) .addAttributeSorted(new RpslAttribute(AttributeType.LAST_MODIFIED, TIMESTAMP_STRING_PAST)) .get(); final RpslObject updatedObject = subject.generateAttributes(null, input, update, updateContext); assertThat(updatedObject.findAttribute(AttributeType.CREATED).getValue(), is(TIMESTAMP_STRING_ACTION)); assertThat(updatedObject.findAttribute(AttributeType.LAST_MODIFIED).getValue(), is(TIMESTAMP_STRING_ACTION)); testHelper.assertNoMessages(); }
@Test public void modify_original_has_timestamps_input_has_no_timestamps_skipLastModified() { testDateTimeProvider.setTime(actionTime()); when(updateContext.getAction(update)).thenReturn(Action.MODIFY); when(overrideOptions.isSkipLastModified()).thenReturn(true); final RpslObject original = new RpslObjectBuilder(TEMPLATE) .addAttributeSorted(new RpslAttribute(AttributeType.CREATED, TIMESTAMP_STRING_PAST)) .addAttributeSorted(new RpslAttribute(AttributeType.LAST_MODIFIED, TIMESTAMP_STRING_PAST)) .get(); final RpslObject input = TEMPLATE; final RpslObject updatedObject = subject.generateAttributes(original, input, update, updateContext); assertThat(updatedObject.findAttribute(AttributeType.CREATED).getValue(), is(TIMESTAMP_STRING_PAST)); assertThat(updatedObject.findAttribute(AttributeType.LAST_MODIFIED).getValue(), is(TIMESTAMP_STRING_PAST)); testHelper.assertNoMessages(); }
@Test public void modify_original_has_timestamps_input_has_wrong_timestamps_skipLastModified() { testDateTimeProvider.setTime(actionTime()); when(updateContext.getAction(update)).thenReturn(Action.MODIFY); when(overrideOptions.isSkipLastModified()).thenReturn(true); final RpslObject original = new RpslObjectBuilder(TEMPLATE) .addAttributeSorted(new RpslAttribute(AttributeType.CREATED, TIMESTAMP_STRING_PAST)) .addAttributeSorted(new RpslAttribute(AttributeType.LAST_MODIFIED, TIMESTAMP_STRING_PAST)) .get(); final RpslObject input = new RpslObjectBuilder(TEMPLATE) .addAttributeSorted(new RpslAttribute(AttributeType.CREATED, TIMESTAMP_STRING_OTHER)) .addAttributeSorted(new RpslAttribute(AttributeType.LAST_MODIFIED, TIMESTAMP_STRING_OTHER)) .get(); final RpslObject updatedObject = subject.generateAttributes(original, input, update, updateContext); assertThat(updatedObject.findAttribute(AttributeType.CREATED).getValue(), is(TIMESTAMP_STRING_PAST)); assertThat(updatedObject.findAttribute(AttributeType.LAST_MODIFIED).getValue(), is(TIMESTAMP_STRING_PAST)); testHelper.assertNoMessages(); }
@Test public void modify_original_has_timestamps_input_has_right_timestamps_skipLastModified() { testDateTimeProvider.setTime(actionTime()); when(updateContext.getAction(update)).thenReturn(Action.MODIFY); when(overrideOptions.isSkipLastModified()).thenReturn(true); final RpslObject original = new RpslObjectBuilder(TEMPLATE) .addAttributeSorted(new RpslAttribute(AttributeType.CREATED, TIMESTAMP_STRING_PAST)) .addAttributeSorted(new RpslAttribute(AttributeType.LAST_MODIFIED, TIMESTAMP_STRING_PAST)) .get(); final RpslObject input = new RpslObjectBuilder(TEMPLATE) .addAttributeSorted(new RpslAttribute(AttributeType.CREATED, TIMESTAMP_STRING_PAST)) .addAttributeSorted(new RpslAttribute(AttributeType.LAST_MODIFIED, TIMESTAMP_STRING_PAST)) .get(); final RpslObject updatedObject = subject.generateAttributes(original, input, update, updateContext); assertThat(updatedObject.findAttribute(AttributeType.CREATED).getValue(), is(TIMESTAMP_STRING_PAST)); assertThat(updatedObject.findAttribute(AttributeType.LAST_MODIFIED).getValue(), is(TIMESTAMP_STRING_PAST)); testHelper.assertNoMessages(); }
@Test public void delete_original_has_timestamps_input_has_no_timestamps_skipLastModified() { testDateTimeProvider.setTime(actionTime()); when(updateContext.getAction(update)).thenReturn(Action.DELETE); when(overrideOptions.isSkipLastModified()).thenReturn(true); final RpslObject original = new RpslObjectBuilder(TEMPLATE) .addAttributeSorted(new RpslAttribute(AttributeType.CREATED, TIMESTAMP_STRING_PAST)) .addAttributeSorted(new RpslAttribute(AttributeType.LAST_MODIFIED, TIMESTAMP_STRING_PAST)) .get(); final RpslObject input = TEMPLATE; final RpslObject updatedObject = subject.generateAttributes(original, input, update, updateContext); assertThat(updatedObject.findAttribute(AttributeType.CREATED).getValue(), is(TIMESTAMP_STRING_PAST)); assertThat(updatedObject.findAttribute(AttributeType.LAST_MODIFIED).getValue(), is(TIMESTAMP_STRING_PAST)); testHelper.assertNoMessages(); } |
KeycertAttributeGenerator extends AttributeGenerator { public RpslObject generateAttributes(final RpslObject originalObject, final Update update, final UpdateContext updateContext) { return generateAttributes(originalObject, originalObject, update, updateContext); } @Autowired KeycertAttributeGenerator(final KeyWrapperFactory keyWrapperFactory); RpslObject generateAttributes(final RpslObject originalObject, final Update update, final UpdateContext updateContext); @Override RpslObject generateAttributes(final RpslObject originalObject, final RpslObject updatedObject, final Update update, final UpdateContext updateContext); } | @Test public void generate_attributes_for_x509_certificate() { final RpslObject keycert = RpslObject.parse( "key-cert: X509-1\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"); when(keyWrapperFactory.createKeyWrapper(keycert, update, updateContext)).thenReturn(X509CertificateWrapper.parse(keycert)); final RpslObject updatedObject = subject.generateAttributes(keycert, update, updateContext); validateAttributeType(updatedObject, AttributeType.METHOD, "X509"); validateAttributeType(updatedObject, AttributeType.FINGERPR, "E7:0F:3B:D4:2F:DD:F5:84:3F:4C:D2:98:78:F3:10:3D"); validateAttributeType(updatedObject, AttributeType.OWNER, "/C=NL/O=RIPE NCC/OU=Members/CN=zz.example.denis/[email protected]"); validateMessages(); }
@Test public void generate_attributes_for_pgp_certificate() throws Exception { final RpslObject keycert = RpslObject.parse( "key-cert: PGPKEY-5763950D\n" + "certif: -----BEGIN PGP PUBLIC KEY BLOCK-----\n" + "certif: Version: GnuPG v1.4.12 (Darwin)\n" + "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-----" + "mnt-by: UPD-MNT\n" + "notify: [email protected]\n" + "source: TEST\n"); when(keyWrapperFactory.createKeyWrapper(keycert, update, updateContext)).thenReturn(PgpPublicKeyWrapper.parse(keycert)); final RpslObject updatedObject = subject.generateAttributes(keycert, update, updateContext); validateAttributeType(updatedObject, AttributeType.METHOD, "PGP"); validateAttributeType(updatedObject, AttributeType.FINGERPR, "884F 8E23 69E5 E6F1 9FB3 63F4 BBCC BB2D 5763 950D"); validateAttributeType(updatedObject, AttributeType.OWNER, "[email protected] <[email protected]>"); validateMessages(); }
@Test public void correct_owner_attribute() { RpslObject keycert = RpslObject.parse( "key-cert: PGPKEY-5763950D\n" + "owner: [email protected] <[email protected]>\n" + "certif: -----BEGIN PGP PUBLIC KEY BLOCK-----\n" + "certif: Version: GnuPG v1.4.12 (Darwin)\n" + "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"); when(keyWrapperFactory.createKeyWrapper(keycert, update, updateContext)).thenReturn(PgpPublicKeyWrapper.parse(keycert)); final RpslObject updatedObject = subject.generateAttributes(keycert, update, updateContext); validateAttributeType(updatedObject, AttributeType.METHOD, "PGP"); validateAttributeType(updatedObject, AttributeType.FINGERPR, "884F 8E23 69E5 E6F1 9FB3 63F4 BBCC BB2D 5763 950D"); validateAttributeType(updatedObject, AttributeType.OWNER, "[email protected] <[email protected]>"); }
@Test public void invalid_owner_attribute() { RpslObject keycert = RpslObject.parse( "key-cert: PGPKEY-5763950D\n" + "owner: [email protected] <[email protected]>\n" + "owner: invalid\n" + "certif: -----BEGIN PGP PUBLIC KEY BLOCK-----\n" + "certif: Version: GnuPG v1.4.12 (Darwin)\n" + "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"); when(keyWrapperFactory.createKeyWrapper(keycert, update, updateContext)).thenReturn(PgpPublicKeyWrapper.parse(keycert)); final RpslObject updatedObject = subject.generateAttributes(keycert, update, updateContext); validateAttributeType(updatedObject, AttributeType.METHOD, "PGP"); validateAttributeType(updatedObject, AttributeType.FINGERPR, "884F 8E23 69E5 E6F1 9FB3 63F4 BBCC BB2D 5763 950D"); validateAttributeType(updatedObject, AttributeType.OWNER, "[email protected] <[email protected]>"); validateMessages(ValidationMessages.suppliedAttributeReplacedWithGeneratedValue(AttributeType.OWNER)); }
@Test public void correct_fingerprint_attribute() { RpslObject keycert = RpslObject.parse("" + "key-cert: PGPKEY-5763950D\n" + "fingerpr: 884F 8E23 69E5 E6F1 9FB3 63F4 BBCC BB2D 5763 950D\n" + "certif: -----BEGIN PGP PUBLIC KEY BLOCK-----\n" + "certif: Version: GnuPG v1\n" + "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"); when(keyWrapperFactory.createKeyWrapper(keycert, update, updateContext)).thenReturn(PgpPublicKeyWrapper.parse(keycert)); final RpslObject updatedObject = subject.generateAttributes(keycert, update, updateContext); validateAttributeType(updatedObject, AttributeType.METHOD, "PGP"); validateAttributeType(updatedObject, AttributeType.FINGERPR, "884F 8E23 69E5 E6F1 9FB3 63F4 BBCC BB2D 5763 950D"); validateAttributeType(updatedObject, AttributeType.OWNER, "[email protected] <[email protected]>"); }
@Test public void invalid_fingerprint_attribute() { RpslObject keycert = RpslObject.parse(""+ "key-cert: PGPKEY-5763950D\n" + "owner: [email protected] <[email protected]>\n" + "fingerpr: abcd\n" + "certif: -----BEGIN PGP PUBLIC KEY BLOCK-----\n" + "certif: Version: GnuPG v1.4.12 (Darwin)\n" + "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"); when(keyWrapperFactory.createKeyWrapper(keycert, update, updateContext)).thenReturn(PgpPublicKeyWrapper.parse(keycert)); final RpslObject updatedObject = subject.generateAttributes(keycert, update, updateContext); validateAttributeType(updatedObject, AttributeType.METHOD, "PGP"); validateAttributeType(updatedObject, AttributeType.FINGERPR, "884F 8E23 69E5 E6F1 9FB3 63F4 BBCC BB2D 5763 950D"); validateAttributeType(updatedObject, AttributeType.OWNER, "[email protected] <[email protected]>"); validateMessages(ValidationMessages.suppliedAttributeReplacedWithGeneratedValue(AttributeType.FINGERPR)); }
@Test public void correct_method_attribute() { RpslObject keycert = RpslObject.parse(""+ "key-cert: PGPKEY-5763950D\n" + "owner: [email protected] <[email protected]>\n" + "method: PGP\n" + "certif: -----BEGIN PGP PUBLIC KEY BLOCK-----\n" + "certif: Version: GnuPG v1.4.12 (Darwin)\n" + "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"); when(keyWrapperFactory.createKeyWrapper(keycert, update, updateContext)).thenReturn(PgpPublicKeyWrapper.parse(keycert)); final RpslObject updatedObject = subject.generateAttributes(keycert, update, updateContext); validateAttributeType(updatedObject, AttributeType.METHOD, "PGP"); validateAttributeType(updatedObject, AttributeType.FINGERPR, "884F 8E23 69E5 E6F1 9FB3 63F4 BBCC BB2D 5763 950D"); validateAttributeType(updatedObject, AttributeType.OWNER, "[email protected] <[email protected]>"); }
@Test public void invalid_method_attribute() { RpslObject keycert = RpslObject.parse( "key-cert: PGPKEY-5763950D\n" + "owner: [email protected] <[email protected]>\n" + "method: invalid method\n" + "certif: -----BEGIN PGP PUBLIC KEY BLOCK-----\n" + "certif: Version: GnuPG v1.4.12 (Darwin)\n" + "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"); when(keyWrapperFactory.createKeyWrapper(keycert, update, updateContext)).thenReturn(PgpPublicKeyWrapper.parse(keycert)); final RpslObject updatedObject = subject.generateAttributes(keycert, update, updateContext); validateAttributeType(updatedObject, AttributeType.METHOD, "PGP"); validateAttributeType(updatedObject, AttributeType.FINGERPR, "884F 8E23 69E5 E6F1 9FB3 63F4 BBCC BB2D 5763 950D"); validateAttributeType(updatedObject, AttributeType.OWNER, "[email protected] <[email protected]>"); validateMessages(ValidationMessages.suppliedAttributeReplacedWithGeneratedValue(AttributeType.METHOD)); }
@Test public void invalid_attribute_is_ignored() { RpslObject keycert = RpslObject.parse( "key-cert: PGPKEY-5763950D\n" + "invalid-attribute: invalid\n" + "certif: -----BEGIN PGP PUBLIC KEY BLOCK-----\n" + "certif: Version: GnuPG v1.4.12 (Darwin)\n" + "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"); when(keyWrapperFactory.createKeyWrapper(keycert, update, updateContext)).thenReturn(PgpPublicKeyWrapper.parse(keycert)); final RpslObject updatedObject = subject.generateAttributes(keycert, update, updateContext); validateAttributeType(updatedObject, AttributeType.METHOD, "PGP"); validateAttributeType(updatedObject, AttributeType.FINGERPR, "884F 8E23 69E5 E6F1 9FB3 63F4 BBCC BB2D 5763 950D"); validateAttributeType(updatedObject, AttributeType.OWNER, "[email protected] <[email protected]>"); }
@Test public void public_key_with_multiple_owners() { RpslObject keycert = RpslObject.parse( "key-cert: PGPKEY-5763950D\n" + "owner: invalid\n" + "certif: -----BEGIN PGP PUBLIC KEY BLOCK-----\n" + "certif: Version: GnuPG v1.4.15 (Darwin)\n" + "certif: Comment: GPGTools - http: "certif: \n" + "certif: mI0EUqWQnQEEAMKfJ/wK0TuUxgTbDdE5LjDuoDNTNfGr0iw2fNSlsxNME3bpRKW9\n" + "certif: YjgllY7D0wbx4BIdV7MUOaYMDEEPCkApHNwK256Ve2S4WxLCWpyGMiXECs6r4Fj+\n" + "certif: Bkyc2O4bxuXoQocbnKVOiFI0SPpkX1pa0IJleqAq5cz77zK1Ha5OOMErABEBAAG0\n" + "certif: G0FkbWluIFVzZXIgPGFkbWluQHJpcGUubmV0Poi4BBMBAgAiBQJSpZCdAhsDBgsJ\n" + "certif: CAcDAgYVCAIJCgsEFgIDAQIeAQIXgAAKCRDHIn7s6l+7lIpAA/4lExw9e9L2pSsx\n" + "certif: JsDZe0JqukvI6bipuFWa26brAlef+6NtDJjQWvfLAAEoeDBlBchHZ4tpl1Wiyt3J\n" + "certif: kIyeIYDIbb9e/w+romlDlyTQo+8/U1iAdb+TOGzacgbJoykU6OjaGbuMbWn0bu2S\n" + "certif: cmnH08tu0Ydhj04v5yPaSfEYGBF9ULQgSG9zdG1hc3RlciA8aG9zdG1hc3RlckBy\n" + "certif: aXBlLm5ldD6IuAQTAQIAIgUCUqWRMQIbAwYLCQgHAwIGFQgCCQoLBBYCAwECHgEC\n" + "certif: F4AACgkQxyJ+7Opfu5SCzAQAqoRLx76WWa5AcVKUr5BYt2MCPn695iOJ7/Lcxgtq\n" + "certif: wVx8ItIzd0rW5L5iqrreJBSof9W8WfSkHJuwTIzznDzjZZgYaU8eb7zB/g4VAr7b\n" + "certif: ZcfW0b5+IcUI+W1XNdX1ByYsXFkwp/si9QT0VO2rEf+Nxt8zrZ8sygSTWoTWEBWY\n" + "certif: 1X24jQRSpZCdAQQAz3jzZHoumwM2tpNQjLdbb/agjeH9zDEb2lMQXSdLx+VdQWeN\n" + "certif: +ywh40Z0beMySXC+4e/pTyliGO5OUly75BiYsowWwLRA17AdR7YNHv+e22mTVf0O\n" + "certif: TkrzUAsU5TAA6ObX6NZWIt3XSCyDOB7m5imOO+vyGwp8p6+6tg2h/oKfedMAEQEA\n" + "certif: AYifBBgBAgAJBQJSpZCdAhsMAAoJEMcifuzqX7uUqBcEAJ4g4bzoRXWJJ6vjuT6w\n" + "certif: UgYCXmEcPSZIwwKPauTj3j7QX46T7u2+yb0qeyK+gFgb4e+iua3KNGb9L82xSEYy\n" + "certif: M8BQ5qhoZnUZjU1DvusYcX7g8Pwe7nntlucKXaMc/1Rgsx2Wpolu59uMLHZ7FUUM\n" + "certif: FUJok98LaNd+xfMg7u+8Fpca\n" + "certif: =tiwc\n" + "certif: -----END PGP PUBLIC KEY BLOCK----- \n" + "mnt-by: UPD-MNT\n" + "notify: [email protected]\n" + "source: TEST\n"); when(keyWrapperFactory.createKeyWrapper(keycert, update, updateContext)).thenReturn(PgpPublicKeyWrapper.parse(keycert)); final RpslObject updatedObject = subject.generateAttributes(keycert, update, updateContext); validateAttributeType(updatedObject, AttributeType.METHOD, "PGP"); validateAttributeType(updatedObject, AttributeType.FINGERPR, "FBFD 0527 454D 5880 3484 413F C722 7EEC EA5F BB94"); validateAttributeType(updatedObject, AttributeType.OWNER, "Hostmaster <[email protected]>", "Admin User <[email protected]>"); validateMessages(ValidationMessages.suppliedAttributeReplacedWithGeneratedValue(AttributeType.OWNER)); }
@Test public void unknown_certificate() { final RpslObject keycert = RpslObject.parse("key-cert: unknown"); final RpslObject updatedObject = subject.generateAttributes(keycert, update, updateContext); assertThat(updatedObject.getAttributes(), hasSize(1)); validateMessages(); }
@Test public void person_object_not_updated() { final RpslObject person = RpslObject.parse("person: first last\nnic-hdl: FL-TEST"); final RpslObject updatedObject = subject.generateAttributes(person, update, updateContext); assertThat(updatedObject, is(person)); validateMessages(); } |
AutnumAttributeGenerator extends AttributeGenerator { @Override public RpslObject generateAttributes(final RpslObject originalObject, final RpslObject updatedObject, final Update update, final UpdateContext updateContext) { switch (updatedObject.getType()) { case AUT_NUM: return generateStatus(originalObject, updatedObject, update, updateContext); default: return updatedObject; } } @Autowired AutnumAttributeGenerator(final AuthoritativeResourceData authoritativeResourceData, final SourceContext sourceContext, final LegacyAutnum legacyAutnum); @Override RpslObject generateAttributes(final RpslObject originalObject, final RpslObject updatedObject, final Update update, final UpdateContext updateContext); } | @Test public void generate_other_status_on_create() { final RpslObject autnum = RpslObject.parse("aut-num: AS3333\nmnt-by: TEST-MNT\nsource: RIPE"); final RpslObject result = autnumStatusAttributeGenerator.generateAttributes(null, autnum, update, updateContext); assertThat(result.getValueForAttribute(AttributeType.STATUS), is(CIString.ciString("OTHER"))); }
@Test public void generate_other_status_on_update() { final RpslObject originalObject = RpslObject.parse("aut-num: AS3333\nmnt-by: RIPE-NCC-HM-MNT\nsource: RIPE"); final RpslObject updatedObject = RpslObject.parse("aut-num: AS3333\nremarks: updated\nmnt-by: RIPE-NCC-HM-MNT\nsource: RIPE"); final RpslObject result = autnumStatusAttributeGenerator.generateAttributes(originalObject, updatedObject, update, updateContext); assertThat(result.getValueForAttribute(AttributeType.STATUS), is(CIString.ciString("OTHER"))); } |
SsoTranslator { public RpslObject translateFromCacheAuthToUsername(final UpdateContext updateContext, final RpslObject rpslObject) { return translateAuthFromCache(updateContext, rpslObject); } @Autowired SsoTranslator(final CrowdClient crowdClient); void populateCacheAuthToUsername(final UpdateContext updateContext, final RpslObject rpslObject); void populateCacheAuthToUuid(final UpdateContext updateContext, final Update update); RpslObject translateFromCacheAuthToUuid(final UpdateContext updateContext, final RpslObject rpslObject); RpslObject translateFromCacheAuthToUsername(final UpdateContext updateContext, final RpslObject rpslObject); } | @Test public void translate_to_uuid_username_stored_in_context_already() { final RpslObject object = RpslObject.parse("mntner: TEST-MNT\nauth: SSO [email protected]"); when(updateContext.getSsoTranslationResult("[email protected]")).thenReturn("BBBB-1234-CCCC-DDDD"); final RpslObject result = subject.translateFromCacheAuthToUsername(updateContext, object); assertThat(result, is(RpslObject.parse("mntner: TEST-MNT\nauth: SSO BBBB-1234-CCCC-DDDD"))); } |
RepoScanner { public RepoScanner() { githubUser = System.getProperty("githubUser"); githubToken = System.getProperty("githubToken"); if (githubUser == null || githubToken == null) { String msg = ("To scan GitHub for submissions please provide your username and a valid Personal Access Token.\n" + "Without this the submissions table will be out of date.\n" + "JVM parameters are githubUser and githubToken"); throw new IllegalStateException(msg); } } RepoScanner(); JSONObject getSubmissionsFromRepo(String repoName); } | @Test public void testRepoScanner() throws IOException { try { JSONObject submissions = new RepoScanner() .getSubmissionsFromRepo("bpmn-miwg/bpmn-miwg-test-suite"); System.out.println(submissions); FileUtils.writeStringToFile(new File("target/submissions.json"), submissions.toJSONString()); } catch (Throwable t) { assumeNoException("Assume no GitHub token provided, continuing", t); } } |
ModelInterchangeMojo extends AbstractMojo { public void execute() throws MojoExecutionException { getLog().info("Running BPMN-MIWG test suite..."); if (!outputDirectory.exists()) { outputDirectory.mkdirs(); } try { Collection<String> inputFolders = new LinkedList<String>(); if (!resources.isEmpty()) { for (Resource resource : resources) { String folderName = resource.getDirectory(); inputFolders.add(folderName); } } Collection<AnalysisJob> jobs = BpmnFileScanner .buildListOfAnalysisJobs(new StandardScanParameters(application, null, inputFolders, outputDirectory.getCanonicalPath())); AnalysisFacade.executeAnalysisJobs(jobs, outputDirectory.getAbsolutePath()); } catch (Exception e) { e.printStackTrace(); } try (FileWriter out = new FileWriter(new File(outputDirectory, "submissions.json"))) { JSONObject submissions = new RepoScanner().getSubmissionsFromRepo("bpmn-miwg/bpmn-miwg-test-suite"); submissions.writeJSONString(out); } catch (Exception e) { e.printStackTrace(); } } void execute(); } | @Test public void testMojo() { try { Resource res = new Resource(); res.setDirectory(SRC_TEST_RESOURCES); mojo.resources.add(res); mojo.execute(); System.out .println("Checking expected output exists with base folder: " + TestUtil.REPORT_BASE_FOLDER_NAME); assertTrue(overview.exists()); Document document = docBuilder.parse(overview); XPathExpression xpath = createXpathExpression(" NodeList nodes = (NodeList) xpath.evaluate(document, XPathConstants.NODESET); assertEquals(7, nodes.getLength()); assertHtmlReportsExist(new File(TestUtil.REPORT_BASE_FOLDER_NAME, XmlCompareAnalysisTool.NAME)); assertHtmlReportsExist(new File(TestUtil.REPORT_BASE_FOLDER_NAME, SchemaAnalysisTool.NAME)); assertHtmlReportsExist(new File(TestUtil.REPORT_BASE_FOLDER_NAME, XpathAnalysisTool.NAME)); File xpathResult = new File(TestUtil.REPORT_BASE_FOLDER_NAME + File.separator + XpathAnalysisTool.NAME + File.separator + MavenTestConsts.W4_MODELER_ID + File.separator + MavenTestConsts.W4_MODELER_ID + "-A.1.0-roundtrip.html"); System.out.println("Checking file: " + xpathResult); assertTrue(xpathResult.exists()); document = docBuilder.parse(xpathResult); nodes = (NodeList) xPath.compile( " XPathConstants.NODESET); assertTrue("Did not find result element", nodes.getLength() == 1); nodes = (NodeList) xPath.compile( " .evaluate(document, XPathConstants.NODESET); assertTrue("Did not find tool element", nodes.getLength() == 1); nodes = (NodeList) xPath .compile( " .evaluate(document, XPathConstants.NODESET); assertTrue("Did not find test element", nodes.getLength() >= 1); } catch (Exception e) { e.printStackTrace(); fail(e.getClass() + ":" + e.getMessage()); } }
@Test public void testMojoHandlingSchemaInvalidBpmn() throws XPathExpressionException, SAXException, IOException, MojoExecutionException { Resource res = new Resource(); res.setDirectory("src/test/invalid-resources"); mojo.resources.add(res); mojo.application = "Yaoqiang BPMN Editor 2.2.6"; mojo.execute(); assertTrue(overview.exists()); Document document = docBuilder.parse(overview); XPathExpression xpath = createXpathExpression(" NodeList nodes = (NodeList) xpath.evaluate(document, XPathConstants.NODESET); Node invalidNode = nodes.item(0); assertEquals("2", invalidNode.getAttributes().getNamedItem("data-xsd-finding") .getNodeValue()); } |
DebugWebViewClient extends WebViewClient implements LogControl { @RequiresApi(api = Build.VERSION_CODES.M) @Override public void onReceivedError(final WebView view, final WebResourceRequest request, final WebResourceError error) { logger.onReceivedError(view, request, error); client.onReceivedError(view, request, error); } DebugWebViewClient(); DebugWebViewClient(@NonNull final WebViewClient client); @SuppressWarnings("WeakerAccess") DebugWebViewClient(
@NonNull final WebViewClient client,
@NonNull final DebugWebViewClientLogger logger); @RequiresApi(api = Build.VERSION_CODES.M) @Override void onReceivedError(final WebView view, final WebResourceRequest request, final WebResourceError error); @Override @Deprecated void onReceivedError(final WebView view, final int errorCode, final String description, final String failingUrl); @RequiresApi(api = Build.VERSION_CODES.M) @Override void onReceivedHttpError(final WebView view, final WebResourceRequest request, final WebResourceResponse errorResponse); @Override void onReceivedSslError(final WebView view, final SslErrorHandler handler, final SslError error); @RequiresApi(api = Build.VERSION_CODES.N) @Override boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request); @Override boolean shouldOverrideUrlLoading(WebView view, String url); @Override void onLoadResource(WebView view, String url); @TargetApi(Build.VERSION_CODES.M) @Override void onPageCommitVisible(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Deprecated WebResourceResponse shouldInterceptRequest(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request); @Override @Deprecated @SuppressWarnings("deprecation") //for use with older versions void onTooManyRedirects(WebView view, Message cancelMsg, Message continueMsg); @Override void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm); @Override void onPageStarted(WebView view, String url, Bitmap facIcon); @Override void onPageFinished(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override void onReceivedClientCertRequest(WebView view, ClientCertRequest request); @Override void onFormResubmission(final WebView view, final Message dontResend, final Message resend); @Override void doUpdateVisitedHistory(final WebView view, final String url, final boolean isReload); @Override boolean shouldOverrideKeyEvent(final WebView view, final KeyEvent event); @SuppressWarnings("unused") void onUnhandledInputEvent(final WebView view, final InputEvent event); @Override void onUnhandledKeyEvent(final WebView view, final KeyEvent event); @Override void onScaleChanged(final WebView view, final float oldScale, final float newScale); @Override void onReceivedLoginRequest(final WebView view, final String realm, final String account, final String args); @RequiresApi(api = Build.VERSION_CODES.O) @Override boolean onRenderProcessGone(final WebView view, final RenderProcessGoneDetail detail); @RequiresApi(api = Build.VERSION_CODES.O_MR1) @Override void onSafeBrowsingHit(final WebView view, final WebResourceRequest request, final int threatType, final SafeBrowsingResponse callback); @Override boolean isLoggingEnabled(); @Override void setLoggingEnabled(final boolean enabled); @Override boolean isLogKeyEventsEnabled(); @Override void setLogKeyEventsEnabled(final boolean enabled); } | @Test public void onReceivedError() { final int code = 500; final String message = "foo"; final String url = "bar"; debugClient.onReceivedError(webView, code, message, url); verifyLogger().onReceivedError(webView, code, message, url); verifyWrappedClient().onReceivedError(webView, code, message, url); }
@Test public void onReceivedError_api23() { final WebResourceRequest request = Mockito.mock(WebResourceRequest.class); final WebResourceError error = Mockito.mock(WebResourceError.class); debugClient.onReceivedError(webView, request, error); verifyLogger().onReceivedError(webView, request, error); verifyWrappedClient().onReceivedError(webView, request, error); } |
DebugWebViewClient extends WebViewClient implements LogControl { @Override @Deprecated @SuppressWarnings("deprecation") public void onTooManyRedirects(WebView view, Message cancelMsg, Message continueMsg) { logger.onTooManyRedirects(view, cancelMsg, continueMsg); client.onTooManyRedirects(view, cancelMsg, continueMsg); } DebugWebViewClient(); DebugWebViewClient(@NonNull final WebViewClient client); @SuppressWarnings("WeakerAccess") DebugWebViewClient(
@NonNull final WebViewClient client,
@NonNull final DebugWebViewClientLogger logger); @RequiresApi(api = Build.VERSION_CODES.M) @Override void onReceivedError(final WebView view, final WebResourceRequest request, final WebResourceError error); @Override @Deprecated void onReceivedError(final WebView view, final int errorCode, final String description, final String failingUrl); @RequiresApi(api = Build.VERSION_CODES.M) @Override void onReceivedHttpError(final WebView view, final WebResourceRequest request, final WebResourceResponse errorResponse); @Override void onReceivedSslError(final WebView view, final SslErrorHandler handler, final SslError error); @RequiresApi(api = Build.VERSION_CODES.N) @Override boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request); @Override boolean shouldOverrideUrlLoading(WebView view, String url); @Override void onLoadResource(WebView view, String url); @TargetApi(Build.VERSION_CODES.M) @Override void onPageCommitVisible(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Deprecated WebResourceResponse shouldInterceptRequest(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request); @Override @Deprecated @SuppressWarnings("deprecation") //for use with older versions void onTooManyRedirects(WebView view, Message cancelMsg, Message continueMsg); @Override void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm); @Override void onPageStarted(WebView view, String url, Bitmap facIcon); @Override void onPageFinished(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override void onReceivedClientCertRequest(WebView view, ClientCertRequest request); @Override void onFormResubmission(final WebView view, final Message dontResend, final Message resend); @Override void doUpdateVisitedHistory(final WebView view, final String url, final boolean isReload); @Override boolean shouldOverrideKeyEvent(final WebView view, final KeyEvent event); @SuppressWarnings("unused") void onUnhandledInputEvent(final WebView view, final InputEvent event); @Override void onUnhandledKeyEvent(final WebView view, final KeyEvent event); @Override void onScaleChanged(final WebView view, final float oldScale, final float newScale); @Override void onReceivedLoginRequest(final WebView view, final String realm, final String account, final String args); @RequiresApi(api = Build.VERSION_CODES.O) @Override boolean onRenderProcessGone(final WebView view, final RenderProcessGoneDetail detail); @RequiresApi(api = Build.VERSION_CODES.O_MR1) @Override void onSafeBrowsingHit(final WebView view, final WebResourceRequest request, final int threatType, final SafeBrowsingResponse callback); @Override boolean isLoggingEnabled(); @Override void setLoggingEnabled(final boolean enabled); @Override boolean isLogKeyEventsEnabled(); @Override void setLogKeyEventsEnabled(final boolean enabled); } | @Test @SuppressWarnings("deprecation") public void onTooManyRedirects() { final Message cancelMsg = Mockito.mock(Message.class); final Message continueMsg = Mockito.mock(Message.class); debugClient.onTooManyRedirects(webView, cancelMsg, continueMsg); verifyLogger().onTooManyRedirects(webView, cancelMsg, continueMsg); verifyWrappedClient().onTooManyRedirects(webView, cancelMsg, continueMsg); } |
DebugWebViewClient extends WebViewClient implements LogControl { @Override public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) { logger.onReceivedHttpAuthRequest(view, handler, host, realm); client.onReceivedHttpAuthRequest(view, handler, host, realm); } DebugWebViewClient(); DebugWebViewClient(@NonNull final WebViewClient client); @SuppressWarnings("WeakerAccess") DebugWebViewClient(
@NonNull final WebViewClient client,
@NonNull final DebugWebViewClientLogger logger); @RequiresApi(api = Build.VERSION_CODES.M) @Override void onReceivedError(final WebView view, final WebResourceRequest request, final WebResourceError error); @Override @Deprecated void onReceivedError(final WebView view, final int errorCode, final String description, final String failingUrl); @RequiresApi(api = Build.VERSION_CODES.M) @Override void onReceivedHttpError(final WebView view, final WebResourceRequest request, final WebResourceResponse errorResponse); @Override void onReceivedSslError(final WebView view, final SslErrorHandler handler, final SslError error); @RequiresApi(api = Build.VERSION_CODES.N) @Override boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request); @Override boolean shouldOverrideUrlLoading(WebView view, String url); @Override void onLoadResource(WebView view, String url); @TargetApi(Build.VERSION_CODES.M) @Override void onPageCommitVisible(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Deprecated WebResourceResponse shouldInterceptRequest(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request); @Override @Deprecated @SuppressWarnings("deprecation") //for use with older versions void onTooManyRedirects(WebView view, Message cancelMsg, Message continueMsg); @Override void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm); @Override void onPageStarted(WebView view, String url, Bitmap facIcon); @Override void onPageFinished(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override void onReceivedClientCertRequest(WebView view, ClientCertRequest request); @Override void onFormResubmission(final WebView view, final Message dontResend, final Message resend); @Override void doUpdateVisitedHistory(final WebView view, final String url, final boolean isReload); @Override boolean shouldOverrideKeyEvent(final WebView view, final KeyEvent event); @SuppressWarnings("unused") void onUnhandledInputEvent(final WebView view, final InputEvent event); @Override void onUnhandledKeyEvent(final WebView view, final KeyEvent event); @Override void onScaleChanged(final WebView view, final float oldScale, final float newScale); @Override void onReceivedLoginRequest(final WebView view, final String realm, final String account, final String args); @RequiresApi(api = Build.VERSION_CODES.O) @Override boolean onRenderProcessGone(final WebView view, final RenderProcessGoneDetail detail); @RequiresApi(api = Build.VERSION_CODES.O_MR1) @Override void onSafeBrowsingHit(final WebView view, final WebResourceRequest request, final int threatType, final SafeBrowsingResponse callback); @Override boolean isLoggingEnabled(); @Override void setLoggingEnabled(final boolean enabled); @Override boolean isLogKeyEventsEnabled(); @Override void setLogKeyEventsEnabled(final boolean enabled); } | @Test public void onReceivedHttpAuthRequest() { final HttpAuthHandler handler = Mockito.mock(HttpAuthHandler.class); final String host = "foo"; final String realm = "bar"; debugClient.onReceivedHttpAuthRequest(webView, handler, host, realm); verifyLogger().onReceivedHttpAuthRequest(webView, handler, host, realm); verifyWrappedClient().onReceivedHttpAuthRequest(webView, handler, host, realm); } |
DebugWebViewClient extends WebViewClient implements LogControl { @Override public void onPageStarted(WebView view, String url, Bitmap facIcon) { logger.onPageStarted(view, url, facIcon); client.onPageStarted(view, url, facIcon); } DebugWebViewClient(); DebugWebViewClient(@NonNull final WebViewClient client); @SuppressWarnings("WeakerAccess") DebugWebViewClient(
@NonNull final WebViewClient client,
@NonNull final DebugWebViewClientLogger logger); @RequiresApi(api = Build.VERSION_CODES.M) @Override void onReceivedError(final WebView view, final WebResourceRequest request, final WebResourceError error); @Override @Deprecated void onReceivedError(final WebView view, final int errorCode, final String description, final String failingUrl); @RequiresApi(api = Build.VERSION_CODES.M) @Override void onReceivedHttpError(final WebView view, final WebResourceRequest request, final WebResourceResponse errorResponse); @Override void onReceivedSslError(final WebView view, final SslErrorHandler handler, final SslError error); @RequiresApi(api = Build.VERSION_CODES.N) @Override boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request); @Override boolean shouldOverrideUrlLoading(WebView view, String url); @Override void onLoadResource(WebView view, String url); @TargetApi(Build.VERSION_CODES.M) @Override void onPageCommitVisible(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Deprecated WebResourceResponse shouldInterceptRequest(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request); @Override @Deprecated @SuppressWarnings("deprecation") //for use with older versions void onTooManyRedirects(WebView view, Message cancelMsg, Message continueMsg); @Override void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm); @Override void onPageStarted(WebView view, String url, Bitmap facIcon); @Override void onPageFinished(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override void onReceivedClientCertRequest(WebView view, ClientCertRequest request); @Override void onFormResubmission(final WebView view, final Message dontResend, final Message resend); @Override void doUpdateVisitedHistory(final WebView view, final String url, final boolean isReload); @Override boolean shouldOverrideKeyEvent(final WebView view, final KeyEvent event); @SuppressWarnings("unused") void onUnhandledInputEvent(final WebView view, final InputEvent event); @Override void onUnhandledKeyEvent(final WebView view, final KeyEvent event); @Override void onScaleChanged(final WebView view, final float oldScale, final float newScale); @Override void onReceivedLoginRequest(final WebView view, final String realm, final String account, final String args); @RequiresApi(api = Build.VERSION_CODES.O) @Override boolean onRenderProcessGone(final WebView view, final RenderProcessGoneDetail detail); @RequiresApi(api = Build.VERSION_CODES.O_MR1) @Override void onSafeBrowsingHit(final WebView view, final WebResourceRequest request, final int threatType, final SafeBrowsingResponse callback); @Override boolean isLoggingEnabled(); @Override void setLoggingEnabled(final boolean enabled); @Override boolean isLogKeyEventsEnabled(); @Override void setLogKeyEventsEnabled(final boolean enabled); } | @Test public void onPageStarted() { final String url = "foo"; final Bitmap bitmap = Mockito.mock(Bitmap.class); debugClient.onPageStarted(webView, url, bitmap); verifyLogger().onPageStarted(webView, url, bitmap); verifyWrappedClient().onPageStarted(webView, url, bitmap); } |
DebugWebViewClient extends WebViewClient implements LogControl { @Override public void onPageFinished(WebView view, String url) { logger.onPageFinished(view, url); client.onPageFinished(view, url); } DebugWebViewClient(); DebugWebViewClient(@NonNull final WebViewClient client); @SuppressWarnings("WeakerAccess") DebugWebViewClient(
@NonNull final WebViewClient client,
@NonNull final DebugWebViewClientLogger logger); @RequiresApi(api = Build.VERSION_CODES.M) @Override void onReceivedError(final WebView view, final WebResourceRequest request, final WebResourceError error); @Override @Deprecated void onReceivedError(final WebView view, final int errorCode, final String description, final String failingUrl); @RequiresApi(api = Build.VERSION_CODES.M) @Override void onReceivedHttpError(final WebView view, final WebResourceRequest request, final WebResourceResponse errorResponse); @Override void onReceivedSslError(final WebView view, final SslErrorHandler handler, final SslError error); @RequiresApi(api = Build.VERSION_CODES.N) @Override boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request); @Override boolean shouldOverrideUrlLoading(WebView view, String url); @Override void onLoadResource(WebView view, String url); @TargetApi(Build.VERSION_CODES.M) @Override void onPageCommitVisible(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Deprecated WebResourceResponse shouldInterceptRequest(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request); @Override @Deprecated @SuppressWarnings("deprecation") //for use with older versions void onTooManyRedirects(WebView view, Message cancelMsg, Message continueMsg); @Override void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm); @Override void onPageStarted(WebView view, String url, Bitmap facIcon); @Override void onPageFinished(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override void onReceivedClientCertRequest(WebView view, ClientCertRequest request); @Override void onFormResubmission(final WebView view, final Message dontResend, final Message resend); @Override void doUpdateVisitedHistory(final WebView view, final String url, final boolean isReload); @Override boolean shouldOverrideKeyEvent(final WebView view, final KeyEvent event); @SuppressWarnings("unused") void onUnhandledInputEvent(final WebView view, final InputEvent event); @Override void onUnhandledKeyEvent(final WebView view, final KeyEvent event); @Override void onScaleChanged(final WebView view, final float oldScale, final float newScale); @Override void onReceivedLoginRequest(final WebView view, final String realm, final String account, final String args); @RequiresApi(api = Build.VERSION_CODES.O) @Override boolean onRenderProcessGone(final WebView view, final RenderProcessGoneDetail detail); @RequiresApi(api = Build.VERSION_CODES.O_MR1) @Override void onSafeBrowsingHit(final WebView view, final WebResourceRequest request, final int threatType, final SafeBrowsingResponse callback); @Override boolean isLoggingEnabled(); @Override void setLoggingEnabled(final boolean enabled); @Override boolean isLogKeyEventsEnabled(); @Override void setLogKeyEventsEnabled(final boolean enabled); } | @Test public void onPageFinished() { final String url = "foo"; debugClient.onPageFinished(webView, url); verifyLogger().onPageFinished(webView, url); verifyWrappedClient().onPageFinished(webView, url); } |
DebugWebViewClient extends WebViewClient implements LogControl { @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override public void onReceivedClientCertRequest(WebView view, ClientCertRequest request) { logger.onReceivedClientCertRequest(view, request); client.onReceivedClientCertRequest(view, request); } DebugWebViewClient(); DebugWebViewClient(@NonNull final WebViewClient client); @SuppressWarnings("WeakerAccess") DebugWebViewClient(
@NonNull final WebViewClient client,
@NonNull final DebugWebViewClientLogger logger); @RequiresApi(api = Build.VERSION_CODES.M) @Override void onReceivedError(final WebView view, final WebResourceRequest request, final WebResourceError error); @Override @Deprecated void onReceivedError(final WebView view, final int errorCode, final String description, final String failingUrl); @RequiresApi(api = Build.VERSION_CODES.M) @Override void onReceivedHttpError(final WebView view, final WebResourceRequest request, final WebResourceResponse errorResponse); @Override void onReceivedSslError(final WebView view, final SslErrorHandler handler, final SslError error); @RequiresApi(api = Build.VERSION_CODES.N) @Override boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request); @Override boolean shouldOverrideUrlLoading(WebView view, String url); @Override void onLoadResource(WebView view, String url); @TargetApi(Build.VERSION_CODES.M) @Override void onPageCommitVisible(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Deprecated WebResourceResponse shouldInterceptRequest(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request); @Override @Deprecated @SuppressWarnings("deprecation") //for use with older versions void onTooManyRedirects(WebView view, Message cancelMsg, Message continueMsg); @Override void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm); @Override void onPageStarted(WebView view, String url, Bitmap facIcon); @Override void onPageFinished(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override void onReceivedClientCertRequest(WebView view, ClientCertRequest request); @Override void onFormResubmission(final WebView view, final Message dontResend, final Message resend); @Override void doUpdateVisitedHistory(final WebView view, final String url, final boolean isReload); @Override boolean shouldOverrideKeyEvent(final WebView view, final KeyEvent event); @SuppressWarnings("unused") void onUnhandledInputEvent(final WebView view, final InputEvent event); @Override void onUnhandledKeyEvent(final WebView view, final KeyEvent event); @Override void onScaleChanged(final WebView view, final float oldScale, final float newScale); @Override void onReceivedLoginRequest(final WebView view, final String realm, final String account, final String args); @RequiresApi(api = Build.VERSION_CODES.O) @Override boolean onRenderProcessGone(final WebView view, final RenderProcessGoneDetail detail); @RequiresApi(api = Build.VERSION_CODES.O_MR1) @Override void onSafeBrowsingHit(final WebView view, final WebResourceRequest request, final int threatType, final SafeBrowsingResponse callback); @Override boolean isLoggingEnabled(); @Override void setLoggingEnabled(final boolean enabled); @Override boolean isLogKeyEventsEnabled(); @Override void setLogKeyEventsEnabled(final boolean enabled); } | @Test public void onReceivedClientCertRequest() { final ClientCertRequest request = Mockito.mock(ClientCertRequest.class); debugClient.onReceivedClientCertRequest(webView, request); verifyLogger().onReceivedClientCertRequest(webView, request); verifyWrappedClient().onReceivedClientCertRequest(webView, request); } |
DebugWebViewClient extends WebViewClient implements LogControl { @Override public void onFormResubmission(final WebView view, final Message dontResend, final Message resend) { logger.onFormResubmission(view, dontResend, resend); client.onFormResubmission(view, dontResend, resend); } DebugWebViewClient(); DebugWebViewClient(@NonNull final WebViewClient client); @SuppressWarnings("WeakerAccess") DebugWebViewClient(
@NonNull final WebViewClient client,
@NonNull final DebugWebViewClientLogger logger); @RequiresApi(api = Build.VERSION_CODES.M) @Override void onReceivedError(final WebView view, final WebResourceRequest request, final WebResourceError error); @Override @Deprecated void onReceivedError(final WebView view, final int errorCode, final String description, final String failingUrl); @RequiresApi(api = Build.VERSION_CODES.M) @Override void onReceivedHttpError(final WebView view, final WebResourceRequest request, final WebResourceResponse errorResponse); @Override void onReceivedSslError(final WebView view, final SslErrorHandler handler, final SslError error); @RequiresApi(api = Build.VERSION_CODES.N) @Override boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request); @Override boolean shouldOverrideUrlLoading(WebView view, String url); @Override void onLoadResource(WebView view, String url); @TargetApi(Build.VERSION_CODES.M) @Override void onPageCommitVisible(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Deprecated WebResourceResponse shouldInterceptRequest(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request); @Override @Deprecated @SuppressWarnings("deprecation") //for use with older versions void onTooManyRedirects(WebView view, Message cancelMsg, Message continueMsg); @Override void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm); @Override void onPageStarted(WebView view, String url, Bitmap facIcon); @Override void onPageFinished(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override void onReceivedClientCertRequest(WebView view, ClientCertRequest request); @Override void onFormResubmission(final WebView view, final Message dontResend, final Message resend); @Override void doUpdateVisitedHistory(final WebView view, final String url, final boolean isReload); @Override boolean shouldOverrideKeyEvent(final WebView view, final KeyEvent event); @SuppressWarnings("unused") void onUnhandledInputEvent(final WebView view, final InputEvent event); @Override void onUnhandledKeyEvent(final WebView view, final KeyEvent event); @Override void onScaleChanged(final WebView view, final float oldScale, final float newScale); @Override void onReceivedLoginRequest(final WebView view, final String realm, final String account, final String args); @RequiresApi(api = Build.VERSION_CODES.O) @Override boolean onRenderProcessGone(final WebView view, final RenderProcessGoneDetail detail); @RequiresApi(api = Build.VERSION_CODES.O_MR1) @Override void onSafeBrowsingHit(final WebView view, final WebResourceRequest request, final int threatType, final SafeBrowsingResponse callback); @Override boolean isLoggingEnabled(); @Override void setLoggingEnabled(final boolean enabled); @Override boolean isLogKeyEventsEnabled(); @Override void setLogKeyEventsEnabled(final boolean enabled); } | @Test public void onFormResubmission() { final Message dontResend = Mockito.mock(Message.class); final Message resend = Mockito.mock(Message.class); debugClient.onFormResubmission(webView, dontResend, resend); verifyLogger().onFormResubmission(webView, dontResend, resend); verifyWrappedClient().onFormResubmission(webView, dontResend, resend); } |
DebugWebViewClient extends WebViewClient implements LogControl { @Override public void doUpdateVisitedHistory(final WebView view, final String url, final boolean isReload) { logger.doUpdateVisitedHistory(view, url, isReload); client.doUpdateVisitedHistory(view, url, isReload); } DebugWebViewClient(); DebugWebViewClient(@NonNull final WebViewClient client); @SuppressWarnings("WeakerAccess") DebugWebViewClient(
@NonNull final WebViewClient client,
@NonNull final DebugWebViewClientLogger logger); @RequiresApi(api = Build.VERSION_CODES.M) @Override void onReceivedError(final WebView view, final WebResourceRequest request, final WebResourceError error); @Override @Deprecated void onReceivedError(final WebView view, final int errorCode, final String description, final String failingUrl); @RequiresApi(api = Build.VERSION_CODES.M) @Override void onReceivedHttpError(final WebView view, final WebResourceRequest request, final WebResourceResponse errorResponse); @Override void onReceivedSslError(final WebView view, final SslErrorHandler handler, final SslError error); @RequiresApi(api = Build.VERSION_CODES.N) @Override boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request); @Override boolean shouldOverrideUrlLoading(WebView view, String url); @Override void onLoadResource(WebView view, String url); @TargetApi(Build.VERSION_CODES.M) @Override void onPageCommitVisible(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Deprecated WebResourceResponse shouldInterceptRequest(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request); @Override @Deprecated @SuppressWarnings("deprecation") //for use with older versions void onTooManyRedirects(WebView view, Message cancelMsg, Message continueMsg); @Override void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm); @Override void onPageStarted(WebView view, String url, Bitmap facIcon); @Override void onPageFinished(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override void onReceivedClientCertRequest(WebView view, ClientCertRequest request); @Override void onFormResubmission(final WebView view, final Message dontResend, final Message resend); @Override void doUpdateVisitedHistory(final WebView view, final String url, final boolean isReload); @Override boolean shouldOverrideKeyEvent(final WebView view, final KeyEvent event); @SuppressWarnings("unused") void onUnhandledInputEvent(final WebView view, final InputEvent event); @Override void onUnhandledKeyEvent(final WebView view, final KeyEvent event); @Override void onScaleChanged(final WebView view, final float oldScale, final float newScale); @Override void onReceivedLoginRequest(final WebView view, final String realm, final String account, final String args); @RequiresApi(api = Build.VERSION_CODES.O) @Override boolean onRenderProcessGone(final WebView view, final RenderProcessGoneDetail detail); @RequiresApi(api = Build.VERSION_CODES.O_MR1) @Override void onSafeBrowsingHit(final WebView view, final WebResourceRequest request, final int threatType, final SafeBrowsingResponse callback); @Override boolean isLoggingEnabled(); @Override void setLoggingEnabled(final boolean enabled); @Override boolean isLogKeyEventsEnabled(); @Override void setLogKeyEventsEnabled(final boolean enabled); } | @Test public void doUpdateVisitedHistory() { final String url = "foo"; final boolean reload = true; debugClient.doUpdateVisitedHistory(webView, url, reload); verifyLogger().doUpdateVisitedHistory(webView, url, reload); verifyWrappedClient().doUpdateVisitedHistory(webView, url, reload); } |
DebugWebViewClient extends WebViewClient implements LogControl { @Override public boolean shouldOverrideKeyEvent(final WebView view, final KeyEvent event) { final boolean retVal = client.shouldOverrideKeyEvent(view, event); logger.shouldOverrideKeyEvent(view, event, retVal); return retVal; } DebugWebViewClient(); DebugWebViewClient(@NonNull final WebViewClient client); @SuppressWarnings("WeakerAccess") DebugWebViewClient(
@NonNull final WebViewClient client,
@NonNull final DebugWebViewClientLogger logger); @RequiresApi(api = Build.VERSION_CODES.M) @Override void onReceivedError(final WebView view, final WebResourceRequest request, final WebResourceError error); @Override @Deprecated void onReceivedError(final WebView view, final int errorCode, final String description, final String failingUrl); @RequiresApi(api = Build.VERSION_CODES.M) @Override void onReceivedHttpError(final WebView view, final WebResourceRequest request, final WebResourceResponse errorResponse); @Override void onReceivedSslError(final WebView view, final SslErrorHandler handler, final SslError error); @RequiresApi(api = Build.VERSION_CODES.N) @Override boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request); @Override boolean shouldOverrideUrlLoading(WebView view, String url); @Override void onLoadResource(WebView view, String url); @TargetApi(Build.VERSION_CODES.M) @Override void onPageCommitVisible(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Deprecated WebResourceResponse shouldInterceptRequest(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request); @Override @Deprecated @SuppressWarnings("deprecation") //for use with older versions void onTooManyRedirects(WebView view, Message cancelMsg, Message continueMsg); @Override void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm); @Override void onPageStarted(WebView view, String url, Bitmap facIcon); @Override void onPageFinished(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override void onReceivedClientCertRequest(WebView view, ClientCertRequest request); @Override void onFormResubmission(final WebView view, final Message dontResend, final Message resend); @Override void doUpdateVisitedHistory(final WebView view, final String url, final boolean isReload); @Override boolean shouldOverrideKeyEvent(final WebView view, final KeyEvent event); @SuppressWarnings("unused") void onUnhandledInputEvent(final WebView view, final InputEvent event); @Override void onUnhandledKeyEvent(final WebView view, final KeyEvent event); @Override void onScaleChanged(final WebView view, final float oldScale, final float newScale); @Override void onReceivedLoginRequest(final WebView view, final String realm, final String account, final String args); @RequiresApi(api = Build.VERSION_CODES.O) @Override boolean onRenderProcessGone(final WebView view, final RenderProcessGoneDetail detail); @RequiresApi(api = Build.VERSION_CODES.O_MR1) @Override void onSafeBrowsingHit(final WebView view, final WebResourceRequest request, final int threatType, final SafeBrowsingResponse callback); @Override boolean isLoggingEnabled(); @Override void setLoggingEnabled(final boolean enabled); @Override boolean isLogKeyEventsEnabled(); @Override void setLogKeyEventsEnabled(final boolean enabled); } | @Test public void shouldOverrideKeyEvent() { final KeyEvent keyEvent = Mockito.mock(KeyEvent.class); final boolean retVal = debugClient.shouldOverrideKeyEvent(webView, keyEvent); verifyLogger().shouldOverrideKeyEvent(webView, keyEvent, retVal); verifyWrappedClient().shouldOverrideKeyEvent(webView, keyEvent); } |
DebugWebViewClient extends WebViewClient implements LogControl { @Override public void onUnhandledKeyEvent(final WebView view, final KeyEvent event) { logger.onUnhandledKeyEvent(view, event); client.onUnhandledKeyEvent(view, event); } DebugWebViewClient(); DebugWebViewClient(@NonNull final WebViewClient client); @SuppressWarnings("WeakerAccess") DebugWebViewClient(
@NonNull final WebViewClient client,
@NonNull final DebugWebViewClientLogger logger); @RequiresApi(api = Build.VERSION_CODES.M) @Override void onReceivedError(final WebView view, final WebResourceRequest request, final WebResourceError error); @Override @Deprecated void onReceivedError(final WebView view, final int errorCode, final String description, final String failingUrl); @RequiresApi(api = Build.VERSION_CODES.M) @Override void onReceivedHttpError(final WebView view, final WebResourceRequest request, final WebResourceResponse errorResponse); @Override void onReceivedSslError(final WebView view, final SslErrorHandler handler, final SslError error); @RequiresApi(api = Build.VERSION_CODES.N) @Override boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request); @Override boolean shouldOverrideUrlLoading(WebView view, String url); @Override void onLoadResource(WebView view, String url); @TargetApi(Build.VERSION_CODES.M) @Override void onPageCommitVisible(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Deprecated WebResourceResponse shouldInterceptRequest(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request); @Override @Deprecated @SuppressWarnings("deprecation") //for use with older versions void onTooManyRedirects(WebView view, Message cancelMsg, Message continueMsg); @Override void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm); @Override void onPageStarted(WebView view, String url, Bitmap facIcon); @Override void onPageFinished(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override void onReceivedClientCertRequest(WebView view, ClientCertRequest request); @Override void onFormResubmission(final WebView view, final Message dontResend, final Message resend); @Override void doUpdateVisitedHistory(final WebView view, final String url, final boolean isReload); @Override boolean shouldOverrideKeyEvent(final WebView view, final KeyEvent event); @SuppressWarnings("unused") void onUnhandledInputEvent(final WebView view, final InputEvent event); @Override void onUnhandledKeyEvent(final WebView view, final KeyEvent event); @Override void onScaleChanged(final WebView view, final float oldScale, final float newScale); @Override void onReceivedLoginRequest(final WebView view, final String realm, final String account, final String args); @RequiresApi(api = Build.VERSION_CODES.O) @Override boolean onRenderProcessGone(final WebView view, final RenderProcessGoneDetail detail); @RequiresApi(api = Build.VERSION_CODES.O_MR1) @Override void onSafeBrowsingHit(final WebView view, final WebResourceRequest request, final int threatType, final SafeBrowsingResponse callback); @Override boolean isLoggingEnabled(); @Override void setLoggingEnabled(final boolean enabled); @Override boolean isLogKeyEventsEnabled(); @Override void setLogKeyEventsEnabled(final boolean enabled); } | @Test public void onUnhandledKeyEvent() { final KeyEvent keyEvent = Mockito.mock(KeyEvent.class); debugClient.onUnhandledKeyEvent(webView, keyEvent); verifyLogger().onUnhandledKeyEvent(webView, keyEvent); verifyWrappedClient().onUnhandledKeyEvent(webView, keyEvent); } |
DebugWebViewClient extends WebViewClient implements LogControl { @Override public void onScaleChanged(final WebView view, final float oldScale, final float newScale) { logger.onScaleChanged(view, oldScale, newScale); client.onScaleChanged(view, oldScale, newScale); } DebugWebViewClient(); DebugWebViewClient(@NonNull final WebViewClient client); @SuppressWarnings("WeakerAccess") DebugWebViewClient(
@NonNull final WebViewClient client,
@NonNull final DebugWebViewClientLogger logger); @RequiresApi(api = Build.VERSION_CODES.M) @Override void onReceivedError(final WebView view, final WebResourceRequest request, final WebResourceError error); @Override @Deprecated void onReceivedError(final WebView view, final int errorCode, final String description, final String failingUrl); @RequiresApi(api = Build.VERSION_CODES.M) @Override void onReceivedHttpError(final WebView view, final WebResourceRequest request, final WebResourceResponse errorResponse); @Override void onReceivedSslError(final WebView view, final SslErrorHandler handler, final SslError error); @RequiresApi(api = Build.VERSION_CODES.N) @Override boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request); @Override boolean shouldOverrideUrlLoading(WebView view, String url); @Override void onLoadResource(WebView view, String url); @TargetApi(Build.VERSION_CODES.M) @Override void onPageCommitVisible(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Deprecated WebResourceResponse shouldInterceptRequest(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request); @Override @Deprecated @SuppressWarnings("deprecation") //for use with older versions void onTooManyRedirects(WebView view, Message cancelMsg, Message continueMsg); @Override void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm); @Override void onPageStarted(WebView view, String url, Bitmap facIcon); @Override void onPageFinished(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override void onReceivedClientCertRequest(WebView view, ClientCertRequest request); @Override void onFormResubmission(final WebView view, final Message dontResend, final Message resend); @Override void doUpdateVisitedHistory(final WebView view, final String url, final boolean isReload); @Override boolean shouldOverrideKeyEvent(final WebView view, final KeyEvent event); @SuppressWarnings("unused") void onUnhandledInputEvent(final WebView view, final InputEvent event); @Override void onUnhandledKeyEvent(final WebView view, final KeyEvent event); @Override void onScaleChanged(final WebView view, final float oldScale, final float newScale); @Override void onReceivedLoginRequest(final WebView view, final String realm, final String account, final String args); @RequiresApi(api = Build.VERSION_CODES.O) @Override boolean onRenderProcessGone(final WebView view, final RenderProcessGoneDetail detail); @RequiresApi(api = Build.VERSION_CODES.O_MR1) @Override void onSafeBrowsingHit(final WebView view, final WebResourceRequest request, final int threatType, final SafeBrowsingResponse callback); @Override boolean isLoggingEnabled(); @Override void setLoggingEnabled(final boolean enabled); @Override boolean isLogKeyEventsEnabled(); @Override void setLogKeyEventsEnabled(final boolean enabled); } | @Test public void onScaleChanged() { final float oldScale = 1.0f; final float newScale = 2.0f; debugClient.onScaleChanged(webView, oldScale, newScale); verifyLogger().onScaleChanged(webView, oldScale, newScale); verifyWrappedClient().onScaleChanged(webView, oldScale, newScale); } |
DebugWebViewClient extends WebViewClient implements LogControl { @Override public void onReceivedLoginRequest(final WebView view, final String realm, final String account, final String args) { logger.onReceivedLoginRequest(view, realm, account, args); client.onReceivedLoginRequest(view, realm, account, args); } DebugWebViewClient(); DebugWebViewClient(@NonNull final WebViewClient client); @SuppressWarnings("WeakerAccess") DebugWebViewClient(
@NonNull final WebViewClient client,
@NonNull final DebugWebViewClientLogger logger); @RequiresApi(api = Build.VERSION_CODES.M) @Override void onReceivedError(final WebView view, final WebResourceRequest request, final WebResourceError error); @Override @Deprecated void onReceivedError(final WebView view, final int errorCode, final String description, final String failingUrl); @RequiresApi(api = Build.VERSION_CODES.M) @Override void onReceivedHttpError(final WebView view, final WebResourceRequest request, final WebResourceResponse errorResponse); @Override void onReceivedSslError(final WebView view, final SslErrorHandler handler, final SslError error); @RequiresApi(api = Build.VERSION_CODES.N) @Override boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request); @Override boolean shouldOverrideUrlLoading(WebView view, String url); @Override void onLoadResource(WebView view, String url); @TargetApi(Build.VERSION_CODES.M) @Override void onPageCommitVisible(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Deprecated WebResourceResponse shouldInterceptRequest(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request); @Override @Deprecated @SuppressWarnings("deprecation") //for use with older versions void onTooManyRedirects(WebView view, Message cancelMsg, Message continueMsg); @Override void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm); @Override void onPageStarted(WebView view, String url, Bitmap facIcon); @Override void onPageFinished(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override void onReceivedClientCertRequest(WebView view, ClientCertRequest request); @Override void onFormResubmission(final WebView view, final Message dontResend, final Message resend); @Override void doUpdateVisitedHistory(final WebView view, final String url, final boolean isReload); @Override boolean shouldOverrideKeyEvent(final WebView view, final KeyEvent event); @SuppressWarnings("unused") void onUnhandledInputEvent(final WebView view, final InputEvent event); @Override void onUnhandledKeyEvent(final WebView view, final KeyEvent event); @Override void onScaleChanged(final WebView view, final float oldScale, final float newScale); @Override void onReceivedLoginRequest(final WebView view, final String realm, final String account, final String args); @RequiresApi(api = Build.VERSION_CODES.O) @Override boolean onRenderProcessGone(final WebView view, final RenderProcessGoneDetail detail); @RequiresApi(api = Build.VERSION_CODES.O_MR1) @Override void onSafeBrowsingHit(final WebView view, final WebResourceRequest request, final int threatType, final SafeBrowsingResponse callback); @Override boolean isLoggingEnabled(); @Override void setLoggingEnabled(final boolean enabled); @Override boolean isLogKeyEventsEnabled(); @Override void setLogKeyEventsEnabled(final boolean enabled); } | @Test public void onReceivedLoginRequest() { final String realm = "realm"; final String account = "account"; final String args = "args"; debugClient.onReceivedLoginRequest(webView, realm, account, args); verifyLogger().onReceivedLoginRequest(webView, realm, account, args); verifyWrappedClient().onReceivedLoginRequest(webView, realm, account, args); } |
DebugWebViewClient extends WebViewClient implements LogControl { @RequiresApi(api = Build.VERSION_CODES.O) @Override public boolean onRenderProcessGone(final WebView view, final RenderProcessGoneDetail detail) { final boolean retVal = client.onRenderProcessGone(view, detail); logger.onRenderProcessGone(view, detail, retVal); return retVal; } DebugWebViewClient(); DebugWebViewClient(@NonNull final WebViewClient client); @SuppressWarnings("WeakerAccess") DebugWebViewClient(
@NonNull final WebViewClient client,
@NonNull final DebugWebViewClientLogger logger); @RequiresApi(api = Build.VERSION_CODES.M) @Override void onReceivedError(final WebView view, final WebResourceRequest request, final WebResourceError error); @Override @Deprecated void onReceivedError(final WebView view, final int errorCode, final String description, final String failingUrl); @RequiresApi(api = Build.VERSION_CODES.M) @Override void onReceivedHttpError(final WebView view, final WebResourceRequest request, final WebResourceResponse errorResponse); @Override void onReceivedSslError(final WebView view, final SslErrorHandler handler, final SslError error); @RequiresApi(api = Build.VERSION_CODES.N) @Override boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request); @Override boolean shouldOverrideUrlLoading(WebView view, String url); @Override void onLoadResource(WebView view, String url); @TargetApi(Build.VERSION_CODES.M) @Override void onPageCommitVisible(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Deprecated WebResourceResponse shouldInterceptRequest(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request); @Override @Deprecated @SuppressWarnings("deprecation") //for use with older versions void onTooManyRedirects(WebView view, Message cancelMsg, Message continueMsg); @Override void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm); @Override void onPageStarted(WebView view, String url, Bitmap facIcon); @Override void onPageFinished(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override void onReceivedClientCertRequest(WebView view, ClientCertRequest request); @Override void onFormResubmission(final WebView view, final Message dontResend, final Message resend); @Override void doUpdateVisitedHistory(final WebView view, final String url, final boolean isReload); @Override boolean shouldOverrideKeyEvent(final WebView view, final KeyEvent event); @SuppressWarnings("unused") void onUnhandledInputEvent(final WebView view, final InputEvent event); @Override void onUnhandledKeyEvent(final WebView view, final KeyEvent event); @Override void onScaleChanged(final WebView view, final float oldScale, final float newScale); @Override void onReceivedLoginRequest(final WebView view, final String realm, final String account, final String args); @RequiresApi(api = Build.VERSION_CODES.O) @Override boolean onRenderProcessGone(final WebView view, final RenderProcessGoneDetail detail); @RequiresApi(api = Build.VERSION_CODES.O_MR1) @Override void onSafeBrowsingHit(final WebView view, final WebResourceRequest request, final int threatType, final SafeBrowsingResponse callback); @Override boolean isLoggingEnabled(); @Override void setLoggingEnabled(final boolean enabled); @Override boolean isLogKeyEventsEnabled(); @Override void setLogKeyEventsEnabled(final boolean enabled); } | @Test public void onRenderProcessGone() { final RenderProcessGoneDetail detail = Mockito.mock(RenderProcessGoneDetail.class); final boolean retVal = debugClient.onRenderProcessGone(webView, detail); verifyLogger().onRenderProcessGone(webView, detail, retVal); verifyWrappedClient().onRenderProcessGone(webView, detail); } |
DebugWebViewClient extends WebViewClient implements LogControl { @RequiresApi(api = Build.VERSION_CODES.O_MR1) @Override public void onSafeBrowsingHit(final WebView view, final WebResourceRequest request, final int threatType, final SafeBrowsingResponse callback) { logger.onSafeBrowsingHit(view, request, threatType, callback); client.onSafeBrowsingHit(view, request, threatType, callback); } DebugWebViewClient(); DebugWebViewClient(@NonNull final WebViewClient client); @SuppressWarnings("WeakerAccess") DebugWebViewClient(
@NonNull final WebViewClient client,
@NonNull final DebugWebViewClientLogger logger); @RequiresApi(api = Build.VERSION_CODES.M) @Override void onReceivedError(final WebView view, final WebResourceRequest request, final WebResourceError error); @Override @Deprecated void onReceivedError(final WebView view, final int errorCode, final String description, final String failingUrl); @RequiresApi(api = Build.VERSION_CODES.M) @Override void onReceivedHttpError(final WebView view, final WebResourceRequest request, final WebResourceResponse errorResponse); @Override void onReceivedSslError(final WebView view, final SslErrorHandler handler, final SslError error); @RequiresApi(api = Build.VERSION_CODES.N) @Override boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request); @Override boolean shouldOverrideUrlLoading(WebView view, String url); @Override void onLoadResource(WebView view, String url); @TargetApi(Build.VERSION_CODES.M) @Override void onPageCommitVisible(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Deprecated WebResourceResponse shouldInterceptRequest(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request); @Override @Deprecated @SuppressWarnings("deprecation") //for use with older versions void onTooManyRedirects(WebView view, Message cancelMsg, Message continueMsg); @Override void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm); @Override void onPageStarted(WebView view, String url, Bitmap facIcon); @Override void onPageFinished(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override void onReceivedClientCertRequest(WebView view, ClientCertRequest request); @Override void onFormResubmission(final WebView view, final Message dontResend, final Message resend); @Override void doUpdateVisitedHistory(final WebView view, final String url, final boolean isReload); @Override boolean shouldOverrideKeyEvent(final WebView view, final KeyEvent event); @SuppressWarnings("unused") void onUnhandledInputEvent(final WebView view, final InputEvent event); @Override void onUnhandledKeyEvent(final WebView view, final KeyEvent event); @Override void onScaleChanged(final WebView view, final float oldScale, final float newScale); @Override void onReceivedLoginRequest(final WebView view, final String realm, final String account, final String args); @RequiresApi(api = Build.VERSION_CODES.O) @Override boolean onRenderProcessGone(final WebView view, final RenderProcessGoneDetail detail); @RequiresApi(api = Build.VERSION_CODES.O_MR1) @Override void onSafeBrowsingHit(final WebView view, final WebResourceRequest request, final int threatType, final SafeBrowsingResponse callback); @Override boolean isLoggingEnabled(); @Override void setLoggingEnabled(final boolean enabled); @Override boolean isLogKeyEventsEnabled(); @Override void setLogKeyEventsEnabled(final boolean enabled); } | @Test public void onSafeBrowsingHit() { final WebResourceRequest request = Mockito.mock(WebResourceRequest.class); final SafeBrowsingResponse callback = Mockito.mock(SafeBrowsingResponse.class); final int threatType = -1; debugClient.onSafeBrowsingHit(webView, request, threatType, callback); verifyLogger().onSafeBrowsingHit(webView, request, threatType, callback); verifyWrappedClient().onSafeBrowsingHit(webView, request, threatType, callback); } |
DebugWebViewClientLogger implements LogControl { @RequiresApi(api = Build.VERSION_CODES.M) public void onReceivedError(final WebView view, final WebResourceRequest request, final WebResourceError error) { if (loggingEnabled) { final Uri url = request.getUrl(); final String method = request.getMethod(); final int code = error.getErrorCode(); logger.logError(String.format(LOCALE, "%s onReceivedError() 1/3 CALL : %d %s %s", SPACE, code, method, url)); logger.logError(String.format(LOCALE, "%s onReceivedError() 2/3 REQ HEADERS: %s", SPACE, request.getRequestHeaders())); logger.logError(String.format(LOCALE, "%s onReceivedError() 3/3 ERR DESC : %s", SPACE, error.getDescription())); } } DebugWebViewClientLogger(); DebugWebViewClientLogger(@NonNull final String tag); @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE) protected DebugWebViewClientLogger(@NonNull final LogEngine logEngine); @RequiresApi(api = Build.VERSION_CODES.M) void onReceivedError(final WebView view, final WebResourceRequest request, final WebResourceError error); void onReceivedError(final WebView view, final int errorCode, final String description, final String failingUrl); @RequiresApi(api = Build.VERSION_CODES.M) void onReceivedHttpError(final WebView view, final WebResourceRequest request, final WebResourceResponse errorResponse); void onReceivedSslError(final WebView view, final SslErrorHandler handler, final SslError error); @RequiresApi(api = Build.VERSION_CODES.N) void shouldOverrideUrlLoading(WebView view, WebResourceRequest request, boolean retVal); void shouldOverrideUrlLoading(WebView view, String url, boolean retVal); void onLoadResource(WebView view, String url); @TargetApi(Build.VERSION_CODES.M) void onPageCommitVisible(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) void shouldInterceptRequest(WebView view, String url, WebResourceResponse retVal); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) void shouldInterceptRequest(WebView view, WebResourceRequest request, final WebResourceResponse retVal); void onTooManyRedirects(WebView view, Message cancelMsg, Message continueMsg); void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm); void onPageStarted(WebView view, String url, Bitmap facIcon); void onPageFinished(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) void onReceivedClientCertRequest(WebView view, ClientCertRequest request); void onFormResubmission(final WebView view, final Message dontResend, final Message resend); void doUpdateVisitedHistory(final WebView view, final String url, final boolean isReload); void shouldOverrideKeyEvent(final WebView view, final KeyEvent event, boolean retVal); void onUnhandledInputEvent(final WebView view, final InputEvent event); void onUnhandledKeyEvent(final WebView view, final KeyEvent event); void onScaleChanged(final WebView view, final float oldScale, final float newScale); void onReceivedLoginRequest(final WebView view, final String realm, final String account, final String args); @RequiresApi(api = Build.VERSION_CODES.O) void onRenderProcessGone(final WebView view, final RenderProcessGoneDetail detail, boolean retVal); @RequiresApi(api = Build.VERSION_CODES.O_MR1) void onSafeBrowsingHit(final WebView view, final WebResourceRequest request, final int threatType, final SafeBrowsingResponse callback); @Override boolean isLoggingEnabled(); @Override void setLoggingEnabled(final boolean enabled); @Override boolean isLogKeyEventsEnabled(); @Override void setLogKeyEventsEnabled(final boolean enabled); } | @Test public void onReceivedError() { final int code = 500; final String message = "foo"; final String url = "bar"; logger.setLoggingEnabled(false); logger.onReceivedError(webView, code, message, url); verifyLogNotCalled(); logger.setLoggingEnabled(true); logger.onReceivedError(webView, code, message, url); verifyLogEngine().logError(Mockito.anyString()); } |
DebugWebViewClientLogger implements LogControl { @RequiresApi(api = Build.VERSION_CODES.M) public void onReceivedHttpError(final WebView view, final WebResourceRequest request, final WebResourceResponse errorResponse) { if (loggingEnabled) { final Uri url = request.getUrl(); final int code = errorResponse.getStatusCode(); final String method = request.getMethod(); logger.logError(String.format(LOCALE, "%s onReceivedHttpError() 1/4 CALL : %d %s %s", SPACE, code, method, url)); logger.logError(String.format(LOCALE, "%s onReceivedHttpError() 2/4 REQ HEADERS: %s", SPACE, request.getRequestHeaders())); logger.logError(String.format(LOCALE, "%s onReceivedHttpError() 3/4 ERR DESC : %s", SPACE, errorResponse.getReasonPhrase())); logger.logError(String.format(LOCALE, "%s onReceivedHttpError() 4/4 ERR HEADERS: %s", SPACE, errorResponse.getResponseHeaders())); } } DebugWebViewClientLogger(); DebugWebViewClientLogger(@NonNull final String tag); @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE) protected DebugWebViewClientLogger(@NonNull final LogEngine logEngine); @RequiresApi(api = Build.VERSION_CODES.M) void onReceivedError(final WebView view, final WebResourceRequest request, final WebResourceError error); void onReceivedError(final WebView view, final int errorCode, final String description, final String failingUrl); @RequiresApi(api = Build.VERSION_CODES.M) void onReceivedHttpError(final WebView view, final WebResourceRequest request, final WebResourceResponse errorResponse); void onReceivedSslError(final WebView view, final SslErrorHandler handler, final SslError error); @RequiresApi(api = Build.VERSION_CODES.N) void shouldOverrideUrlLoading(WebView view, WebResourceRequest request, boolean retVal); void shouldOverrideUrlLoading(WebView view, String url, boolean retVal); void onLoadResource(WebView view, String url); @TargetApi(Build.VERSION_CODES.M) void onPageCommitVisible(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) void shouldInterceptRequest(WebView view, String url, WebResourceResponse retVal); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) void shouldInterceptRequest(WebView view, WebResourceRequest request, final WebResourceResponse retVal); void onTooManyRedirects(WebView view, Message cancelMsg, Message continueMsg); void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm); void onPageStarted(WebView view, String url, Bitmap facIcon); void onPageFinished(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) void onReceivedClientCertRequest(WebView view, ClientCertRequest request); void onFormResubmission(final WebView view, final Message dontResend, final Message resend); void doUpdateVisitedHistory(final WebView view, final String url, final boolean isReload); void shouldOverrideKeyEvent(final WebView view, final KeyEvent event, boolean retVal); void onUnhandledInputEvent(final WebView view, final InputEvent event); void onUnhandledKeyEvent(final WebView view, final KeyEvent event); void onScaleChanged(final WebView view, final float oldScale, final float newScale); void onReceivedLoginRequest(final WebView view, final String realm, final String account, final String args); @RequiresApi(api = Build.VERSION_CODES.O) void onRenderProcessGone(final WebView view, final RenderProcessGoneDetail detail, boolean retVal); @RequiresApi(api = Build.VERSION_CODES.O_MR1) void onSafeBrowsingHit(final WebView view, final WebResourceRequest request, final int threatType, final SafeBrowsingResponse callback); @Override boolean isLoggingEnabled(); @Override void setLoggingEnabled(final boolean enabled); @Override boolean isLogKeyEventsEnabled(); @Override void setLogKeyEventsEnabled(final boolean enabled); } | @Test public void onReceivedHttpError() { final WebResourceRequest request = Mockito.mock(WebResourceRequest.class); final WebResourceResponse response = Mockito.mock(WebResourceResponse.class); logger.setLoggingEnabled(false); logger.onReceivedHttpError(webView, request, response); verifyLogNotCalled(); logger.setLoggingEnabled(true); logger.onReceivedHttpError(webView, request, response); verifyLogEngine().logError(Mockito.anyString()); } |
DebugWebViewClientLogger implements LogControl { public void onReceivedSslError(final WebView view, final SslErrorHandler handler, final SslError error) { if (loggingEnabled) { logger.logError(String.format(LOCALE, "%s onReceivedSslError() ERR: %s", SPACE, error)); } } DebugWebViewClientLogger(); DebugWebViewClientLogger(@NonNull final String tag); @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE) protected DebugWebViewClientLogger(@NonNull final LogEngine logEngine); @RequiresApi(api = Build.VERSION_CODES.M) void onReceivedError(final WebView view, final WebResourceRequest request, final WebResourceError error); void onReceivedError(final WebView view, final int errorCode, final String description, final String failingUrl); @RequiresApi(api = Build.VERSION_CODES.M) void onReceivedHttpError(final WebView view, final WebResourceRequest request, final WebResourceResponse errorResponse); void onReceivedSslError(final WebView view, final SslErrorHandler handler, final SslError error); @RequiresApi(api = Build.VERSION_CODES.N) void shouldOverrideUrlLoading(WebView view, WebResourceRequest request, boolean retVal); void shouldOverrideUrlLoading(WebView view, String url, boolean retVal); void onLoadResource(WebView view, String url); @TargetApi(Build.VERSION_CODES.M) void onPageCommitVisible(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) void shouldInterceptRequest(WebView view, String url, WebResourceResponse retVal); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) void shouldInterceptRequest(WebView view, WebResourceRequest request, final WebResourceResponse retVal); void onTooManyRedirects(WebView view, Message cancelMsg, Message continueMsg); void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm); void onPageStarted(WebView view, String url, Bitmap facIcon); void onPageFinished(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) void onReceivedClientCertRequest(WebView view, ClientCertRequest request); void onFormResubmission(final WebView view, final Message dontResend, final Message resend); void doUpdateVisitedHistory(final WebView view, final String url, final boolean isReload); void shouldOverrideKeyEvent(final WebView view, final KeyEvent event, boolean retVal); void onUnhandledInputEvent(final WebView view, final InputEvent event); void onUnhandledKeyEvent(final WebView view, final KeyEvent event); void onScaleChanged(final WebView view, final float oldScale, final float newScale); void onReceivedLoginRequest(final WebView view, final String realm, final String account, final String args); @RequiresApi(api = Build.VERSION_CODES.O) void onRenderProcessGone(final WebView view, final RenderProcessGoneDetail detail, boolean retVal); @RequiresApi(api = Build.VERSION_CODES.O_MR1) void onSafeBrowsingHit(final WebView view, final WebResourceRequest request, final int threatType, final SafeBrowsingResponse callback); @Override boolean isLoggingEnabled(); @Override void setLoggingEnabled(final boolean enabled); @Override boolean isLogKeyEventsEnabled(); @Override void setLogKeyEventsEnabled(final boolean enabled); } | @Test public void onReceivedSslError() { final SslErrorHandler errorHandler = Mockito.mock(SslErrorHandler.class); final SslError sslError = Mockito.mock(SslError.class); logger.setLoggingEnabled(false); logger.onReceivedSslError(webView, errorHandler, sslError); verifyLogNotCalled(); logger.setLoggingEnabled(true); logger.onReceivedSslError(webView, errorHandler, sslError); verifyLogEngine().logError(Mockito.anyString()); } |
DebugWebViewClientLogger implements LogControl { @RequiresApi(api = Build.VERSION_CODES.N) public void shouldOverrideUrlLoading(WebView view, WebResourceRequest request, boolean retVal) { if (loggingEnabled) { final Uri url = request.getUrl(); final String method = request.getMethod(); final boolean redirect = request.isRedirect(); final boolean mainframe = request.isForMainFrame(); final boolean gesture = request.hasGesture(); logger.log(String.format(LOCALE, "%s shouldOverrideUrlLoading() 1/4 CALL : %s %s", SPACE, method, url)); logger.log(String.format(LOCALE, "%s shouldOverrideUrlLoading() 2/4 CALL INFO : redirect=%s, forMainFrame=%s, hasGesture=%s", SPACE, redirect, mainframe, gesture)); logger.log(String.format(LOCALE, "%s shouldOverrideUrlLoading() 3/4 REQ HEADERS: %s", SPACE, request.getRequestHeaders())); logger.log(String.format(LOCALE, "%s shouldOverrideUrlLoading() 4/4 OVERRIDE : %s", SPACE, retVal)); } } DebugWebViewClientLogger(); DebugWebViewClientLogger(@NonNull final String tag); @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE) protected DebugWebViewClientLogger(@NonNull final LogEngine logEngine); @RequiresApi(api = Build.VERSION_CODES.M) void onReceivedError(final WebView view, final WebResourceRequest request, final WebResourceError error); void onReceivedError(final WebView view, final int errorCode, final String description, final String failingUrl); @RequiresApi(api = Build.VERSION_CODES.M) void onReceivedHttpError(final WebView view, final WebResourceRequest request, final WebResourceResponse errorResponse); void onReceivedSslError(final WebView view, final SslErrorHandler handler, final SslError error); @RequiresApi(api = Build.VERSION_CODES.N) void shouldOverrideUrlLoading(WebView view, WebResourceRequest request, boolean retVal); void shouldOverrideUrlLoading(WebView view, String url, boolean retVal); void onLoadResource(WebView view, String url); @TargetApi(Build.VERSION_CODES.M) void onPageCommitVisible(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) void shouldInterceptRequest(WebView view, String url, WebResourceResponse retVal); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) void shouldInterceptRequest(WebView view, WebResourceRequest request, final WebResourceResponse retVal); void onTooManyRedirects(WebView view, Message cancelMsg, Message continueMsg); void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm); void onPageStarted(WebView view, String url, Bitmap facIcon); void onPageFinished(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) void onReceivedClientCertRequest(WebView view, ClientCertRequest request); void onFormResubmission(final WebView view, final Message dontResend, final Message resend); void doUpdateVisitedHistory(final WebView view, final String url, final boolean isReload); void shouldOverrideKeyEvent(final WebView view, final KeyEvent event, boolean retVal); void onUnhandledInputEvent(final WebView view, final InputEvent event); void onUnhandledKeyEvent(final WebView view, final KeyEvent event); void onScaleChanged(final WebView view, final float oldScale, final float newScale); void onReceivedLoginRequest(final WebView view, final String realm, final String account, final String args); @RequiresApi(api = Build.VERSION_CODES.O) void onRenderProcessGone(final WebView view, final RenderProcessGoneDetail detail, boolean retVal); @RequiresApi(api = Build.VERSION_CODES.O_MR1) void onSafeBrowsingHit(final WebView view, final WebResourceRequest request, final int threatType, final SafeBrowsingResponse callback); @Override boolean isLoggingEnabled(); @Override void setLoggingEnabled(final boolean enabled); @Override boolean isLogKeyEventsEnabled(); @Override void setLogKeyEventsEnabled(final boolean enabled); } | @Test public void shouldOverrideUrlLoading() { final String url = "foo"; logger.setLoggingEnabled(false); logger.shouldOverrideUrlLoading(webView, url, false); verifyLogNotCalled(); logger.setLoggingEnabled(true); logger.shouldOverrideUrlLoading(webView, url, false); verifyLogEngine().log(Mockito.anyString()); } |
DebugWebViewClientLogger implements LogControl { public void onLoadResource(WebView view, String url) { if (loggingEnabled) { logger.log(String.format(LOCALE, "%s onLoadResource() %s", SPACE, url)); } } DebugWebViewClientLogger(); DebugWebViewClientLogger(@NonNull final String tag); @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE) protected DebugWebViewClientLogger(@NonNull final LogEngine logEngine); @RequiresApi(api = Build.VERSION_CODES.M) void onReceivedError(final WebView view, final WebResourceRequest request, final WebResourceError error); void onReceivedError(final WebView view, final int errorCode, final String description, final String failingUrl); @RequiresApi(api = Build.VERSION_CODES.M) void onReceivedHttpError(final WebView view, final WebResourceRequest request, final WebResourceResponse errorResponse); void onReceivedSslError(final WebView view, final SslErrorHandler handler, final SslError error); @RequiresApi(api = Build.VERSION_CODES.N) void shouldOverrideUrlLoading(WebView view, WebResourceRequest request, boolean retVal); void shouldOverrideUrlLoading(WebView view, String url, boolean retVal); void onLoadResource(WebView view, String url); @TargetApi(Build.VERSION_CODES.M) void onPageCommitVisible(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) void shouldInterceptRequest(WebView view, String url, WebResourceResponse retVal); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) void shouldInterceptRequest(WebView view, WebResourceRequest request, final WebResourceResponse retVal); void onTooManyRedirects(WebView view, Message cancelMsg, Message continueMsg); void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm); void onPageStarted(WebView view, String url, Bitmap facIcon); void onPageFinished(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) void onReceivedClientCertRequest(WebView view, ClientCertRequest request); void onFormResubmission(final WebView view, final Message dontResend, final Message resend); void doUpdateVisitedHistory(final WebView view, final String url, final boolean isReload); void shouldOverrideKeyEvent(final WebView view, final KeyEvent event, boolean retVal); void onUnhandledInputEvent(final WebView view, final InputEvent event); void onUnhandledKeyEvent(final WebView view, final KeyEvent event); void onScaleChanged(final WebView view, final float oldScale, final float newScale); void onReceivedLoginRequest(final WebView view, final String realm, final String account, final String args); @RequiresApi(api = Build.VERSION_CODES.O) void onRenderProcessGone(final WebView view, final RenderProcessGoneDetail detail, boolean retVal); @RequiresApi(api = Build.VERSION_CODES.O_MR1) void onSafeBrowsingHit(final WebView view, final WebResourceRequest request, final int threatType, final SafeBrowsingResponse callback); @Override boolean isLoggingEnabled(); @Override void setLoggingEnabled(final boolean enabled); @Override boolean isLogKeyEventsEnabled(); @Override void setLogKeyEventsEnabled(final boolean enabled); } | @Test public void onLoadResource() { final String url = "foo"; logger.setLoggingEnabled(false); logger.onLoadResource(webView, url); verifyLogNotCalled(); logger.setLoggingEnabled(true); logger.onLoadResource(webView, url); verifyLogEngine().log(Mockito.anyString()); } |
DebugWebViewClientLogger implements LogControl { @TargetApi(Build.VERSION_CODES.M) public void onPageCommitVisible(WebView view, String url) { if (loggingEnabled) { logger.log(String.format(LOCALE, "%s onPageCommitVisible() %s", SPACE, url)); } } DebugWebViewClientLogger(); DebugWebViewClientLogger(@NonNull final String tag); @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE) protected DebugWebViewClientLogger(@NonNull final LogEngine logEngine); @RequiresApi(api = Build.VERSION_CODES.M) void onReceivedError(final WebView view, final WebResourceRequest request, final WebResourceError error); void onReceivedError(final WebView view, final int errorCode, final String description, final String failingUrl); @RequiresApi(api = Build.VERSION_CODES.M) void onReceivedHttpError(final WebView view, final WebResourceRequest request, final WebResourceResponse errorResponse); void onReceivedSslError(final WebView view, final SslErrorHandler handler, final SslError error); @RequiresApi(api = Build.VERSION_CODES.N) void shouldOverrideUrlLoading(WebView view, WebResourceRequest request, boolean retVal); void shouldOverrideUrlLoading(WebView view, String url, boolean retVal); void onLoadResource(WebView view, String url); @TargetApi(Build.VERSION_CODES.M) void onPageCommitVisible(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) void shouldInterceptRequest(WebView view, String url, WebResourceResponse retVal); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) void shouldInterceptRequest(WebView view, WebResourceRequest request, final WebResourceResponse retVal); void onTooManyRedirects(WebView view, Message cancelMsg, Message continueMsg); void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm); void onPageStarted(WebView view, String url, Bitmap facIcon); void onPageFinished(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) void onReceivedClientCertRequest(WebView view, ClientCertRequest request); void onFormResubmission(final WebView view, final Message dontResend, final Message resend); void doUpdateVisitedHistory(final WebView view, final String url, final boolean isReload); void shouldOverrideKeyEvent(final WebView view, final KeyEvent event, boolean retVal); void onUnhandledInputEvent(final WebView view, final InputEvent event); void onUnhandledKeyEvent(final WebView view, final KeyEvent event); void onScaleChanged(final WebView view, final float oldScale, final float newScale); void onReceivedLoginRequest(final WebView view, final String realm, final String account, final String args); @RequiresApi(api = Build.VERSION_CODES.O) void onRenderProcessGone(final WebView view, final RenderProcessGoneDetail detail, boolean retVal); @RequiresApi(api = Build.VERSION_CODES.O_MR1) void onSafeBrowsingHit(final WebView view, final WebResourceRequest request, final int threatType, final SafeBrowsingResponse callback); @Override boolean isLoggingEnabled(); @Override void setLoggingEnabled(final boolean enabled); @Override boolean isLogKeyEventsEnabled(); @Override void setLogKeyEventsEnabled(final boolean enabled); } | @Test public void onPageCommitVisible() { final String url = "foo"; logger.setLoggingEnabled(false); logger.onPageCommitVisible(webView, url); verifyLogNotCalled(); logger.setLoggingEnabled(true); logger.onPageCommitVisible(webView, url); verifyLogEngine().log(Mockito.anyString()); } |
DebugWebViewClientLogger implements LogControl { @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) public void shouldInterceptRequest(WebView view, String url, WebResourceResponse retVal) { if (loggingEnabled) { final String result = retVal == null ? "false" : StringUtils.toString(retVal); logger.log(String.format(LOCALE, "%s shouldInterceptRequest() 1/2 CALL : %s", SPACE, url)); logger.log(String.format(LOCALE, "%s shouldInterceptRequest() 2/2 OVERRIDE: %s", SPACE, url, result)); } } DebugWebViewClientLogger(); DebugWebViewClientLogger(@NonNull final String tag); @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE) protected DebugWebViewClientLogger(@NonNull final LogEngine logEngine); @RequiresApi(api = Build.VERSION_CODES.M) void onReceivedError(final WebView view, final WebResourceRequest request, final WebResourceError error); void onReceivedError(final WebView view, final int errorCode, final String description, final String failingUrl); @RequiresApi(api = Build.VERSION_CODES.M) void onReceivedHttpError(final WebView view, final WebResourceRequest request, final WebResourceResponse errorResponse); void onReceivedSslError(final WebView view, final SslErrorHandler handler, final SslError error); @RequiresApi(api = Build.VERSION_CODES.N) void shouldOverrideUrlLoading(WebView view, WebResourceRequest request, boolean retVal); void shouldOverrideUrlLoading(WebView view, String url, boolean retVal); void onLoadResource(WebView view, String url); @TargetApi(Build.VERSION_CODES.M) void onPageCommitVisible(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) void shouldInterceptRequest(WebView view, String url, WebResourceResponse retVal); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) void shouldInterceptRequest(WebView view, WebResourceRequest request, final WebResourceResponse retVal); void onTooManyRedirects(WebView view, Message cancelMsg, Message continueMsg); void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm); void onPageStarted(WebView view, String url, Bitmap facIcon); void onPageFinished(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) void onReceivedClientCertRequest(WebView view, ClientCertRequest request); void onFormResubmission(final WebView view, final Message dontResend, final Message resend); void doUpdateVisitedHistory(final WebView view, final String url, final boolean isReload); void shouldOverrideKeyEvent(final WebView view, final KeyEvent event, boolean retVal); void onUnhandledInputEvent(final WebView view, final InputEvent event); void onUnhandledKeyEvent(final WebView view, final KeyEvent event); void onScaleChanged(final WebView view, final float oldScale, final float newScale); void onReceivedLoginRequest(final WebView view, final String realm, final String account, final String args); @RequiresApi(api = Build.VERSION_CODES.O) void onRenderProcessGone(final WebView view, final RenderProcessGoneDetail detail, boolean retVal); @RequiresApi(api = Build.VERSION_CODES.O_MR1) void onSafeBrowsingHit(final WebView view, final WebResourceRequest request, final int threatType, final SafeBrowsingResponse callback); @Override boolean isLoggingEnabled(); @Override void setLoggingEnabled(final boolean enabled); @Override boolean isLogKeyEventsEnabled(); @Override void setLogKeyEventsEnabled(final boolean enabled); } | @Test public void shouldInterceptRequest() { final String url = "foo"; final WebResourceResponse response = Mockito.mock(WebResourceResponse.class); logger.setLoggingEnabled(false); logger.shouldInterceptRequest(webView, url, response); verifyLogNotCalled(); logger.setLoggingEnabled(true); logger.shouldInterceptRequest(webView, url, response); verifyLogEngine().log(Mockito.anyString()); } |
DebugWebViewClient extends WebViewClient implements LogControl { @RequiresApi(api = Build.VERSION_CODES.M) @Override public void onReceivedHttpError(final WebView view, final WebResourceRequest request, final WebResourceResponse errorResponse) { logger.onReceivedHttpError(view, request, errorResponse); client.onReceivedHttpError(view, request, errorResponse); } DebugWebViewClient(); DebugWebViewClient(@NonNull final WebViewClient client); @SuppressWarnings("WeakerAccess") DebugWebViewClient(
@NonNull final WebViewClient client,
@NonNull final DebugWebViewClientLogger logger); @RequiresApi(api = Build.VERSION_CODES.M) @Override void onReceivedError(final WebView view, final WebResourceRequest request, final WebResourceError error); @Override @Deprecated void onReceivedError(final WebView view, final int errorCode, final String description, final String failingUrl); @RequiresApi(api = Build.VERSION_CODES.M) @Override void onReceivedHttpError(final WebView view, final WebResourceRequest request, final WebResourceResponse errorResponse); @Override void onReceivedSslError(final WebView view, final SslErrorHandler handler, final SslError error); @RequiresApi(api = Build.VERSION_CODES.N) @Override boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request); @Override boolean shouldOverrideUrlLoading(WebView view, String url); @Override void onLoadResource(WebView view, String url); @TargetApi(Build.VERSION_CODES.M) @Override void onPageCommitVisible(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Deprecated WebResourceResponse shouldInterceptRequest(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request); @Override @Deprecated @SuppressWarnings("deprecation") //for use with older versions void onTooManyRedirects(WebView view, Message cancelMsg, Message continueMsg); @Override void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm); @Override void onPageStarted(WebView view, String url, Bitmap facIcon); @Override void onPageFinished(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override void onReceivedClientCertRequest(WebView view, ClientCertRequest request); @Override void onFormResubmission(final WebView view, final Message dontResend, final Message resend); @Override void doUpdateVisitedHistory(final WebView view, final String url, final boolean isReload); @Override boolean shouldOverrideKeyEvent(final WebView view, final KeyEvent event); @SuppressWarnings("unused") void onUnhandledInputEvent(final WebView view, final InputEvent event); @Override void onUnhandledKeyEvent(final WebView view, final KeyEvent event); @Override void onScaleChanged(final WebView view, final float oldScale, final float newScale); @Override void onReceivedLoginRequest(final WebView view, final String realm, final String account, final String args); @RequiresApi(api = Build.VERSION_CODES.O) @Override boolean onRenderProcessGone(final WebView view, final RenderProcessGoneDetail detail); @RequiresApi(api = Build.VERSION_CODES.O_MR1) @Override void onSafeBrowsingHit(final WebView view, final WebResourceRequest request, final int threatType, final SafeBrowsingResponse callback); @Override boolean isLoggingEnabled(); @Override void setLoggingEnabled(final boolean enabled); @Override boolean isLogKeyEventsEnabled(); @Override void setLogKeyEventsEnabled(final boolean enabled); } | @Test public void onReceivedHttpError() { final WebResourceRequest request = Mockito.mock(WebResourceRequest.class); final WebResourceResponse response = Mockito.mock(WebResourceResponse.class); debugClient.onReceivedHttpError(webView, request, response); verifyLogger().onReceivedHttpError(webView, request, response); verifyWrappedClient().onReceivedHttpError(webView, request, response); } |
DebugWebViewClientLogger implements LogControl { public void onTooManyRedirects(WebView view, Message cancelMsg, Message continueMsg) { if (loggingEnabled) { logger.logError(String.format(LOCALE, "%s onTooManyRedirects()", SPACE)); } } DebugWebViewClientLogger(); DebugWebViewClientLogger(@NonNull final String tag); @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE) protected DebugWebViewClientLogger(@NonNull final LogEngine logEngine); @RequiresApi(api = Build.VERSION_CODES.M) void onReceivedError(final WebView view, final WebResourceRequest request, final WebResourceError error); void onReceivedError(final WebView view, final int errorCode, final String description, final String failingUrl); @RequiresApi(api = Build.VERSION_CODES.M) void onReceivedHttpError(final WebView view, final WebResourceRequest request, final WebResourceResponse errorResponse); void onReceivedSslError(final WebView view, final SslErrorHandler handler, final SslError error); @RequiresApi(api = Build.VERSION_CODES.N) void shouldOverrideUrlLoading(WebView view, WebResourceRequest request, boolean retVal); void shouldOverrideUrlLoading(WebView view, String url, boolean retVal); void onLoadResource(WebView view, String url); @TargetApi(Build.VERSION_CODES.M) void onPageCommitVisible(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) void shouldInterceptRequest(WebView view, String url, WebResourceResponse retVal); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) void shouldInterceptRequest(WebView view, WebResourceRequest request, final WebResourceResponse retVal); void onTooManyRedirects(WebView view, Message cancelMsg, Message continueMsg); void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm); void onPageStarted(WebView view, String url, Bitmap facIcon); void onPageFinished(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) void onReceivedClientCertRequest(WebView view, ClientCertRequest request); void onFormResubmission(final WebView view, final Message dontResend, final Message resend); void doUpdateVisitedHistory(final WebView view, final String url, final boolean isReload); void shouldOverrideKeyEvent(final WebView view, final KeyEvent event, boolean retVal); void onUnhandledInputEvent(final WebView view, final InputEvent event); void onUnhandledKeyEvent(final WebView view, final KeyEvent event); void onScaleChanged(final WebView view, final float oldScale, final float newScale); void onReceivedLoginRequest(final WebView view, final String realm, final String account, final String args); @RequiresApi(api = Build.VERSION_CODES.O) void onRenderProcessGone(final WebView view, final RenderProcessGoneDetail detail, boolean retVal); @RequiresApi(api = Build.VERSION_CODES.O_MR1) void onSafeBrowsingHit(final WebView view, final WebResourceRequest request, final int threatType, final SafeBrowsingResponse callback); @Override boolean isLoggingEnabled(); @Override void setLoggingEnabled(final boolean enabled); @Override boolean isLogKeyEventsEnabled(); @Override void setLogKeyEventsEnabled(final boolean enabled); } | @Test public void onTooManyRedirects() { final Message cancelMsg = Mockito.mock(Message.class); final Message continueMsg = Mockito.mock(Message.class); logger.setLoggingEnabled(false); logger.onTooManyRedirects(webView, cancelMsg, continueMsg); verifyLogNotCalled(); logger.setLoggingEnabled(true); logger.onTooManyRedirects(webView, cancelMsg, continueMsg); verifyLogEngine().logError(Mockito.anyString()); } |
DebugWebViewClientLogger implements LogControl { public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) { if (loggingEnabled) { logger.logSecurity(String.format(LOCALE, "%s onReceivedHttpAuthRequest() %s %s %s", SPACE, host, realm, handler)); } } DebugWebViewClientLogger(); DebugWebViewClientLogger(@NonNull final String tag); @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE) protected DebugWebViewClientLogger(@NonNull final LogEngine logEngine); @RequiresApi(api = Build.VERSION_CODES.M) void onReceivedError(final WebView view, final WebResourceRequest request, final WebResourceError error); void onReceivedError(final WebView view, final int errorCode, final String description, final String failingUrl); @RequiresApi(api = Build.VERSION_CODES.M) void onReceivedHttpError(final WebView view, final WebResourceRequest request, final WebResourceResponse errorResponse); void onReceivedSslError(final WebView view, final SslErrorHandler handler, final SslError error); @RequiresApi(api = Build.VERSION_CODES.N) void shouldOverrideUrlLoading(WebView view, WebResourceRequest request, boolean retVal); void shouldOverrideUrlLoading(WebView view, String url, boolean retVal); void onLoadResource(WebView view, String url); @TargetApi(Build.VERSION_CODES.M) void onPageCommitVisible(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) void shouldInterceptRequest(WebView view, String url, WebResourceResponse retVal); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) void shouldInterceptRequest(WebView view, WebResourceRequest request, final WebResourceResponse retVal); void onTooManyRedirects(WebView view, Message cancelMsg, Message continueMsg); void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm); void onPageStarted(WebView view, String url, Bitmap facIcon); void onPageFinished(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) void onReceivedClientCertRequest(WebView view, ClientCertRequest request); void onFormResubmission(final WebView view, final Message dontResend, final Message resend); void doUpdateVisitedHistory(final WebView view, final String url, final boolean isReload); void shouldOverrideKeyEvent(final WebView view, final KeyEvent event, boolean retVal); void onUnhandledInputEvent(final WebView view, final InputEvent event); void onUnhandledKeyEvent(final WebView view, final KeyEvent event); void onScaleChanged(final WebView view, final float oldScale, final float newScale); void onReceivedLoginRequest(final WebView view, final String realm, final String account, final String args); @RequiresApi(api = Build.VERSION_CODES.O) void onRenderProcessGone(final WebView view, final RenderProcessGoneDetail detail, boolean retVal); @RequiresApi(api = Build.VERSION_CODES.O_MR1) void onSafeBrowsingHit(final WebView view, final WebResourceRequest request, final int threatType, final SafeBrowsingResponse callback); @Override boolean isLoggingEnabled(); @Override void setLoggingEnabled(final boolean enabled); @Override boolean isLogKeyEventsEnabled(); @Override void setLogKeyEventsEnabled(final boolean enabled); } | @Test public void onReceivedHttpAuthRequest() { final HttpAuthHandler handler = Mockito.mock(HttpAuthHandler.class); final String host = "foo"; final String realm = "bar"; logger.setLoggingEnabled(false); logger.onReceivedHttpAuthRequest(webView, handler, host, realm); verifyLogNotCalled(); logger.setLoggingEnabled(true); logger.onReceivedHttpAuthRequest(webView, handler, host, realm); verifyLogEngine().logSecurity(Mockito.anyString()); } |
DebugWebViewClientLogger implements LogControl { public void onPageStarted(WebView view, String url, Bitmap facIcon) { if (loggingEnabled) { logger.log(String.format(LOCALE, "%s onPageStarted() %s", IN, url)); } } DebugWebViewClientLogger(); DebugWebViewClientLogger(@NonNull final String tag); @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE) protected DebugWebViewClientLogger(@NonNull final LogEngine logEngine); @RequiresApi(api = Build.VERSION_CODES.M) void onReceivedError(final WebView view, final WebResourceRequest request, final WebResourceError error); void onReceivedError(final WebView view, final int errorCode, final String description, final String failingUrl); @RequiresApi(api = Build.VERSION_CODES.M) void onReceivedHttpError(final WebView view, final WebResourceRequest request, final WebResourceResponse errorResponse); void onReceivedSslError(final WebView view, final SslErrorHandler handler, final SslError error); @RequiresApi(api = Build.VERSION_CODES.N) void shouldOverrideUrlLoading(WebView view, WebResourceRequest request, boolean retVal); void shouldOverrideUrlLoading(WebView view, String url, boolean retVal); void onLoadResource(WebView view, String url); @TargetApi(Build.VERSION_CODES.M) void onPageCommitVisible(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) void shouldInterceptRequest(WebView view, String url, WebResourceResponse retVal); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) void shouldInterceptRequest(WebView view, WebResourceRequest request, final WebResourceResponse retVal); void onTooManyRedirects(WebView view, Message cancelMsg, Message continueMsg); void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm); void onPageStarted(WebView view, String url, Bitmap facIcon); void onPageFinished(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) void onReceivedClientCertRequest(WebView view, ClientCertRequest request); void onFormResubmission(final WebView view, final Message dontResend, final Message resend); void doUpdateVisitedHistory(final WebView view, final String url, final boolean isReload); void shouldOverrideKeyEvent(final WebView view, final KeyEvent event, boolean retVal); void onUnhandledInputEvent(final WebView view, final InputEvent event); void onUnhandledKeyEvent(final WebView view, final KeyEvent event); void onScaleChanged(final WebView view, final float oldScale, final float newScale); void onReceivedLoginRequest(final WebView view, final String realm, final String account, final String args); @RequiresApi(api = Build.VERSION_CODES.O) void onRenderProcessGone(final WebView view, final RenderProcessGoneDetail detail, boolean retVal); @RequiresApi(api = Build.VERSION_CODES.O_MR1) void onSafeBrowsingHit(final WebView view, final WebResourceRequest request, final int threatType, final SafeBrowsingResponse callback); @Override boolean isLoggingEnabled(); @Override void setLoggingEnabled(final boolean enabled); @Override boolean isLogKeyEventsEnabled(); @Override void setLogKeyEventsEnabled(final boolean enabled); } | @Test public void onPageStarted() { final String url = "foo"; final Bitmap bitmap = Mockito.mock(Bitmap.class); logger.setLoggingEnabled(false); logger.onPageStarted(webView, url, bitmap); verifyLogNotCalled(); logger.setLoggingEnabled(true); logger.onPageStarted(webView, url, bitmap); verifyLogEngine().log(Mockito.anyString()); } |
DebugWebViewClientLogger implements LogControl { public void onPageFinished(WebView view, String url) { if (loggingEnabled) { logger.log(String.format(LOCALE, "%s onPageFinished() %s", OUT, url)); } } DebugWebViewClientLogger(); DebugWebViewClientLogger(@NonNull final String tag); @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE) protected DebugWebViewClientLogger(@NonNull final LogEngine logEngine); @RequiresApi(api = Build.VERSION_CODES.M) void onReceivedError(final WebView view, final WebResourceRequest request, final WebResourceError error); void onReceivedError(final WebView view, final int errorCode, final String description, final String failingUrl); @RequiresApi(api = Build.VERSION_CODES.M) void onReceivedHttpError(final WebView view, final WebResourceRequest request, final WebResourceResponse errorResponse); void onReceivedSslError(final WebView view, final SslErrorHandler handler, final SslError error); @RequiresApi(api = Build.VERSION_CODES.N) void shouldOverrideUrlLoading(WebView view, WebResourceRequest request, boolean retVal); void shouldOverrideUrlLoading(WebView view, String url, boolean retVal); void onLoadResource(WebView view, String url); @TargetApi(Build.VERSION_CODES.M) void onPageCommitVisible(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) void shouldInterceptRequest(WebView view, String url, WebResourceResponse retVal); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) void shouldInterceptRequest(WebView view, WebResourceRequest request, final WebResourceResponse retVal); void onTooManyRedirects(WebView view, Message cancelMsg, Message continueMsg); void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm); void onPageStarted(WebView view, String url, Bitmap facIcon); void onPageFinished(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) void onReceivedClientCertRequest(WebView view, ClientCertRequest request); void onFormResubmission(final WebView view, final Message dontResend, final Message resend); void doUpdateVisitedHistory(final WebView view, final String url, final boolean isReload); void shouldOverrideKeyEvent(final WebView view, final KeyEvent event, boolean retVal); void onUnhandledInputEvent(final WebView view, final InputEvent event); void onUnhandledKeyEvent(final WebView view, final KeyEvent event); void onScaleChanged(final WebView view, final float oldScale, final float newScale); void onReceivedLoginRequest(final WebView view, final String realm, final String account, final String args); @RequiresApi(api = Build.VERSION_CODES.O) void onRenderProcessGone(final WebView view, final RenderProcessGoneDetail detail, boolean retVal); @RequiresApi(api = Build.VERSION_CODES.O_MR1) void onSafeBrowsingHit(final WebView view, final WebResourceRequest request, final int threatType, final SafeBrowsingResponse callback); @Override boolean isLoggingEnabled(); @Override void setLoggingEnabled(final boolean enabled); @Override boolean isLogKeyEventsEnabled(); @Override void setLogKeyEventsEnabled(final boolean enabled); } | @Test public void onPageFinished() { final String url = "foo"; logger.setLoggingEnabled(false); logger.onPageFinished(webView, url); verifyLogNotCalled(); logger.setLoggingEnabled(true); logger.onPageFinished(webView, url); verifyLogEngine().log(Mockito.anyString()); } |
DebugWebViewClientLogger implements LogControl { @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) public void onReceivedClientCertRequest(WebView view, ClientCertRequest request) { if (loggingEnabled) { logger.logSecurity(String.format(LOCALE, "%s onReceivedClientCertRequest() %s", SPACE, StringUtils.toString(request))); } } DebugWebViewClientLogger(); DebugWebViewClientLogger(@NonNull final String tag); @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE) protected DebugWebViewClientLogger(@NonNull final LogEngine logEngine); @RequiresApi(api = Build.VERSION_CODES.M) void onReceivedError(final WebView view, final WebResourceRequest request, final WebResourceError error); void onReceivedError(final WebView view, final int errorCode, final String description, final String failingUrl); @RequiresApi(api = Build.VERSION_CODES.M) void onReceivedHttpError(final WebView view, final WebResourceRequest request, final WebResourceResponse errorResponse); void onReceivedSslError(final WebView view, final SslErrorHandler handler, final SslError error); @RequiresApi(api = Build.VERSION_CODES.N) void shouldOverrideUrlLoading(WebView view, WebResourceRequest request, boolean retVal); void shouldOverrideUrlLoading(WebView view, String url, boolean retVal); void onLoadResource(WebView view, String url); @TargetApi(Build.VERSION_CODES.M) void onPageCommitVisible(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) void shouldInterceptRequest(WebView view, String url, WebResourceResponse retVal); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) void shouldInterceptRequest(WebView view, WebResourceRequest request, final WebResourceResponse retVal); void onTooManyRedirects(WebView view, Message cancelMsg, Message continueMsg); void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm); void onPageStarted(WebView view, String url, Bitmap facIcon); void onPageFinished(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) void onReceivedClientCertRequest(WebView view, ClientCertRequest request); void onFormResubmission(final WebView view, final Message dontResend, final Message resend); void doUpdateVisitedHistory(final WebView view, final String url, final boolean isReload); void shouldOverrideKeyEvent(final WebView view, final KeyEvent event, boolean retVal); void onUnhandledInputEvent(final WebView view, final InputEvent event); void onUnhandledKeyEvent(final WebView view, final KeyEvent event); void onScaleChanged(final WebView view, final float oldScale, final float newScale); void onReceivedLoginRequest(final WebView view, final String realm, final String account, final String args); @RequiresApi(api = Build.VERSION_CODES.O) void onRenderProcessGone(final WebView view, final RenderProcessGoneDetail detail, boolean retVal); @RequiresApi(api = Build.VERSION_CODES.O_MR1) void onSafeBrowsingHit(final WebView view, final WebResourceRequest request, final int threatType, final SafeBrowsingResponse callback); @Override boolean isLoggingEnabled(); @Override void setLoggingEnabled(final boolean enabled); @Override boolean isLogKeyEventsEnabled(); @Override void setLogKeyEventsEnabled(final boolean enabled); } | @Test public void onReceivedClientCertRequest() { final ClientCertRequest request = Mockito.mock(ClientCertRequest.class); logger.setLoggingEnabled(false); logger.onReceivedClientCertRequest(webView, request); verifyLogNotCalled(); logger.setLoggingEnabled(true); logger.onReceivedClientCertRequest(webView, request); verifyLogEngine().logSecurity(Mockito.anyString()); } |
DebugWebViewClientLogger implements LogControl { public void onFormResubmission(final WebView view, final Message dontResend, final Message resend) { if (loggingEnabled) { logger.log(String.format(LOCALE, "%s onFormResubmission()", SPACE)); } } DebugWebViewClientLogger(); DebugWebViewClientLogger(@NonNull final String tag); @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE) protected DebugWebViewClientLogger(@NonNull final LogEngine logEngine); @RequiresApi(api = Build.VERSION_CODES.M) void onReceivedError(final WebView view, final WebResourceRequest request, final WebResourceError error); void onReceivedError(final WebView view, final int errorCode, final String description, final String failingUrl); @RequiresApi(api = Build.VERSION_CODES.M) void onReceivedHttpError(final WebView view, final WebResourceRequest request, final WebResourceResponse errorResponse); void onReceivedSslError(final WebView view, final SslErrorHandler handler, final SslError error); @RequiresApi(api = Build.VERSION_CODES.N) void shouldOverrideUrlLoading(WebView view, WebResourceRequest request, boolean retVal); void shouldOverrideUrlLoading(WebView view, String url, boolean retVal); void onLoadResource(WebView view, String url); @TargetApi(Build.VERSION_CODES.M) void onPageCommitVisible(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) void shouldInterceptRequest(WebView view, String url, WebResourceResponse retVal); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) void shouldInterceptRequest(WebView view, WebResourceRequest request, final WebResourceResponse retVal); void onTooManyRedirects(WebView view, Message cancelMsg, Message continueMsg); void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm); void onPageStarted(WebView view, String url, Bitmap facIcon); void onPageFinished(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) void onReceivedClientCertRequest(WebView view, ClientCertRequest request); void onFormResubmission(final WebView view, final Message dontResend, final Message resend); void doUpdateVisitedHistory(final WebView view, final String url, final boolean isReload); void shouldOverrideKeyEvent(final WebView view, final KeyEvent event, boolean retVal); void onUnhandledInputEvent(final WebView view, final InputEvent event); void onUnhandledKeyEvent(final WebView view, final KeyEvent event); void onScaleChanged(final WebView view, final float oldScale, final float newScale); void onReceivedLoginRequest(final WebView view, final String realm, final String account, final String args); @RequiresApi(api = Build.VERSION_CODES.O) void onRenderProcessGone(final WebView view, final RenderProcessGoneDetail detail, boolean retVal); @RequiresApi(api = Build.VERSION_CODES.O_MR1) void onSafeBrowsingHit(final WebView view, final WebResourceRequest request, final int threatType, final SafeBrowsingResponse callback); @Override boolean isLoggingEnabled(); @Override void setLoggingEnabled(final boolean enabled); @Override boolean isLogKeyEventsEnabled(); @Override void setLogKeyEventsEnabled(final boolean enabled); } | @Test public void onFormResubmission() { final Message dontResend = Mockito.mock(Message.class); final Message resend = Mockito.mock(Message.class); logger.setLoggingEnabled(false); logger.onFormResubmission(webView, dontResend, resend); verifyLogNotCalled(); logger.setLoggingEnabled(true); logger.onFormResubmission(webView, dontResend, resend); verifyLogEngine().log(Mockito.anyString()); } |
DebugWebViewClientLogger implements LogControl { public void doUpdateVisitedHistory(final WebView view, final String url, final boolean isReload) { if (loggingEnabled) { logger.log(String.format(LOCALE, "%s doUpdateVisitedHistory() %s, isReload: %s", SPACE, url, isReload)); } } DebugWebViewClientLogger(); DebugWebViewClientLogger(@NonNull final String tag); @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE) protected DebugWebViewClientLogger(@NonNull final LogEngine logEngine); @RequiresApi(api = Build.VERSION_CODES.M) void onReceivedError(final WebView view, final WebResourceRequest request, final WebResourceError error); void onReceivedError(final WebView view, final int errorCode, final String description, final String failingUrl); @RequiresApi(api = Build.VERSION_CODES.M) void onReceivedHttpError(final WebView view, final WebResourceRequest request, final WebResourceResponse errorResponse); void onReceivedSslError(final WebView view, final SslErrorHandler handler, final SslError error); @RequiresApi(api = Build.VERSION_CODES.N) void shouldOverrideUrlLoading(WebView view, WebResourceRequest request, boolean retVal); void shouldOverrideUrlLoading(WebView view, String url, boolean retVal); void onLoadResource(WebView view, String url); @TargetApi(Build.VERSION_CODES.M) void onPageCommitVisible(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) void shouldInterceptRequest(WebView view, String url, WebResourceResponse retVal); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) void shouldInterceptRequest(WebView view, WebResourceRequest request, final WebResourceResponse retVal); void onTooManyRedirects(WebView view, Message cancelMsg, Message continueMsg); void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm); void onPageStarted(WebView view, String url, Bitmap facIcon); void onPageFinished(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) void onReceivedClientCertRequest(WebView view, ClientCertRequest request); void onFormResubmission(final WebView view, final Message dontResend, final Message resend); void doUpdateVisitedHistory(final WebView view, final String url, final boolean isReload); void shouldOverrideKeyEvent(final WebView view, final KeyEvent event, boolean retVal); void onUnhandledInputEvent(final WebView view, final InputEvent event); void onUnhandledKeyEvent(final WebView view, final KeyEvent event); void onScaleChanged(final WebView view, final float oldScale, final float newScale); void onReceivedLoginRequest(final WebView view, final String realm, final String account, final String args); @RequiresApi(api = Build.VERSION_CODES.O) void onRenderProcessGone(final WebView view, final RenderProcessGoneDetail detail, boolean retVal); @RequiresApi(api = Build.VERSION_CODES.O_MR1) void onSafeBrowsingHit(final WebView view, final WebResourceRequest request, final int threatType, final SafeBrowsingResponse callback); @Override boolean isLoggingEnabled(); @Override void setLoggingEnabled(final boolean enabled); @Override boolean isLogKeyEventsEnabled(); @Override void setLogKeyEventsEnabled(final boolean enabled); } | @Test public void doUpdateVisitedHistory() { final String url = "foo"; final boolean reload = true; logger.setLoggingEnabled(false); logger.doUpdateVisitedHistory(webView, url, reload); verifyLogNotCalled(); logger.setLoggingEnabled(true); logger.doUpdateVisitedHistory(webView, url, reload); verifyLogEngine().log(Mockito.anyString()); } |
DebugWebViewClientLogger implements LogControl { public void shouldOverrideKeyEvent(final WebView view, final KeyEvent event, boolean retVal) { if (loggingEnabled && logKeyEventsEnabled) { logger.logKeyEvent(String.format(LOCALE, "%s shouldOverrideKeyEvent() 1/2 EVENT : %s", SPACE, event)); logger.logKeyEvent(String.format(LOCALE, "%s shouldOverrideKeyEvent() 2/2 OVERRIDE: %s", SPACE, retVal)); } } DebugWebViewClientLogger(); DebugWebViewClientLogger(@NonNull final String tag); @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE) protected DebugWebViewClientLogger(@NonNull final LogEngine logEngine); @RequiresApi(api = Build.VERSION_CODES.M) void onReceivedError(final WebView view, final WebResourceRequest request, final WebResourceError error); void onReceivedError(final WebView view, final int errorCode, final String description, final String failingUrl); @RequiresApi(api = Build.VERSION_CODES.M) void onReceivedHttpError(final WebView view, final WebResourceRequest request, final WebResourceResponse errorResponse); void onReceivedSslError(final WebView view, final SslErrorHandler handler, final SslError error); @RequiresApi(api = Build.VERSION_CODES.N) void shouldOverrideUrlLoading(WebView view, WebResourceRequest request, boolean retVal); void shouldOverrideUrlLoading(WebView view, String url, boolean retVal); void onLoadResource(WebView view, String url); @TargetApi(Build.VERSION_CODES.M) void onPageCommitVisible(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) void shouldInterceptRequest(WebView view, String url, WebResourceResponse retVal); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) void shouldInterceptRequest(WebView view, WebResourceRequest request, final WebResourceResponse retVal); void onTooManyRedirects(WebView view, Message cancelMsg, Message continueMsg); void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm); void onPageStarted(WebView view, String url, Bitmap facIcon); void onPageFinished(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) void onReceivedClientCertRequest(WebView view, ClientCertRequest request); void onFormResubmission(final WebView view, final Message dontResend, final Message resend); void doUpdateVisitedHistory(final WebView view, final String url, final boolean isReload); void shouldOverrideKeyEvent(final WebView view, final KeyEvent event, boolean retVal); void onUnhandledInputEvent(final WebView view, final InputEvent event); void onUnhandledKeyEvent(final WebView view, final KeyEvent event); void onScaleChanged(final WebView view, final float oldScale, final float newScale); void onReceivedLoginRequest(final WebView view, final String realm, final String account, final String args); @RequiresApi(api = Build.VERSION_CODES.O) void onRenderProcessGone(final WebView view, final RenderProcessGoneDetail detail, boolean retVal); @RequiresApi(api = Build.VERSION_CODES.O_MR1) void onSafeBrowsingHit(final WebView view, final WebResourceRequest request, final int threatType, final SafeBrowsingResponse callback); @Override boolean isLoggingEnabled(); @Override void setLoggingEnabled(final boolean enabled); @Override boolean isLogKeyEventsEnabled(); @Override void setLogKeyEventsEnabled(final boolean enabled); } | @Test public void shouldOverrideKeyEvent() { final KeyEvent keyEvent = Mockito.mock(KeyEvent.class); logger.setLoggingEnabled(false); logger.setLogKeyEventsEnabled(false); logger.shouldOverrideKeyEvent(webView, keyEvent, false); verifyLogNotCalled(); logger.setLoggingEnabled(false); logger.setLogKeyEventsEnabled(true); logger.shouldOverrideKeyEvent(webView, keyEvent, false); verifyLogNotCalled(); logger.setLoggingEnabled(true); logger.setLogKeyEventsEnabled(false); logger.shouldOverrideKeyEvent(webView, keyEvent, false); verifyLogNotCalled(); logger.setLoggingEnabled(true); logger.setLogKeyEventsEnabled(true); logger.shouldOverrideKeyEvent(webView, keyEvent, false); verifyLogEngine().logKeyEvent(Mockito.anyString()); } |
DebugWebViewClientLogger implements LogControl { public void onUnhandledInputEvent(final WebView view, final InputEvent event) { if (loggingEnabled && logKeyEventsEnabled) { logger.logKeyEvent(String.format(LOCALE, "%s onUnhandledInputEvent() %s", SPACE, event)); } } DebugWebViewClientLogger(); DebugWebViewClientLogger(@NonNull final String tag); @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE) protected DebugWebViewClientLogger(@NonNull final LogEngine logEngine); @RequiresApi(api = Build.VERSION_CODES.M) void onReceivedError(final WebView view, final WebResourceRequest request, final WebResourceError error); void onReceivedError(final WebView view, final int errorCode, final String description, final String failingUrl); @RequiresApi(api = Build.VERSION_CODES.M) void onReceivedHttpError(final WebView view, final WebResourceRequest request, final WebResourceResponse errorResponse); void onReceivedSslError(final WebView view, final SslErrorHandler handler, final SslError error); @RequiresApi(api = Build.VERSION_CODES.N) void shouldOverrideUrlLoading(WebView view, WebResourceRequest request, boolean retVal); void shouldOverrideUrlLoading(WebView view, String url, boolean retVal); void onLoadResource(WebView view, String url); @TargetApi(Build.VERSION_CODES.M) void onPageCommitVisible(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) void shouldInterceptRequest(WebView view, String url, WebResourceResponse retVal); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) void shouldInterceptRequest(WebView view, WebResourceRequest request, final WebResourceResponse retVal); void onTooManyRedirects(WebView view, Message cancelMsg, Message continueMsg); void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm); void onPageStarted(WebView view, String url, Bitmap facIcon); void onPageFinished(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) void onReceivedClientCertRequest(WebView view, ClientCertRequest request); void onFormResubmission(final WebView view, final Message dontResend, final Message resend); void doUpdateVisitedHistory(final WebView view, final String url, final boolean isReload); void shouldOverrideKeyEvent(final WebView view, final KeyEvent event, boolean retVal); void onUnhandledInputEvent(final WebView view, final InputEvent event); void onUnhandledKeyEvent(final WebView view, final KeyEvent event); void onScaleChanged(final WebView view, final float oldScale, final float newScale); void onReceivedLoginRequest(final WebView view, final String realm, final String account, final String args); @RequiresApi(api = Build.VERSION_CODES.O) void onRenderProcessGone(final WebView view, final RenderProcessGoneDetail detail, boolean retVal); @RequiresApi(api = Build.VERSION_CODES.O_MR1) void onSafeBrowsingHit(final WebView view, final WebResourceRequest request, final int threatType, final SafeBrowsingResponse callback); @Override boolean isLoggingEnabled(); @Override void setLoggingEnabled(final boolean enabled); @Override boolean isLogKeyEventsEnabled(); @Override void setLogKeyEventsEnabled(final boolean enabled); } | @Test public void onUnhandledInputEvent() { final InputEvent inputEvent = Mockito.mock(InputEvent.class); logger.setLoggingEnabled(false); logger.setLogKeyEventsEnabled(false); logger.onUnhandledInputEvent(webView, inputEvent); verifyLogNotCalled(); logger.setLoggingEnabled(false); logger.setLogKeyEventsEnabled(true); logger.onUnhandledInputEvent(webView, inputEvent); verifyLogNotCalled(); logger.setLoggingEnabled(true); logger.setLogKeyEventsEnabled(false); logger.onUnhandledInputEvent(webView, inputEvent); verifyLogNotCalled(); logger.setLoggingEnabled(true); logger.setLogKeyEventsEnabled(true); logger.onUnhandledInputEvent(webView, inputEvent); verifyLogEngine().logKeyEvent(Mockito.anyString()); } |
DebugWebViewClientLogger implements LogControl { public void onUnhandledKeyEvent(final WebView view, final KeyEvent event) { if (loggingEnabled && logKeyEventsEnabled) { logger.logKeyEvent(String.format(LOCALE, "%s onUnhandledKeyEvent() %s", SPACE, event)); } } DebugWebViewClientLogger(); DebugWebViewClientLogger(@NonNull final String tag); @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE) protected DebugWebViewClientLogger(@NonNull final LogEngine logEngine); @RequiresApi(api = Build.VERSION_CODES.M) void onReceivedError(final WebView view, final WebResourceRequest request, final WebResourceError error); void onReceivedError(final WebView view, final int errorCode, final String description, final String failingUrl); @RequiresApi(api = Build.VERSION_CODES.M) void onReceivedHttpError(final WebView view, final WebResourceRequest request, final WebResourceResponse errorResponse); void onReceivedSslError(final WebView view, final SslErrorHandler handler, final SslError error); @RequiresApi(api = Build.VERSION_CODES.N) void shouldOverrideUrlLoading(WebView view, WebResourceRequest request, boolean retVal); void shouldOverrideUrlLoading(WebView view, String url, boolean retVal); void onLoadResource(WebView view, String url); @TargetApi(Build.VERSION_CODES.M) void onPageCommitVisible(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) void shouldInterceptRequest(WebView view, String url, WebResourceResponse retVal); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) void shouldInterceptRequest(WebView view, WebResourceRequest request, final WebResourceResponse retVal); void onTooManyRedirects(WebView view, Message cancelMsg, Message continueMsg); void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm); void onPageStarted(WebView view, String url, Bitmap facIcon); void onPageFinished(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) void onReceivedClientCertRequest(WebView view, ClientCertRequest request); void onFormResubmission(final WebView view, final Message dontResend, final Message resend); void doUpdateVisitedHistory(final WebView view, final String url, final boolean isReload); void shouldOverrideKeyEvent(final WebView view, final KeyEvent event, boolean retVal); void onUnhandledInputEvent(final WebView view, final InputEvent event); void onUnhandledKeyEvent(final WebView view, final KeyEvent event); void onScaleChanged(final WebView view, final float oldScale, final float newScale); void onReceivedLoginRequest(final WebView view, final String realm, final String account, final String args); @RequiresApi(api = Build.VERSION_CODES.O) void onRenderProcessGone(final WebView view, final RenderProcessGoneDetail detail, boolean retVal); @RequiresApi(api = Build.VERSION_CODES.O_MR1) void onSafeBrowsingHit(final WebView view, final WebResourceRequest request, final int threatType, final SafeBrowsingResponse callback); @Override boolean isLoggingEnabled(); @Override void setLoggingEnabled(final boolean enabled); @Override boolean isLogKeyEventsEnabled(); @Override void setLogKeyEventsEnabled(final boolean enabled); } | @Test public void onUnhandledKeyEvent() { final KeyEvent keyEvent = Mockito.mock(KeyEvent.class); logger.setLoggingEnabled(false); logger.setLogKeyEventsEnabled(false); logger.onUnhandledKeyEvent(webView, keyEvent); verifyLogNotCalled(); logger.setLoggingEnabled(false); logger.setLogKeyEventsEnabled(true); logger.onUnhandledKeyEvent(webView, keyEvent); verifyLogNotCalled(); logger.setLoggingEnabled(true); logger.setLogKeyEventsEnabled(false); logger.onUnhandledKeyEvent(webView, keyEvent); verifyLogNotCalled(); logger.setLoggingEnabled(true); logger.setLogKeyEventsEnabled(true); logger.onUnhandledKeyEvent(webView, keyEvent); verifyLogEngine().logKeyEvent(Mockito.anyString()); } |
DebugWebViewClient extends WebViewClient implements LogControl { @Override public void onReceivedSslError(final WebView view, final SslErrorHandler handler, final SslError error) { logger.onReceivedSslError(view, handler, error); client.onReceivedSslError(view, handler, error); } DebugWebViewClient(); DebugWebViewClient(@NonNull final WebViewClient client); @SuppressWarnings("WeakerAccess") DebugWebViewClient(
@NonNull final WebViewClient client,
@NonNull final DebugWebViewClientLogger logger); @RequiresApi(api = Build.VERSION_CODES.M) @Override void onReceivedError(final WebView view, final WebResourceRequest request, final WebResourceError error); @Override @Deprecated void onReceivedError(final WebView view, final int errorCode, final String description, final String failingUrl); @RequiresApi(api = Build.VERSION_CODES.M) @Override void onReceivedHttpError(final WebView view, final WebResourceRequest request, final WebResourceResponse errorResponse); @Override void onReceivedSslError(final WebView view, final SslErrorHandler handler, final SslError error); @RequiresApi(api = Build.VERSION_CODES.N) @Override boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request); @Override boolean shouldOverrideUrlLoading(WebView view, String url); @Override void onLoadResource(WebView view, String url); @TargetApi(Build.VERSION_CODES.M) @Override void onPageCommitVisible(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Deprecated WebResourceResponse shouldInterceptRequest(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request); @Override @Deprecated @SuppressWarnings("deprecation") //for use with older versions void onTooManyRedirects(WebView view, Message cancelMsg, Message continueMsg); @Override void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm); @Override void onPageStarted(WebView view, String url, Bitmap facIcon); @Override void onPageFinished(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override void onReceivedClientCertRequest(WebView view, ClientCertRequest request); @Override void onFormResubmission(final WebView view, final Message dontResend, final Message resend); @Override void doUpdateVisitedHistory(final WebView view, final String url, final boolean isReload); @Override boolean shouldOverrideKeyEvent(final WebView view, final KeyEvent event); @SuppressWarnings("unused") void onUnhandledInputEvent(final WebView view, final InputEvent event); @Override void onUnhandledKeyEvent(final WebView view, final KeyEvent event); @Override void onScaleChanged(final WebView view, final float oldScale, final float newScale); @Override void onReceivedLoginRequest(final WebView view, final String realm, final String account, final String args); @RequiresApi(api = Build.VERSION_CODES.O) @Override boolean onRenderProcessGone(final WebView view, final RenderProcessGoneDetail detail); @RequiresApi(api = Build.VERSION_CODES.O_MR1) @Override void onSafeBrowsingHit(final WebView view, final WebResourceRequest request, final int threatType, final SafeBrowsingResponse callback); @Override boolean isLoggingEnabled(); @Override void setLoggingEnabled(final boolean enabled); @Override boolean isLogKeyEventsEnabled(); @Override void setLogKeyEventsEnabled(final boolean enabled); } | @Test public void onReceivedSslError() { final SslErrorHandler errorHandler = Mockito.mock(SslErrorHandler.class); final SslError sslError = Mockito.mock(SslError.class); debugClient.onReceivedSslError(webView, errorHandler, sslError); verifyLogger().onReceivedSslError(webView, errorHandler, sslError); verifyWrappedClient().onReceivedSslError(webView, errorHandler, sslError); } |
DebugWebViewClientLogger implements LogControl { public void onScaleChanged(final WebView view, final float oldScale, final float newScale) { if (loggingEnabled) { logger.log(String.format(LOCALE, "%s onScaleChanged() old: %s, new: %s", SPACE, oldScale, newScale)); } } DebugWebViewClientLogger(); DebugWebViewClientLogger(@NonNull final String tag); @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE) protected DebugWebViewClientLogger(@NonNull final LogEngine logEngine); @RequiresApi(api = Build.VERSION_CODES.M) void onReceivedError(final WebView view, final WebResourceRequest request, final WebResourceError error); void onReceivedError(final WebView view, final int errorCode, final String description, final String failingUrl); @RequiresApi(api = Build.VERSION_CODES.M) void onReceivedHttpError(final WebView view, final WebResourceRequest request, final WebResourceResponse errorResponse); void onReceivedSslError(final WebView view, final SslErrorHandler handler, final SslError error); @RequiresApi(api = Build.VERSION_CODES.N) void shouldOverrideUrlLoading(WebView view, WebResourceRequest request, boolean retVal); void shouldOverrideUrlLoading(WebView view, String url, boolean retVal); void onLoadResource(WebView view, String url); @TargetApi(Build.VERSION_CODES.M) void onPageCommitVisible(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) void shouldInterceptRequest(WebView view, String url, WebResourceResponse retVal); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) void shouldInterceptRequest(WebView view, WebResourceRequest request, final WebResourceResponse retVal); void onTooManyRedirects(WebView view, Message cancelMsg, Message continueMsg); void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm); void onPageStarted(WebView view, String url, Bitmap facIcon); void onPageFinished(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) void onReceivedClientCertRequest(WebView view, ClientCertRequest request); void onFormResubmission(final WebView view, final Message dontResend, final Message resend); void doUpdateVisitedHistory(final WebView view, final String url, final boolean isReload); void shouldOverrideKeyEvent(final WebView view, final KeyEvent event, boolean retVal); void onUnhandledInputEvent(final WebView view, final InputEvent event); void onUnhandledKeyEvent(final WebView view, final KeyEvent event); void onScaleChanged(final WebView view, final float oldScale, final float newScale); void onReceivedLoginRequest(final WebView view, final String realm, final String account, final String args); @RequiresApi(api = Build.VERSION_CODES.O) void onRenderProcessGone(final WebView view, final RenderProcessGoneDetail detail, boolean retVal); @RequiresApi(api = Build.VERSION_CODES.O_MR1) void onSafeBrowsingHit(final WebView view, final WebResourceRequest request, final int threatType, final SafeBrowsingResponse callback); @Override boolean isLoggingEnabled(); @Override void setLoggingEnabled(final boolean enabled); @Override boolean isLogKeyEventsEnabled(); @Override void setLogKeyEventsEnabled(final boolean enabled); } | @Test public void onScaleChanged() { final float oldScale = 1.0f; final float newScale = 2.0f; logger.setLoggingEnabled(false); logger.onScaleChanged(webView, oldScale, newScale); verifyLogNotCalled(); logger.setLoggingEnabled(true); logger.onScaleChanged(webView, oldScale, newScale); verifyLogEngine().log(Mockito.anyString()); } |
DebugWebViewClientLogger implements LogControl { public void onReceivedLoginRequest(final WebView view, final String realm, final String account, final String args) { if (loggingEnabled) { logger.logSecurity(String.format(LOCALE, "%s onReceivedLoginRequest() %s, %s, %s", SPACE, realm, account, args)); } } DebugWebViewClientLogger(); DebugWebViewClientLogger(@NonNull final String tag); @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE) protected DebugWebViewClientLogger(@NonNull final LogEngine logEngine); @RequiresApi(api = Build.VERSION_CODES.M) void onReceivedError(final WebView view, final WebResourceRequest request, final WebResourceError error); void onReceivedError(final WebView view, final int errorCode, final String description, final String failingUrl); @RequiresApi(api = Build.VERSION_CODES.M) void onReceivedHttpError(final WebView view, final WebResourceRequest request, final WebResourceResponse errorResponse); void onReceivedSslError(final WebView view, final SslErrorHandler handler, final SslError error); @RequiresApi(api = Build.VERSION_CODES.N) void shouldOverrideUrlLoading(WebView view, WebResourceRequest request, boolean retVal); void shouldOverrideUrlLoading(WebView view, String url, boolean retVal); void onLoadResource(WebView view, String url); @TargetApi(Build.VERSION_CODES.M) void onPageCommitVisible(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) void shouldInterceptRequest(WebView view, String url, WebResourceResponse retVal); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) void shouldInterceptRequest(WebView view, WebResourceRequest request, final WebResourceResponse retVal); void onTooManyRedirects(WebView view, Message cancelMsg, Message continueMsg); void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm); void onPageStarted(WebView view, String url, Bitmap facIcon); void onPageFinished(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) void onReceivedClientCertRequest(WebView view, ClientCertRequest request); void onFormResubmission(final WebView view, final Message dontResend, final Message resend); void doUpdateVisitedHistory(final WebView view, final String url, final boolean isReload); void shouldOverrideKeyEvent(final WebView view, final KeyEvent event, boolean retVal); void onUnhandledInputEvent(final WebView view, final InputEvent event); void onUnhandledKeyEvent(final WebView view, final KeyEvent event); void onScaleChanged(final WebView view, final float oldScale, final float newScale); void onReceivedLoginRequest(final WebView view, final String realm, final String account, final String args); @RequiresApi(api = Build.VERSION_CODES.O) void onRenderProcessGone(final WebView view, final RenderProcessGoneDetail detail, boolean retVal); @RequiresApi(api = Build.VERSION_CODES.O_MR1) void onSafeBrowsingHit(final WebView view, final WebResourceRequest request, final int threatType, final SafeBrowsingResponse callback); @Override boolean isLoggingEnabled(); @Override void setLoggingEnabled(final boolean enabled); @Override boolean isLogKeyEventsEnabled(); @Override void setLogKeyEventsEnabled(final boolean enabled); } | @Test public void onReceivedLoginRequest() { final String realm = "realm"; final String account = "account"; final String args = "args"; logger.setLoggingEnabled(false); logger.onReceivedLoginRequest(webView, realm, account, args); verifyLogNotCalled(); logger.setLoggingEnabled(true); logger.onReceivedLoginRequest(webView, realm, account, args); verifyLogEngine().logSecurity(Mockito.anyString()); } |
DebugWebViewClientLogger implements LogControl { @RequiresApi(api = Build.VERSION_CODES.O) public void onRenderProcessGone(final WebView view, final RenderProcessGoneDetail detail, boolean retVal) { if (loggingEnabled) { logger.log(String.format(LOCALE, "%s onRenderProcessGone() 1/2 DETAIL: %s", SPACE, detail)); logger.log(String.format(LOCALE, "%s onRenderProcessGone() 2/2 RESULT: %s", SPACE, retVal)); } } DebugWebViewClientLogger(); DebugWebViewClientLogger(@NonNull final String tag); @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE) protected DebugWebViewClientLogger(@NonNull final LogEngine logEngine); @RequiresApi(api = Build.VERSION_CODES.M) void onReceivedError(final WebView view, final WebResourceRequest request, final WebResourceError error); void onReceivedError(final WebView view, final int errorCode, final String description, final String failingUrl); @RequiresApi(api = Build.VERSION_CODES.M) void onReceivedHttpError(final WebView view, final WebResourceRequest request, final WebResourceResponse errorResponse); void onReceivedSslError(final WebView view, final SslErrorHandler handler, final SslError error); @RequiresApi(api = Build.VERSION_CODES.N) void shouldOverrideUrlLoading(WebView view, WebResourceRequest request, boolean retVal); void shouldOverrideUrlLoading(WebView view, String url, boolean retVal); void onLoadResource(WebView view, String url); @TargetApi(Build.VERSION_CODES.M) void onPageCommitVisible(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) void shouldInterceptRequest(WebView view, String url, WebResourceResponse retVal); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) void shouldInterceptRequest(WebView view, WebResourceRequest request, final WebResourceResponse retVal); void onTooManyRedirects(WebView view, Message cancelMsg, Message continueMsg); void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm); void onPageStarted(WebView view, String url, Bitmap facIcon); void onPageFinished(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) void onReceivedClientCertRequest(WebView view, ClientCertRequest request); void onFormResubmission(final WebView view, final Message dontResend, final Message resend); void doUpdateVisitedHistory(final WebView view, final String url, final boolean isReload); void shouldOverrideKeyEvent(final WebView view, final KeyEvent event, boolean retVal); void onUnhandledInputEvent(final WebView view, final InputEvent event); void onUnhandledKeyEvent(final WebView view, final KeyEvent event); void onScaleChanged(final WebView view, final float oldScale, final float newScale); void onReceivedLoginRequest(final WebView view, final String realm, final String account, final String args); @RequiresApi(api = Build.VERSION_CODES.O) void onRenderProcessGone(final WebView view, final RenderProcessGoneDetail detail, boolean retVal); @RequiresApi(api = Build.VERSION_CODES.O_MR1) void onSafeBrowsingHit(final WebView view, final WebResourceRequest request, final int threatType, final SafeBrowsingResponse callback); @Override boolean isLoggingEnabled(); @Override void setLoggingEnabled(final boolean enabled); @Override boolean isLogKeyEventsEnabled(); @Override void setLogKeyEventsEnabled(final boolean enabled); } | @Test public void onRenderProcessGone() { final RenderProcessGoneDetail detail = Mockito.mock(RenderProcessGoneDetail.class); logger.setLoggingEnabled(false); logger.onRenderProcessGone(webView, detail, false); verifyLogNotCalled(); logger.setLoggingEnabled(true); logger.onRenderProcessGone(webView, detail, false); verifyLogEngine().log(Mockito.anyString()); } |
DebugWebViewClientLogger implements LogControl { @RequiresApi(api = Build.VERSION_CODES.O_MR1) public void onSafeBrowsingHit(final WebView view, final WebResourceRequest request, final int threatType, final SafeBrowsingResponse callback) { if (loggingEnabled) { final Uri url = request.getUrl(); final String method = request.getMethod(); final String threat = StringUtils.resolveThreatType(threatType); logger.log(String.format(LOCALE, "%s onSafeBrowsingHit() 1/3 CALL : %s %s", SPACE, method, url)); logger.log(String.format(LOCALE, "%s onSafeBrowsingHit() 2/3 REQ HEADERS: %s", SPACE, request.getRequestHeaders())); logger.log(String.format(LOCALE, "%s onSafeBrowsingHit() 3/3 THREAT : %s", SPACE, threat)); } } DebugWebViewClientLogger(); DebugWebViewClientLogger(@NonNull final String tag); @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE) protected DebugWebViewClientLogger(@NonNull final LogEngine logEngine); @RequiresApi(api = Build.VERSION_CODES.M) void onReceivedError(final WebView view, final WebResourceRequest request, final WebResourceError error); void onReceivedError(final WebView view, final int errorCode, final String description, final String failingUrl); @RequiresApi(api = Build.VERSION_CODES.M) void onReceivedHttpError(final WebView view, final WebResourceRequest request, final WebResourceResponse errorResponse); void onReceivedSslError(final WebView view, final SslErrorHandler handler, final SslError error); @RequiresApi(api = Build.VERSION_CODES.N) void shouldOverrideUrlLoading(WebView view, WebResourceRequest request, boolean retVal); void shouldOverrideUrlLoading(WebView view, String url, boolean retVal); void onLoadResource(WebView view, String url); @TargetApi(Build.VERSION_CODES.M) void onPageCommitVisible(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) void shouldInterceptRequest(WebView view, String url, WebResourceResponse retVal); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) void shouldInterceptRequest(WebView view, WebResourceRequest request, final WebResourceResponse retVal); void onTooManyRedirects(WebView view, Message cancelMsg, Message continueMsg); void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm); void onPageStarted(WebView view, String url, Bitmap facIcon); void onPageFinished(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) void onReceivedClientCertRequest(WebView view, ClientCertRequest request); void onFormResubmission(final WebView view, final Message dontResend, final Message resend); void doUpdateVisitedHistory(final WebView view, final String url, final boolean isReload); void shouldOverrideKeyEvent(final WebView view, final KeyEvent event, boolean retVal); void onUnhandledInputEvent(final WebView view, final InputEvent event); void onUnhandledKeyEvent(final WebView view, final KeyEvent event); void onScaleChanged(final WebView view, final float oldScale, final float newScale); void onReceivedLoginRequest(final WebView view, final String realm, final String account, final String args); @RequiresApi(api = Build.VERSION_CODES.O) void onRenderProcessGone(final WebView view, final RenderProcessGoneDetail detail, boolean retVal); @RequiresApi(api = Build.VERSION_CODES.O_MR1) void onSafeBrowsingHit(final WebView view, final WebResourceRequest request, final int threatType, final SafeBrowsingResponse callback); @Override boolean isLoggingEnabled(); @Override void setLoggingEnabled(final boolean enabled); @Override boolean isLogKeyEventsEnabled(); @Override void setLogKeyEventsEnabled(final boolean enabled); } | @Test public void onSafeBrowsingHit() { final WebResourceRequest request = Mockito.mock(WebResourceRequest.class); final SafeBrowsingResponse callback = Mockito.mock(SafeBrowsingResponse.class); final int threatType = -1; logger.setLoggingEnabled(false); logger.onSafeBrowsingHit(webView, request, threatType, callback); verifyLogNotCalled(); logger.setLoggingEnabled(true); logger.onSafeBrowsingHit(webView, request, threatType, callback); verifyLogEngine().log(Mockito.anyString()); } |
DebugWebViewClient extends WebViewClient implements LogControl { @RequiresApi(api = Build.VERSION_CODES.N) @Override public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) { final boolean retVal = client.shouldOverrideUrlLoading(view, request); logger.shouldOverrideUrlLoading(view, request, retVal); return retVal; } DebugWebViewClient(); DebugWebViewClient(@NonNull final WebViewClient client); @SuppressWarnings("WeakerAccess") DebugWebViewClient(
@NonNull final WebViewClient client,
@NonNull final DebugWebViewClientLogger logger); @RequiresApi(api = Build.VERSION_CODES.M) @Override void onReceivedError(final WebView view, final WebResourceRequest request, final WebResourceError error); @Override @Deprecated void onReceivedError(final WebView view, final int errorCode, final String description, final String failingUrl); @RequiresApi(api = Build.VERSION_CODES.M) @Override void onReceivedHttpError(final WebView view, final WebResourceRequest request, final WebResourceResponse errorResponse); @Override void onReceivedSslError(final WebView view, final SslErrorHandler handler, final SslError error); @RequiresApi(api = Build.VERSION_CODES.N) @Override boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request); @Override boolean shouldOverrideUrlLoading(WebView view, String url); @Override void onLoadResource(WebView view, String url); @TargetApi(Build.VERSION_CODES.M) @Override void onPageCommitVisible(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Deprecated WebResourceResponse shouldInterceptRequest(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request); @Override @Deprecated @SuppressWarnings("deprecation") //for use with older versions void onTooManyRedirects(WebView view, Message cancelMsg, Message continueMsg); @Override void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm); @Override void onPageStarted(WebView view, String url, Bitmap facIcon); @Override void onPageFinished(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override void onReceivedClientCertRequest(WebView view, ClientCertRequest request); @Override void onFormResubmission(final WebView view, final Message dontResend, final Message resend); @Override void doUpdateVisitedHistory(final WebView view, final String url, final boolean isReload); @Override boolean shouldOverrideKeyEvent(final WebView view, final KeyEvent event); @SuppressWarnings("unused") void onUnhandledInputEvent(final WebView view, final InputEvent event); @Override void onUnhandledKeyEvent(final WebView view, final KeyEvent event); @Override void onScaleChanged(final WebView view, final float oldScale, final float newScale); @Override void onReceivedLoginRequest(final WebView view, final String realm, final String account, final String args); @RequiresApi(api = Build.VERSION_CODES.O) @Override boolean onRenderProcessGone(final WebView view, final RenderProcessGoneDetail detail); @RequiresApi(api = Build.VERSION_CODES.O_MR1) @Override void onSafeBrowsingHit(final WebView view, final WebResourceRequest request, final int threatType, final SafeBrowsingResponse callback); @Override boolean isLoggingEnabled(); @Override void setLoggingEnabled(final boolean enabled); @Override boolean isLogKeyEventsEnabled(); @Override void setLogKeyEventsEnabled(final boolean enabled); } | @Test public void shouldOverrideUrlLoading() { final String url = "foo"; final boolean retVal = debugClient.shouldOverrideUrlLoading(webView, url); verifyLogger().shouldOverrideUrlLoading(webView, url, retVal); verifyWrappedClient().shouldOverrideUrlLoading(webView, url); }
@Test public void shouldOverrideUrlLoading1() { final WebResourceRequest request = Mockito.mock(WebResourceRequest.class); final boolean retVal = debugClient.shouldOverrideUrlLoading(webView, request); verifyLogger().shouldOverrideUrlLoading(webView, request, retVal); verifyWrappedClient().shouldOverrideUrlLoading(webView, request); } |
DebugWebViewClient extends WebViewClient implements LogControl { @Override public void onLoadResource(WebView view, String url) { logger.onLoadResource(view, url); client.onLoadResource(view, url); } DebugWebViewClient(); DebugWebViewClient(@NonNull final WebViewClient client); @SuppressWarnings("WeakerAccess") DebugWebViewClient(
@NonNull final WebViewClient client,
@NonNull final DebugWebViewClientLogger logger); @RequiresApi(api = Build.VERSION_CODES.M) @Override void onReceivedError(final WebView view, final WebResourceRequest request, final WebResourceError error); @Override @Deprecated void onReceivedError(final WebView view, final int errorCode, final String description, final String failingUrl); @RequiresApi(api = Build.VERSION_CODES.M) @Override void onReceivedHttpError(final WebView view, final WebResourceRequest request, final WebResourceResponse errorResponse); @Override void onReceivedSslError(final WebView view, final SslErrorHandler handler, final SslError error); @RequiresApi(api = Build.VERSION_CODES.N) @Override boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request); @Override boolean shouldOverrideUrlLoading(WebView view, String url); @Override void onLoadResource(WebView view, String url); @TargetApi(Build.VERSION_CODES.M) @Override void onPageCommitVisible(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Deprecated WebResourceResponse shouldInterceptRequest(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request); @Override @Deprecated @SuppressWarnings("deprecation") //for use with older versions void onTooManyRedirects(WebView view, Message cancelMsg, Message continueMsg); @Override void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm); @Override void onPageStarted(WebView view, String url, Bitmap facIcon); @Override void onPageFinished(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override void onReceivedClientCertRequest(WebView view, ClientCertRequest request); @Override void onFormResubmission(final WebView view, final Message dontResend, final Message resend); @Override void doUpdateVisitedHistory(final WebView view, final String url, final boolean isReload); @Override boolean shouldOverrideKeyEvent(final WebView view, final KeyEvent event); @SuppressWarnings("unused") void onUnhandledInputEvent(final WebView view, final InputEvent event); @Override void onUnhandledKeyEvent(final WebView view, final KeyEvent event); @Override void onScaleChanged(final WebView view, final float oldScale, final float newScale); @Override void onReceivedLoginRequest(final WebView view, final String realm, final String account, final String args); @RequiresApi(api = Build.VERSION_CODES.O) @Override boolean onRenderProcessGone(final WebView view, final RenderProcessGoneDetail detail); @RequiresApi(api = Build.VERSION_CODES.O_MR1) @Override void onSafeBrowsingHit(final WebView view, final WebResourceRequest request, final int threatType, final SafeBrowsingResponse callback); @Override boolean isLoggingEnabled(); @Override void setLoggingEnabled(final boolean enabled); @Override boolean isLogKeyEventsEnabled(); @Override void setLogKeyEventsEnabled(final boolean enabled); } | @Test public void onLoadResource() { final String url = "foo"; debugClient.onLoadResource(webView, url); verifyLogger().onLoadResource(webView, url); verifyWrappedClient().onLoadResource(webView, url); } |
DebugWebViewClient extends WebViewClient implements LogControl { @TargetApi(Build.VERSION_CODES.M) @Override public void onPageCommitVisible(WebView view, String url) { logger.onPageCommitVisible(view, url); client.onPageCommitVisible(view, url); } DebugWebViewClient(); DebugWebViewClient(@NonNull final WebViewClient client); @SuppressWarnings("WeakerAccess") DebugWebViewClient(
@NonNull final WebViewClient client,
@NonNull final DebugWebViewClientLogger logger); @RequiresApi(api = Build.VERSION_CODES.M) @Override void onReceivedError(final WebView view, final WebResourceRequest request, final WebResourceError error); @Override @Deprecated void onReceivedError(final WebView view, final int errorCode, final String description, final String failingUrl); @RequiresApi(api = Build.VERSION_CODES.M) @Override void onReceivedHttpError(final WebView view, final WebResourceRequest request, final WebResourceResponse errorResponse); @Override void onReceivedSslError(final WebView view, final SslErrorHandler handler, final SslError error); @RequiresApi(api = Build.VERSION_CODES.N) @Override boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request); @Override boolean shouldOverrideUrlLoading(WebView view, String url); @Override void onLoadResource(WebView view, String url); @TargetApi(Build.VERSION_CODES.M) @Override void onPageCommitVisible(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Deprecated WebResourceResponse shouldInterceptRequest(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request); @Override @Deprecated @SuppressWarnings("deprecation") //for use with older versions void onTooManyRedirects(WebView view, Message cancelMsg, Message continueMsg); @Override void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm); @Override void onPageStarted(WebView view, String url, Bitmap facIcon); @Override void onPageFinished(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override void onReceivedClientCertRequest(WebView view, ClientCertRequest request); @Override void onFormResubmission(final WebView view, final Message dontResend, final Message resend); @Override void doUpdateVisitedHistory(final WebView view, final String url, final boolean isReload); @Override boolean shouldOverrideKeyEvent(final WebView view, final KeyEvent event); @SuppressWarnings("unused") void onUnhandledInputEvent(final WebView view, final InputEvent event); @Override void onUnhandledKeyEvent(final WebView view, final KeyEvent event); @Override void onScaleChanged(final WebView view, final float oldScale, final float newScale); @Override void onReceivedLoginRequest(final WebView view, final String realm, final String account, final String args); @RequiresApi(api = Build.VERSION_CODES.O) @Override boolean onRenderProcessGone(final WebView view, final RenderProcessGoneDetail detail); @RequiresApi(api = Build.VERSION_CODES.O_MR1) @Override void onSafeBrowsingHit(final WebView view, final WebResourceRequest request, final int threatType, final SafeBrowsingResponse callback); @Override boolean isLoggingEnabled(); @Override void setLoggingEnabled(final boolean enabled); @Override boolean isLogKeyEventsEnabled(); @Override void setLogKeyEventsEnabled(final boolean enabled); } | @Test public void onPageCommitVisible() { final String url = "foo"; debugClient.onPageCommitVisible(webView, url); verifyLogger().onPageCommitVisible(webView, url); verifyWrappedClient().onPageCommitVisible(webView, url); } |
DebugWebViewClient extends WebViewClient implements LogControl { @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Deprecated public WebResourceResponse shouldInterceptRequest(WebView view, String url) { final WebResourceResponse retVal = client.shouldInterceptRequest(view, url); logger.shouldInterceptRequest(view, url, retVal); return retVal; } DebugWebViewClient(); DebugWebViewClient(@NonNull final WebViewClient client); @SuppressWarnings("WeakerAccess") DebugWebViewClient(
@NonNull final WebViewClient client,
@NonNull final DebugWebViewClientLogger logger); @RequiresApi(api = Build.VERSION_CODES.M) @Override void onReceivedError(final WebView view, final WebResourceRequest request, final WebResourceError error); @Override @Deprecated void onReceivedError(final WebView view, final int errorCode, final String description, final String failingUrl); @RequiresApi(api = Build.VERSION_CODES.M) @Override void onReceivedHttpError(final WebView view, final WebResourceRequest request, final WebResourceResponse errorResponse); @Override void onReceivedSslError(final WebView view, final SslErrorHandler handler, final SslError error); @RequiresApi(api = Build.VERSION_CODES.N) @Override boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request); @Override boolean shouldOverrideUrlLoading(WebView view, String url); @Override void onLoadResource(WebView view, String url); @TargetApi(Build.VERSION_CODES.M) @Override void onPageCommitVisible(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Deprecated WebResourceResponse shouldInterceptRequest(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request); @Override @Deprecated @SuppressWarnings("deprecation") //for use with older versions void onTooManyRedirects(WebView view, Message cancelMsg, Message continueMsg); @Override void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm); @Override void onPageStarted(WebView view, String url, Bitmap facIcon); @Override void onPageFinished(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override void onReceivedClientCertRequest(WebView view, ClientCertRequest request); @Override void onFormResubmission(final WebView view, final Message dontResend, final Message resend); @Override void doUpdateVisitedHistory(final WebView view, final String url, final boolean isReload); @Override boolean shouldOverrideKeyEvent(final WebView view, final KeyEvent event); @SuppressWarnings("unused") void onUnhandledInputEvent(final WebView view, final InputEvent event); @Override void onUnhandledKeyEvent(final WebView view, final KeyEvent event); @Override void onScaleChanged(final WebView view, final float oldScale, final float newScale); @Override void onReceivedLoginRequest(final WebView view, final String realm, final String account, final String args); @RequiresApi(api = Build.VERSION_CODES.O) @Override boolean onRenderProcessGone(final WebView view, final RenderProcessGoneDetail detail); @RequiresApi(api = Build.VERSION_CODES.O_MR1) @Override void onSafeBrowsingHit(final WebView view, final WebResourceRequest request, final int threatType, final SafeBrowsingResponse callback); @Override boolean isLoggingEnabled(); @Override void setLoggingEnabled(final boolean enabled); @Override boolean isLogKeyEventsEnabled(); @Override void setLogKeyEventsEnabled(final boolean enabled); } | @Test public void shouldInterceptRequest() { final String url = "foo"; final WebResourceResponse retVal = debugClient.shouldInterceptRequest(webView, url); verifyLogger().shouldInterceptRequest(webView, url, retVal); verifyWrappedClient().shouldInterceptRequest(webView, url); }
@Test public void shouldInterceptRequest_api21() { final WebResourceRequest request = Mockito.mock(WebResourceRequest.class); final WebResourceResponse retVal = debugClient.shouldInterceptRequest(webView, request); verifyLogger().shouldInterceptRequest(webView, request, retVal); verifyWrappedClient().shouldInterceptRequest(webView, request); } |
AbstractCloudConnector implements CloudConnector { @Override public List<ServiceInfo> getServiceInfos() { List<ServiceInfo> serviceInfos = new ArrayList<ServiceInfo>(); for (SD serviceData : getServicesData()) { serviceInfos.add(getServiceInfo(serviceData)); } return serviceInfos; } AbstractCloudConnector(Class<? extends ServiceInfoCreator<? extends ServiceInfo, ?>> serviceInfoCreatorClass); @Override List<ServiceInfo> getServiceInfos(); } | @Test public void fallbacksCorrectly() { TestServiceData acceptableServiceData = new TestServiceData("my-service1", "test-tag"); TestServiceData unAcceptableServiceData = new TestServiceData("my-service2", "unknown-tag"); CloudConnector testCloudConnector = new TestCloudConnector(acceptableServiceData, unAcceptableServiceData); List<ServiceInfo> serviceInfos = testCloudConnector.getServiceInfos(); assertNotNull(serviceInfos); assertEquals(2, serviceInfos.size()); assertThat(serviceInfos.get(0), is(instanceOf(TestServiceInfo.class))); assertThat(serviceInfos.get(0), is(instanceOf(BaseServiceInfo.class))); } |
RelationalServiceInfo extends UriBasedServiceInfo { @ServiceProperty(category = "connection") public String getJdbcUrl() { return jdbcUrl == null ? buildJdbcUrl() : jdbcUrl; } RelationalServiceInfo(String id, String uriString, String jdbcUrlDatabaseType); RelationalServiceInfo(String id, String uriString, String jdbcUrl, String jdbcUrlDatabaseType); @ServiceProperty(category = "connection") String getJdbcUrl(); static final String JDBC_PREFIX; } | @Test public void jdbcUrlWithQueryNoUsernamePassword() { RelationalServiceInfo serviceInfo = createServiceInfo("dbtype: assertEquals("jdbc:jdbcdbtype: }
@Test public void jdbcUrl() { RelationalServiceInfo serviceInfo = createServiceInfoWithJdbcUrl("bad: "jdbc:jdbcdbtype: assertEquals("jdbc:jdbcdbtype: }
@Test public void jdbcFullUrl() { RelationalServiceInfo serviceInfo = createServiceInfo("dbtype: assertEquals("jdbc:jdbcdbtype: }
@Test public void jdbcUrlNoPort() { RelationalServiceInfo serviceInfo = createServiceInfo("dbtype: assertEquals("jdbc:jdbcdbtype: }
@Test public void jdbcUrlNoUsernamePassword() { RelationalServiceInfo serviceInfo = createServiceInfo("dbtype: assertEquals("jdbc:jdbcdbtype: }
@Test public void jdbcUrlNoPassword() { RelationalServiceInfo serviceInfo = createServiceInfo("dbtype: assertEquals("jdbc:jdbcdbtype: }
@Test public void jdbcUrlWithQuery() { RelationalServiceInfo serviceInfo = createServiceInfo("dbtype: assertEquals("jdbc:jdbcdbtype: } |
Cloud { public Properties getCloudProperties() { Map<String, List<ServiceInfo>> mappedServiceInfos = new HashMap<>(); for (ServiceInfo serviceInfo : getServiceInfos()) { String key = getServiceLabel(serviceInfo); List<ServiceInfo> serviceInfosForLabel = mappedServiceInfos.computeIfAbsent(key, k -> new ArrayList<>()); serviceInfosForLabel.add(serviceInfo); } final String servicePropKeyLead = "cloud.services."; Properties cloudProperties = new Properties(); for (Entry<String, List<ServiceInfo>> mappedServiceInfo : mappedServiceInfos.entrySet()) { List<ServiceInfo> serviceInfos = mappedServiceInfo.getValue(); for (ServiceInfo serviceInfo : serviceInfos) { String idBasedKey = servicePropKeyLead + serviceInfo.getId(); cloudProperties.putAll(getServiceProperties(idBasedKey, serviceInfo)); if (serviceInfos.size() == 1) { String labelBasedKey = servicePropKeyLead + mappedServiceInfo.getKey(); cloudProperties.putAll(getServiceProperties(labelBasedKey, serviceInfo)); } } } cloudProperties.putAll(getAppProperties()); return cloudProperties; } Cloud(CloudConnector cloudConnector, List<ServiceConnectorCreator<?, ? extends ServiceInfo>> serviceConnectorCreators); ApplicationInstanceInfo getApplicationInstanceInfo(); ServiceInfo getServiceInfo(String serviceId); List<ServiceInfo> getServiceInfos(); List<ServiceInfo> getServiceInfos(Class<T> serviceConnectorType); @SuppressWarnings("unchecked") List<T> getServiceInfosByType(Class<T> serviceInfoType); T getSingletonServiceInfoByType(Class<T> serviceInfoType); SC getServiceConnector(String serviceId, Class<SC> serviceConnectorType,
ServiceConnectorConfig serviceConnectorConfig); SC getSingletonServiceConnector(Class<SC> serviceConnectorType, ServiceConnectorConfig serviceConnectorConfig); void registerServiceConnectorCreator(ServiceConnectorCreator<?, ? extends ServiceInfo> serviceConnectorCreator); Properties getCloudProperties(); } | @Test public void appProps() { Map<String, Object> appProps = new HashMap<>(); appProps.put("foo", "bar"); appProps.put("users", null); StubCloudConnector stubCloudConnector = CloudTestUtil.getTestCloudConnector(new StubApplicationInstanceInfo("instance-id-1", "myapp", appProps)); Cloud testCloud = new Cloud(stubCloudConnector, serviceConnectorCreators); assertEquals("myapp", testCloud.getCloudProperties().get("cloud.application.app-id")); assertEquals("instance-id-1", testCloud.getCloudProperties().get("cloud.application.instance-id")); assertEquals("bar", testCloud.getCloudProperties().get("cloud.application.foo")); }
@Test public void appPropsWithNullValues() { StubCloudConnector stubCloudConnector = CloudTestUtil.getTestCloudConnector(new StubApplicationInstanceInfo(null, null, null)); Cloud testCloud = new Cloud(stubCloudConnector, serviceConnectorCreators); assertNull(testCloud.getCloudProperties().get("cloud.application.app-id")); assertNull(testCloud.getCloudProperties().get("cloud.application.instance-id")); }
@Test public void servicePropsTwoServicesOfTheSameLabel() { StubServiceInfo testServiceInfo1 = new StubServiceInfo("test-id1", "test-host", 1000, "test-username", "test-password"); StubServiceInfo testServiceInfo2 = new StubServiceInfo("test-id2", "test-host", 1000, "test-username", "test-password"); StubCloudConnector stubCloudConnector = CloudTestUtil.getTestCloudConnector(testServiceInfo1, testServiceInfo2); Cloud testCloud = new Cloud(stubCloudConnector, serviceConnectorCreators); Properties cloudProperties = testCloud.getCloudProperties(); assertStubServiceProp("cloud.services.test-id1", testServiceInfo1, cloudProperties); assertStubServiceProp("cloud.services.test-id2", testServiceInfo2, cloudProperties); assertNull(cloudProperties.get("cloud.services.stub.connection.host")); }
@Test public void servicePropsOneServiceOfTheSameLabel() { StubServiceInfo testServiceInfo = new StubServiceInfo("test-id", "test-host", 1000, "test-username", "test-password"); StubCloudConnector stubCloudConnector = CloudTestUtil.getTestCloudConnector(testServiceInfo); Cloud testCloud = new Cloud(stubCloudConnector, serviceConnectorCreators); Properties cloudProperties = testCloud.getCloudProperties(); assertStubServiceProp("cloud.services.test-id", testServiceInfo, cloudProperties); assertStubServiceProp("cloud.services.stub", testServiceInfo, cloudProperties); } |
Cloud { public <SC> SC getServiceConnector(String serviceId, Class<SC> serviceConnectorType, ServiceConnectorConfig serviceConnectorConfig) { ServiceInfo serviceInfo = getServiceInfo(serviceId); return getServiceConnector(serviceInfo, serviceConnectorType, serviceConnectorConfig); } Cloud(CloudConnector cloudConnector, List<ServiceConnectorCreator<?, ? extends ServiceInfo>> serviceConnectorCreators); ApplicationInstanceInfo getApplicationInstanceInfo(); ServiceInfo getServiceInfo(String serviceId); List<ServiceInfo> getServiceInfos(); List<ServiceInfo> getServiceInfos(Class<T> serviceConnectorType); @SuppressWarnings("unchecked") List<T> getServiceInfosByType(Class<T> serviceInfoType); T getSingletonServiceInfoByType(Class<T> serviceInfoType); SC getServiceConnector(String serviceId, Class<SC> serviceConnectorType,
ServiceConnectorConfig serviceConnectorConfig); SC getSingletonServiceConnector(Class<SC> serviceConnectorType, ServiceConnectorConfig serviceConnectorConfig); void registerServiceConnectorCreator(ServiceConnectorCreator<?, ? extends ServiceInfo> serviceConnectorCreator); Properties getCloudProperties(); } | @Test public void serviceConnectorCreationDefaultTypeAndConfig() { StubServiceInfo testServiceInfo = new StubServiceInfo("test-id", "test-host", 1000, "test-username", "test-password"); StubCloudConnector stubCloudConnector = CloudTestUtil.getTestCloudConnector(testServiceInfo); serviceConnectorCreators.add(new StubServiceConnectorCreator()); Cloud testCloud = new Cloud(stubCloudConnector, serviceConnectorCreators); StubServiceConnector connector = testCloud.getServiceConnector(testServiceInfo.getId(), null, null); assertStubService(testServiceInfo, connector, null); }
@Test public void serviceConnectorCreationSpecifiedTypeAndConfig() { StubServiceInfo testServiceInfo = new StubServiceInfo("test-id", "test-host", 1000, "test-username", "test-password"); StubCloudConnector stubCloudConnector = CloudTestUtil.getTestCloudConnector(testServiceInfo); serviceConnectorCreators.add(new StubServiceConnectorCreator()); Cloud testCloud = new Cloud(stubCloudConnector, serviceConnectorCreators); StubServiceConnectorConfig config = new StubServiceConnectorConfig("test-config"); StubServiceConnector connector = testCloud.getServiceConnector(testServiceInfo.getId(), StubServiceConnector.class, config); assertStubService(testServiceInfo, connector, config); } |
Cloud { public <SC> SC getSingletonServiceConnector(Class<SC> serviceConnectorType, ServiceConnectorConfig serviceConnectorConfig) { List<ServiceInfo> matchingServiceInfos = getServiceInfos(serviceConnectorType); if (matchingServiceInfos.size() != 1) { throw new CloudException("No unique service matching " + serviceConnectorType + " found. Expected 1, found " + matchingServiceInfos.size()); } ServiceInfo matchingServiceInfo = matchingServiceInfos.get(0); return getServiceConnector(matchingServiceInfo, serviceConnectorType, serviceConnectorConfig); } Cloud(CloudConnector cloudConnector, List<ServiceConnectorCreator<?, ? extends ServiceInfo>> serviceConnectorCreators); ApplicationInstanceInfo getApplicationInstanceInfo(); ServiceInfo getServiceInfo(String serviceId); List<ServiceInfo> getServiceInfos(); List<ServiceInfo> getServiceInfos(Class<T> serviceConnectorType); @SuppressWarnings("unchecked") List<T> getServiceInfosByType(Class<T> serviceInfoType); T getSingletonServiceInfoByType(Class<T> serviceInfoType); SC getServiceConnector(String serviceId, Class<SC> serviceConnectorType,
ServiceConnectorConfig serviceConnectorConfig); SC getSingletonServiceConnector(Class<SC> serviceConnectorType, ServiceConnectorConfig serviceConnectorConfig); void registerServiceConnectorCreator(ServiceConnectorCreator<?, ? extends ServiceInfo> serviceConnectorCreator); Properties getCloudProperties(); } | @Test public void getSingletonServiceConnectorSingleService() { StubServiceInfo testServiceInfo = new StubServiceInfo("test-id", "test-host", 1000, "test-username", "test-password"); StubCloudConnector stubCloudConnector = CloudTestUtil.getTestCloudConnector(testServiceInfo); serviceConnectorCreators.add(new StubServiceConnectorCreator()); Cloud testCloud = new Cloud(stubCloudConnector, serviceConnectorCreators); StubServiceConnector connector = testCloud.getSingletonServiceConnector(null, null); assertStubService(testServiceInfo, connector, null); }
@Test(expected=CloudException.class) public void getSingletonServiceConnectorNoService() { StubCloudConnector stubCloudConnector = CloudTestUtil.getTestCloudConnector(); Cloud testCloud = new Cloud(stubCloudConnector, serviceConnectorCreators); testCloud.getSingletonServiceConnector(null, null); }
@Test(expected=CloudException.class) public void getSingletonServiceConnectorMultipleServices() { StubServiceInfo testServiceInfo1 = new StubServiceInfo("test-id", "test-host", 1000, "test-username", "test-password"); StubServiceInfo testServiceInfo2 = new StubServiceInfo("test-id", "test-host", 1000, "test-username", "test-password"); StubCloudConnector stubCloudConnector = CloudTestUtil.getTestCloudConnector(testServiceInfo1, testServiceInfo2); serviceConnectorCreators.add(new StubServiceConnectorCreator()); Cloud testCloud = new Cloud(stubCloudConnector, serviceConnectorCreators); testCloud.getSingletonServiceConnector(null, null); }
@Test(expected=CloudException.class) public void getSingletonServiceConnectorNoMatchingServiceConnectorCreator() { BaseServiceInfo testServiceInfo = new BaseServiceInfo("user-service"); StubCloudConnector stubCloudConnector = CloudTestUtil.getTestCloudConnector(testServiceInfo); serviceConnectorCreators.add(new StubServiceConnectorCreator()); Cloud testCloud = new Cloud(stubCloudConnector, serviceConnectorCreators); testCloud.getSingletonServiceConnector(StubServiceConnector.class, null); } |
Cloud { public List<ServiceInfo> getServiceInfos() { return flatten(cloudConnector.getServiceInfos()); } Cloud(CloudConnector cloudConnector, List<ServiceConnectorCreator<?, ? extends ServiceInfo>> serviceConnectorCreators); ApplicationInstanceInfo getApplicationInstanceInfo(); ServiceInfo getServiceInfo(String serviceId); List<ServiceInfo> getServiceInfos(); List<ServiceInfo> getServiceInfos(Class<T> serviceConnectorType); @SuppressWarnings("unchecked") List<T> getServiceInfosByType(Class<T> serviceInfoType); T getSingletonServiceInfoByType(Class<T> serviceInfoType); SC getServiceConnector(String serviceId, Class<SC> serviceConnectorType,
ServiceConnectorConfig serviceConnectorConfig); SC getSingletonServiceConnector(Class<SC> serviceConnectorType, ServiceConnectorConfig serviceConnectorConfig); void registerServiceConnectorCreator(ServiceConnectorCreator<?, ? extends ServiceInfo> serviceConnectorCreator); Properties getCloudProperties(); } | @Test public void serviceInfoNoServices() { StubCloudConnector stubCloudConnector = CloudTestUtil.getTestCloudConnector(); Cloud testCloud = new Cloud(stubCloudConnector, serviceConnectorCreators); assertEquals(0, testCloud.getServiceInfos().size()); assertEquals(0, testCloud.getServiceInfos(StubServiceInfo.class).size()); }
@Test public void serviceInfoMultipleServicesOfTheSameType() { StubServiceInfo testServiceInfo1 = new StubServiceInfo("test-id1", "test-host", 1000, "test-username", "test-password"); StubServiceInfo testServiceInfo2 = new StubServiceInfo("test-id2", "test-host", 1000, "test-username", "test-password"); StubCloudConnector stubCloudConnector = CloudTestUtil.getTestCloudConnector(testServiceInfo1, testServiceInfo2); serviceConnectorCreators.add(new StubServiceConnectorCreator()); Cloud testCloud = new Cloud(stubCloudConnector, serviceConnectorCreators); assertEquals(2, testCloud.getServiceInfos().size()); assertEquals(2, testCloud.getServiceInfos(StubServiceConnector.class).size()); } |
CloudFactory { List<CloudConnector> getCloudConnectors() { return cloudConnectors; } CloudFactory(); Cloud getCloud(); void registerCloudConnector(CloudConnector cloudConnector); } | @Test public void cloudConnectorRegistration() { CloudFactory cloudFactory = new CloudFactory(); List<CloudConnector> registeredConnectors = cloudFactory.getCloudConnectors(); assertEquals("One connector registered", 1, registeredConnectors.size()); assertEquals("Registered connector is stub connector", StubCloudConnector.class, registeredConnectors.get(0).getClass()); } |
Cloud { public ServiceInfo getServiceInfo(String serviceId) { for (ServiceInfo serviceInfo : getServiceInfos()) { if (serviceInfo.getId().equals(serviceId)) { return serviceInfo; } } throw new CloudException("No service with id " + serviceId + " found"); } Cloud(CloudConnector cloudConnector, List<ServiceConnectorCreator<?, ? extends ServiceInfo>> serviceConnectorCreators); ApplicationInstanceInfo getApplicationInstanceInfo(); ServiceInfo getServiceInfo(String serviceId); List<ServiceInfo> getServiceInfos(); List<ServiceInfo> getServiceInfos(Class<T> serviceConnectorType); @SuppressWarnings("unchecked") List<T> getServiceInfosByType(Class<T> serviceInfoType); T getSingletonServiceInfoByType(Class<T> serviceInfoType); SC getServiceConnector(String serviceId, Class<SC> serviceConnectorType,
ServiceConnectorConfig serviceConnectorConfig); SC getSingletonServiceConnector(Class<SC> serviceConnectorType, ServiceConnectorConfig serviceConnectorConfig); void registerServiceConnectorCreator(ServiceConnectorCreator<?, ? extends ServiceInfo> serviceConnectorCreator); Properties getCloudProperties(); } | @Test public void getServiceInfoByValidId() { StubServiceInfo testServiceInfo1 = new StubServiceInfo("test-id1", "test-host", 1000, "test-username", "test-password"); StubServiceInfo testServiceInfo2 = new StubServiceInfo("test-id2", "test-host", 1000, "test-username", "test-password"); StubCloudConnector stubCloudConnector = CloudTestUtil.getTestCloudConnector(testServiceInfo1, testServiceInfo2); Cloud testCloud = new Cloud(stubCloudConnector, serviceConnectorCreators); assertEquals(testServiceInfo1, testCloud.getServiceInfo(testServiceInfo1.getId())); assertEquals(testServiceInfo2, testCloud.getServiceInfo(testServiceInfo2.getId())); }
@Test(expected=CloudException.class) public void getServiceInfoByInvalidId() { StubCloudConnector stubCloudConnector = CloudTestUtil.getTestCloudConnector(); Cloud testCloud = new Cloud(stubCloudConnector, serviceConnectorCreators); testCloud.getServiceInfo("foo"); }
@Test public void compositeServiceInfo() { StubServiceInfo testServiceInfo1 = new StubServiceInfo("test-id-1", "test-host", 1000, "test-username", "test-password"); StubServiceInfo testServiceInfo2 = new StubServiceInfo("test-id-2", "test-host", 1000, "test-username", "test-password"); ServiceInfo testCompositeServiceInfo = new StubCompositeServiceInfo("test-composite",testServiceInfo1, testServiceInfo2); StubCloudConnector stubCloudConnector = CloudTestUtil.getTestCloudConnector(testCompositeServiceInfo); Cloud testCloud = new Cloud(stubCloudConnector, serviceConnectorCreators); assertNotNull(testCloud.getServiceInfo("test-id-1")); assertNotNull(testCloud.getServiceInfo("test-id-2")); }
@Test public void compositeServiceInfoRecursive() { StubServiceInfo testServiceInfo1a = new StubServiceInfo("test-id-1a", "test-host", 1000, "test-username", "test-password"); StubServiceInfo testServiceInfo1b = new StubServiceInfo("test-id-1b", "test-host", 1000, "test-username", "test-password"); ServiceInfo testCompositeServiceInfo1 = new StubCompositeServiceInfo("test-composite-1",testServiceInfo1a, testServiceInfo1b); StubServiceInfo testServiceInfo2a = new StubServiceInfo("test-id-2a", "test-host", 1000, "test-username", "test-password"); StubServiceInfo testServiceInfo2b = new StubServiceInfo("test-id-2b", "test-host", 1000, "test-username", "test-password"); ServiceInfo testCompositeServiceInfo2 = new StubCompositeServiceInfo("test-composite-2",testServiceInfo2a, testServiceInfo2b); ServiceInfo testCompositeServiceInfo = new StubCompositeServiceInfo("test-composite",testCompositeServiceInfo1, testCompositeServiceInfo2); StubCloudConnector stubCloudConnector = CloudTestUtil.getTestCloudConnector(testCompositeServiceInfo); Cloud testCloud = new Cloud(stubCloudConnector, serviceConnectorCreators); assertNotNull(testCloud.getServiceInfo("test-id-1a")); assertNotNull(testCloud.getServiceInfo("test-id-1b")); assertNotNull(testCloud.getServiceInfo("test-id-2a")); assertNotNull(testCloud.getServiceInfo("test-id-2b")); } |
Cloud { @SuppressWarnings("unchecked") public <T extends ServiceInfo> List<T> getServiceInfosByType(Class<T> serviceInfoType) { List<ServiceInfo> allServiceInfos = getServiceInfos(); List<T> matchingServiceInfos = new ArrayList<>(); for (ServiceInfo serviceInfo : allServiceInfos) { if (serviceInfoType.isAssignableFrom(serviceInfo.getClass())) { matchingServiceInfos.add((T) serviceInfo); } } return matchingServiceInfos; } Cloud(CloudConnector cloudConnector, List<ServiceConnectorCreator<?, ? extends ServiceInfo>> serviceConnectorCreators); ApplicationInstanceInfo getApplicationInstanceInfo(); ServiceInfo getServiceInfo(String serviceId); List<ServiceInfo> getServiceInfos(); List<ServiceInfo> getServiceInfos(Class<T> serviceConnectorType); @SuppressWarnings("unchecked") List<T> getServiceInfosByType(Class<T> serviceInfoType); T getSingletonServiceInfoByType(Class<T> serviceInfoType); SC getServiceConnector(String serviceId, Class<SC> serviceConnectorType,
ServiceConnectorConfig serviceConnectorConfig); SC getSingletonServiceConnector(Class<SC> serviceConnectorType, ServiceConnectorConfig serviceConnectorConfig); void registerServiceConnectorCreator(ServiceConnectorCreator<?, ? extends ServiceInfo> serviceConnectorCreator); Properties getCloudProperties(); } | @Test public void getServiceInfosByType() { StubServiceInfo testServiceInfo = new StubServiceInfo("test-id", "test-host", 1000, "test-username", "test-password"); TestServiceInfoTypeA testServiceInfoTypeA1 = new TestServiceInfoTypeA("test-id-a1"); TestServiceInfoTypeA testServiceInfoTypeA2 = new TestServiceInfoTypeA("test-id-a2"); TestServiceInfoTypeB testServiceInfoTypeB = new TestServiceInfoTypeB("test-id-b"); StubCloudConnector stubCloudConnector = CloudTestUtil.getTestCloudConnector(testServiceInfo, testServiceInfoTypeA1, testServiceInfoTypeA2, testServiceInfoTypeB); Cloud testCloud = new Cloud(stubCloudConnector, serviceConnectorCreators); List<TestServiceInfoTypeA> actualServiceInfoTypeA = testCloud.getServiceInfosByType(TestServiceInfoTypeA.class); assertEquals(2, actualServiceInfoTypeA.size()); assertEquals(1, testCloud.getServiceInfosByType(TestServiceInfoTypeB.class).size()); } |
Cloud { public <T extends ServiceInfo> T getSingletonServiceInfoByType(Class<T> serviceInfoType) { List<T> serviceInfos = getServiceInfosByType(serviceInfoType); if (serviceInfos.size() != 1) { throw new CloudException( "No unique service info " + serviceInfoType + " found. Expected 1, found " + serviceInfos.size()); } return serviceInfos.get(0); } Cloud(CloudConnector cloudConnector, List<ServiceConnectorCreator<?, ? extends ServiceInfo>> serviceConnectorCreators); ApplicationInstanceInfo getApplicationInstanceInfo(); ServiceInfo getServiceInfo(String serviceId); List<ServiceInfo> getServiceInfos(); List<ServiceInfo> getServiceInfos(Class<T> serviceConnectorType); @SuppressWarnings("unchecked") List<T> getServiceInfosByType(Class<T> serviceInfoType); T getSingletonServiceInfoByType(Class<T> serviceInfoType); SC getServiceConnector(String serviceId, Class<SC> serviceConnectorType,
ServiceConnectorConfig serviceConnectorConfig); SC getSingletonServiceConnector(Class<SC> serviceConnectorType, ServiceConnectorConfig serviceConnectorConfig); void registerServiceConnectorCreator(ServiceConnectorCreator<?, ? extends ServiceInfo> serviceConnectorCreator); Properties getCloudProperties(); } | @Test(expected=CloudException.class) public void getSingletonServiceInfoByTypeNoService() { StubCloudConnector stubCloudConnector = CloudTestUtil.getTestCloudConnector(); Cloud testCloud = new Cloud(stubCloudConnector, serviceConnectorCreators); testCloud.getSingletonServiceInfoByType(StubServiceInfo.class); }
@Test(expected=CloudException.class) public void getSingletonServiceInfoByTypeMultipleServices() { StubServiceInfo testServiceInfo1 = new StubServiceInfo("test-id", "test-host", 1000, "test-username", "test-password"); StubServiceInfo testServiceInfo2 = new StubServiceInfo("test-id", "test-host", 1000, "test-username", "test-password"); StubCloudConnector stubCloudConnector = CloudTestUtil.getTestCloudConnector(testServiceInfo1, testServiceInfo2); Cloud testCloud = new Cloud(stubCloudConnector, serviceConnectorCreators); testCloud.getSingletonServiceInfoByType(StubServiceInfo.class); }
@Test public void getSingletonServiceInfoByTypeSingleService() { StubServiceInfo testServiceInfo = new StubServiceInfo("test-id", "test-host", 1000, "test-username", "test-password"); StubCloudConnector stubCloudConnector = CloudTestUtil.getTestCloudConnector(testServiceInfo); Cloud testCloud = new Cloud(stubCloudConnector, serviceConnectorCreators); assertNotNull(testCloud.getSingletonServiceInfoByType(StubServiceInfo.class)); } |
CloudFactory { List<ServiceConnectorCreator<?, ? extends ServiceInfo>> getServiceCreators() { return serviceCreators; } CloudFactory(); Cloud getCloud(); void registerCloudConnector(CloudConnector cloudConnector); } | @Test public void cloudServiceConnectorCreatorRegistration() { CloudFactory cloudFactory = new CloudFactory(); List<ServiceConnectorCreator<?, ? extends ServiceInfo>> registeredServiceConnectorCreators = cloudFactory.getServiceCreators(); assertEquals("One serviceCreators registered", 2, registeredServiceConnectorCreators.size()); assertEquals("First registered connector is a stub", StubServiceConnectorCreator.class, registeredServiceConnectorCreators.get(0).getClass()); assertEquals("Second egistered connector is a non-parameterized stub", NonParameterizedStubServiceConnectorCreator.class, registeredServiceConnectorCreators.get(1).getClass()); } |
LocalConfigUtil { static Map<String, String> readServices(Properties properties) { Map<String, String> services = new HashMap<String, String>(); for (String propertyName : properties.stringPropertyNames()) { if (LocalConfigConnector.META_PROPERTIES.contains(propertyName)) { logger.finer("skipping meta property " + propertyName); continue; } Matcher m = LocalConfigConnector.SERVICE_PROPERTY_PATTERN.matcher(propertyName); if (!m.matches()) { logger.finest("skipping non-Spring-Cloud property " + propertyName); continue; } String serviceId = m.group(1); String serviceUri = properties.getProperty(propertyName); logger.fine("found service URI for service " + serviceId); services.put(serviceId, serviceUri); } return services; } private LocalConfigUtil(); } | @Test public void testPropertyParsing() { first.setProperty("spring.cloud.appId", "should skip me because I'm meta"); first.setProperty("spring.cloud.service1", "one"); first.setProperty("spring.cloud.", "should skip me because I don't have an ID"); first.setProperty("spring.cloud.service.two", "two"); first.setProperty("foobar", "should skip me because I don't match the prefix"); Map<String, String> services = LocalConfigUtil.readServices(first); assertEquals(2, services.size()); assertEquals("one", services.get("service1")); assertEquals("two", services.get("service.two")); } |
LocalConfigUtil { static List<UriBasedServiceData> readServicesData(LinkedHashMap<String, Properties> propertySources) { Map<String, String> collectedServices = new HashMap<String, String>(); for (Map.Entry<String, Properties> propertySource : propertySources.entrySet()) { if (propertySource.getValue().isEmpty()) { logger.info("no " + propertySource.getKey()); continue; } logger.info("reading services from " + propertySource.getKey()); Map<String, String> services = readServices(propertySource.getValue()); for (Map.Entry<String, String> service : services.entrySet()) { String oldUri = collectedServices.put(service.getKey(), service.getValue()); if (oldUri == null) logger.info("added service '" + service.getKey() + "' from " + propertySource.getKey()); else logger.warning("replaced service '" + service.getKey() + "' with new URI from " + propertySource.getKey()); } } List<UriBasedServiceData> serviceData = new ArrayList<UriBasedServiceData>(collectedServices.size()); for (Map.Entry<String, String> serviceInfo : collectedServices.entrySet()) { serviceData.add(new UriBasedServiceData(serviceInfo.getKey(), serviceInfo.getValue())); } return serviceData; } private LocalConfigUtil(); } | @Test public void testCollation() { first.setProperty("spring.cloud.first", "firstUri"); second.setProperty("spring.cloud.second", "secondUri"); List<UriBasedServiceData> serviceData = LocalConfigUtil.readServicesData(propertySources); assertEquals(2, serviceData.size()); boolean foundFirst = false; for (UriBasedServiceData kvp : serviceData) { if (kvp.getKey().equals("first")) { assertEquals("firstUri", kvp.getUri()); foundFirst = true; } } assertTrue(foundFirst); }
@Test public void testOverride() { first.setProperty("spring.cloud.duplicate", "firstUri"); second.setProperty("spring.cloud.duplicate", "secondUri"); List<UriBasedServiceData> serviceData = LocalConfigUtil.readServicesData(propertySources); assertEquals(1, serviceData.size()); UriBasedServiceData kvp = serviceData.get(0); assertEquals("duplicate", kvp.getKey()); assertEquals("secondUri", kvp.getUri()); } |
LocalConfigConnector extends AbstractCloudConnector<UriBasedServiceData> { @Override public boolean isInMatchingCloud() { if (fileProperties == null) readFileProperties(); String appId = findProperty(APP_ID_PROPERTY); if (appId == null) logger.info("the property " + APP_ID_PROPERTY + " was not found in the system properties or configuration file"); return appId != null; } @SuppressWarnings({"unchecked", "rawtypes"}) LocalConfigConnector(); @Override boolean isInMatchingCloud(); @Override ApplicationInstanceInfo getApplicationInstanceInfo(); static final String PROPERTY_PREFIX; static final Pattern SERVICE_PROPERTY_PATTERN; static final String APP_ID_PROPERTY; static final String PROPERTIES_FILE_PROPERTY; static final List<String> META_PROPERTIES; } | @Test public void testNoAppIdAnywhere() { assertFalse(connector.isInMatchingCloud()); } |
PropertiesFileResolver { File findCloudPropertiesFileFromSystem() { String filename = null; try { filename = env.getSystemProperty(LocalConfigConnector.PROPERTIES_FILE_PROPERTY); } catch (SecurityException e) { logger.log(Level.WARNING, "SecurityManager prevented reading system property " + LocalConfigConnector.PROPERTIES_FILE_PROPERTY, e); return null; } if (filename == null) { logger.fine("didn't find system property for a configuration file"); return null; } File file = new File(filename); logger.info("found system property for a configuration file: " + file); return file; } PropertiesFileResolver(final EnvironmentAccessor env, final String classpathPropertiesFilename); PropertiesFileResolver(final EnvironmentAccessor env); PropertiesFileResolver(); static final String BOOTSTRAP_PROPERTIES_FILENAME; } | @Test public void testSecurityExceptionHandling() { env = mock(PassthroughEnvironmentAccessor.class); resolver = new PropertiesFileResolver(env); when(env.getSystemProperty(LocalConfigConnector.PROPERTIES_FILE_PROPERTY)).thenThrow(new SecurityException()); assertNull(resolver.findCloudPropertiesFileFromSystem()); verify(env).getSystemProperty(LocalConfigConnector.PROPERTIES_FILE_PROPERTY); }
@Test public void testMissingSystemProperty() { assertNull(resolver.findCloudPropertiesFileFromSystem()); }
@Test public void testSystemProperty() { env.setSystemProperty(LocalConfigConnector.PROPERTIES_FILE_PROPERTY, PROPERTIES_FILE_NAME); assertEquals(PROPERTIES_FILE_NAME, resolver.findCloudPropertiesFileFromSystem().getPath()); } |
PropertiesFileResolver { File findCloudPropertiesFileFromClasspath() { InputStream in = getClass().getClassLoader().getResourceAsStream(classpathPropertiesFilename); if (in == null) { logger.info("no " + classpathPropertiesFilename + " found on the classpath to direct us to an external properties file"); return null; } Properties properties = new Properties(); try { properties.load(in); } catch (IOException e) { logger.log(Level.SEVERE, "found " + classpathPropertiesFilename + " on the classpath but couldn't load it as a properties file", e); return null; } String template = properties.getProperty(LocalConfigConnector.PROPERTIES_FILE_PROPERTY); if (template == null) { logger.log(Level.SEVERE, "found properties file " + classpathPropertiesFilename + " on the classpath, but it didn't contain a property named " + LocalConfigConnector.PROPERTIES_FILE_PROPERTY); return null; } if (properties.entrySet().size() > 1) logger.warning("the properties file " + classpathPropertiesFilename + " contained properties besides " + LocalConfigConnector.PROPERTIES_FILE_PROPERTY + "; ignoring"); logger.fine("substituting system properties into '" + template + "'"); File configFile = new File(new StrSubstitutor(systemPropertiesLookup(env)).replace(template)); logger.info("derived configuration file name: " + configFile); return configFile; } PropertiesFileResolver(final EnvironmentAccessor env, final String classpathPropertiesFilename); PropertiesFileResolver(final EnvironmentAccessor env); PropertiesFileResolver(); static final String BOOTSTRAP_PROPERTIES_FILENAME; } | @Test public void testNoClasspathFile() { resolver = new PropertiesFileResolver(env, "bazquux.properties"); assertNull(resolver.findCloudPropertiesFileFromClasspath()); }
@Test public void testClasspathFileWithoutKey() { resolver = new PropertiesFileResolver(env, "localconfig.testuris.properties"); assertNull(resolver.findCloudPropertiesFileFromClasspath()); }
@Test public void testLiteral() { resolver = new PropertiesFileResolver(env, "spring-cloud-literal.properties"); assertEquals(PROPERTIES_FILE_NAME, resolver.findCloudPropertiesFileFromClasspath().getPath()); }
@Test public void testTemplate() { resolver = new PropertiesFileResolver(env, "spring-cloud-template.properties"); env.setSystemProperty("user.home", "/foo"); assertEquals(PROPERTIES_FILE_NAME, resolver.findCloudPropertiesFileFromClasspath().getPath()); } |
CloudFactory { public Cloud getCloud() { CloudConnector suitableCloudConnector = null; for (CloudConnector cloudConnector : cloudConnectors) { if (cloudConnector.isInMatchingCloud()) { suitableCloudConnector = cloudConnector; break; } } if (suitableCloudConnector == null) { throw new CloudException("No suitable cloud connector found"); } return new Cloud(suitableCloudConnector, serviceCreators); } CloudFactory(); Cloud getCloud(); void registerCloudConnector(CloudConnector cloudConnector); } | @Test public void cloudRetriveal() { CloudFactory cloudFactory = new CloudFactory(); Cloud cloud = cloudFactory.getCloud(); assertNotNull(cloud); } |
PropertiesFileResolver { File findCloudPropertiesFile() { File file = findCloudPropertiesFileFromSystem(); if (file != null) { logger.info("using configuration file from system properties"); return file; } file = findCloudPropertiesFileFromClasspath(); if (file != null) logger.info("using configuration file derived from " + classpathPropertiesFilename); else logger.info("did not find any Spring Cloud configuration file"); return file; } PropertiesFileResolver(final EnvironmentAccessor env, final String classpathPropertiesFilename); PropertiesFileResolver(final EnvironmentAccessor env); PropertiesFileResolver(); static final String BOOTSTRAP_PROPERTIES_FILENAME; } | @Test public void testFromSystem() { env.setSystemProperty(LocalConfigConnector.PROPERTIES_FILE_PROPERTY, PROPERTIES_FILE_NAME); assertEquals(PROPERTIES_FILE_NAME, resolver.findCloudPropertiesFile().getPath()); }
@Test public void testFromClasspath() { resolver = new PropertiesFileResolver(env, "spring-cloud-template.properties"); env.setSystemProperty("user.home", "/foo"); assertEquals(PROPERTIES_FILE_NAME, resolver.findCloudPropertiesFile().getPath()); }
@Test public void testNowhere() { assertNull(resolver.findCloudPropertiesFile()); }
@Test public void testPrecedence() { env.setSystemProperty(LocalConfigConnector.PROPERTIES_FILE_PROPERTY, PROPERTIES_FILE_NAME); resolver = new PropertiesFileResolver(env, "spring-cloud-literal.properties"); assertEquals(PROPERTIES_FILE_NAME, resolver.findCloudPropertiesFile().getPath()); } |
CassandraClusterCreator extends AbstractServiceConnectorCreator<Cluster, CassandraServiceInfo> { @Override public Cluster create(CassandraServiceInfo serviceInfo, ServiceConnectorConfig serviceConnectorConfig) { Builder builder = Cluster.builder() .addContactPoints(serviceInfo.getContactPoints().toArray(new String[0])) .withPort(serviceInfo.getPort()); if (StringUtils.hasText(serviceInfo.getUsername())) { builder.withCredentials(serviceInfo.getUsername(), serviceInfo.getPassword()); } if (serviceConnectorConfig instanceof CassandraClusterConfig) { CassandraClusterConfig config = (CassandraClusterConfig) serviceConnectorConfig; if (config.getCompression() != null) { builder.withCompression(config.getCompression()); } builder.withPoolingOptions(config.getPoolingOptions()); builder.withSocketOptions(config.getSocketOptions()); builder.withQueryOptions(config.getQueryOptions()); builder.withNettyOptions(config.getNettyOptions()); builder.withLoadBalancingPolicy(config.getLoadBalancingPolicy()); builder.withReconnectionPolicy(config.getReconnectionPolicy()); builder.withRetryPolicy(config.getRetryPolicy()); if (config.getProtocolVersion() != null) { builder.withProtocolVersion(config.getProtocolVersion()); } if (!config.isMetricsEnabled()) { builder.withoutMetrics(); } if (!config.isJmxReportingEnabled()) { builder.withoutJMXReporting(); } } return builder.build(); } @Override Cluster create(CassandraServiceInfo serviceInfo,
ServiceConnectorConfig serviceConnectorConfig); } | @Test public void shouldCreateCluster() throws Exception { CassandraServiceInfo info = new CassandraServiceInfo("local", Collections.singletonList("127.0.0.1"), 9142); Cluster cluster = creator.create(info, null); Configuration configuration = cluster.getConfiguration(); assertThat(configuration.getProtocolOptions().getAuthProvider(), is(AuthProvider.NONE)); }
@Test public void shouldCreateClusterWithAuthentication() throws Exception { CassandraServiceInfo info = new CassandraServiceInfo("local", Collections.singletonList("127.0.0.1"), 9142, "walter", "white"); Cluster cluster = creator.create(info, null); Configuration configuration = cluster.getConfiguration(); assertThat(configuration.getProtocolOptions().getAuthProvider(), is(instanceOf(PlainTextAuthProvider.class))); }
@Test public void shouldCreateClusterWithConfig() throws Exception { CassandraServiceInfo info = new CassandraServiceInfo("local", Collections.singletonList("127.0.0.1"), 9142); CassandraClusterConfig config = new CassandraClusterConfig(); config.setCompression(ProtocolOptions.Compression.NONE); config.setPoolingOptions(new PoolingOptions().setPoolTimeoutMillis(1234)); config.setQueryOptions(new QueryOptions()); config.setProtocolVersion(ProtocolVersion.NEWEST_SUPPORTED); config.setLoadBalancingPolicy(new RoundRobinPolicy()); config.setReconnectionPolicy(new ConstantReconnectionPolicy(1)); config.setRetryPolicy(DowngradingConsistencyRetryPolicy.INSTANCE); config.setSocketOptions(new SocketOptions()); Cluster cluster = creator.create(info, config); Configuration configuration = cluster.getConfiguration(); assertThat(configuration.getProtocolOptions().getCompression(), is(config.getCompression())); assertThat(configuration.getQueryOptions(), is(config.getQueryOptions())); assertThat(configuration.getSocketOptions(), is(config.getSocketOptions())); Policies policies = configuration.getPolicies(); assertThat(policies.getLoadBalancingPolicy(), is(config.getLoadBalancingPolicy())); assertThat(policies.getReconnectionPolicy(), is(config.getReconnectionPolicy())); assertThat(policies.getRetryPolicy(), is(config.getRetryPolicy())); } |
UrlDecodingDataSource extends DelegatingDataSource { @Override public Connection getConnection() throws SQLException { if (successfullyConnected) return super.getConnection(); synchronized (this) { Connection connection; try { connection = super.getConnection(); successfullyConnected = true; } catch (SQLException e) { logger.info("Database connection failed. Trying again with url-decoded jdbc url"); DataSource targetDataSource = getTargetDataSource(); if (targetDataSource == null) throw new IllegalStateException("target DataSource should never be null"); BeanWrapper dataSourceWrapper = new BeanWrapperImpl(targetDataSource); String decodedJdbcUrl = decode((String) dataSourceWrapper.getPropertyValue(urlPropertyName)); DataSource urlDecodedConnectionTestDataSource = connectionTestDataSourceFactory.apply(decodedJdbcUrl); urlDecodedConnectionTestDataSource.getConnection(); logger.info("Connection test successful. Continuing with url-decoded jdbc url"); dataSourceWrapper.setPropertyValue(urlPropertyName, decodedJdbcUrl); connection = super.getConnection(); successfullyConnected = true; } return connection; } } UrlDecodingDataSource(String jdbcUrl); UrlDecodingDataSource(DataSource targetDataSource, String urlPropertyName); UrlDecodingDataSource(DataSource targetDataSource, String urlPropertyName, Function<String, DataSource> connectionTestDataSourceFactory); @Override Connection getConnection(); } | @Test public void whenConnectionToEncodedUrlIsSuccessful() throws SQLException { MockDataSource delegateDataSource = pooledDataSourceRequiringEncodedUrl(); UrlDecodingDataSource urlDecodingDataSource = new UrlDecodingDataSource(delegateDataSource, "url"); Connection connection = urlDecodingDataSource.getConnection(); assertNotNull("Returned connection must not be null", connection); assertEquals(ENCODED_URL, delegateDataSource.url); assertEquals("Connection must be made using the pooled (delegate) data source", TRUE, connection.getClientInfo(IS_POOLED)); }
@Test public void whenConnectionToDecodedUrlIsSuccessful() throws SQLException { MockDataSource delegateDataSource = pooledDataSourceRequiringDecodedUrl(); UrlDecodingDataSource urlDecodingDataSource = new UrlDecodingDataSource(delegateDataSource, URL_PROPERTY_NAME, UrlDecodingDataSourceTest::dataSourceRequiringDecodedUrl); Connection connection = urlDecodingDataSource.getConnection(); assertNotNull("Returned connection must not be null", connection); assertEquals(DECODED_URL, delegateDataSource.url); assertEquals("Connection must be made using the pooled (delegate) data source", TRUE, connection.getClientInfo(IS_POOLED)); }
@Test(expected = SQLException.class) public void whenNoConnectionIsSuccessful() throws SQLException { MockDataSource delegateDataSource = pooledDataSourceUnableToConnectToAnyUrl(); UrlDecodingDataSource urlDecodingDataSource = new UrlDecodingDataSource(delegateDataSource, URL_PROPERTY_NAME, UrlDecodingDataSourceTest::dataSourceUnableToConnectToAnyUrl); try { urlDecodingDataSource.getConnection(); } catch (SQLException e) { assertEquals(ENCODED_URL, delegateDataSource.url); throw e; } }
@Test public void successfulUrlDecodedConnectionTestIsOnlyPerformedOnce() throws SQLException { MockDataSource delegateDataSource = pooledDataSourceRequiringDecodedUrl(); DataSource decodedUrlConnectionTestDataSource = mock(DataSource.class); when(decodedUrlConnectionTestDataSource.getConnection()).thenReturn(mock(Connection.class)); UrlDecodingDataSource urlDecodingDataSource = new UrlDecodingDataSource(delegateDataSource, URL_PROPERTY_NAME, url -> decodedUrlConnectionTestDataSource); urlDecodingDataSource.getConnection(); urlDecodingDataSource.getConnection(); verify(decodedUrlConnectionTestDataSource, times(1)).getConnection(); }
@Test public void unsuccessfulUrlDecodedConnectionTestIsTriedAgain() throws SQLException { MockDataSource delegateDataSource = pooledDataSourceRequiringDecodedUrl(); DataSource decodedUrlConnectionTestDataSource = mock(DataSource.class); when(decodedUrlConnectionTestDataSource.getConnection()).thenThrow(new SQLException("unable to connect")); UrlDecodingDataSource urlDecodingDataSource = new UrlDecodingDataSource(delegateDataSource, URL_PROPERTY_NAME, url -> decodedUrlConnectionTestDataSource); try { urlDecodingDataSource.getConnection(); } catch (SQLException e) {} try { urlDecodingDataSource.getConnection(); } catch (SQLException e) {} verify(decodedUrlConnectionTestDataSource, times(2)).getConnection(); } |
CloudFoundryServiceInfoCreator implements ServiceInfoCreator<SI, Map<String, Object>> { @SuppressWarnings("unchecked") protected boolean tagsMatch(Map<String, Object> serviceData) { List<String> serviceTags = (List<String>) serviceData.get("tags"); return tags.containsOne(serviceTags); } CloudFoundryServiceInfoCreator(Tags tags, String... uriSchemes); boolean accept(Map<String, Object> serviceData); String[] getUriSchemes(); String getDefaultUriScheme(); } | @Test public void tagsMatch() { DummyServiceInfoCreator serviceInfoCreator = new DummyServiceInfoCreator(new Tags("firstTag", "secondTag")); assertAcceptedWithTags(serviceInfoCreator, "firstTag", "noMatchTag"); assertAcceptedWithTags(serviceInfoCreator, "noMatchTag", "secondTag"); assertAcceptedWithTags(serviceInfoCreator, "firstTag", "secondTag"); assertNotAcceptedWithTags(serviceInfoCreator, "noMatchTag"); assertNotAcceptedWithTags(serviceInfoCreator); } |
CloudFoundryServiceInfoCreator implements ServiceInfoCreator<SI, Map<String, Object>> { protected boolean uriKeyMatchesScheme(Map<String, Object> serviceData) { if (uriSchemes == null) { return false; } Map<String, Object> credentials = getCredentials(serviceData); if (credentials != null) { for (String uriScheme : uriSchemes) { if (credentials.containsKey(uriScheme + "Uri") || credentials.containsKey(uriScheme + "uri") || credentials.containsKey(uriScheme + "Url") || credentials.containsKey(uriScheme + "url")) { return true; } } } return false; } CloudFoundryServiceInfoCreator(Tags tags, String... uriSchemes); boolean accept(Map<String, Object> serviceData); String[] getUriSchemes(); String getDefaultUriScheme(); } | @Test public void uriKeyMatchesScheme() { DummyServiceInfoCreator serviceInfoCreator = new DummyServiceInfoCreator(new Tags(), "amqp", "amqps"); assertAcceptedWithCredentials(serviceInfoCreator, "amqpUri", "https: assertAcceptedWithCredentials(serviceInfoCreator, "amqpsUri", "https: assertAcceptedWithCredentials(serviceInfoCreator, "amqpUrl", "https: assertAcceptedWithCredentials(serviceInfoCreator, "amqpsUrl", "https: assertAcceptedWithCredentials(serviceInfoCreator, "amqpuri", "https: assertAcceptedWithCredentials(serviceInfoCreator, "amqpsuri", "https: assertAcceptedWithCredentials(serviceInfoCreator, "amqpurl", "https: assertAcceptedWithCredentials(serviceInfoCreator, "amqpsurl", "https: } |
Tags { public boolean containsOne(List<String> tags) { if (tags != null) { for (String value : values) { for (String tag : tags) { if (tag.equalsIgnoreCase(value)) { return true; } } } } return false; } Tags(String... values); String[] getTags(); boolean containsOne(List<String> tags); boolean contains(String tag); boolean startsWith(String tag); } | @Test public void containsOne() { Tags tags = new Tags("test1", "test2"); assertTrue(tags.containsOne(Arrays.asList("test1", "testx"))); assertTrue(tags.containsOne(Arrays.asList("testx", "test2"))); assertTrue(tags.containsOne(Arrays.asList("TESTX", "TEST2"))); assertFalse(tags.containsOne(Arrays.asList("testx", "testy"))); }
@Test public void containsOneWithEmptyTags() { assertFalse(EMPTY_TAGS.containsOne(Arrays.asList("test"))); } |
Tags { public boolean contains(String tag) { if (tag != null) { for (String value : values) { if (tag.equalsIgnoreCase(value)) { return true; } } } return false; } Tags(String... values); String[] getTags(); boolean containsOne(List<String> tags); boolean contains(String tag); boolean startsWith(String tag); } | @Test public void contains() { Tags tags = new Tags("test1", "test2"); assertTrue(tags.contains("test1")); assertTrue(tags.contains("test2")); assertTrue(tags.contains("TEST2")); assertFalse(tags.contains("testx")); }
@Test public void containsWithEmptyTags() { assertFalse(EMPTY_TAGS.contains("test")); } |
Tags { public boolean startsWith(String tag) { if (tag != null) { for (String value : values) { if (startsWithIgnoreCase(tag, value)) { return true; } } } return false; } Tags(String... values); String[] getTags(); boolean containsOne(List<String> tags); boolean contains(String tag); boolean startsWith(String tag); } | @Test public void startsWith() { Tags tags = new Tags("test"); assertTrue(tags.startsWith("test-123")); assertTrue(tags.startsWith("TEST-123")); assertFalse(tags.startsWith("abcd")); }
@Test public void startsWithWithEmptyTags() { assertFalse(EMPTY_TAGS.startsWith("test")); } |
Subsets and Splits