src_fm_fc_ms_ff
stringlengths
43
86.8k
target
stringlengths
20
276k
InterledgerAddressUtils { public boolean isDestinationAllowedFromAccount( final AccountId sourceAccountId, final InterledgerAddress destinationAddress ) { Objects.requireNonNull(sourceAccountId); Objects.requireNonNull(destinationAddress); if (isPaymentNetworkAddress(destinationAddress)) { return ALLOWED; } else if (destinationAddress.startsWith(connectorSettingsSupplier.get().operatorAddress())) { return ALLOWED; } else if (destinationAddress.startsWith(InterledgerAddressPrefix.PRIVATE.getValue())) { return accountSettingsRepository.isInternal(sourceAccountId).orElse(NOT_ALLOWED); } else if (destinationAddress.startsWith(InterledgerAddressPrefix.PEER.getValue())) { return accountSettingsRepository.isNotInternal(sourceAccountId).orElse(NOT_ALLOWED); } else if (destinationAddress.startsWith(InterledgerAddressPrefix.SELF.getValue())) { return accountSettingsRepository.isInternal(sourceAccountId).orElse(NOT_ALLOWED); } else { return NOT_ALLOWED; } } InterledgerAddressUtils( final Supplier<ConnectorSettings> connectorSettingsSupplier, final AccountSettingsRepository accountSettingsRepository ); boolean isExternalForwardingAllowed(final InterledgerAddress destinationAddress); boolean isDestinationAllowedFromAccount( final AccountId sourceAccountId, final InterledgerAddress destinationAddress ); }
@Test public void isDestinationAllowedFromAccount() { assertThat(interledgerAddressUtils.isDestinationAllowedFromAccount( ACCOUNT_ID, InterledgerAddress.of("g.foo.receiver")) ).isTrue(); when(connectorSettingsMock.operatorAddress()).thenReturn(InterledgerAddress.of("g.foo")); assertThat(interledgerAddressUtils.isDestinationAllowedFromAccount( ACCOUNT_ID, InterledgerAddress.of("g.foo.receiver")) ).isTrue(); mockAccountAsInternal(true); assertThat(interledgerAddressUtils.isDestinationAllowedFromAccount( ACCOUNT_ID, InterledgerAddress.of("private.foo.receiver")) ).isTrue(); mockAccountAsInternal(false); assertThat(interledgerAddressUtils.isDestinationAllowedFromAccount( ACCOUNT_ID, InterledgerAddress.of("private.foo.receiver")) ).isFalse(); mockAccountAsInternal(true); assertThat(interledgerAddressUtils.isDestinationAllowedFromAccount( ACCOUNT_ID, InterledgerAddress.of("peer.foo.receiver")) ).isFalse(); mockAccountAsInternal(false); assertThat(interledgerAddressUtils.isDestinationAllowedFromAccount( ACCOUNT_ID, InterledgerAddress.of("peer.foo.receiver")) ).isTrue(); mockAccountAsInternal(true); assertThat(interledgerAddressUtils.isDestinationAllowedFromAccount( ACCOUNT_ID, InterledgerAddress.of("self.foo.receiver")) ).isTrue(); mockAccountAsInternal(false); assertThat(interledgerAddressUtils.isDestinationAllowedFromAccount( ACCOUNT_ID, InterledgerAddress.of("self.foo.receiver")) ).isFalse(); assertThat(interledgerAddressUtils.isDestinationAllowedFromAccount( ACCOUNT_ID, InterledgerAddress.of("example.foo.receiver")) ).isFalse(); assertThat(interledgerAddressUtils.isDestinationAllowedFromAccount( ACCOUNT_ID, InterledgerAddress.of("local.foo.receiver")) ).isFalse(); assertThat(interledgerAddressUtils.isDestinationAllowedFromAccount( ACCOUNT_ID, InterledgerAddress.of("test.foo.receiver")) ).isTrue(); assertThat(interledgerAddressUtils.isDestinationAllowedFromAccount( ACCOUNT_ID, InterledgerAddress.of("test1.foo.receiver")) ).isTrue(); assertThat(interledgerAddressUtils.isDestinationAllowedFromAccount( ACCOUNT_ID, InterledgerAddress.of("test2.foo.receiver")) ).isTrue(); assertThat(interledgerAddressUtils.isDestinationAllowedFromAccount( ACCOUNT_ID, InterledgerAddress.of("test3.foo.receiver")) ).isTrue(); }
EthCurrencyProvider implements CurrencyProviderSpi { @Override public Set<CurrencyUnit> getCurrencies(CurrencyQuery query) { if (query.isEmpty() || query.getCurrencyCodes().contains(ETH)) { return currencyUnits; } return Collections.emptySet(); } EthCurrencyProvider(); @Override Set<CurrencyUnit> getCurrencies(CurrencyQuery query); static final String ETH; }
@Test public void getCurrencies() { final Set<CurrencyUnit> currencyUnits = provider.getCurrencies( CurrencyQueryBuilder.of() .setCurrencyCodes(ETH) .setCountries(Locale.CANADA) .set(LocalDate.of(1970, 1, 1)) .setProviderNames(ETH).build() ); assertThat(currencyUnits.size()).isEqualTo(1); assertThat(currencyUnits.stream().findFirst().get().getCurrencyCode()).isEqualTo(ETH); }
DropRoundingProvider implements RoundingProviderSpi { public MonetaryRounding getRounding(RoundingQuery query) { final CurrencyUnit currency = query.getCurrency(); if (currency != null && (XRP.equals(currency.getCurrencyCode()))) { return dropsRounding; } else if (DROP.equals(query.getRoundingName())) { return dropsRounding; } return null; } DropRoundingProvider(); MonetaryRounding getRounding(RoundingQuery query); Set<String> getRoundingNames(); }
@Test public void testRoundDropsWithAllDecimals() { final MonetaryAmount xrpAmount = Monetary.getAmountFactory(Money.class) .setCurrency(XRP) .setNumber(new BigDecimal("0.123456789")) .create(); assertThat(xrpAmount.getNumber().numberValue(BigDecimal.class)).isEqualTo(new BigDecimal("0.123456789")); final MonetaryAmount xrpRounded = xrpAmount.with(Monetary.getRounding(xrpAmount.getCurrency())); assertThat(xrpRounded.getNumber().numberValue(BigDecimal.class)).isEqualTo(new BigDecimal("0.123457")); } @Test public void testRoundXrpWhenSmallerThanDrops() { final MonetaryAmount xrpAmount = Monetary.getAmountFactory(Money.class) .setCurrency(XRP) .setNumber(new BigDecimal("0.000000001")) .create(); assertThat(xrpAmount.getNumber().numberValue(BigDecimal.class)).isEqualTo(new BigDecimal("0.000000001")); final MonetaryAmount xrpRounded = xrpAmount.with(Monetary.getRounding(xrpAmount.getCurrency())); assertThat(xrpRounded.getNumber().numberValue(BigDecimal.class)).isEqualTo(new BigDecimal("0")); } @Test public void testRoundDropsWith1Xrp() { final Money xrpAmount = Monetary.getAmountFactory(Money.class) .setCurrency(XRP) .setNumber(new BigDecimal("1.123456789")) .create(); assertThat(xrpAmount.getNumber().numberValue(BigDecimal.class)).isEqualTo(new BigDecimal("1.123456789")); final MonetaryAmount xrpRounded = xrpAmount.with(Monetary.getRounding(xrpAmount.getCurrency())); assertThat(xrpRounded.getNumber().numberValue(BigDecimal.class)).isEqualTo(new BigDecimal("1.123457")); } @Test public void testRoundDrops() { final MonetaryAmount xrpAmount = Monetary.getAmountFactory(Money.class) .setCurrency(XRP) .setNumber(new BigDecimal("221.123456")) .create(); assertThat(xrpAmount.getNumber().numberValue(BigDecimal.class)).isEqualTo(new BigDecimal("221.123456")); final MonetaryAmount xrpRounded = xrpAmount.with(Monetary.getRounding(xrpAmount.getCurrency())); assertThat(xrpRounded.getNumber().numberValue(BigDecimal.class)).isEqualTo(new BigDecimal("221.123456")); } @Test public void getRounding() { final MonetaryRounding rounding = dropRoundingProvider.getRounding(RoundingQueryBuilder.of() .setCurrency(Monetary.getCurrency(XRP)) .build()); assertThat(rounding.getRoundingContext().getProviderName()).isEqualTo("DropsProvider"); assertThat(rounding.getRoundingContext().getRoundingName()).isEqualTo(DROP); } @Test(expected = UnknownCurrencyException.class) public void getRoundingNotFound() { try { dropRoundingProvider.getRounding(RoundingQueryBuilder.of() .setCurrency(Monetary.getCurrency("Foo")) .build()); } catch (UnknownCurrencyException e) { assertThat(e.getMessage()).isEqualTo("Unknown currency code: Foo"); throw e; } }
DropRoundingProvider implements RoundingProviderSpi { public Set<String> getRoundingNames() { return roundingNames; } DropRoundingProvider(); MonetaryRounding getRounding(RoundingQuery query); Set<String> getRoundingNames(); }
@Test public void getRoundingNames() { assertThat(dropRoundingProvider.getRoundingNames().size()).isEqualTo(1); assertThat(dropRoundingProvider.getRoundingNames().contains(DROP)).isTrue(); }
CryptoCompareRateProvider extends AbstractRateProvider { @Override public ExchangeRate getExchangeRate(ConversionQuery conversionQuery) { Objects.requireNonNull(conversionQuery); try { return this.exchangeRateCache.get(conversionQuery, fxLoader()); } catch (Exception e) { throw new MonetaryException("Failed to load currency conversion data", e); } } CryptoCompareRateProvider( final Supplier<String> apiKeySupplier, final RestTemplate restTemplate, final Cache<ConversionQuery, ExchangeRate> exchangeRateCache ); @Override ExchangeRate getExchangeRate(ConversionQuery conversionQuery); }
@Test public void getExchangeRateWithUnknownCurrencyInCryptoCompare() { expectedException.expect(MonetaryException.class); expectedException.expectMessage("Unknown currency code: FOO"); provider.getExchangeRate( ConversionQueryBuilder.of().setBaseCurrency("FOO").setTermCurrency("USD").setRateTypes(RateType.DEFERRED) .build() ); } @Test public void getExchangeRateWithNoRateFoundInCryptoCompare() { expectedException.expect(MonetaryException.class); expectedException.expectMessage("Failed to load currency conversion data"); provider.getExchangeRate( ConversionQueryBuilder.of().setBaseCurrency("XRP").setTermCurrency("USD").setRateTypes(RateType.DEFERRED) .build() ); } @Test public void getExchangeRateWhenRateExistsInCache() { ExchangeRate exchangeRateMock = mock(ExchangeRate.class); when(cacheMock.get(any(), any())).thenReturn(exchangeRateMock); this.provider = new CryptoCompareRateProvider(() -> "apiKey", restTemplate, cacheMock); final ExchangeRate actual = provider.getExchangeRate( ConversionQueryBuilder.of().setBaseCurrency("XRP").setTermCurrency("USD").setRateTypes(RateType.DEFERRED) .build() ); assertThat(actual).isEqualTo(exchangeRateMock); }
XrpCurrencyProvider implements CurrencyProviderSpi { @Override public Set<CurrencyUnit> getCurrencies(CurrencyQuery query) { if (query.isEmpty() || query.getCurrencyCodes().contains(XRP)) { return currencyUnits; } return Collections.emptySet(); } XrpCurrencyProvider(); @Override Set<CurrencyUnit> getCurrencies(CurrencyQuery query); static final String DROP; static final String XRP; }
@Test public void getCurrencies() { final Set<CurrencyUnit> currencyUnits = provider.getCurrencies( CurrencyQueryBuilder.of() .setCurrencyCodes(XRP) .setCountries(Locale.CANADA) .set(LocalDate.of(1970, 1, 1)) .setProviderNames(XRP).build() ); assertThat(currencyUnits.size()).isEqualTo(1); assertThat(currencyUnits.stream().findFirst().get().getCurrencyCode()).isEqualTo(XRP); } @Test public void getCurrenciesUnknownProvider() { final Set<CurrencyUnit> currencyUnits = provider.getCurrencies( CurrencyQueryBuilder.of() .setCountries(Locale.CANADA) .set(LocalDate.of(1970, 1, 1)) .setProviderNames(DROP).build() ); assertThat(currencyUnits.size()).isEqualTo(0); }
DefaultNextHopPacketMapper implements NextHopPacketMapper { public NextHopInfo getNextHopPacket( final AccountSettings sourceAccountSettings, final InterledgerPreparePacket sourcePacket ) throws RuntimeException { if (logger.isDebugEnabled()) { logger.debug( "Constructing NextHop InterledgerPreparePacket. sourceAccountSettings={} packet={}", sourceAccountSettings, sourcePacket ); } final InterledgerAddress destinationAddress = sourcePacket.getDestination(); final Route nextHopRoute = this.externalRoutingService.findBestNexHop(destinationAddress) .orElseThrow(() -> new InterledgerProtocolException( InterledgerRejectPacket.builder() .triggeredBy(connectorSettingsSupplier.get().operatorAddress()) .code(InterledgerErrorCode.F02_UNREACHABLE) .message(DESTINATION_ADDRESS_IS_UNREACHABLE) .build(), String.format( "No route found from accountId to destination. sourceAccountSettings=%s destinationAddress=%s", sourceAccountSettings, destinationAddress.getValue() ) ) ); if (logger.isDebugEnabled()) { logger.debug("Determined next hop: {}", nextHopRoute); } if (sourceAccountSettings.accountId().equals(nextHopRoute.nextHopAccountId())) { throw new InterledgerProtocolException( InterledgerRejectPacket.builder() .triggeredBy(connectorSettingsSupplier.get().operatorAddress()) .code(InterledgerErrorCode.F02_UNREACHABLE) .message(DESTINATION_ADDRESS_IS_UNREACHABLE) .build(), String.format( "Refusing to route payments back to sender. sourceAccountSettings=%s destinationAccount=%s", sourceAccountSettings, nextHopRoute.nextHopAccountId() ) ); } final AccountSettings destinationAccountSettings = this.accountSettingsLoadingCache.safeGetAccountId(nextHopRoute.nextHopAccountId()); final UnsignedLong nextAmount = this.determineNextAmount( sourceAccountSettings, destinationAccountSettings, sourcePacket ); if (!sourcePacket.getAmount().equals(UnsignedLong.ZERO) && UnsignedLong.ZERO.equals(nextAmount)) { logger.warn( "While packet-switching, a non-zero source packet amount translated into a zero-value destination amount. " + "sourcePacket={} nextHopRoute={}", sourcePacket, nextHopRoute); } return NextHopInfo.builder() .nextHopAccountId(nextHopRoute.nextHopAccountId()) .nextHopPacket( InterledgerPreparePacket.builder() .from(sourcePacket) .amount(nextAmount) .expiresAt(determineDestinationExpiresAt(Clock.systemUTC(), sourcePacket.getExpiresAt(), sourcePacket.getDestination())) .build()) .build(); } DefaultNextHopPacketMapper( final Supplier<ConnectorSettings> connectorSettingsSupplier, final PaymentRouter<Route> externalRoutingService, final InterledgerAddressUtils addressUtils, final JavaMoneyUtils javaMoneyUtils, final AccountSettingsLoadingCache accountSettingsLoadingCache ); @VisibleForTesting DefaultNextHopPacketMapper( final Supplier<ConnectorSettings> connectorSettingsSupplier, final PaymentRouter<Route> externalRoutingService, final InterledgerAddressUtils addressUtils, final JavaMoneyUtils javaMoneyUtils, final AccountSettingsLoadingCache accountSettingsLoadingCache, final Function<CurrencyUnit, CurrencyConversion> currencyConverter ); NextHopInfo getNextHopPacket( final AccountSettings sourceAccountSettings, final InterledgerPreparePacket sourcePacket ); @Deprecated BigDecimal determineExchangeRate( final AccountSettings sourceAccountSettings, final AccountSettings destinationAccountSettings, final InterledgerPreparePacket sourcePacket ); }
@Test public void getNextHopPacket() { Instant now = Instant.now(clock); AccountSettings settings = defaultSenderAccountSettings().build(); InterledgerPreparePacket preparePacket = defaultPreparePacket(now).build(); when(mockAccountCache.safeGetAccountId(NEXT_HOP.nextHopAccountId())) .thenReturn(defaultNextHopSettings().build()); when(mockRoutingService.findBestNexHop(RECEIVER)).thenReturn(Optional.of(NEXT_HOP)); NextHopInfo result = mapper.getNextHopPacket(settings, preparePacket); InterledgerPreparePacket expectedPreparePacket = defaultExpectedPreparePacket(preparePacket).build(); assertPreparePacket(result, expectedPreparePacket); } @Test public void getNextHopPacketNoDestinationAddressFoundFromRoutingService() { Instant now = Instant.now(clock); AccountSettings settings = defaultSenderAccountSettings().build(); InterledgerPreparePacket preparePacket = defaultPreparePacket(now).build(); when(mockAccountCache.safeGetAccountId(NEXT_HOP.nextHopAccountId())) .thenReturn(defaultNextHopSettings().build()); when(mockRoutingService.findBestNexHop(RECEIVER)).thenReturn(Optional.empty()); expectedException.expect(InterledgerProtocolException.class); expectedException.expectMessage("No route found from accountId to destination"); mapper.getNextHopPacket(settings, preparePacket); } @Test public void getNextHopPacketSourceAccountIdMatchesNextHopAccountId() { Instant now = Instant.now(clock); AccountSettings settings = defaultSenderAccountSettings().build(); InterledgerPreparePacket preparePacket = defaultPreparePacket(now).build(); when(mockAccountCache.safeGetAccountId(NEXT_HOP_2.nextHopAccountId())) .thenReturn(defaultNextHopSettings().build()); when(mockRoutingService.findBestNexHop(RECEIVER)).thenReturn(Optional.of(NEXT_HOP_2)); expectedException.expect(InterledgerProtocolException.class); expectedException.expectMessage("Refusing to route payments back to sender"); mapper.getNextHopPacket(settings, preparePacket); } @Test public void getNextHopPacketWhenExpired() { Instant now = Instant.now(clock); AccountSettings settings = defaultSenderAccountSettings().build(); InterledgerPreparePacket preparePacket = defaultPreparePacket(now).expiresAt(now.minusSeconds(30)).build(); when(mockAccountCache.safeGetAccountId(NEXT_HOP.nextHopAccountId())) .thenReturn(defaultNextHopSettings().build()); when(mockRoutingService.findBestNexHop(RECEIVER)).thenReturn(Optional.of(NEXT_HOP)); expectedException.expect(InterledgerProtocolException.class); expectedException.expectMessage("Source transfer has already expired."); mapper.getNextHopPacket(settings, preparePacket); }
SpringProfileUtils { public static boolean isProfileActive(Environment environment, String profile) { return Arrays.asList(environment.getActiveProfiles()) .stream() .anyMatch(active -> active.trim().equalsIgnoreCase(profile.trim())); } static boolean isProfileActive(Environment environment, String profile); }
@Test public void activeProfilesEmpty() { when(environment.getActiveProfiles()).thenReturn(new String[] {}); assertThat(SpringProfileUtils.isProfileActive(environment, "foo")).isFalse(); assertThat(SpringProfileUtils.isProfileActive(environment, "")).isFalse(); } @Test public void activeProfiles() { when(environment.getActiveProfiles()).thenReturn(new String[] {"Foo", "BAR", "baz"}); assertThat(SpringProfileUtils.isProfileActive(environment, "Foo")).isTrue(); assertThat(SpringProfileUtils.isProfileActive(environment, "foo")).isTrue(); assertThat(SpringProfileUtils.isProfileActive(environment, "FOO")).isTrue(); assertThat(SpringProfileUtils.isProfileActive(environment, "BAR")).isTrue(); assertThat(SpringProfileUtils.isProfileActive(environment, "Bar")).isTrue(); assertThat(SpringProfileUtils.isProfileActive(environment, "bar")).isTrue(); assertThat(SpringProfileUtils.isProfileActive(environment, "baz")).isTrue(); assertThat(SpringProfileUtils.isProfileActive(environment, "Baz")).isTrue(); assertThat(SpringProfileUtils.isProfileActive(environment, "BAZ")).isTrue(); assertThat(SpringProfileUtils.isProfileActive(environment, "foobar")).isFalse(); } @Test public void activeProfilesTrimmed() { when(environment.getActiveProfiles()).thenReturn(new String[] {"foo"}); assertThat(SpringProfileUtils.isProfileActive(environment, "foo ")).isTrue(); assertThat(SpringProfileUtils.isProfileActive(environment, " foo")).isTrue(); assertThat(SpringProfileUtils.isProfileActive(environment, " foo ")).isTrue(); }
DefaultNextHopPacketMapper implements NextHopPacketMapper { @VisibleForTesting protected UnsignedLong determineNextAmount( final AccountSettings sourceAccountSettings, final AccountSettings destinationAccountSettings, final InterledgerPreparePacket sourcePacket ) { Objects.requireNonNull(sourceAccountSettings); Objects.requireNonNull(destinationAccountSettings); Objects.requireNonNull(sourcePacket); final CurrencyUnit sourceCurrencyUnit = Monetary.getCurrency(sourceAccountSettings.assetCode()); final int sourceScale = sourceAccountSettings.assetScale(); final MonetaryAmount sourceAmount = javaMoneyUtils.toMonetaryAmount(sourceCurrencyUnit, sourcePacket.getAmount().bigIntegerValue(), sourceScale); final CurrencyUnit destinationCurrencyUnit = Monetary.getCurrency(destinationAccountSettings.assetCode()); final int destinationScale = destinationAccountSettings.assetScale(); final CurrencyConversion destCurrencyConversion = currencyConverter.apply(destinationCurrencyUnit); return UnsignedLong.valueOf( javaMoneyUtils.toInterledgerAmount(sourceAmount.with(destCurrencyConversion), destinationScale)); } DefaultNextHopPacketMapper( final Supplier<ConnectorSettings> connectorSettingsSupplier, final PaymentRouter<Route> externalRoutingService, final InterledgerAddressUtils addressUtils, final JavaMoneyUtils javaMoneyUtils, final AccountSettingsLoadingCache accountSettingsLoadingCache ); @VisibleForTesting DefaultNextHopPacketMapper( final Supplier<ConnectorSettings> connectorSettingsSupplier, final PaymentRouter<Route> externalRoutingService, final InterledgerAddressUtils addressUtils, final JavaMoneyUtils javaMoneyUtils, final AccountSettingsLoadingCache accountSettingsLoadingCache, final Function<CurrencyUnit, CurrencyConversion> currencyConverter ); NextHopInfo getNextHopPacket( final AccountSettings sourceAccountSettings, final InterledgerPreparePacket sourcePacket ); @Deprecated BigDecimal determineExchangeRate( final AccountSettings sourceAccountSettings, final AccountSettings destinationAccountSettings, final InterledgerPreparePacket sourcePacket ); }
@Test public void determineNextAmountWithConversion() { Instant now = Instant.now(clock); AccountSettings sourceSettings = defaultSenderAccountSettings() .assetCode("EUR") .build(); InterledgerPreparePacket preparePacket = defaultPreparePacket(now) .amount(UnsignedLong.valueOf(100)) .build(); when(mockAccountCache.safeGetAccountId(NEXT_HOP.nextHopAccountId())) .thenReturn(defaultNextHopSettings().build()); when(mockRoutingService.findBestNexHop(RECEIVER)).thenReturn(Optional.of(NEXT_HOP)); int conversionRate = 2; mockConversionRate(conversionRate); UnsignedLong result = mapper.determineNextAmount(sourceSettings, defaultNextHopSettings().build(), preparePacket); assertThat(result).isEqualTo(UnsignedLong.valueOf(200)); } @Test public void determineNextAmountSameConversionProperRounding() { Instant now = Instant.now(clock); AccountSettings sourceSettings = defaultSenderAccountSettings() .assetCode("XRP") .assetScale(9) .build(); AccountSettings nextHop = defaultSenderAccountSettings() .accountId(AccountId.of("netHop")) .assetCode("XRP") .assetScale(9) .build(); InterledgerPreparePacket preparePacket = defaultPreparePacket(now) .amount(UnsignedLong.valueOf(1)) .build(); when(mockAccountCache.safeGetAccountId(NEXT_HOP.nextHopAccountId())).thenReturn(nextHop); when(mockRoutingService.findBestNexHop(RECEIVER)).thenReturn(Optional.of(NEXT_HOP)); int conversionRate = 1; mockConversionRate(conversionRate); UnsignedLong result = mapper.determineNextAmount(sourceSettings, nextHop, preparePacket); assertThat(result).isEqualTo(UnsignedLong.valueOf(1)); } @Test public void determineNextAmountAlwaysRoundsDown1() { Instant now = Instant.now(clock); AccountSettings sourceSettings = defaultSenderAccountSettings() .assetCode("USD") .assetScale(2) .build(); InterledgerPreparePacket preparePacket = defaultPreparePacket(now) .amount(UnsignedLong.valueOf(99)) .build(); when(mockAccountCache.safeGetAccountId(NEXT_HOP.nextHopAccountId())) .thenReturn(defaultNextHopSettings().build()); when(mockRoutingService.findBestNexHop(RECEIVER)).thenReturn(Optional.of(NEXT_HOP)); int conversionRate = 1; mockConversionRate(conversionRate); final AccountSettings nextHopAccountSettings = defaultNextHopSettings().assetCode("USD").assetScale(0).build(); UnsignedLong result = mapper.determineNextAmount(sourceSettings, nextHopAccountSettings, preparePacket); assertThat(result).isEqualTo(UnsignedLong.ZERO); } @Test public void determineNextAmountAlwaysRoundsDown2() { Instant now = Instant.now(clock); AccountSettings sourceSettings = defaultSenderAccountSettings() .assetCode("USD") .assetScale(2) .build(); InterledgerPreparePacket preparePacket = defaultPreparePacket(now) .amount(UnsignedLong.valueOf(100)) .build(); when(mockAccountCache.safeGetAccountId(NEXT_HOP.nextHopAccountId())) .thenReturn(defaultNextHopSettings().build()); when(mockRoutingService.findBestNexHop(RECEIVER)).thenReturn(Optional.of(NEXT_HOP)); int conversionRate = 1; mockConversionRate(conversionRate); final AccountSettings nextHopAccountSettings = defaultNextHopSettings().assetCode("USD").assetScale(0).build(); UnsignedLong result = mapper.determineNextAmount(sourceSettings, nextHopAccountSettings, preparePacket); assertThat(result).isEqualTo(UnsignedLong.valueOf(1L)); } @Test public void determineNextAmountAlwaysRoundsDown3() { Instant now = Instant.now(clock); AccountSettings sourceSettings = defaultSenderAccountSettings() .assetCode("USD") .assetScale(2) .build(); InterledgerPreparePacket preparePacket = defaultPreparePacket(now) .amount(UnsignedLong.valueOf(101)) .build(); when(mockAccountCache.safeGetAccountId(NEXT_HOP.nextHopAccountId())) .thenReturn(defaultNextHopSettings().build()); when(mockRoutingService.findBestNexHop(RECEIVER)).thenReturn(Optional.of(NEXT_HOP)); int conversionRate = 1; mockConversionRate(conversionRate); final AccountSettings nextHopAccountSettings = defaultNextHopSettings().assetCode("USD").assetScale(0).build(); UnsignedLong result = mapper.determineNextAmount(sourceSettings, nextHopAccountSettings, preparePacket); assertThat(result).isEqualTo(UnsignedLong.valueOf(1L)); } @Test public void determineNextAmountExternalForwardingNotAllowedForDestination() { mockExternalForwardingAllowed(false); Instant now = Instant.now(clock); AccountSettings sourceSettings = defaultSenderAccountSettings().build(); InterledgerPreparePacket preparePacket = defaultPreparePacket(now).build(); UnsignedLong result = mapper.determineNextAmount(sourceSettings, defaultNextHopSettings().build(), preparePacket); assertThat(result).isEqualTo(UnsignedLong.valueOf(10000)); } @Test public void determineNextAmountWithNullSourceAccountSettings() { expectedException.expect(NullPointerException.class); mapper.determineNextAmount(null, mock(AccountSettings.class), mock(InterledgerPreparePacket.class)); } @Test public void determineNextAmountWithNullDestinationAccountSettings() { expectedException.expect(NullPointerException.class); mapper.determineNextAmount(mock(AccountSettings.class), null, mock(InterledgerPreparePacket.class)); } @Test public void determineNextAmountWithNullSourcePacket() { expectedException.expect(NullPointerException.class); mapper.determineNextAmount(mock(AccountSettings.class), mock(AccountSettings.class), null); }
DefaultNextHopPacketMapper implements NextHopPacketMapper { @VisibleForTesting protected Instant determineDestinationExpiresAt( final Clock clock, final Instant sourceExpiry, final InterledgerAddress destinationAddress ) { Objects.requireNonNull(sourceExpiry); if (!this.addressUtils.isExternalForwardingAllowed(destinationAddress)) { return sourceExpiry; } else { final Instant nowTime = Instant.now(clock); if (sourceExpiry.isBefore(nowTime)) { throw new InterledgerProtocolException( InterledgerRejectPacket.builder() .triggeredBy(connectorSettingsSupplier.get().operatorAddress()) .code(InterledgerErrorCode.R02_INSUFFICIENT_TIMEOUT) .message(String .format("Source transfer has already expired. sourceExpiry: {%s}, currentTime: {%s}", sourceExpiry, nowTime)) .build() ); } final int minMessageWindow = connectorSettingsSupplier.get().minMessageWindowMillis(); final int maxHoldTime = connectorSettingsSupplier.get().maxHoldTimeMillis(); final Instant adjustedSourceExpiryInstant = sourceExpiry.minusMillis(minMessageWindow); final Instant maxHoldInstant = nowTime.plusMillis(maxHoldTime); final Instant destinationExpiryTime = lesser(adjustedSourceExpiryInstant, maxHoldInstant); if (destinationExpiryTime.minusMillis(minMessageWindow).isBefore(nowTime)) { throw new InterledgerProtocolException( InterledgerRejectPacket.builder() .triggeredBy(connectorSettingsSupplier.get().operatorAddress()) .code(InterledgerErrorCode.R02_INSUFFICIENT_TIMEOUT) .message(String.format( "Source transfer expires too soon to complete payment. SourceExpiry: {%s}, " + "RequiredSourceExpiry: {%s}, CurrentTime: {%s}", sourceExpiry, nowTime.plusMillis(minMessageWindow), nowTime)) .build() ); } else { return destinationExpiryTime; } } } DefaultNextHopPacketMapper( final Supplier<ConnectorSettings> connectorSettingsSupplier, final PaymentRouter<Route> externalRoutingService, final InterledgerAddressUtils addressUtils, final JavaMoneyUtils javaMoneyUtils, final AccountSettingsLoadingCache accountSettingsLoadingCache ); @VisibleForTesting DefaultNextHopPacketMapper( final Supplier<ConnectorSettings> connectorSettingsSupplier, final PaymentRouter<Route> externalRoutingService, final InterledgerAddressUtils addressUtils, final JavaMoneyUtils javaMoneyUtils, final AccountSettingsLoadingCache accountSettingsLoadingCache, final Function<CurrencyUnit, CurrencyConversion> currencyConverter ); NextHopInfo getNextHopPacket( final AccountSettings sourceAccountSettings, final InterledgerPreparePacket sourcePacket ); @Deprecated BigDecimal determineExchangeRate( final AccountSettings sourceAccountSettings, final AccountSettings destinationAccountSettings, final InterledgerPreparePacket sourcePacket ); }
@Test public void determineDestinationExpiresAtNoExternalForwarding() { mockExternalForwardingAllowed(false); Instant expiry = Instant.now(clock).plusSeconds(10); mockExternalForwardingAllowed(false); assertThat(mapper.determineDestinationExpiresAt(clock, expiry, RECEIVER)).isEqualTo(expiry); } @Test public void determineDestinationExpiresAtLimitedByMaxHold() { Instant now = Instant.now(clock); Instant expiry = now.plusMillis(10000); int maxHoldTimeMillis = 5000; int minMessageWindowMillis = 1000; connectorSettings.setMaxHoldTimeMillis(maxHoldTimeMillis); connectorSettings.setMinMessageWindowMillis(minMessageWindowMillis); mockExternalForwardingAllowed(true); assertThat(mapper.determineDestinationExpiresAt(clock, expiry, RECEIVER)) .isEqualTo(now.plusMillis(maxHoldTimeMillis)); } @Test public void determineDestinationExpiresReducedByMinMessageWindow() { Instant now = Instant.now(clock); Instant expiry = now.plusMillis(10000); int maxHoldTimeMillis = 10000; int minMessageWindowMillis = 1000; connectorSettings.setMaxHoldTimeMillis(maxHoldTimeMillis); connectorSettings.setMinMessageWindowMillis(minMessageWindowMillis); mockExternalForwardingAllowed(true); assertThat(mapper.determineDestinationExpiresAt(clock, expiry, RECEIVER)) .isEqualTo(expiry.minusMillis(minMessageWindowMillis)); } @Test public void determineDestinationExpiresAfterMinMessageWindow() { Instant now = Instant.now(clock); Instant expiry = now.plusMillis(1000); int maxHoldTimeMillis = 10000; int minMessageWindowMillis = 2000; connectorSettings.setMaxHoldTimeMillis(maxHoldTimeMillis); connectorSettings.setMinMessageWindowMillis(minMessageWindowMillis); mockExternalForwardingAllowed(true); expectedException.expect(InterledgerProtocolException.class); mapper.determineDestinationExpiresAt(clock, expiry, RECEIVER); } @Test public void determineDestinationExpiresExactlyAtMinMessageWindow() { Instant now = Instant.now(clock); Instant expiry = now.plusMillis(1000); int maxHoldTimeMillis = 10000; int minMessageWindowMillis = 1000; connectorSettings.setMaxHoldTimeMillis(maxHoldTimeMillis); connectorSettings.setMinMessageWindowMillis(minMessageWindowMillis); mockExternalForwardingAllowed(true); expectedException.expect(InterledgerProtocolException.class); expectedException.expectMessage("Interledger Rejection: Source transfer expires too soon to complete payment"); mapper.determineDestinationExpiresAt(clock, expiry, RECEIVER); } @Test public void determineDestinationExpiresAlreadyExpired() { Instant now = Instant.now(clock); Instant expiry = now.minusMillis(500); int maxHoldTimeMillis = 10000; int minMessageWindowMillis = 2000; connectorSettings.setMaxHoldTimeMillis(maxHoldTimeMillis); connectorSettings.setMinMessageWindowMillis(minMessageWindowMillis); mockExternalForwardingAllowed(true); expectedException.expect(InterledgerProtocolException.class); expectedException.expectMessage("Interledger Rejection: Source transfer has already expired"); mapper.determineDestinationExpiresAt(clock, expiry, RECEIVER); } @Test public void determineDestinationExpiresAtSourceExpiryRequired() { int maxHoldTimeMillis = 10000; int minMessageWindowMillis = 1000; connectorSettings.setMaxHoldTimeMillis(maxHoldTimeMillis); connectorSettings.setMinMessageWindowMillis(minMessageWindowMillis); mockExternalForwardingAllowed(true); expectedException.expect(NullPointerException.class); mapper.determineDestinationExpiresAt(clock, null, RECEIVER); }
DefaultNextHopPacketMapper implements NextHopPacketMapper { @VisibleForTesting protected Instant lesser(final Instant first, final Instant second) { if (first.isBefore(second)) { return first; } else { return second; } } DefaultNextHopPacketMapper( final Supplier<ConnectorSettings> connectorSettingsSupplier, final PaymentRouter<Route> externalRoutingService, final InterledgerAddressUtils addressUtils, final JavaMoneyUtils javaMoneyUtils, final AccountSettingsLoadingCache accountSettingsLoadingCache ); @VisibleForTesting DefaultNextHopPacketMapper( final Supplier<ConnectorSettings> connectorSettingsSupplier, final PaymentRouter<Route> externalRoutingService, final InterledgerAddressUtils addressUtils, final JavaMoneyUtils javaMoneyUtils, final AccountSettingsLoadingCache accountSettingsLoadingCache, final Function<CurrencyUnit, CurrencyConversion> currencyConverter ); NextHopInfo getNextHopPacket( final AccountSettings sourceAccountSettings, final InterledgerPreparePacket sourcePacket ); @Deprecated BigDecimal determineExchangeRate( final AccountSettings sourceAccountSettings, final AccountSettings destinationAccountSettings, final InterledgerPreparePacket sourcePacket ); }
@Test public void lesser() { Instant now = Instant.now(clock); Instant nowPlusOne = Instant.now(clock).plusSeconds(1); assertThat(mapper.lesser(now, nowPlusOne)).isEqualTo(now); assertThat(mapper.lesser(nowPlusOne, now)).isEqualTo(now); assertThat(mapper.lesser(now, now)).isEqualTo(now); }
DefaultLinkManager implements LinkManager, LinkConnectionEventListener { @Override public Link<? extends LinkSettings> getOrCreateLink(final AccountId accountId) { Objects.requireNonNull(accountId); return Optional.ofNullable(this.connectedLinks.get(accountId)) .orElseGet(() -> { final AccountSettings accountSettings = accountSettingsRepository.findByAccountIdWithConversion(accountId) .orElseThrow(() -> new AccountNotFoundProblem(accountId)); return (Link) getOrCreateLink(accountSettings); }); } DefaultLinkManager( final Supplier<InterledgerAddress> operatorAddressSupplier, final AccountSettingsRepository accountSettingsRepository, final LinkSettingsFactory linkSettingsFactory, final LinkFactoryProvider linkFactoryProvider, final AccountIdResolver accountIdResolver, final CircuitBreakerConfig defaultCircuitBreakerConfig, final LocalDestinationAddressUtils localDestinationAddressUtils, final EventBus eventBus ); @Override Link<? extends LinkSettings> getOrCreateLink(final AccountId accountId); @Override Link<? extends LinkSettings> getOrCreateLink(final AccountSettings accountSettings); @Override Link<? extends LinkSettings> getOrCreateLink(final AccountId accountId, final LinkSettings linkSettings); @Override Set<Link<? extends LinkSettings>> getAllConnectedLinks(); @Override Link<? extends LinkSettings> getOrCreateSpspReceiverLink(final AccountSettings accountSettings); @Override @Subscribe void onConnect(final LinkConnectedEvent event); @Override @Subscribe void onDisconnect(final LinkDisconnectedEvent event); }
@Test public void getOrCreateLinkWithNullAccountSettings() { expectedException.expect(NullPointerException.class); expectedException.expectMessage("accountId must not be null"); final AccountSettings nullAccountSettings = null; defaultLinkManager.getOrCreateLink(nullAccountSettings); } @Test public void getOrCreateLinkForPingLink() { when(localDestinationAddressUtilsMock.isConnectorPingAccountId(any())).thenReturn(true); when(linkFactoryProviderMock.getLinkFactory(PingLoopbackLink.LINK_TYPE).constructLink(any(), any())) .thenReturn(pingLinkMock); final AccountSettings accountSettingsMock = mock(AccountSettings.class); when(accountSettingsMock.accountId()).thenReturn(LocalDestinationAddressUtils.PING_ACCOUNT_ID); final Link<? extends LinkSettings> link = defaultLinkManager.getOrCreateLink(accountSettingsMock); assertThat(link).isEqualTo(pingLinkMock); Mockito.verifyNoInteractions(linkSettingsFactoryMock); } @Test public void getOrCreateLinkForNonPingLink() { final LinkSettings linkSettingsMock = mock(LinkSettings.class); when(nonPingLinkMock.getOperatorAddressSupplier()).thenReturn(INTERLEDGER_ADDRESS_SUPPLIER); when(nonPingLinkMock.getLinkSettings()).thenReturn(linkSettingsMock); when(localDestinationAddressUtilsMock.isConnectorPingAccountId(any())).thenReturn(false); when(linkFactoryProviderMock.getLinkFactory(any()).constructLink(any(), any())).thenReturn(nonPingLinkMock); when(linkSettingsFactoryMock.construct(any())).thenReturn(linkSettingsMock); final AccountSettings accountSettingsMock = mock(AccountSettings.class); when(accountSettingsMock.accountId()).thenReturn(AccountId.of("foo")); final Link<? extends LinkSettings> link = defaultLinkManager.getOrCreateLink(accountSettingsMock); assertThat(link.getLinkId()).isEqualTo(nonPingLinkMock.getLinkId()); }
DefaultLinkFilterChain implements LinkFilterChain { @Override public InterledgerResponsePacket doFilter( final AccountSettings destinationAccountSettings, final InterledgerPreparePacket preparePacket ) { Objects.requireNonNull(destinationAccountSettings); Objects.requireNonNull(preparePacket); try { if (this._filterIndex < this.linkFilters.size()) { return linkFilters.get(_filterIndex++).doFilter(destinationAccountSettings, preparePacket, this); } else { try { LOGGER.debug( "Sending outbound ILP Prepare. destinationAccountSettings: {}; link={}; packet={};", destinationAccountSettings, link, preparePacket ); final Duration timeoutDuration = Duration.between(Instant.now(), preparePacket.getExpiresAt()); if (timeoutDuration.isNegative() || timeoutDuration.isZero()) { return packetRejector.reject( LinkId.of(destinationAccountSettings.accountId().value()), preparePacket, R02_INSUFFICIENT_TIMEOUT, "The connector could not forward the payment, because the timeout was too low" ); } return CompletableFuture.supplyAsync(() -> link.sendPacket(preparePacket), EXECUTOR) .get(timeoutDuration.getSeconds(), TimeUnit.SECONDS); } catch (InterruptedException | ExecutionException e) { LOGGER.error(e.getMessage(), e); return packetRejector.reject( LinkId.of(destinationAccountSettings.accountId().value()), preparePacket, InterledgerErrorCode.T00_INTERNAL_ERROR, String.format("Internal Error: %s", e.getCause() != null ? e.getCause().getMessage() : e.getMessage()) ); } catch (TimeoutException e) { LOGGER.error(e.getMessage(), e); return packetRejector.reject( LinkId.of(destinationAccountSettings.accountId().value()), preparePacket, InterledgerErrorCode.R00_TRANSFER_TIMED_OUT, "Transfer Timed-out" ); } catch (Exception e) { LOGGER.error(e.getMessage(), e); return packetRejector.reject( LinkId.of(destinationAccountSettings.accountId().value()), preparePacket, InterledgerErrorCode.T00_INTERNAL_ERROR, String.format("Internal Error: %s", e.getMessage()) ); } } } catch (Exception e) { LOGGER.error("Failure in LinkFilterChain: " + e.getMessage(), e); if (InterledgerRuntimeException.class.isAssignableFrom(e.getClass())) { return ((InterledgerProtocolException) e).getInterledgerRejectPacket(); } else { return packetRejector.reject( LinkId.of(destinationAccountSettings.accountId().value()), preparePacket, InterledgerErrorCode.T00_INTERNAL_ERROR, String.format("Internal Error: %s", e.getMessage()) ); } } } DefaultLinkFilterChain( final PacketRejector packetRejector, final List<LinkFilter> linkFilters, final Link outboundLink ); @Override InterledgerResponsePacket doFilter( final AccountSettings destinationAccountSettings, final InterledgerPreparePacket preparePacket ); }
@Test public void filterPacketWithNoFilters() { assertThat(this.linkFilters.size()).isEqualTo(0); filterChain.doFilter(OUTGOING_ACCOUNT_SETTINGS, PREPARE_PACKET).handle( fulfillPacket -> assertThat(fulfillPacket.getFulfillment()).isEqualTo(LoopbackLink.LOOPBACK_FULFILLMENT), rejectPacket -> fail("Should have fulfilled but rejected!") ); } @Test public void filterPacketWithMultipleFilters() { final LinkFilter linkFilter1 = (sourceAccountSettings, sourcePreparePacket, filterChain) -> { linkFilter1PreProcessed.set(true); final InterledgerResponsePacket response = filterChain.doFilter(sourceAccountSettings, sourcePreparePacket); linkFilter1PostProcessed.set(true); return response; }; this.linkFilters.add(linkFilter1); final LinkFilter linkFilter2 = (sourceAccountSettings, sourcePreparePacket, filterChain) -> { linkFilter2PreProcessed.set(true); final InterledgerResponsePacket response = filterChain.doFilter(sourceAccountSettings, sourcePreparePacket); linkFilter2PostProcessed.set(true); return response; }; this.linkFilters.add(linkFilter2); assertThat(this.linkFilters.size()).isEqualTo(2); filterChain.doFilter(OUTGOING_ACCOUNT_SETTINGS, PREPARE_PACKET).handle( fulfillPacket -> assertThat(fulfillPacket.getFulfillment()).isEqualTo(LoopbackLink.LOOPBACK_FULFILLMENT), rejectPacket -> fail("Should have fulfilled but rejected!") ); assertThat(linkFilter1PreProcessed).isTrue(); assertThat(linkFilter1PostProcessed).isTrue(); assertThat(linkFilter2PreProcessed).isTrue(); assertThat(linkFilter2PostProcessed).isTrue(); assertThat(linkFilter3PreProcessed).isFalse(); assertThat(linkFilter3PostProcessed).isFalse(); } @Test public void filterPacketWithExceptionInFirstFilter() { final LinkFilter linkFilter1 = (sourceAccountSettings, sourcePreparePacket, filterChain) -> { linkFilter1PreProcessed.set(true); throw new RuntimeException("Simulated LinkFilter exception"); }; this.linkFilters.add(linkFilter1); final LinkFilter linkFilter2 = (sourceAccountSettings, sourcePreparePacket, filterChain) -> { linkFilter2PreProcessed.set(true); InterledgerResponsePacket responsePacket = filterChain.doFilter(sourceAccountSettings, sourcePreparePacket); linkFilter2PostProcessed.set(true); return responsePacket; }; this.linkFilters.add(linkFilter2); final LinkFilter linkFilter3 = (sourceAccountSettings, sourcePreparePacket, filterChain) -> { linkFilter3PreProcessed.set(true); InterledgerResponsePacket responsePacket = filterChain.doFilter(sourceAccountSettings, sourcePreparePacket); linkFilter3PostProcessed.set(true); return responsePacket; }; this.linkFilters.add(linkFilter3); assertThat(this.linkFilters.size()).isEqualTo(3); filterChain.doFilter(OUTGOING_ACCOUNT_SETTINGS, PREPARE_PACKET).handle( fulfillPacket -> fail("Should have rejected but fulfilled!"), rejectPacket -> assertThat(rejectPacket.getCode()).isEqualTo(InterledgerErrorCode.T00_INTERNAL_ERROR) ); assertThat(linkFilter1PreProcessed).isTrue(); assertThat(linkFilter1PostProcessed).isFalse(); assertThat(linkFilter2PreProcessed).isFalse(); assertThat(linkFilter2PostProcessed).isFalse(); assertThat(linkFilter3PreProcessed).isFalse(); assertThat(linkFilter3PostProcessed).isFalse(); } @Test public void filterPacketWithExceptionInMiddleFilter() { final LinkFilter linkFilter1 = (sourceAccountSettings, sourcePreparePacket, filterChain) -> { linkFilter1PreProcessed.set(true); InterledgerResponsePacket responsePacket = filterChain.doFilter(sourceAccountSettings, sourcePreparePacket); linkFilter1PostProcessed.set(true); return responsePacket; }; this.linkFilters.add(linkFilter1); final LinkFilter linkFilter2 = (sourceAccountSettings, sourcePreparePacket, filterChain) -> { linkFilter2PreProcessed.set(true); throw new RuntimeException("Simulated LinkFilter exception"); }; this.linkFilters.add(linkFilter2); final LinkFilter linkFilter3 = (sourceAccountSettings, sourcePreparePacket, filterChain) -> { linkFilter3PreProcessed.set(true); InterledgerResponsePacket responsePacket = filterChain.doFilter(sourceAccountSettings, sourcePreparePacket); linkFilter3PostProcessed.set(true); return responsePacket; }; this.linkFilters.add(linkFilter3); assertThat(this.linkFilters.size()).isEqualTo(3); filterChain.doFilter(OUTGOING_ACCOUNT_SETTINGS, PREPARE_PACKET).handle( fulfillPacket -> fail("Should have rejected but fulfilled!"), rejectPacket -> assertThat(rejectPacket.getCode()).isEqualTo(InterledgerErrorCode.T00_INTERNAL_ERROR) ); assertThat(linkFilter1PreProcessed).isTrue(); assertThat(linkFilter1PostProcessed).isTrue(); assertThat(linkFilter2PreProcessed).isTrue(); assertThat(linkFilter2PostProcessed).isFalse(); assertThat(linkFilter3PreProcessed).isFalse(); assertThat(linkFilter3PostProcessed).isFalse(); } @Test public void filterPacketWithExceptionInLastFilter() { final LinkFilter linkFilter1 = (sourceAccountSettings, sourcePreparePacket, filterChain) -> { linkFilter1PreProcessed.set(true); InterledgerResponsePacket responsePacket = filterChain.doFilter(sourceAccountSettings, sourcePreparePacket); linkFilter1PostProcessed.set(true); return responsePacket; }; this.linkFilters.add(linkFilter1); final LinkFilter linkFilter2 = (sourceAccountSettings, sourcePreparePacket, filterChain) -> { linkFilter2PreProcessed.set(true); InterledgerResponsePacket responsePacket = filterChain.doFilter(sourceAccountSettings, sourcePreparePacket); linkFilter2PostProcessed.set(true); return responsePacket; }; this.linkFilters.add(linkFilter2); final LinkFilter linkFilter3 = (sourceAccountSettings, sourcePreparePacket, filterChain) -> { linkFilter3PreProcessed.set(true); throw new RuntimeException("Simulated LinkFilter exception"); }; this.linkFilters.add(linkFilter3); assertThat(this.linkFilters.size()).isEqualTo(3); filterChain.doFilter(OUTGOING_ACCOUNT_SETTINGS, PREPARE_PACKET).handle( fulfillPacket -> fail("Should have rejected but fulfilled!"), rejectPacket -> assertThat(rejectPacket.getCode()).isEqualTo(InterledgerErrorCode.T00_INTERNAL_ERROR) ); assertThat(linkFilter1PreProcessed).isTrue(); assertThat(linkFilter1PostProcessed).isTrue(); assertThat(linkFilter2PreProcessed).isTrue(); assertThat(linkFilter2PostProcessed).isTrue(); assertThat(linkFilter3PreProcessed).isTrue(); assertThat(linkFilter3PostProcessed).isFalse(); } @Test public void filterPacketWithExpiredPacket() { final LinkFilter linkFilter1 = (sourceAccountSettings, sourcePreparePacket, filterChain) -> { linkFilter1PreProcessed.set(true); InterledgerResponsePacket responsePacket = filterChain.doFilter(sourceAccountSettings, sourcePreparePacket); linkFilter1PostProcessed.set(true); return responsePacket; }; this.linkFilters.add(linkFilter1); final LinkFilter linkFilter2 = (sourceAccountSettings, sourcePreparePacket, filterChain) -> { linkFilter2PreProcessed.set(true); InterledgerResponsePacket responsePacket = filterChain.doFilter(sourceAccountSettings, sourcePreparePacket); linkFilter2PostProcessed.set(true); return responsePacket; }; this.linkFilters.add(linkFilter2); final LinkFilter linkFilter3 = (sourceAccountSettings, sourcePreparePacket, filterChain) -> { linkFilter3PreProcessed.set(true); InterledgerResponsePacket responsePacket = filterChain.doFilter(sourceAccountSettings, sourcePreparePacket); linkFilter3PostProcessed.set(true); return responsePacket; }; this.linkFilters.add(linkFilter3); assertThat(this.linkFilters.size()).isEqualTo(3); final InterledgerPreparePacket expiredPreparePacket = InterledgerPreparePacket.builder() .destination(InterledgerAddress.of("example.foo")) .amount(UnsignedLong.ONE) .expiresAt(Instant.MIN) .executionCondition(InterledgerCondition.of(new byte[32])) .build(); filterChain.doFilter(OUTGOING_ACCOUNT_SETTINGS, expiredPreparePacket).handle( fulfillPacket -> fail("Should have rejected but fulfilled!"), rejectPacket -> assertThat(rejectPacket.getCode()).isEqualTo(InterledgerErrorCode.R02_INSUFFICIENT_TIMEOUT) ); assertThat(linkFilter1PreProcessed).isTrue(); assertThat(linkFilter1PostProcessed).isTrue(); assertThat(linkFilter2PreProcessed).isTrue(); assertThat(linkFilter2PostProcessed).isTrue(); assertThat(linkFilter3PreProcessed).isTrue(); assertThat(linkFilter3PostProcessed).isTrue(); } @Test public void filterPacketWithExpiredFuture() throws InterruptedException { final LinkFilter linkFilter1 = (sourceAccountSettings, sourcePreparePacket, filterChain) -> { linkFilter1PreProcessed.set(true); InterledgerResponsePacket responsePacket = filterChain.doFilter(sourceAccountSettings, sourcePreparePacket); linkFilter1PostProcessed.set(true); return responsePacket; }; this.linkFilters.add(linkFilter1); final LinkFilter linkFilter2 = (sourceAccountSettings, sourcePreparePacket, filterChain) -> { linkFilter2PreProcessed.set(true); InterledgerResponsePacket responsePacket = filterChain.doFilter(sourceAccountSettings, sourcePreparePacket); linkFilter2PostProcessed.set(true); return responsePacket; }; this.linkFilters.add(linkFilter2); final LinkFilter linkFilter3 = (sourceAccountSettings, sourcePreparePacket, filterChain) -> { linkFilter3PreProcessed.set(true); InterledgerResponsePacket responsePacket = filterChain.doFilter(sourceAccountSettings, sourcePreparePacket); linkFilter3PostProcessed.set(true); return responsePacket; }; this.linkFilters.add(linkFilter3); assertThat(this.linkFilters.size()).isEqualTo(3); final InterledgerPreparePacket expiredPreparePacket = InterledgerPreparePacket.builder() .destination(InterledgerAddress.of("example.foo")) .amount(UnsignedLong.ONE) .expiresAt(Instant.now().plusMillis(250)) .executionCondition(InterledgerCondition.of(new byte[32])) .build(); filterChain.doFilter(OUTGOING_ACCOUNT_SETTINGS, expiredPreparePacket).handle( fulfillPacket -> fail("Should have rejected but fulfilled!"), rejectPacket -> assertThat(rejectPacket.getCode()).isEqualTo(InterledgerErrorCode.R00_TRANSFER_TIMED_OUT) ); assertThat(linkFilter1PreProcessed).isTrue(); assertThat(linkFilter1PostProcessed).isTrue(); assertThat(linkFilter2PreProcessed).isTrue(); assertThat(linkFilter2PostProcessed).isTrue(); assertThat(linkFilter3PreProcessed).isTrue(); assertThat(linkFilter3PostProcessed).isTrue(); }
OutgoingMetricsLinkFilter extends AbstractLinkFilter implements LinkFilter { @Override public InterledgerResponsePacket doFilter( final AccountSettings destinationAccountSettings, final InterledgerPreparePacket outgoingPreparePacket, final LinkFilterChain filterChain ) { Objects.requireNonNull(destinationAccountSettings); Objects.requireNonNull(outgoingPreparePacket); Objects.requireNonNull(filterChain); try { this.metricsService.trackOutgoingPacketPrepared(destinationAccountSettings, outgoingPreparePacket); return filterChain.doFilter(destinationAccountSettings, outgoingPreparePacket) .map( (interledgerFulfillPacket) -> { metricsService.trackOutgoingPacketFulfilled(destinationAccountSettings, interledgerFulfillPacket); return interledgerFulfillPacket; }, (interledgerRejectPacket) -> { metricsService.trackOutgoingPacketRejected(destinationAccountSettings, interledgerRejectPacket); return interledgerRejectPacket; } ); } catch (InterledgerProtocolException e) { this.metricsService.trackOutgoingPacketRejected(destinationAccountSettings, e.getInterledgerRejectPacket()); throw e; } catch (Exception e) { metricsService.trackOutgoingPacketFailed(destinationAccountSettings); throw e; } } OutgoingMetricsLinkFilter( final Supplier<InterledgerAddress> operatorAddressSupplier, final MetricsService metricsService ); @Override InterledgerResponsePacket doFilter( final AccountSettings destinationAccountSettings, final InterledgerPreparePacket outgoingPreparePacket, final LinkFilterChain filterChain ); }
@Test public void doFilterWithFulfill() { when(filterChainMock.doFilter(accountSettings(), preparePacket())).thenReturn(fulfillPacket()); final InterledgerResponsePacket actual = filter.doFilter(accountSettings(), preparePacket(), filterChainMock); assertThat(actual).isEqualTo(fulfillPacket()); verifyNoMoreInteractions(packetRejectorMock); verify(metricsServiceMock).trackOutgoingPacketPrepared(accountSettings(), preparePacket()); verify(metricsServiceMock).trackOutgoingPacketFulfilled(accountSettings(), fulfillPacket()); verifyNoMoreInteractions(metricsServiceMock); } @Test public void doFilterWithReject() { when(filterChainMock.doFilter(accountSettings(), preparePacket())).thenReturn(rejectPacket()); final InterledgerResponsePacket actual = filter.doFilter(accountSettings(), preparePacket(), filterChainMock); assertThat(actual).isEqualTo(rejectPacket()); verifyNoMoreInteractions(packetRejectorMock); verify(metricsServiceMock).trackOutgoingPacketPrepared(accountSettings(), preparePacket()); verify(metricsServiceMock).trackOutgoingPacketRejected(accountSettings(), rejectPacket()); verifyNoMoreInteractions(metricsServiceMock); } @Test public void doFilterWithInterledgerProtocolException() { final AccountSettings accountSettings = accountSettings(); final InterledgerPreparePacket preparePacket = preparePacket(); expectedException.expect(InterledgerProtocolException.class); expectedException.expectMessage("Interledger Rejection: "); doThrow(new InterledgerProtocolException(rejectPacket())) .when(filterChainMock) .doFilter(eq(accountSettings), eq(preparePacket)); try { filter.doFilter(accountSettings, preparePacket, filterChainMock); fail("cannot run doFilter"); } catch (Exception e) { verifyNoMoreInteractions(packetRejectorMock); verify(metricsServiceMock).trackOutgoingPacketPrepared(accountSettings, preparePacket); verify(metricsServiceMock).trackOutgoingPacketRejected(accountSettings, rejectPacket()); verifyNoMoreInteractions(metricsServiceMock); throw e; } } @Test public void doFilterWithException() { final AccountSettings accountSettings = accountSettings(); final InterledgerPreparePacket preparePacket = preparePacket(); expectedException.expect(RuntimeException.class); expectedException.expectMessage("foo"); doThrow(new RuntimeException("foo")).when(filterChainMock).doFilter(eq(accountSettings), eq(preparePacket)); try { filter.doFilter(accountSettings, preparePacket, filterChainMock); fail("cannot run doFilter"); } catch (Exception e) { verifyNoMoreInteractions(packetRejectorMock); verify(metricsServiceMock).trackOutgoingPacketPrepared(accountSettings, preparePacket); verify(metricsServiceMock).trackOutgoingPacketFailed(accountSettings); verifyNoMoreInteractions(metricsServiceMock); throw e; } }
SettlementEngineIdempotencyKeyGenerator implements KeyGenerator { @Override public Object generate(Object target, Method method, Object... params) { if (target != null && SettlementController.class.isAssignableFrom(target.getClass())) { Preconditions.checkArgument(params.length > 0, "params is expected to have at least 1 value"); Object idempotencyKey = params[0] != null ? params[0] : null; return idempotencyKey; } else { return null; } } @Override Object generate(Object target, Method method, Object... params); }
@Test(expected = IllegalArgumentException.class) public void generateWithTooFewParams() { try { generator.generate(settlementControllerMock, null, new Object[0]); } catch (IllegalArgumentException e) { assertThat(e.getMessage()).isEqualTo("params is expected to have at least 1 value"); throw e; } } @Test public void generateWithNonSettlementControllerTarget() { assertThat(generator.generate(objectMock, null, new Object[0])).isNull(); } @Test public void generateWithOneParam() { final String idempotencyId = UUID.randomUUID().toString(); assertThat(generator.generate(settlementControllerMock, null, new Object[] {idempotencyId})).isEqualTo(idempotencyId); } @Test public void generateWithMultipleParams() { final String idempotencyId = UUID.randomUUID().toString(); assertThat(generator.generate(settlementControllerMock, null, new Object[] {idempotencyId, "foo", "bar"})).isEqualTo(idempotencyId); }
OutgoingBalanceLinkFilter extends AbstractLinkFilter implements LinkFilter { @Override public InterledgerResponsePacket doFilter( final AccountSettings destinationAccountSettings, final InterledgerPreparePacket outgoingPreparePacket, final LinkFilterChain filterChain ) { Objects.requireNonNull(destinationAccountSettings, "destinationAccountSettings must not be null"); Objects.requireNonNull(outgoingPreparePacket, "outgoingPreparePacket must not be null"); Objects.requireNonNull(filterChain, "filterChain must not be null"); final InterledgerResponsePacket responsePacket = filterChain.doFilter(destinationAccountSettings, outgoingPreparePacket); responsePacket.handle( (interledgerFulfillPacket) -> { if (UnsignedLong.ZERO.equals(outgoingPreparePacket.getAmount())) { return; } final BalanceTracker.UpdateBalanceForFulfillResponse balanceForFulfillResponse; try { balanceForFulfillResponse = balanceTracker.updateBalanceForFulfill( destinationAccountSettings, outgoingPreparePacket.getAmount().longValue() ); } catch (Exception e) { logger.error(String.format( "RECONCILIATION REQUIRED: Unable to update balance in Redis after receiving a valid Fulfillment. " + "outgoingPreparePacket=%s fulfillmentPacket=%s. error==%s", outgoingPreparePacket, interledgerFulfillPacket, e.getMessage() ), e ); return; } this.maybeSettle( destinationAccountSettings, outgoingPreparePacket, interledgerFulfillPacket, balanceForFulfillResponse ); }, (interledgerRejectPacket) -> logger.warn( "Outgoing packet not applied due to ILP Reject. outgoingDestinationAccount={} amount={} newBalance={} " + "outgoingPreparePacket={} rejectPacket={}", destinationAccountSettings, outgoingPreparePacket.getAmount(), balanceTracker.balance(destinationAccountSettings.accountId()), outgoingPreparePacket, interledgerRejectPacket ) ); return responsePacket; } OutgoingBalanceLinkFilter( final Supplier<InterledgerAddress> operatorAddressSupplier, final BalanceTracker balanceTracker, final SettlementService settlementService, final EventBus eventBus ); @Override InterledgerResponsePacket doFilter( final AccountSettings destinationAccountSettings, final InterledgerPreparePacket outgoingPreparePacket, final LinkFilterChain filterChain ); }
@Test public void doFilterWithNullAccountSettings() { expectedException.expect(NullPointerException.class); expectedException.expectMessage("destinationAccountSettings must not be null"); linkFilter.doFilter(null, preparePacket(), filterChainMock); } @Test public void doFilterWithNullPreparePacket() { expectedException.expect(NullPointerException.class); expectedException.expectMessage("outgoingPreparePacket must not be null"); linkFilter.doFilter(accountSettings(), null, filterChainMock); } @Test public void doFilterWithNulFilterChain() { expectedException.expect(NullPointerException.class); expectedException.expectMessage("filterChain must not be null"); linkFilter.doFilter(accountSettings(), preparePacket(), null); } @Test public void doFilterForFulfillZeroValuePacket() { when(filterChainMock.doFilter(accountSettings(), preparePacket())).thenReturn(fulfillPacket()); InterledgerResponsePacket actual = linkFilter.doFilter( accountSettings(), preparePacket(), filterChainMock ); assertThat(actual).isEqualTo(fulfillPacket()); verifyNoMoreInteractions(balanceTrackerMock); verifyNoMoreInteractions(settlementServiceMock); verifyNoMoreInteractions(eventBusMock); } @Test public void doFilterForFulfillWithNonZerorPacketValueAndNoSettlementEngine() { when(filterChainMock.doFilter(accountSettings(), preparePacket(UnsignedLong.ONE))).thenReturn(fulfillPacket()); when(balanceTrackerMock.updateBalanceForFulfill(accountSettings(), 1L)).thenReturn( UpdateBalanceForFulfillResponse.builder() .accountBalance(AccountBalance.builder() .accountId(ACCOUNT_ID) .clearingBalance(10L) .prepaidAmount(10L) .build()) .clearingAmountToSettle(10L) .build() ); final InterledgerResponsePacket actual = linkFilter.doFilter( accountSettings(), preparePacket(UnsignedLong.ONE), filterChainMock ); assertThat(actual).isEqualTo(fulfillPacket()); verify(balanceTrackerMock).updateBalanceForFulfill(eq(accountSettings()), eq(1L)); verifyNoMoreInteractions(balanceTrackerMock); verifyNoMoreInteractions(settlementServiceMock); verifyNoMoreInteractions(eventBusMock); } @Test public void testMaybeSettleWithNoThreshold() { final AccountSettings accountSettings = accountSettingsBuilder() .settlementEngineDetails( SettlementEngineDetails.builder() .settlementEngineAccountId(SETTLEMENT_ENGINE_ACCOUNT_ID) .baseUrl(HttpUrl.parse("http: .build() ) .build(); when(filterChainMock.doFilter(accountSettings, preparePacket(UnsignedLong.ONE))).thenReturn(fulfillPacket()); when(balanceTrackerMock.updateBalanceForFulfill(accountSettings, 1L)).thenReturn( UpdateBalanceForFulfillResponse.builder() .accountBalance(AccountBalance.builder() .accountId(ACCOUNT_ID) .clearingBalance(10L) .prepaidAmount(10L) .build()) .clearingAmountToSettle(10L) .build() ); final InterledgerResponsePacket actual = linkFilter.doFilter( accountSettings, preparePacket(UnsignedLong.ONE), filterChainMock ); assertThat(actual).isEqualTo(fulfillPacket()); verify(balanceTrackerMock).updateBalanceForFulfill(eq(accountSettings()), eq(1L)); verifyNoMoreInteractions(balanceTrackerMock); verifyNoMoreInteractions(settlementServiceMock); verifyNoMoreInteractions(eventBusMock); } @Test public void testMaybeSettleWhenClearingAmountToSettleIsBelowThreshold() { final AccountSettings accountSettings = accountSettingsWithSettlementEngine(100L).build(); when(filterChainMock.doFilter(accountSettings, preparePacket(UnsignedLong.ONE))).thenReturn(fulfillPacket()); when(balanceTrackerMock.updateBalanceForFulfill(accountSettings, 1L)).thenReturn( UpdateBalanceForFulfillResponse.builder() .accountBalance(AccountBalance.builder() .accountId(ACCOUNT_ID) .clearingBalance(10L) .prepaidAmount(10L) .build()) .clearingAmountToSettle(10L) .build() ); final InterledgerResponsePacket actual = linkFilter.doFilter( accountSettings, preparePacket(UnsignedLong.ONE), filterChainMock ); assertThat(actual).isEqualTo(fulfillPacket()); verify(balanceTrackerMock).updateBalanceForFulfill(eq(accountSettings()), eq(1L)); verifyNoMoreInteractions(balanceTrackerMock); verifyNoMoreInteractions(settlementServiceMock); verifyNoMoreInteractions(eventBusMock); } @Test public void testMaybeSettleWhenClearingAmountToSettleIsAtThreshold() { final AccountSettings accountSettings = accountSettingsWithSettlementEngine(100L).build(); when(filterChainMock.doFilter(accountSettings, preparePacket(UnsignedLong.ONE))).thenReturn(fulfillPacket()); when(balanceTrackerMock.updateBalanceForFulfill(accountSettings, 1L)).thenReturn( UpdateBalanceForFulfillResponse.builder() .accountBalance(AccountBalance.builder() .accountId(ACCOUNT_ID) .clearingBalance(1L) .prepaidAmount(0L) .build()) .clearingAmountToSettle(100L) .build() ); final SettlementQuantity expectedSettlementQuantityInClearingUnits = SettlementQuantity.builder() .scale(9) .amount(BigInteger.valueOf(100L)) .build(); when(settlementServiceMock.initiateLocalSettlement( anyString(), eq(accountSettings), eq(expectedSettlementQuantityInClearingUnits) )).thenReturn(SettlementQuantity.builder() .amount(BigInteger.valueOf(100L)) .scale(2) .build()); final InterledgerResponsePacket actual = linkFilter.doFilter( accountSettings, preparePacket(UnsignedLong.ONE), filterChainMock ); assertThat(actual).isEqualTo(fulfillPacket()); verify(balanceTrackerMock).updateBalanceForFulfill(eq(accountSettings()), eq(1L)); verify(settlementServiceMock).initiateLocalSettlement( anyString(), eq(accountSettings), eq(expectedSettlementQuantityInClearingUnits) ); verifyNoMoreInteractions(balanceTrackerMock); verifyNoMoreInteractions(settlementServiceMock); verify(eventBusMock).post(Mockito.any()); verifyNoMoreInteractions(eventBusMock); } @Test public void testMaybeSettleWhenClearingAmountToSettleIsAboveThreshold() { final AccountSettings accountSettings = accountSettingsWithSettlementEngine(100L).build(); when(filterChainMock.doFilter(accountSettings, preparePacket(UnsignedLong.ONE))).thenReturn(fulfillPacket()); when(balanceTrackerMock.updateBalanceForFulfill(accountSettings, 1L)).thenReturn( UpdateBalanceForFulfillResponse.builder() .accountBalance(AccountBalance.builder() .accountId(ACCOUNT_ID) .clearingBalance(0L) .prepaidAmount(0L) .build()) .clearingAmountToSettle(200L) .build() ); final SettlementQuantity expectedSettlementQuantityInClearingUnits = SettlementQuantity.builder() .scale(9) .amount(BigInteger.valueOf(200L)) .build(); when(settlementServiceMock.initiateLocalSettlement( anyString(), eq(accountSettings), eq(expectedSettlementQuantityInClearingUnits) )).thenReturn(SettlementQuantity.builder() .amount(BigInteger.valueOf(200L)) .scale(2) .build()); final InterledgerResponsePacket actual = linkFilter.doFilter( accountSettings, preparePacket(UnsignedLong.ONE), filterChainMock ); assertThat(actual).isEqualTo(fulfillPacket()); verify(balanceTrackerMock).updateBalanceForFulfill(eq(accountSettings()), eq(1L)); verify(settlementServiceMock).initiateLocalSettlement( anyString(), eq(accountSettings), eq(expectedSettlementQuantityInClearingUnits) ); verifyNoMoreInteractions(balanceTrackerMock); verifyNoMoreInteractions(settlementServiceMock); verify(eventBusMock).post(Mockito.any()); verifyNoMoreInteractions(eventBusMock); } @Test public void testMaybeSettleWhenClearingAmountToSettleIsAboveThresholdButSettleServiceThrows() { final AccountSettings accountSettings = accountSettingsWithSettlementEngine(100L).build(); when(filterChainMock.doFilter(accountSettings, preparePacket(UnsignedLong.ONE))).thenReturn(fulfillPacket()); when(balanceTrackerMock.updateBalanceForFulfill(accountSettings, 1L)).thenReturn( UpdateBalanceForFulfillResponse.builder() .accountBalance(AccountBalance.builder() .accountId(ACCOUNT_ID) .clearingBalance(0L) .prepaidAmount(0L) .build()) .clearingAmountToSettle(200L) .build() ); final SettlementQuantity expectedSettlementQuantityInClearingUnits = SettlementQuantity.builder() .scale(9) .amount(BigInteger.valueOf(200L)) .build(); doThrow(new SettlementServiceException("foo", ACCOUNT_ID, SETTLEMENT_ENGINE_ACCOUNT_ID)) .when(settlementServiceMock).initiateLocalSettlement(anyString(), Mockito.any(), Mockito.any()); final InterledgerResponsePacket actual = linkFilter.doFilter( accountSettings, preparePacket(UnsignedLong.ONE), filterChainMock ); assertThat(actual).isEqualTo(fulfillPacket()); verify(balanceTrackerMock).updateBalanceForFulfill(eq(accountSettings()), eq(1L)); verify(settlementServiceMock).initiateLocalSettlement( anyString(), eq(accountSettings), eq(expectedSettlementQuantityInClearingUnits) ); verifyNoMoreInteractions(balanceTrackerMock); verifyNoMoreInteractions(settlementServiceMock); verify(eventBusMock).post(Mockito.any()); verifyNoMoreInteractions(eventBusMock); } @Test public void doFilterForReject() { when(filterChainMock.doFilter(accountSettings(), preparePacket())).thenReturn(rejectPacket()); InterledgerResponsePacket actual = linkFilter.doFilter( accountSettings(), preparePacket(), filterChainMock ); assertThat(actual).isEqualTo(rejectPacket()); verify(balanceTrackerMock).balance(ACCOUNT_ID); verifyNoMoreInteractions(balanceTrackerMock); verifyNoMoreInteractions(settlementServiceMock); } @Test public void doFilterForFailureInBalanceTracker() { when(filterChainMock.doFilter(accountSettings(), preparePacket(UnsignedLong.ONE))).thenReturn(fulfillPacket()); doThrow(new BalanceTrackerException()).when(balanceTrackerMock).updateBalanceForFulfill( accountSettings(), 1L ); final InterledgerResponsePacket actual = linkFilter.doFilter( accountSettings(), preparePacket(UnsignedLong.ONE), filterChainMock ); assertThat(actual).isEqualTo(fulfillPacket()); verify(balanceTrackerMock).updateBalanceForFulfill(eq(accountSettings()), eq(1L)); verifyNoMoreInteractions(balanceTrackerMock); verifyNoMoreInteractions(settlementServiceMock); verifyNoMoreInteractions(eventBusMock); }
ByteArrayUtils { public static byte[] generate32RandomBytes() { final byte[] rndBytes = new byte[32]; secureRandom.nextBytes(rndBytes); return rndBytes; } static boolean isEqualUsingConstantTime(byte[] val1, byte[] val2); static byte[] generate32RandomBytes(); }
@Test public void generateRandom32Bytes() { assertThat(ByteArrayUtils.generate32RandomBytes()) .hasSize(32) .isNotEqualTo(ByteArrayUtils.generate32RandomBytes()); }
OutgoingMaxPacketAmountLinkFilter extends AbstractLinkFilter implements LinkFilter { @Override public InterledgerResponsePacket doFilter( final AccountSettings destinationAccountSettings, final InterledgerPreparePacket destPreparePacket, final LinkFilterChain filterChain ) { Objects.requireNonNull(destinationAccountSettings); Objects.requireNonNull(destPreparePacket); Objects.requireNonNull(filterChain); return destinationAccountSettings.maximumPacketAmount() .filter(maxPacketAmount -> destPreparePacket.getAmount().compareTo(maxPacketAmount) > 0) .map(maxPacketAmount -> { logger.error( "Rejecting packet for exceeding max amount. accountId={} maxAmount={} actualAmount={}", destinationAccountSettings.accountId(), maxPacketAmount, destPreparePacket.getAmount() ); return (InterledgerResponsePacket) reject( destinationAccountSettings.accountId(), destPreparePacket, InterledgerErrorCode.F08_AMOUNT_TOO_LARGE, String.format( "Packet size too large: maxAmount=%s actualAmount=%s", maxPacketAmount, destPreparePacket.getAmount()) ); }) .orElseGet(() -> filterChain.doFilter(destinationAccountSettings, destPreparePacket)); } OutgoingMaxPacketAmountLinkFilter(Supplier<InterledgerAddress> operatorAddressSupplier); @Override InterledgerResponsePacket doFilter( final AccountSettings destinationAccountSettings, final InterledgerPreparePacket destPreparePacket, final LinkFilterChain filterChain ); }
@Test public void filterHatesNullSettings() { OutgoingMaxPacketAmountLinkFilter filter = createFilter(); expectedException.expect(NullPointerException.class); filter.doFilter(null, createPrepareWithAmount(10), filterChain); } @Test public void filterHatesNullPrepare() { OutgoingMaxPacketAmountLinkFilter filter = createFilter(); expectedException.expect(NullPointerException.class); filter.doFilter(createAccountSettingsWithMaxAmount(UnsignedLong.valueOf(100)), null, filterChain); } @Test public void filterHatesNullChain() { OutgoingMaxPacketAmountLinkFilter filter = createFilter(); expectedException.expect(NullPointerException.class); filter.doFilter(createAccountSettingsWithMaxAmount(UnsignedLong.valueOf(100)), createPrepareWithAmount(10), null); } @Test public void passAlongWhenBelowMax() { OutgoingMaxPacketAmountLinkFilter filter = createFilter(); AccountSettings settings = createAccountSettingsWithMaxAmount(UnsignedLong.valueOf(1000)); InterledgerPreparePacket prepare = createPrepareWithAmount(999); filter.doFilter(settings, prepare, filterChain); verify(filterChain, times(1)).doFilter(settings, prepare); } @Test public void rejectWhenBeyondMax() { OutgoingMaxPacketAmountLinkFilter filter = createFilter(); AccountSettings settings = createAccountSettingsWithMaxAmount(UnsignedLong.valueOf(1000)); InterledgerPreparePacket prepare = createPrepareWithAmount(1001); InterledgerResponsePacket response = filter.doFilter(settings, prepare, filterChain); assertThat(response).isInstanceOf(InterledgerRejectPacket.class) .extracting("code", "message") .containsExactly(InterledgerErrorCode.F08_AMOUNT_TOO_LARGE, "Packet size too large: maxAmount=1000 actualAmount=1001"); verify(filterChain, times(0)).doFilter(settings, prepare); }
DefaultLinkSettingsFactory implements LinkSettingsFactory { @Override public LinkSettings construct(final AccountSettings accountSettings) { Objects.requireNonNull(accountSettings); switch (accountSettings.linkType().value().toUpperCase()) { case IlpOverHttpLink.LINK_TYPE_STRING: { return IlpOverHttpLinkSettings.fromCustomSettings(accountSettings.customSettings()).build(); } case LoopbackLink.LINK_TYPE_STRING: { return LinkSettings.builder().customSettings(accountSettings.customSettings()) .linkType(LoopbackLink.LINK_TYPE).build(); } case PingLoopbackLink.LINK_TYPE_STRING: { return LinkSettings.builder().customSettings(accountSettings.customSettings()) .linkType(PingLoopbackLink.LINK_TYPE).build(); } case StatelessSpspReceiverLink.LINK_TYPE_STRING: { return StatelessSpspReceiverLinkSettings.builder() .assetScale(accountSettings.assetScale()) .assetCode(accountSettings.assetCode()) .build(); } default: { throw new IllegalArgumentException("Unsupported LinkType: " + accountSettings.linkType()); } } } @Override LinkSettings construct(final AccountSettings accountSettings); }
@Test public void constructUnsupportedLink() { expectedException.expect(IllegalArgumentException.class); expectedException.expectMessage("Unsupported LinkType: LinkType(FOO)"); factory.construct( AccountSettings.builder() .accountId(AccountId.of("foo")) .linkType(LinkType.of("foo")) .accountRelationship(AccountRelationship.PEER) .assetCode("XRP") .assetScale(2) .build() ); } @Test public void constructIlpOverHttpLink() { final Map<String, Object> customSettings = Maps.newHashMap(); customSettings.put(IncomingLinkSettings.HTTP_INCOMING_AUTH_TYPE, "JWT_HS_256"); customSettings.put(IncomingLinkSettings.HTTP_INCOMING_TOKEN_ISSUER, "https: customSettings.put(IncomingLinkSettings.HTTP_INCOMING_TOKEN_AUDIENCE, "https: customSettings.put(IncomingLinkSettings.HTTP_INCOMING_TOKEN_SUBJECT, "connie"); customSettings.put(IncomingLinkSettings.HTTP_INCOMING_SHARED_SECRET, ENCRYPTED_SHH); customSettings.put(OutgoingLinkSettings.HTTP_OUTGOING_AUTH_TYPE, "JWT_HS_256"); customSettings.put(OutgoingLinkSettings.HTTP_OUTGOING_TOKEN_ISSUER, "https: customSettings.put(OutgoingLinkSettings.HTTP_OUTGOING_TOKEN_AUDIENCE, "https: customSettings.put(OutgoingLinkSettings.HTTP_OUTGOING_TOKEN_SUBJECT, "connie"); customSettings.put(OutgoingLinkSettings.HTTP_OUTGOING_SHARED_SECRET, ENCRYPTED_SHH); customSettings.put(OutgoingLinkSettings.HTTP_OUTGOING_URL, "https: AccountSettings accountSettings = AccountSettings.builder() .accountId(AccountId.of("foo")) .linkType(IlpOverHttpLink.LINK_TYPE) .accountRelationship(AccountRelationship.PEER) .assetCode("XRP") .assetScale(2) .customSettings(customSettings) .build(); final LinkSettings actual = factory.construct(accountSettings); assertThat(actual.getLinkType()).isEqualTo(IlpOverHttpLink.LINK_TYPE); assertThat(actual.getCustomSettings()).isEqualTo(customSettings); } @Test public void constructLoopLink() { AccountSettings accountSettings = AccountSettings.builder() .accountId(AccountId.of("foo")) .linkType(LoopbackLink.LINK_TYPE) .accountRelationship(AccountRelationship.PEER) .assetCode("XRP") .assetScale(2) .build(); final LinkSettings actual = factory.construct(accountSettings); assertThat(actual.getLinkType()).isEqualTo(LoopbackLink.LINK_TYPE); assertThat(actual.getCustomSettings().isEmpty()).isTrue(); } @Test public void testConstructUnidirectionalPingLink() { AccountSettings accountSettings = AccountSettings.builder() .accountId(AccountId.of("foo")) .linkType(PingLoopbackLink.LINK_TYPE) .accountRelationship(AccountRelationship.PEER) .assetCode("XRP") .assetScale(2) .build(); final LinkSettings actual = factory.construct(accountSettings); assertThat(actual.getLinkType()).isEqualTo(PingLoopbackLink.LINK_TYPE); assertThat(actual.getCustomSettings().isEmpty()).isTrue(); } @Test public void testConstructStatelessSpspReceiverLink() { AccountSettings accountSettings = AccountSettings.builder() .accountId(AccountId.of("foo")) .linkType(StatelessSpspReceiverLink.LINK_TYPE) .accountRelationship(AccountRelationship.PEER) .assetCode("XRP") .assetScale(2) .build(); final LinkSettings actual = factory.construct(accountSettings); assertThat(actual.getLinkType()).isEqualTo(StatelessSpspReceiverLink.LINK_TYPE); assertThat(actual.getCustomSettings().isEmpty()).isTrue(); final StatelessSpspReceiverLinkSettings statelessSpspReceiverLinkSettings = (StatelessSpspReceiverLinkSettings) actual; assertThat(statelessSpspReceiverLinkSettings.assetCode()).isEqualTo("XRP"); assertThat(statelessSpspReceiverLinkSettings.assetScale()).isEqualTo(2); }
DefaultLinkSettingsValidator implements LinkSettingsValidator { @Override public <T extends LinkSettings> T validateSettings(T linkSettings) { if (linkSettings instanceof IlpOverHttpLinkSettings) { return (T) validateIlpLinkSettings((IlpOverHttpLinkSettings) linkSettings); } return linkSettings; } DefaultLinkSettingsValidator(ConnectorEncryptionService encryptionService, Supplier<ConnectorSettings> connectorSettingsSupplier); @Override T validateSettings(T linkSettings); }
@Test public void validateGenericLinkSettings() { ImmutableLinkSettings settings = LinkSettings.builder() .linkType(PingLoopbackLink.LINK_TYPE) .putCustomSettings("foo", "bar").build(); assertThat(validator.validateSettings(settings)).isEqualTo(settings); } @Test public void validateIlpOverHttpLinkSettingsFromBase64() { final IlpOverHttpLinkSettings linkSettings = newSettings(INCOMING_BASE_64, OUTGOING_BASE_64); IlpOverHttpLinkSettings expected = newSettings(ENCRYPTED_INCOMING_SECRET.encodedValue(), ENCRYPTED_OUTGOING_SECRET.encodedValue()); assertThat(validator.validateSettings(linkSettings).incomingLinkSettings()) .isEqualTo(expected.incomingLinkSettings()); assertThat(validator.validateSettings(linkSettings).outgoingLinkSettings()) .isEqualTo(expected.outgoingLinkSettings()); } @Test public void ilpOverHttpLinkSettingsFromEncryptedSecret() { final IlpOverHttpLinkSettings linkSettings = newSettings(ENCRYPTED_INCOMING_SECRET, ENCRYPTED_OUTGOING_SECRET); IlpOverHttpLinkSettings expected = newSettings(ENCRYPTED_INCOMING_SECRET.encodedValue(), ENCRYPTED_OUTGOING_SECRET.encodedValue()); assertThat(validator.validateSettings(linkSettings).incomingLinkSettings()) .isEqualTo(expected.incomingLinkSettings()); assertThat(validator.validateSettings(linkSettings).outgoingLinkSettings()) .isEqualTo(expected.outgoingLinkSettings()); } @Test public void require32ByteSecretFailsIfConfigured() { when(connectorSettings.enabledFeatures().isRequire32ByteSharedSecrets()).thenReturn(true); final IlpOverHttpLinkSettings linkSettings = newSettings(INCOMING_BASE_64, OUTGOING_BASE_64); expectedException.expect(IllegalArgumentException.class); expectedException.expectMessage("shared secret must be 32 bytes"); validator.validateSettings(linkSettings); } @Test public void validationFailsDecryption() { reset(decryptor); when(decryptor.withDecrypted(any(), any())).thenThrow(new IllegalArgumentException("couldn't decrypt")); final IlpOverHttpLinkSettings linkSettings = newSettings(ENCRYPTED_INCOMING_SECRET, ENCRYPTED_OUTGOING_SECRET); expectedException.expect(IllegalArgumentException.class); expectedException.expectMessage("couldn't decrypt"); validator.validateSettings(linkSettings); } @Test public void validationFailsEncryption() { when(mockConnectorEncryptionService.encryptWithAccountSettingsKey(any())) .thenThrow(new IllegalArgumentException("couldn't encrypt")); final IlpOverHttpLinkSettings linkSettings = newSettings(INCOMING_BASE_64, OUTGOING_BASE_64); expectedException.expect(IllegalArgumentException.class); expectedException.expectMessage("couldn't encrypt"); validator.validateSettings(linkSettings); } @Test public void sharedSecretFailsWhenNotAscii() { String zalgoIsTonyThePonyHeComes = "ZA̡͊͠͝LGΌ ISͮ̂҉̯͈͕̹̘̱ TO͇̹̺ͅƝ̴ȳ̳ TH̘Ë͖́̉ ͠P̯͍̭O̚N̐Y̡ H̸̡̪̯ͨ͊̽̅̾̎Ȩ̬̩̾͛ͪ̈́̀́͘ ̶̧̨̱̹̭̯ͧ̾ͬC̷̙̲̝͖ͭ̏ͥͮ͟Oͮ͏̮̪̝͍M̲̖͊̒ͪͩͬ̚̚͜Ȇ̴̟̟͙̞ͩ͌͝S̨̥̫͎̭ͯ̿̔̀ͅ"; final IlpOverHttpLinkSettings linkSettings = newSettings(zalgoIsTonyThePonyHeComes, zalgoIsTonyThePonyHeComes); expectedException.expect(IllegalArgumentException.class); expectedException.expectMessage("Shared secret must be ascii"); validator.validateSettings(linkSettings); } @Test public void encryptedSecretIsUpdatedIfNotUsingCurrentKey() { EncryptedSecret incomingSecretWithNewerVersion = EncryptedSecret.fromEncodedValue("enc:JKS:crypto.p12:secret0:2:aes_gcm:updated-incoming-secret"); EncryptedSecret outgoingSecretWithNewerVersion = EncryptedSecret.fromEncodedValue("enc:JKS:crypto.p12:secret0:2:aes_gcm:updated-outgoing-secret"); when(mockConnectorEncryptionService.encryptWithAccountSettingsKey(INCOMING_BASE_64.getBytes())) .thenReturn(incomingSecretWithNewerVersion); when(mockConnectorEncryptionService.encryptWithAccountSettingsKey(OUTGOING_BASE_64.getBytes())) .thenReturn(outgoingSecretWithNewerVersion); final IlpOverHttpLinkSettings linkSettings = newSettings(ENCRYPTED_INCOMING_SECRET, ENCRYPTED_OUTGOING_SECRET); IlpOverHttpLinkSettings expected = newSettings(incomingSecretWithNewerVersion.encodedValue(), outgoingSecretWithNewerVersion.encodedValue()); assertThat(validator.validateSettings(linkSettings).incomingLinkSettings()) .isEqualTo(expected.incomingLinkSettings()); assertThat(validator.validateSettings(linkSettings).outgoingLinkSettings()) .isEqualTo(expected.outgoingLinkSettings()); } @Test public void encryptedSecretIsNotUpdatedIfUsingCurrentKey() { EncryptedSecret incomingSecretWithSameVersion = EncryptedSecret.fromEncodedValue("enc:JKS:crypto.p12:secret0:1:aes_gcm:updated-incoming-secret"); EncryptedSecret outgoingSecretWithSameVersion = EncryptedSecret.fromEncodedValue("enc:JKS:crypto.p12:secret0:1:aes_gcm:updated-outgoing-secret"); when(mockConnectorEncryptionService.encryptWithAccountSettingsKey(INCOMING_BASE_64.getBytes())) .thenReturn(incomingSecretWithSameVersion); when(mockConnectorEncryptionService.encryptWithAccountSettingsKey(OUTGOING_BASE_64.getBytes())) .thenReturn(outgoingSecretWithSameVersion); final IlpOverHttpLinkSettings linkSettings = newSettings(ENCRYPTED_INCOMING_SECRET, ENCRYPTED_OUTGOING_SECRET); IlpOverHttpLinkSettings expected = newSettings(ENCRYPTED_INCOMING_SECRET.encodedValue(), ENCRYPTED_OUTGOING_SECRET.encodedValue()); assertThat(validator.validateSettings(linkSettings).incomingLinkSettings()) .isEqualTo(expected.incomingLinkSettings()); assertThat(validator.validateSettings(linkSettings).outgoingLinkSettings()) .isEqualTo(expected.outgoingLinkSettings()); }
CoordinationEventBusBridge { @Subscribe public void onCoordinatedEvent(AbstractCoordinatedEvent event) { publish(event); } CoordinationEventBusBridge(CoordinationMessagePublisher coordinationMessagePublisher, EventBus eventBus); @Subscribe void onCoordinatedEvent(AbstractCoordinatedEvent event); }
@Test public void ignoresPreviouslyCoordinatedMessage() { TestCoordinatedEvent event = new TestCoordinatedEvent(); event.markReceivedViaCoordination(); bridge.onCoordinatedEvent(event); verifyNoInteractions(publisher); } @Test public void nullEventFails() { expectedException.expect(NullPointerException.class); bridge.onCoordinatedEvent(null); }
RuntimeUtils { public static boolean gcpProfileEnabled(final Environment environment) { Objects.requireNonNull(environment); return Arrays.stream(environment.getActiveProfiles()) .anyMatch(Runtimes.GCP::equalsIgnoreCase); } static boolean gcpProfileEnabled(final Environment environment); static Optional<String> getGoogleCloudProjectId(); static KeyStoreType determineKeystoreType(Environment environment); static boolean walletModeEnabled(final Environment env); static boolean packetSwitchModeEnabled(final Environment env); }
@Test public void testGcpProfileEnabled() { when(environmentMock.getActiveProfiles()).thenReturn(new String[] {"foo", "bar"}); assertThat(RuntimeUtils.gcpProfileEnabled(environmentMock)).isFalse(); when(environmentMock.getActiveProfiles()).thenReturn(new String[] {RuntimeProperties.Runtimes.GCP}); assertThat(RuntimeUtils.gcpProfileEnabled(environmentMock)).isTrue(); }
RuntimeUtils { public static Optional<String> getGoogleCloudProjectId() { return Optional.ofNullable(System.getenv().get(GOOGLE_CLOUD_PROJECT)) .filter(projectId -> !projectId.isEmpty()); } static boolean gcpProfileEnabled(final Environment environment); static Optional<String> getGoogleCloudProjectId(); static KeyStoreType determineKeystoreType(Environment environment); static boolean walletModeEnabled(final Environment env); static boolean packetSwitchModeEnabled(final Environment env); }
@Test public void testGetGcpProjectName() throws ReflectiveOperationException { assertThat(RuntimeUtils.getGoogleCloudProjectId().isPresent()).isFalse(); System.setProperty(GOOGLE_CLOUD_PROJECT, "foo"); assertThat(RuntimeUtils.getGoogleCloudProjectId().isPresent()).isFalse(); updateEnv(GOOGLE_CLOUD_PROJECT, "foo"); assertThat(RuntimeUtils.getGoogleCloudProjectId().isPresent()).isTrue(); }
RuntimeUtils { public static KeyStoreType determineKeystoreType(Environment environment) { Objects.requireNonNull(environment); if (isGcpKmsEnabled(environment)) { return KeyStoreType.GCP; } else if (isJksKmsEnabled(environment)) { return KeyStoreType.JKS; } else { throw new RuntimeException( String.format("Unsupported Keystore Type. Please defined either `%s` or `%s`", INTERLEDGER_CONNECTOR_KEYSTORE_GCP_ENABLED, INTERLEDGER_CONNECTOR_KEYSTORE_JKS_ENABLED) ); } } static boolean gcpProfileEnabled(final Environment environment); static Optional<String> getGoogleCloudProjectId(); static KeyStoreType determineKeystoreType(Environment environment); static boolean walletModeEnabled(final Environment env); static boolean packetSwitchModeEnabled(final Environment env); }
@Test public void testDetermineKeystoreTypeGcpKmsNull() { when(environmentMock.getProperty(INTERLEDGER_CONNECTOR_KEYSTORE_GCP_ENABLED)).thenReturn(null); expectedException.expect(RuntimeException.class); expectedException.expectMessage(ERR_MESSAGE); RuntimeUtils.determineKeystoreType(environmentMock); } @Test public void testDetermineKeystoreTypeGcpKmsFalse() { when(environmentMock.getProperty(INTERLEDGER_CONNECTOR_KEYSTORE_GCP_ENABLED)).thenReturn(Boolean.FALSE.toString()); expectedException.expect(RuntimeException.class); expectedException.expectMessage(ERR_MESSAGE); RuntimeUtils.determineKeystoreType(environmentMock); } @Test public void testDetermineKeystoreTypeGcpKmsTrue() { when(environmentMock.getProperty(INTERLEDGER_CONNECTOR_KEYSTORE_GCP_ENABLED)).thenReturn(Boolean.TRUE.toString()); assertThat(RuntimeUtils.determineKeystoreType(environmentMock)).isEqualTo(KeyStoreType.GCP); } @Test public void testDetermineKeystoreTypeJksNull() { when(environmentMock.getProperty(INTERLEDGER_CONNECTOR_KEYSTORE_JKS_ENABLED)).thenReturn(null); expectedException.expect(RuntimeException.class); expectedException.expectMessage(ERR_MESSAGE); RuntimeUtils.determineKeystoreType(environmentMock); } @Test public void testDetermineKeystoreTypeJksFalse() { when(environmentMock.getProperty(INTERLEDGER_CONNECTOR_KEYSTORE_JKS_ENABLED)).thenReturn(Boolean.FALSE.toString()); expectedException.expect(RuntimeException.class); expectedException.expectMessage(ERR_MESSAGE); RuntimeUtils.determineKeystoreType(environmentMock); } @Test public void testDetermineKeystoreTypeJksTrue() { when(environmentMock.getProperty(INTERLEDGER_CONNECTOR_KEYSTORE_JKS_ENABLED)).thenReturn(Boolean.TRUE.toString()); assertThat(RuntimeUtils.determineKeystoreType(environmentMock)).isEqualTo(KeyStoreType.JKS); }
OerPreparePacketHttpMessageConverter extends AbstractGenericHttpMessageConverter<InterledgerPacket> implements HttpMessageConverter<InterledgerPacket> { @Override public boolean canRead(Type type, Class<?> contextClass, MediaType mediaType) { if (contextClass != null && IlpHttpController.class.isAssignableFrom(contextClass)) { return super.canRead(type, contextClass, mediaType); } else { return false; } } OerPreparePacketHttpMessageConverter(final CodecContext ilpCodecContext); @Override boolean canRead(Type type, Class<?> contextClass, MediaType mediaType); @Override InterledgerPacket read(Type type, Class<?> contextClass, HttpInputMessage inputMessage); }
@Test public void testCanRead() { assertThat(converter.canRead(InterledgerPreparePacket.class, IlpHttpController.class, APPLICATION_JSON)).isFalse(); assertThat(converter.canRead(InterledgerPreparePacket.class, IlpHttpController.class, APPLICATION_OCTET_STREAM)).isTrue(); assertThat(converter.canRead(InterledgerPreparePacket.class, SettlementController.class, APPLICATION_JSON)).isFalse(); assertThat(converter.canRead(InterledgerPreparePacket.class, SettlementController.class, APPLICATION_OCTET_STREAM)).isFalse(); assertThat(converter.canRead(String.class, IlpHttpController.class, APPLICATION_JSON)).isFalse(); assertThat(converter.canRead(String.class, IlpHttpController.class, APPLICATION_OCTET_STREAM)).isTrue(); assertThat(converter.canRead(null, IlpHttpController.class, APPLICATION_OCTET_STREAM)).isTrue(); assertThat(converter.canRead(InterledgerPreparePacket.class, null, APPLICATION_OCTET_STREAM)).isFalse(); assertThat(converter.canRead(InterledgerPreparePacket.class, IlpHttpController.class, null)).isTrue(); assertThat(converter.canRead(null, null, null)).isFalse(); }
MetaDataController { @RequestMapping( path = PathConstants.SLASH, method = RequestMethod.GET, produces = {APPLICATION_JSON_VALUE, MediaTypes.PROBLEM_VALUE} ) public ResponseEntity<ConnectorSettingsResponse> getConnectorMetaData() { return new ResponseEntity<>(ConnectorSettingsResponse.builder() .operatorAddress(this.connectorSettingsSupplier.get().operatorAddress()) .version(this.buildProperties.getVersion()) .build(), HttpStatus.OK); } MetaDataController(Supplier<ConnectorSettings> connectorSettingsSupplier); @RequestMapping( path = PathConstants.SLASH, method = RequestMethod.GET, produces = {APPLICATION_JSON_VALUE, MediaTypes.PROBLEM_VALUE} ) ResponseEntity<ConnectorSettingsResponse> getConnectorMetaData(); }
@Test public void getConnectorMetaData() { ResponseEntity<String> metaDataResponse = restTemplate.getForEntity(PathConstants.SLASH, String.class); logger.info("metaDataResponse: " + metaDataResponse.getBody()); JsonContentAssert assertJson = assertThat(jsonTester.from(metaDataResponse.getBody())); assertJson.extractingJsonPathValue("ilp_address").isEqualTo(testConnectorAddress); assertJson.hasJsonPath("version"); }
IlpOverHttpAuthenticationProvider implements AuthenticationProvider { @Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { try { if (authentication instanceof BearerAuthentication) { AuthenticationDecision result = authenticateBearer((BearerAuthentication) authentication); if (result.isAuthenticated()) { return result; } else { throw new BadCredentialsException("Authentication failed for principal: " + result.getPrincipal()); } } else { logger.debug("Unsupported authentication type: " + authentication.getClass()); return null; } } catch (AccountNotFoundProblem e) { throw new BadCredentialsException("Invalid credentials: " + authentication.getPrincipal()); } catch (BadCredentialsException e) { throw handleBadCredentialsException(e, authentication); } catch (Exception e) { if (e.getCause() != null && BadCredentialsException.class.isAssignableFrom(e.getCause().getClass())) { throw e; } else { throw new BadCredentialsException("Unable to validate token due to system error", e); } } } IlpOverHttpAuthenticationProvider( final Supplier<ConnectorSettings> connectorSettingsSupplier, final Decryptor decryptor, final AccountSettingsRepository accountSettingsRepository, final LinkSettingsFactory linkSettingsFactory, final CacheMetricsCollector cacheMetrics, AccessTokenManager accessTokenManager); @Override Authentication authenticate(Authentication authentication); @Subscribe @SuppressWarnings("PMD.UnusedPublicMethod") void handleCredentialsUpdatedEvent(AccountCredentialsUpdatedEvent event); @Override boolean supports(Class<?> authentication); }
@Test public void authenticateSimpleWithValidToken() { mockAccountSettings(AuthType.SIMPLE); Authentication result = ilpOverHttpAuthenticationProvider.authenticate(BearerAuthentication.builder() .isAuthenticated(false) .principal(ACCOUNT_ID.toString()) .bearerToken(SECRET.getBytes()) .hmacSha256(HashCode.fromString("1234")) .build() ); assertThat(result.isAuthenticated()).isTrue(); assertThat(result.getPrincipal()).isEqualTo(ACCOUNT_ID); } @Test public void authenticateSimpleWithInvalidSecret() { mockAccountSettings(AuthType.SIMPLE); expectedException.expect(BadCredentialsException.class); expectedException.expectMessage("Authentication failed for principal: bob"); ilpOverHttpAuthenticationProvider.authenticate(BearerAuthentication.builder() .principal("bob") .isAuthenticated(false) .bearerToken("badtoken".getBytes()) .hmacSha256(HashCode.fromString("1234")) .build() ); } @Test public void authenticateSimpleWithInvalidPrincipal() { String principal = "bad_principal"; mockAccountSettings(AuthType.SIMPLE); expectedException.expect(BadCredentialsException.class); expectedException.expectMessage("Invalid credentials: " + principal); ilpOverHttpAuthenticationProvider.authenticate(BearerAuthentication.builder() .isAuthenticated(false) .principal(principal) .bearerToken(SECRET.getBytes()) .hmacSha256(HashCode.fromString("1234")) .build()); } @Test public void authenticateJwtWithValidToken() { mockAccountSettings(AuthType.JWT_HS_256); Authentication result = ilpOverHttpAuthenticationProvider.authenticate(BearerAuthentication.builder() .isAuthenticated(false) .principal(ACCOUNT_ID.toString()) .bearerToken(JWT_TOKEN.getBytes()) .hmacSha256(HashCode.fromString("1234")) .build() ); assertThat(result.isAuthenticated()).isTrue(); assertThat(result.getPrincipal()).isEqualTo(ACCOUNT_ID); } @Test public void authenticateJwtWithInvalidToken() { mockAccountSettings(AuthType.JWT_HS_256); expectedException.expect(BadCredentialsException.class); expectedException.expectMessage("Authentication failed for principal"); ilpOverHttpAuthenticationProvider.authenticate(BearerAuthentication.builder() .isAuthenticated(false) .principal(ACCOUNT_ID.toString()) .bearerToken("not a jwt".getBytes()) .hmacSha256(HashCode.fromString("1234")) .build() ); } @Test public void authenticateInternalServerError() { mockAccountSettings(AuthType.JWT_HS_256); when(accountSettingsRepository.findByAccountIdWithConversion(any())).thenThrow( new RuntimeException("Something bad happened on the server") ); expectedException.expect(BadCredentialsException.class); expectedException.expectMessage("Unable to validate token due to system error"); ilpOverHttpAuthenticationProvider.authenticate(BearerAuthentication.builder() .isAuthenticated(false) .principal(ACCOUNT_ID.toString()) .bearerToken(JWT_TOKEN.getBytes()) .hmacSha256(HashCode.fromString("1234")) .build() ); }
DelegatingEncryptionService implements EncryptionService { @Override public KeyStoreType keyStoreType() { return serviceMap.values().stream().map(EncryptionService::keyStoreType).findFirst().get(); } DelegatingEncryptionService(final Set<EncryptionService> encryptionServices); @Override KeyStoreType keyStoreType(); @Override byte[] decrypt(KeyMetadata keyMetadata, EncryptionAlgorithm encryptionAlgorithm, byte[] cipherMessage); @Override EncryptedSecret encrypt(KeyMetadata keyMetadata, EncryptionAlgorithm encryptionAlgorithm, byte[] plainText); @Override T withDecrypted(EncryptedSecret encryptedSecret, Function<byte[], T> callable); }
@Test public void keyStoreType() { assertThat(new DelegatingEncryptionService(Sets.newHashSet(mockGcp)).keyStoreType()).isEqualTo(KeyStoreType.GCP); assertThat(new DelegatingEncryptionService(Sets.newHashSet(mockJks)).keyStoreType()).isEqualTo(KeyStoreType.JKS); }
JwksUtils { public static HttpUrl getJwksUrl(HttpUrl issuerUrl) { HttpUrl.Builder builder = new HttpUrl.Builder() .scheme(issuerUrl.scheme()) .host(issuerUrl.host()) .port(issuerUrl.port()); issuerUrl.pathSegments().forEach(builder::addPathSegment); return builder.addPathSegment(".well-known") .addPathSegment("jwks.json") .build(); } static HttpUrl getJwksUrl(HttpUrl issuerUrl); }
@Test public void getJwksUrlAtRootPath() { HttpUrl issuer = HttpUrl.parse("https: HttpUrl expectedJwks = HttpUrl.parse("https: assertThat(JwksUtils.getJwksUrl(issuer)).isEqualTo(expectedJwks); } @Test public void getJwksUrlAtRootPathTrailingSlash() { HttpUrl issuer = HttpUrl.parse("https: HttpUrl expectedJwks = HttpUrl.parse("https: assertThat(JwksUtils.getJwksUrl(issuer)).isEqualTo(expectedJwks); } @Test public void getJwksUrlAtSubPath() { HttpUrl issuer = HttpUrl.parse("https: HttpUrl expectedJwks = HttpUrl.parse("https: assertThat(JwksUtils.getJwksUrl(issuer)).isEqualTo(expectedJwks); } @Test public void getJwksUrlAtSubPathTrailingSlash() { HttpUrl issuer = HttpUrl.parse("https: HttpUrl expectedJwks = HttpUrl.parse("https: assertThat(JwksUtils.getJwksUrl(issuer)).isEqualTo(expectedJwks); }
BearerTokenSecurityContextRepository implements SecurityContextRepository { @Override public boolean containsContext(HttpServletRequest request) { return parseToken(request).isPresent() && parseAccountId(request).isPresent(); } BearerTokenSecurityContextRepository(byte[] ephemeralBytes); @Override SecurityContext loadContext(HttpRequestResponseHolder requestResponseHolder); @Override void saveContext(SecurityContext context, HttpServletRequest request, HttpServletResponse response); @Override boolean containsContext(HttpServletRequest request); }
@Test public void loadContextNoAccountIdInUrl() { String token = "foo:bar"; mockRequestPath("/routes/foo/ilp"); when(mockRequest.getHeader("Authorization")).thenReturn("Bearer " + token); assertThat(repository.containsContext(mockRequest)).isFalse(); } @Test public void containsContext() { mockRequestPath("/accounts/foo/ilp"); when(mockRequest.getHeader("Authorization")).thenReturn("Bearer token"); assertThat(repository.containsContext(mockRequest)).isTrue(); }
BearerTokenSecurityContextRepository implements SecurityContextRepository { @Override public SecurityContext loadContext(HttpRequestResponseHolder requestResponseHolder) { SecurityContext context = SecurityContextHolder.createEmptyContext(); parseToken(requestResponseHolder.getRequest()).ifPresent(token -> { context.setAuthentication(BearerAuthentication.builder() .isAuthenticated(false) .principal(parseAccountId(requestResponseHolder.getRequest()).get()) .hmacSha256(Hashing.hmacSha256(ephemeralBytes).hashBytes(token)) .bearerToken(token) .build()); }); return context; } BearerTokenSecurityContextRepository(byte[] ephemeralBytes); @Override SecurityContext loadContext(HttpRequestResponseHolder requestResponseHolder); @Override void saveContext(SecurityContext context, HttpServletRequest request, HttpServletResponse response); @Override boolean containsContext(HttpServletRequest request); }
@Test public void loadContextNoAuthHeader() { mockRequestPath("/accounts/foo/ilp"); SecurityContext securityContext = repository.loadContext(holder); assertThat(securityContext.getAuthentication()).isNull(); } @Test public void loadContextDeprecatedNoBearerPrefix() { mockRequestPath("/accounts/foo/ilp"); String deprecatedBearerToken = "undercover token"; when(mockRequest.getHeader("Authorization")).thenReturn(deprecatedBearerToken); SecurityContext securityContext = repository.loadContext(holder); assertThat(securityContext.getAuthentication()).isNotNull(); assertThat(securityContext.getAuthentication().getCredentials()).isEqualTo(deprecatedBearerToken.getBytes()); } @Test public void loadContextBasicAuth() { mockRequestPath("/accounts/foo/ilp"); String basicAuth = "Basic token"; when(mockRequest.getHeader("Authorization")).thenReturn(basicAuth); SecurityContext securityContext = repository.loadContext(holder); assertThat(securityContext.getAuthentication()).isNull(); }
AsnUuidCodec extends AsnOctetStringBasedObjectCodec<UUID> { @VisibleForTesting protected final static byte[] getBytesFromUUID(final UUID uuid) { final ByteBuffer bb = ByteBuffer.wrap(new byte[16]); bb.putLong(uuid.getMostSignificantBits()); bb.putLong(uuid.getLeastSignificantBits()); return bb.array(); } AsnUuidCodec(); @Override UUID decode(); @Override void encode(final UUID value); }
@Test public void testUUIDHas16Bytes() { final UUID uuid = UUID.randomUUID(); final byte[] result = AsnUuidCodec.getBytesFromUUID(uuid); assertThat(result.length).as("Resulting byte array should have had 16 elements.").isEqualTo(16); } @Test public void testNotSameUUIDFromByteArray() { final UUID uuid = UUID.fromString("80de5eaf-9379-4cb5-aaa4-1250649326cc"); final byte[] result = AsnUuidCodec.getBytesFromUUID(uuid); final UUID newUuid = UUID.nameUUIDFromBytes(result); assertThat(uuid).isNotEqualTo(newUuid); }
DelegatingEncryptionService implements EncryptionService { @Override public byte[] decrypt(KeyMetadata keyMetadata, EncryptionAlgorithm encryptionAlgorithm, byte[] cipherMessage) { return getDelegate(keyMetadata).decrypt(keyMetadata, encryptionAlgorithm, cipherMessage); } DelegatingEncryptionService(final Set<EncryptionService> encryptionServices); @Override KeyStoreType keyStoreType(); @Override byte[] decrypt(KeyMetadata keyMetadata, EncryptionAlgorithm encryptionAlgorithm, byte[] cipherMessage); @Override EncryptedSecret encrypt(KeyMetadata keyMetadata, EncryptionAlgorithm encryptionAlgorithm, byte[] plainText); @Override T withDecrypted(EncryptedSecret encryptedSecret, Function<byte[], T> callable); }
@Test public void decrypt() { DelegatingEncryptionService service = new DelegatingEncryptionService(Sets.newHashSet(mockGcp, mockJks)); assertThat(service.decrypt(GCP_SECRET)).isEqualTo(GCP_DECRYPTED); assertThat(service.decrypt(JKS_SECRET)).isEqualTo(JKS_DECRYPTED); } @Test public void decryptThrowsExceptionIfNoProvider() { DelegatingEncryptionService service = new DelegatingEncryptionService(Sets.newHashSet(mockGcp)); expectedException.expect(RuntimeException.class); service.decrypt(JKS_SECRET); }
CircuitBreakingLink extends AbstractLink<LinkSettings> implements Link<LinkSettings> { @Override public InterledgerResponsePacket sendPacket(final InterledgerPreparePacket preparePacket) { Objects.requireNonNull(preparePacket); final CircuitBreaker circuitBreaker = circuitBreakerRegistry.circuitBreaker(this.getLinkId().value()); return CircuitBreaker.decorateFunction(circuitBreaker, linkDelegate::sendPacket).apply(preparePacket); } @VisibleForTesting CircuitBreakingLink(final Link<?> linkDelegate); CircuitBreakingLink( final Link<?> linkDelegate, final CircuitBreakerConfig circuitBreakerConfig ); @Override InterledgerResponsePacket sendPacket(final InterledgerPreparePacket preparePacket); @Override LinkId getLinkId(); @Override void setLinkId(final LinkId linkId); @Override Supplier<InterledgerAddress> getOperatorAddressSupplier(); @Override LinkSettings getLinkSettings(); @Override void registerLinkHandler(LinkHandler dataHandler); @Override Optional<LinkHandler> getLinkHandler(); @Override void unregisterLinkHandler(); T getLinkDelegateTyped(); }
@Test public void sendPacketWithIlpExceptionsBelowThreshold() { final CircuitBreaker circuitBreaker = CircuitBreakerRegistry.of(CONFIG).circuitBreaker(LINK_ID_VALUE); CheckedFunction1<InterledgerPreparePacket, InterledgerResponsePacket> function = CircuitBreaker.decorateCheckedFunction(circuitBreaker, (preparePacket) -> link.sendPacket(PREPARE_PACKET)); Try<InterledgerResponsePacket> result = Try.of(() -> function.apply(PREPARE_PACKET)); assertThat(result.isFailure()).isFalse(); assertThat(result.failed().isEmpty()).isTrue(); assertThat(circuitBreaker.getState()).isEqualTo(CircuitBreaker.State.CLOSED); } @Test public void sendPacketWithIlpExceptionsAboveThreshold() { final CircuitBreaker circuitBreaker = CircuitBreakerRegistry.of(CONFIG).circuitBreaker(LINK_ID_VALUE); Try<InterledgerResponsePacket> result = null; for (int i = 0; i < 2; i++) { CheckedFunction1<InterledgerPreparePacket, InterledgerResponsePacket> function = CircuitBreaker.decorateCheckedFunction(circuitBreaker, (preparePacket) -> link.sendPacket(PREPARE_PACKET)); result = Try.of(() -> function.apply(PREPARE_PACKET)); } assertThat(result.isFailure()).isFalse(); assertThat(result.failed().isEmpty()).isTrue(); assertThat(circuitBreaker.getState()).isEqualTo(CircuitBreaker.State.CLOSED); } @Test public void sendPacketWithNumFailuresBelowThreshold() { final CircuitBreaker circuitBreaker = CircuitBreakerRegistry.of(CONFIG).circuitBreaker(LINK_ID_VALUE); doThrow(new RuntimeException("foo")).when(linkDelegateMock).sendPacket(any()); CheckedFunction1<InterledgerPreparePacket, InterledgerResponsePacket> function = CircuitBreaker.decorateCheckedFunction(circuitBreaker, (preparePacket) -> link.sendPacket(PREPARE_PACKET)); Try<InterledgerResponsePacket> result = Try.of(() -> function.apply(PREPARE_PACKET)); assertThat(result.isFailure()).isTrue(); assertThat(circuitBreaker.getState()).isEqualTo(CircuitBreaker.State.CLOSED); assertThat(result.failed().get().getClass().toString()).isEqualTo(RuntimeException.class.toString()); } @Test public void sendPacketWithNumFailuresAboveThreshold() { final CircuitBreaker circuitBreaker = CircuitBreakerRegistry.of(CONFIG).circuitBreaker(LINK_ID_VALUE); doThrow(new RuntimeException("foo")).when(linkDelegateMock).sendPacket(any()); Try<InterledgerResponsePacket> result = null; for (int i = 0; i < 2; i++) { CheckedFunction1<InterledgerPreparePacket, InterledgerResponsePacket> function = CircuitBreaker.decorateCheckedFunction(circuitBreaker, (preparePacket) -> link.sendPacket(PREPARE_PACKET)); result = Try.of(() -> function.apply(PREPARE_PACKET)); } assertThat(result.isFailure()).isTrue(); assertThat(circuitBreaker.getState()).isEqualTo(CircuitBreaker.State.OPEN); assertThat(result.failed().get().getClass().getName()).isEqualTo(RuntimeException.class.getName()); }
CircuitBreakingLink extends AbstractLink<LinkSettings> implements Link<LinkSettings> { @Override public LinkId getLinkId() { return this.linkDelegate.getLinkId(); } @VisibleForTesting CircuitBreakingLink(final Link<?> linkDelegate); CircuitBreakingLink( final Link<?> linkDelegate, final CircuitBreakerConfig circuitBreakerConfig ); @Override InterledgerResponsePacket sendPacket(final InterledgerPreparePacket preparePacket); @Override LinkId getLinkId(); @Override void setLinkId(final LinkId linkId); @Override Supplier<InterledgerAddress> getOperatorAddressSupplier(); @Override LinkSettings getLinkSettings(); @Override void registerLinkHandler(LinkHandler dataHandler); @Override Optional<LinkHandler> getLinkHandler(); @Override void unregisterLinkHandler(); T getLinkDelegateTyped(); }
@Test public void getLinkId() { this.link.setLinkId(LINK_ID); this.link.getLinkId(); verify(linkDelegateMock).getOperatorAddressSupplier(); verify(linkDelegateMock).getLinkSettings(); verify(linkDelegateMock).getLinkId(); verify(linkDelegateMock).setLinkId(any()); verifyNoMoreInteractions(linkDelegateMock); }
CircuitBreakingLink extends AbstractLink<LinkSettings> implements Link<LinkSettings> { @Override public Supplier<InterledgerAddress> getOperatorAddressSupplier() { return this.linkDelegate.getOperatorAddressSupplier(); } @VisibleForTesting CircuitBreakingLink(final Link<?> linkDelegate); CircuitBreakingLink( final Link<?> linkDelegate, final CircuitBreakerConfig circuitBreakerConfig ); @Override InterledgerResponsePacket sendPacket(final InterledgerPreparePacket preparePacket); @Override LinkId getLinkId(); @Override void setLinkId(final LinkId linkId); @Override Supplier<InterledgerAddress> getOperatorAddressSupplier(); @Override LinkSettings getLinkSettings(); @Override void registerLinkHandler(LinkHandler dataHandler); @Override Optional<LinkHandler> getLinkHandler(); @Override void unregisterLinkHandler(); T getLinkDelegateTyped(); }
@Test public void getOperatorAddressSupplier() { this.link.getOperatorAddressSupplier(); verify(linkDelegateMock, times(2)).getOperatorAddressSupplier(); verify(linkDelegateMock).getLinkSettings(); verifyNoMoreInteractions(linkDelegateMock); }
CircuitBreakingLink extends AbstractLink<LinkSettings> implements Link<LinkSettings> { @Override public LinkSettings getLinkSettings() { return this.linkDelegate.getLinkSettings(); } @VisibleForTesting CircuitBreakingLink(final Link<?> linkDelegate); CircuitBreakingLink( final Link<?> linkDelegate, final CircuitBreakerConfig circuitBreakerConfig ); @Override InterledgerResponsePacket sendPacket(final InterledgerPreparePacket preparePacket); @Override LinkId getLinkId(); @Override void setLinkId(final LinkId linkId); @Override Supplier<InterledgerAddress> getOperatorAddressSupplier(); @Override LinkSettings getLinkSettings(); @Override void registerLinkHandler(LinkHandler dataHandler); @Override Optional<LinkHandler> getLinkHandler(); @Override void unregisterLinkHandler(); T getLinkDelegateTyped(); }
@Test public void getLinkSettings() { this.link.getLinkSettings(); verify(linkDelegateMock).getOperatorAddressSupplier(); verify(linkDelegateMock, times(2)).getLinkSettings(); verifyNoMoreInteractions(linkDelegateMock); }
CircuitBreakingLink extends AbstractLink<LinkSettings> implements Link<LinkSettings> { @Override public void registerLinkHandler(LinkHandler dataHandler) throws LinkHandlerAlreadyRegisteredException { this.linkDelegate.registerLinkHandler(dataHandler); } @VisibleForTesting CircuitBreakingLink(final Link<?> linkDelegate); CircuitBreakingLink( final Link<?> linkDelegate, final CircuitBreakerConfig circuitBreakerConfig ); @Override InterledgerResponsePacket sendPacket(final InterledgerPreparePacket preparePacket); @Override LinkId getLinkId(); @Override void setLinkId(final LinkId linkId); @Override Supplier<InterledgerAddress> getOperatorAddressSupplier(); @Override LinkSettings getLinkSettings(); @Override void registerLinkHandler(LinkHandler dataHandler); @Override Optional<LinkHandler> getLinkHandler(); @Override void unregisterLinkHandler(); T getLinkDelegateTyped(); }
@Test public void registerLinkHandler() { this.link.registerLinkHandler(null); verify(linkDelegateMock).getOperatorAddressSupplier(); verify(linkDelegateMock).getLinkSettings(); verify(linkDelegateMock).registerLinkHandler(any()); verifyNoMoreInteractions(linkDelegateMock); }
CircuitBreakingLink extends AbstractLink<LinkSettings> implements Link<LinkSettings> { @Override public Optional<LinkHandler> getLinkHandler() { return this.linkDelegate.getLinkHandler(); } @VisibleForTesting CircuitBreakingLink(final Link<?> linkDelegate); CircuitBreakingLink( final Link<?> linkDelegate, final CircuitBreakerConfig circuitBreakerConfig ); @Override InterledgerResponsePacket sendPacket(final InterledgerPreparePacket preparePacket); @Override LinkId getLinkId(); @Override void setLinkId(final LinkId linkId); @Override Supplier<InterledgerAddress> getOperatorAddressSupplier(); @Override LinkSettings getLinkSettings(); @Override void registerLinkHandler(LinkHandler dataHandler); @Override Optional<LinkHandler> getLinkHandler(); @Override void unregisterLinkHandler(); T getLinkDelegateTyped(); }
@Test public void getLinkHandler() { assertThat(link.getLinkHandler()).isEqualTo(Optional.empty()); verify(linkDelegateMock).getOperatorAddressSupplier(); verify(linkDelegateMock).getLinkSettings(); verify(linkDelegateMock).getLinkHandler(); verifyNoMoreInteractions(linkDelegateMock); }
CircuitBreakingLink extends AbstractLink<LinkSettings> implements Link<LinkSettings> { @Override public void unregisterLinkHandler() { this.linkDelegate.unregisterLinkHandler(); } @VisibleForTesting CircuitBreakingLink(final Link<?> linkDelegate); CircuitBreakingLink( final Link<?> linkDelegate, final CircuitBreakerConfig circuitBreakerConfig ); @Override InterledgerResponsePacket sendPacket(final InterledgerPreparePacket preparePacket); @Override LinkId getLinkId(); @Override void setLinkId(final LinkId linkId); @Override Supplier<InterledgerAddress> getOperatorAddressSupplier(); @Override LinkSettings getLinkSettings(); @Override void registerLinkHandler(LinkHandler dataHandler); @Override Optional<LinkHandler> getLinkHandler(); @Override void unregisterLinkHandler(); T getLinkDelegateTyped(); }
@Test public void unregisterLinkHandler() { this.link.unregisterLinkHandler(); verify(linkDelegateMock).getOperatorAddressSupplier(); verify(linkDelegateMock).getLinkSettings(); verify(linkDelegateMock).unregisterLinkHandler(); verifyNoMoreInteractions(linkDelegateMock); }
StaticRouteEntityConverter implements Converter<StaticRouteEntity, StaticRoute> { @Override public StaticRoute convert(StaticRouteEntity staticRouteEntity) { Objects.requireNonNull(staticRouteEntity); return StaticRoute.builder() .nextHopAccountId(staticRouteEntity.getBoxedAccountId()) .routePrefix(staticRouteEntity.getPrefix()) .createdAt(Optional.ofNullable(staticRouteEntity.getCreatedDate()).orElseGet(() -> Instant.now())) .modifiedAt(Optional.ofNullable(staticRouteEntity.getModifiedDate()).orElseGet(() -> Instant.now())) .build(); } @Override StaticRoute convert(StaticRouteEntity staticRouteEntity); }
@Test public void convert() { StaticRouteEntityConverter converter = new StaticRouteEntityConverter(); StaticRoute route = StaticRoute.builder() .routePrefix(InterledgerAddressPrefix.of("g.example")) .nextHopAccountId(AccountId.of("foo")) .build(); StaticRouteEntity entity = new StaticRouteEntity(route); StaticRoute converted = converter.convert(entity); assertThat(converted).extracting("routePrefix", "nextHopAccountId") .containsExactly(route.routePrefix(), route.nextHopAccountId()); assertThat(converted).isEqualTo(route); assertThat(entity).isEqualTo(new StaticRouteEntity(converted)); }
AccountBalanceSettingsEntityConverter implements Converter<AccountBalanceSettingsEntity, AccountBalanceSettings> { @Override public AccountBalanceSettings convert(final AccountBalanceSettingsEntity accountSettingsEntity) { Objects.requireNonNull(accountSettingsEntity); return AccountBalanceSettings.builder() .settleTo(accountSettingsEntity.getSettleTo()) .settleThreshold(accountSettingsEntity.getSettleThreshold()) .minBalance(accountSettingsEntity.getMinBalance()) .build(); } @Override AccountBalanceSettings convert(final AccountBalanceSettingsEntity accountSettingsEntity); }
@Test public void convert() { final AccountBalanceSettings accountBalanceSettings = AccountBalanceSettings.builder() .settleThreshold(100L) .settleTo(1L) .minBalance(50L) .build(); final AccountBalanceSettingsEntity entity = new AccountBalanceSettingsEntity(accountBalanceSettings); final AccountBalanceSettings actual = converter.convert(entity); assertThat(actual.settleThreshold()).isEqualTo(accountBalanceSettings.settleThreshold()); assertThat(actual.settleTo()).isEqualTo(accountBalanceSettings.settleTo()); assertThat(actual.minBalance()).isEqualTo(accountBalanceSettings.minBalance()); }
AccountSettingsEntityConverter implements Converter<AccountSettingsEntity, AccountSettings> { @Override public AccountSettings convert(final AccountSettingsEntity accountSettingsEntity) { Objects.requireNonNull(accountSettingsEntity); final ImmutableAccountSettings.Builder builder = AccountSettings.builder() .accountId(accountSettingsEntity.getAccountId()) .createdAt(Optional.ofNullable(accountSettingsEntity.getCreatedDate()).orElseGet(() -> Instant.now())) .modifiedAt(Optional.ofNullable(accountSettingsEntity.getCreatedDate()).orElseGet(() -> Instant.now())) .description(accountSettingsEntity.getDescription()) .assetScale(accountSettingsEntity.getAssetScale()) .assetCode(accountSettingsEntity.getAssetCode()) .linkType(accountSettingsEntity.getLinkType()) .accountRelationship(accountSettingsEntity.getAccountRelationship()) .ilpAddressSegment(accountSettingsEntity.getIlpAddressSegment()) .isSendRoutes(accountSettingsEntity.isSendRoutes()) .isReceiveRoutes(accountSettingsEntity.isReceiveRoutes()) .putAllCustomSettings(accountSettingsEntity.getCustomSettings()); accountSettingsEntity.getMaximumPacketAmount() .ifPresent(maxPacketAmount -> builder.maximumPacketAmount(UnsignedLong.valueOf(maxPacketAmount))); Optional.ofNullable(accountSettingsEntity.getRateLimitSettingsEntity()) .ifPresent(rateLimitSettingsEntity -> builder .rateLimitSettings(rateLimitSettingsEntityConverter.convert(rateLimitSettingsEntity))); Optional.ofNullable(accountSettingsEntity.getBalanceSettingsEntity()) .ifPresent(balanceSettingsEntity -> builder .balanceSettings(accountBalanceSettingsEntityConverter.convert(balanceSettingsEntity))); Optional.ofNullable(accountSettingsEntity.getSettlementEngineDetailsEntity()) .ifPresent(settlementEngineDetailsEntity -> builder .settlementEngineDetails(settlementEngineDetailsEntityConverter.convert(settlementEngineDetailsEntity)) ); return builder.build(); } AccountSettingsEntityConverter( final RateLimitSettingsEntityConverter rateLimitSettingsEntityConverter, final AccountBalanceSettingsEntityConverter accountBalanceSettingsEntityConverter, final SettlementEngineDetailsEntityConverter settlementEngineDetailsEntityConverter ); @Override AccountSettings convert(final AccountSettingsEntity accountSettingsEntity); }
@Test public void convertWithEmptyEmbeds() { final AccountSettings accountSettings = AccountSettings.builder() .accountId(AccountId.of("123")) .description("test description") .assetCode("USD") .assetScale(2) .accountRelationship(AccountRelationship.PEER) .ilpAddressSegment("g.foo") .linkType(LinkType.of("foo")) .build(); final AccountSettingsEntity entity = new AccountSettingsEntity(accountSettings); AccountSettings actual = converter.convert(entity); assertThat(actual.accountId()).isEqualTo(accountSettings.accountId()); assertThat(actual.description()).isEqualTo(accountSettings.description()); assertThat(actual.assetScale()).isEqualTo(accountSettings.assetScale()); assertThat(actual.assetCode()).isEqualTo(accountSettings.assetCode()); assertThat(actual.accountRelationship()).isEqualTo(accountSettings.accountRelationship()); assertThat(actual.ilpAddressSegment()).isEqualTo(accountSettings.ilpAddressSegment()); assertThat(actual.linkType()).isEqualTo(accountSettings.linkType()); assertThat(actual.rateLimitSettings()).isEqualTo(accountSettings.rateLimitSettings()); assertThat(actual.balanceSettings()).isEqualTo(accountSettings.balanceSettings()); assertThat(actual.settlementEngineDetails()).isEqualTo(accountSettings.settlementEngineDetails()); } @Test public void convertFullObject() { final AccountBalanceSettings balanceSettings = AccountBalanceSettings.builder() .settleThreshold(100L) .settleTo(1L) .minBalance(50L) .build(); final AccountRateLimitSettings rateLimitSettings = AccountRateLimitSettings.builder() .maxPacketsPerSecond(2) .build(); final SettlementEngineDetails settlementEngineDetails = SettlementEngineDetails.builder() .baseUrl(HttpUrl.parse("https: .settlementEngineAccountId(SettlementEngineAccountId.of(UUID.randomUUID().toString())) .build(); final AccountSettings accountSettings = AccountSettings.builder() .accountId(AccountId.of("123")) .createdAt(Instant.MAX) .modifiedAt(Instant.MAX) .description("test description") .assetCode("USD") .assetScale(2) .accountRelationship(AccountRelationship.PEER) .ilpAddressSegment("g.foo") .linkType(LinkType.of("foo")) .balanceSettings(balanceSettings) .rateLimitSettings(rateLimitSettings) .settlementEngineDetails(settlementEngineDetails) .build(); final AccountSettingsEntity entity = new AccountSettingsEntity(accountSettings); AccountSettings actual = converter.convert(entity); assertThat(actual.accountId()).isEqualTo(accountSettings.accountId()); assertThat(actual.createdAt().minusSeconds(1).isBefore(Instant.now())).isTrue(); assertThat(actual.modifiedAt().minusSeconds(1).isBefore(Instant.now())).isTrue(); assertThat(actual.description()).isEqualTo(accountSettings.description()); assertThat(actual.assetScale()).isEqualTo(accountSettings.assetScale()); assertThat(actual.assetCode()).isEqualTo(accountSettings.assetCode()); assertThat(actual.accountRelationship()).isEqualTo(accountSettings.accountRelationship()); assertThat(actual.ilpAddressSegment()).isEqualTo(accountSettings.ilpAddressSegment()); assertThat(actual.linkType()).isEqualTo(accountSettings.linkType()); assertThat(actual.rateLimitSettings()).isEqualTo(accountSettings.rateLimitSettings()); assertThat(actual.balanceSettings()).isEqualTo(accountSettings.balanceSettings()); assertThat(actual.settlementEngineDetails()).isEqualTo(accountSettings.settlementEngineDetails()); }
RateLimitSettingsEntityConverter implements Converter<AccountRateLimitSettingsEntity, AccountRateLimitSettings> { @Override public AccountRateLimitSettings convert(final AccountRateLimitSettingsEntity entity) { return AccountRateLimitSettings.builder() .maxPacketsPerSecond(entity.getMaxPacketsPerSecond()) .build(); } @Override AccountRateLimitSettings convert(final AccountRateLimitSettingsEntity entity); }
@Test public void convert() { final AccountRateLimitSettings rateLimitSettings = AccountRateLimitSettings.builder() .maxPacketsPerSecond(2) .build(); final AccountRateLimitSettingsEntity entity = new AccountRateLimitSettingsEntity(rateLimitSettings); AccountRateLimitSettings actual = converter.convert(entity); assertThat(actual.maxPacketsPerSecond()).isEqualTo(rateLimitSettings.maxPacketsPerSecond()); }
FxRateOverridesEntityConverter implements Converter<FxRateOverrideEntity, FxRateOverride> { @Override public FxRateOverride convert(FxRateOverrideEntity rateOverrideEntity) { Objects.requireNonNull(rateOverrideEntity); return FxRateOverride.builder() .id(rateOverrideEntity.getId()) .assetCodeFrom(rateOverrideEntity.getAssetCodeFrom()) .assetCodeTo(rateOverrideEntity.getAssetCodeTo()) .rate(rateOverrideEntity.getRate()) .createdAt(Optional.ofNullable(rateOverrideEntity.getCreatedDate()).orElseGet(() -> Instant.now())) .modifiedAt(Optional.ofNullable(rateOverrideEntity.getModifiedDate()).orElseGet(() -> Instant.now())) .build(); } @Override FxRateOverride convert(FxRateOverrideEntity rateOverrideEntity); }
@Test public void convert() { FxRateOverridesEntityConverter converter = new FxRateOverridesEntityConverter(); FxRateOverride dto = FxRateOverride.builder() .id(1l) .rate(BigDecimal.ONE) .assetCodeTo("DAVEANDBUSTERS") .assetCodeFrom("CHUCKIECHEESE") .build(); FxRateOverrideEntity entity = new FxRateOverrideEntity(dto); FxRateOverride convertedDto = converter.convert(entity); assertThat(convertedDto).extracting("id", "rate", "assetCodeTo", "assetCodeFrom") .containsExactly(dto.id(), dto.rate(), dto.assetCodeTo(), dto.assetCodeFrom()); assertThat(convertedDto).isEqualTo(dto); assertThat(new FxRateOverrideEntity(convertedDto)).isEqualTo(entity); }
SettlementEngineDetailsEntityConverter implements Converter<SettlementEngineDetailsEntity, SettlementEngineDetails> { @Override public SettlementEngineDetails convert(final SettlementEngineDetailsEntity settlementEngineDetailsEntity) { Objects.requireNonNull(settlementEngineDetailsEntity); return SettlementEngineDetails.builder() .settlementEngineAccountId( SettlementEngineAccountId.of(settlementEngineDetailsEntity.getSettlementEngineAccountId()) ) .baseUrl(HttpUrl.parse(settlementEngineDetailsEntity.getBaseUrl())) .customSettings(settlementEngineDetailsEntity.getCustomSettings()) .build(); } @Override SettlementEngineDetails convert(final SettlementEngineDetailsEntity settlementEngineDetailsEntity); }
@Test public void convert() { final SettlementEngineDetails settlementEngineDetails = SettlementEngineDetails.builder() .baseUrl(HttpUrl.parse("https: .settlementEngineAccountId(SettlementEngineAccountId.of(UUID.randomUUID().toString())) .putCustomSettings("xrpAddress", "rsWs4m35EJctu7Go3FydVwQeGdMQX96XLH") .build(); final SettlementEngineDetailsEntity entity = new SettlementEngineDetailsEntity(settlementEngineDetails); SettlementEngineDetails actual = converter.convert(entity); assertThat(actual.baseUrl()).isEqualTo(settlementEngineDetails.baseUrl()); assertThat(actual.settlementEngineAccountId()).isEqualTo(settlementEngineDetails.settlementEngineAccountId()); assertThat(actual.customSettings().get("xrpAddress")).isEqualTo("rsWs4m35EJctu7Go3FydVwQeGdMQX96XLH"); }
InMemoryForwardingRoutingTable extends InMemoryRoutingTable<RouteUpdate> implements ForwardingRoutingTable<RouteUpdate> { @Override public void clearRouteInLogAtEpoch(final int epoch) { this.routeUpdateLog.put(epoch, null); } InMemoryForwardingRoutingTable(); @Override RoutingTableId getRoutingTableId(); @Override int getCurrentEpoch(); @Override List<InterledgerAddressPrefix> getKeysStartingWith(InterledgerAddressPrefix addressPrefix); @Override Iterable<RouteUpdate> getPartialRouteLog(final int numberToSkip, final int limit); @Override void clearRouteInLogAtEpoch(final int epoch); @Override void setEpochValue(final int epoch, final RouteUpdate routeUpdate); }
@Test public void clearRouteInLogAtEpoch() { assertThat(routingTable.getCurrentEpoch()).isEqualTo(0); routingTable.setEpochValue(1, createRouteUpdate(1, BOB_ACCT, BOB_PREFIX)); assertThat(routingTable.getCurrentEpoch()).isEqualTo(1); ImmutableRouteUpdate aliceRouteUpdate = createRouteUpdate(1, ALICE_ACCT, ALICE_PREFIX); routingTable.setEpochValue(2, aliceRouteUpdate); routingTable.clearRouteInLogAtEpoch(1); assertThat(routingTable.getPartialRouteLog(0, 10)).hasSize(2) .containsExactlyInAnyOrder(null, aliceRouteUpdate); }
InMemoryForwardingRoutingTable extends InMemoryRoutingTable<RouteUpdate> implements ForwardingRoutingTable<RouteUpdate> { @Override public void setEpochValue(final int epoch, final RouteUpdate routeUpdate) { Objects.requireNonNull(routeUpdate); this.routeUpdateLog.put(epoch, routeUpdate); if (epoch != getCurrentEpoch() + 1) { logger.warn("Specified epoch is not 1 greater than current. epoch={}, currentEpoch={}", epoch, getCurrentEpoch()); } this.currentEpoch.set(epoch); } InMemoryForwardingRoutingTable(); @Override RoutingTableId getRoutingTableId(); @Override int getCurrentEpoch(); @Override List<InterledgerAddressPrefix> getKeysStartingWith(InterledgerAddressPrefix addressPrefix); @Override Iterable<RouteUpdate> getPartialRouteLog(final int numberToSkip, final int limit); @Override void clearRouteInLogAtEpoch(final int epoch); @Override void setEpochValue(final int epoch, final RouteUpdate routeUpdate); }
@Test public void setEpochValue() { assertThat(routingTable.getCurrentEpoch()).isEqualTo(0); routingTable.setEpochValue(1, createRouteUpdate(1, BOB_ACCT, BOB_PREFIX)); assertThat(routingTable.getCurrentEpoch()).isEqualTo(1); routingTable.setEpochValue(2, createRouteUpdate(1, ALICE_ACCT, ALICE_PREFIX)); assertThat(routingTable.getCurrentEpoch()).isEqualTo(2); }
DelegatingEncryptionService implements EncryptionService { @Override public EncryptedSecret encrypt(KeyMetadata keyMetadata, EncryptionAlgorithm encryptionAlgorithm, byte[] plainText) { return getDelegate(keyMetadata).encrypt(keyMetadata, encryptionAlgorithm, plainText); } DelegatingEncryptionService(final Set<EncryptionService> encryptionServices); @Override KeyStoreType keyStoreType(); @Override byte[] decrypt(KeyMetadata keyMetadata, EncryptionAlgorithm encryptionAlgorithm, byte[] cipherMessage); @Override EncryptedSecret encrypt(KeyMetadata keyMetadata, EncryptionAlgorithm encryptionAlgorithm, byte[] plainText); @Override T withDecrypted(EncryptedSecret encryptedSecret, Function<byte[], T> callable); }
@Test public void encrypt() { DelegatingEncryptionService service = new DelegatingEncryptionService(Sets.newHashSet(mockGcp, mockJks)); assertThat(service.encrypt(GCP_SECRET.keyMetadata(), GCP_SECRET.encryptionAlgorithm(), GCP_DECRYPTED)) .isEqualTo(GCP_SECRET); assertThat(service.encrypt(JKS_SECRET.keyMetadata(), JKS_SECRET.encryptionAlgorithm(), JKS_DECRYPTED)) .isEqualTo(JKS_SECRET); } @Test public void encryptThrowsExceptionIfNoProvider() { DelegatingEncryptionService service = new DelegatingEncryptionService(Sets.newHashSet(mockJks)); expectedException.expect(RuntimeException.class); service.encrypt(GCP_SECRET.keyMetadata(), GCP_SECRET.encryptionAlgorithm(), GCP_DECRYPTED); }
InMemoryForwardingRoutingTable extends InMemoryRoutingTable<RouteUpdate> implements ForwardingRoutingTable<RouteUpdate> { @Override public Iterable<RouteUpdate> getPartialRouteLog(final int numberToSkip, final int limit) { return Iterables.limit(Iterables.skip(this.routeUpdateLog.values(), numberToSkip), limit); } InMemoryForwardingRoutingTable(); @Override RoutingTableId getRoutingTableId(); @Override int getCurrentEpoch(); @Override List<InterledgerAddressPrefix> getKeysStartingWith(InterledgerAddressPrefix addressPrefix); @Override Iterable<RouteUpdate> getPartialRouteLog(final int numberToSkip, final int limit); @Override void clearRouteInLogAtEpoch(final int epoch); @Override void setEpochValue(final int epoch, final RouteUpdate routeUpdate); }
@Test public void getPartialRouteLog() { ImmutableRouteUpdate bobRouteUpdate = createRouteUpdate(1, BOB_ACCT, BOB_PREFIX); ImmutableRouteUpdate aliceRouteUpdate = createRouteUpdate(1, ALICE_ACCT, ALICE_PREFIX); routingTable.setEpochValue(1, bobRouteUpdate); routingTable.setEpochValue(2, aliceRouteUpdate); assertThat(routingTable.getPartialRouteLog(0, 10)).hasSize(2) .containsExactlyInAnyOrder(bobRouteUpdate, aliceRouteUpdate); assertThat(routingTable.getPartialRouteLog(1, 10)).hasSize(1) .containsExactlyInAnyOrder(aliceRouteUpdate); assertThat(routingTable.getPartialRouteLog(2, 10)).isEmpty(); }
LocalDestinationAddressPaymentRouter implements PaymentRouter<Route> { @Override public Optional<Route> findBestNexHop(final InterledgerAddress finalDestinationAddress) { Objects.requireNonNull(finalDestinationAddress, "finalDestinationAddress must not be null!"); final Optional<AccountId> accountId; if (localDestinationAddressUtils.isLocalDestinationAddress(finalDestinationAddress)) { final EnabledProtocolSettings enabledProtocolSettings = this.connectorSettingsSupplier.get().enabledProtocols(); if (enabledProtocolSettings.isPingProtocolEnabled() && localDestinationAddressUtils.isAddressForConnectorPingAccount(finalDestinationAddress)) { accountId = this.pingAccountId; } else if (localDestinationAddressUtils.isLocalSpspDestinationAddress(finalDestinationAddress)) { accountId = Optional.of(localDestinationAddressUtils.parseSpspAccountId(finalDestinationAddress)); } else if (localDestinationAddressUtils.isLocalAccountDestinationAddress(finalDestinationAddress)) { accountId = Optional.of(localDestinationAddressUtils.parseLocalAccountId(finalDestinationAddress)); } else { accountId = Optional.empty(); } } else { accountId = Optional.empty(); } return accountId .map($ -> ImmutableRoute.builder() .routePrefix(InterledgerAddressPrefix.of(finalDestinationAddress.getValue())) .nextHopAccountId($) .build() ); } LocalDestinationAddressPaymentRouter( final Supplier<ConnectorSettings> connectorSettingsSupplier, final LocalDestinationAddressUtils localDestinationAddressUtils ); @Override Optional<Route> findBestNexHop(final InterledgerAddress finalDestinationAddress); }
@Test public void findBestNexHopWithNullAddress() { expectedException.expect(NullPointerException.class); expectedException.expectMessage("finalDestinationAddress must not be null!"); localDestinationAddressPaymentRouter.findBestNexHop(null); } @Test public void findBestNexHopWhenNotLocalAddress() { when(localDestinationAddressUtilsMock.isLocalDestinationAddress(any())).thenReturn(false); assertThat(localDestinationAddressPaymentRouter.findBestNexHop(DESTINATION_ADDRESS)).isEmpty(); verify(localDestinationAddressUtilsMock).getConnectorPingAccountId(); verify(localDestinationAddressUtilsMock).isLocalDestinationAddress(any()); verifyNoMoreInteractions(localDestinationAddressUtilsMock); } @Test public void findBestNexHopWhenPingWithPingDisabled() { when(localDestinationAddressUtilsMock.isLocalDestinationAddress(any())).thenReturn(true); when(connectorSettingsMock.enabledProtocols().isPingProtocolEnabled()).thenReturn(false); when(localDestinationAddressUtilsMock.isAddressForConnectorPingAccount(any())).thenReturn(true); assertThat(localDestinationAddressPaymentRouter.findBestNexHop(DESTINATION_ADDRESS)).isEmpty(); verify(localDestinationAddressUtilsMock).getConnectorPingAccountId(); verify(localDestinationAddressUtilsMock).isLocalDestinationAddress(any()); verify(localDestinationAddressUtilsMock).isLocalSpspDestinationAddress(any()); verify(localDestinationAddressUtilsMock).isLocalAccountDestinationAddress(any()); verifyNoMoreInteractions(localDestinationAddressUtilsMock); } @Test public void findBestNexHopWhenLocalWithPingDisabled() { when(localDestinationAddressUtilsMock.isLocalDestinationAddress(any())).thenReturn(true); when(connectorSettingsMock.enabledProtocols().isPingProtocolEnabled()).thenReturn(false); when(localDestinationAddressUtilsMock.isAddressForConnectorPingAccount(any())).thenReturn(false); when(localDestinationAddressUtilsMock.isLocalAccountDestinationAddress(any())).thenReturn(true); when(localDestinationAddressUtilsMock.parseLocalAccountId(any())).thenReturn(AccountId.of("foo")); final Optional<Route> actual = localDestinationAddressPaymentRouter.findBestNexHop(DESTINATION_ADDRESS); assertThat(actual).isPresent(); assertThat(actual.get().nextHopAccountId()).isEqualTo(AccountId.of("foo")); verify(localDestinationAddressUtilsMock).getConnectorPingAccountId(); verify(localDestinationAddressUtilsMock).isLocalDestinationAddress(any()); verify(localDestinationAddressUtilsMock).isLocalSpspDestinationAddress(any()); verify(localDestinationAddressUtilsMock).isLocalAccountDestinationAddress(any()); verify(localDestinationAddressUtilsMock).parseLocalAccountId(any()); verifyNoMoreInteractions(localDestinationAddressUtilsMock); } @Test public void findBestNexHopWhenLocalWithPingEnabledNotPing() { when(localDestinationAddressUtilsMock.isLocalDestinationAddress(any())).thenReturn(true); when(connectorSettingsMock.enabledProtocols().isPingProtocolEnabled()).thenReturn(true); when(localDestinationAddressUtilsMock.isAddressForConnectorPingAccount(any())).thenReturn(false); when(localDestinationAddressUtilsMock.isLocalAccountDestinationAddress(any())).thenReturn(true); when(localDestinationAddressUtilsMock.parseLocalAccountId(any())).thenReturn(AccountId.of("foo")); final Optional<Route> actual = localDestinationAddressPaymentRouter.findBestNexHop(DESTINATION_ADDRESS); assertThat(actual).isPresent(); assertThat(actual.get().nextHopAccountId()).isEqualTo(AccountId.of("foo")); verify(localDestinationAddressUtilsMock).getConnectorPingAccountId(); verify(localDestinationAddressUtilsMock).isLocalDestinationAddress(any()); verify(localDestinationAddressUtilsMock).isAddressForConnectorPingAccount(any()); verify(localDestinationAddressUtilsMock).isLocalSpspDestinationAddress(any()); verify(localDestinationAddressUtilsMock).isLocalAccountDestinationAddress(any()); verify(localDestinationAddressUtilsMock).parseLocalAccountId(any()); verifyNoMoreInteractions(localDestinationAddressUtilsMock); } @Test public void findBestNexHopWhenLocalWithPingEnabledAddressIsPing() { when(localDestinationAddressUtilsMock.isLocalDestinationAddress(any())).thenReturn(true); when(connectorSettingsMock.enabledProtocols().isPingProtocolEnabled()).thenReturn(true); when(localDestinationAddressUtilsMock.isAddressForConnectorPingAccount(any())).thenReturn(true); final Optional<Route> actual = localDestinationAddressPaymentRouter.findBestNexHop(DESTINATION_ADDRESS); assertThat(actual).isNotEmpty(); assertThat(actual.get().nextHopAccountId()).isEqualTo(PING_ACCOUNT_ID); verify(localDestinationAddressUtilsMock).getConnectorPingAccountId(); verify(localDestinationAddressUtilsMock).isLocalDestinationAddress(any()); verify(localDestinationAddressUtilsMock).isAddressForConnectorPingAccount(any()); verifyNoMoreInteractions(localDestinationAddressUtilsMock); } @Test public void findBestNexHopWhenLocalSpspAddress() { final AccountId accountId = AccountId.of("foo"); when(localDestinationAddressUtilsMock.isLocalDestinationAddress(any())).thenReturn(true); when(connectorSettingsMock.enabledProtocols().isPingProtocolEnabled()).thenReturn(false); when(localDestinationAddressUtilsMock.isAddressForConnectorPingAccount(any())).thenReturn(false); when(localDestinationAddressUtilsMock.isLocalSpspDestinationAddress(any())).thenReturn(true); when(localDestinationAddressUtilsMock.parseSpspAccountId(any())).thenReturn(accountId); final Optional<Route> actual = localDestinationAddressPaymentRouter.findBestNexHop(DESTINATION_ADDRESS); assertThat(actual).isNotEmpty(); assertThat(actual.get().nextHopAccountId()).isEqualTo(accountId); verify(localDestinationAddressUtilsMock).getConnectorPingAccountId(); verify(localDestinationAddressUtilsMock).isLocalDestinationAddress(any()); verify(localDestinationAddressUtilsMock).isLocalSpspDestinationAddress(any()); verify(localDestinationAddressUtilsMock).parseSpspAccountId(any()); verifyNoMoreInteractions(localDestinationAddressUtilsMock); } @Test public void findBestNexHopWhenLocalAccountAddress() { final AccountId accountId = AccountId.of("foo"); when(localDestinationAddressUtilsMock.isLocalDestinationAddress(any())).thenReturn(true); when(connectorSettingsMock.enabledProtocols().isPingProtocolEnabled()).thenReturn(false); when(localDestinationAddressUtilsMock.isAddressForConnectorPingAccount(any())).thenReturn(false); when(localDestinationAddressUtilsMock.isLocalSpspDestinationAddress(any())).thenReturn(false); when(localDestinationAddressUtilsMock.isLocalAccountDestinationAddress(any())).thenReturn(true); when(localDestinationAddressUtilsMock.parseLocalAccountId(any())).thenReturn(accountId); final Optional<Route> actual = localDestinationAddressPaymentRouter.findBestNexHop(DESTINATION_ADDRESS); assertThat(actual).isNotEmpty(); assertThat(actual.get().nextHopAccountId()).isEqualTo(accountId); verify(localDestinationAddressUtilsMock).getConnectorPingAccountId(); verify(localDestinationAddressUtilsMock).isLocalDestinationAddress(any()); verify(localDestinationAddressUtilsMock).isLocalSpspDestinationAddress(any()); verify(localDestinationAddressUtilsMock).isLocalAccountDestinationAddress(any()); verify(localDestinationAddressUtilsMock).parseLocalAccountId(any()); verifyNoMoreInteractions(localDestinationAddressUtilsMock); } @Test public void findBestNexHopWhenLocalDestinationButNoSubMatches() { when(localDestinationAddressUtilsMock.isLocalDestinationAddress(any())).thenReturn(true); when(connectorSettingsMock.enabledProtocols().isPingProtocolEnabled()).thenReturn(false); when(localDestinationAddressUtilsMock.isAddressForConnectorPingAccount(any())).thenReturn(false); when(localDestinationAddressUtilsMock.isLocalSpspDestinationAddress(any())).thenReturn(false); when(localDestinationAddressUtilsMock.isLocalAccountDestinationAddress(any())).thenReturn(false); assertThat(localDestinationAddressPaymentRouter.findBestNexHop(DESTINATION_ADDRESS)).isEmpty(); verify(localDestinationAddressUtilsMock).getConnectorPingAccountId(); verify(localDestinationAddressUtilsMock).isLocalDestinationAddress(any()); verify(localDestinationAddressUtilsMock).isLocalSpspDestinationAddress(any()); verify(localDestinationAddressUtilsMock).isLocalAccountDestinationAddress(any()); verifyNoMoreInteractions(localDestinationAddressUtilsMock); }
DefaultRouteBroadcaster implements RouteBroadcaster { @Override public Optional<RoutableAccount> registerCcpEnabledAccount(final AccountId accountId) { Objects.requireNonNull(accountId); return accountSettingsRepository.findByAccountIdWithConversion(accountId) .map(this::registerCcpEnabledAccount) .filter(Optional::isPresent) .map(Optional::get); } DefaultRouteBroadcaster( final Supplier<ConnectorSettings> connectorSettingsSupplier, final CodecContext ccpCodecContext, final ForwardingRoutingTable<RouteUpdate> outgoingRoutingTable, final AccountSettingsRepository accountSettingsRepository, final LinkManager linkManager, final ExecutorService executorService ); @Override Optional<RoutableAccount> registerCcpEnabledAccount(final AccountId accountId); @Override Optional<RoutableAccount> registerCcpEnabledAccount(final AccountSettings accountSettings); @Override Optional<RoutableAccount> getCcpEnabledAccount(final AccountId accountId); @Override Stream<RoutableAccount> getAllCcpEnabledAccounts(); }
@Test public void registerCcpEnabledAccountWithNullId() { expectedException.expect(NullPointerException.class); AccountId nullAccountId = null; defaultRouteBroadcaster.registerCcpEnabledAccount(nullAccountId); } @Test public void registerCcpEnabledAccountSendFalseReceiveFalse() { final AccountSettings accountSettings = accountSettings(false, false); when(accountSettingsRepositoryMock.findByAccountIdWithConversion(any())) .thenReturn(Optional.of(accountSettings)); assertThat(defaultRouteBroadcaster.registerCcpEnabledAccount(ACCOUNT_ID_1)).isEmpty(); Mockito.verifyNoInteractions(link); Mockito.verifyNoInteractions(executorServiceMock); } @Test public void registerCcpEnabledAccountSendTrueReceiveFalse() { final AccountSettings accountSettings = accountSettings(true, false); when(accountSettingsRepositoryMock.findByAccountIdWithConversion(any())) .thenReturn(Optional.of(accountSettings)); final Optional<RoutableAccount> optRoutableAccount = defaultRouteBroadcaster .registerCcpEnabledAccount(ACCOUNT_ID_1); assertThat(optRoutableAccount).isNotEmpty(); final RoutableAccount routableAccount = optRoutableAccount.get(); assertThat(routableAccount.accountId()).isEqualTo(ACCOUNT_ID_1); Mockito.verifyNoInteractions(link); Mockito.verifyNoInteractions(executorServiceMock); } @Test public void registerCcpEnabledAccountSendFalseReceiveTrue() { final AccountSettings accountSettings = accountSettings(false, true); when(accountSettingsRepositoryMock.findByAccountIdWithConversion(Mockito.any())) .thenReturn(Optional.of(accountSettings)); final Optional<RoutableAccount> optRoutableAccount = defaultRouteBroadcaster .registerCcpEnabledAccount(ACCOUNT_ID_1); assertThat(optRoutableAccount).isNotEmpty(); final RoutableAccount routableAccount = optRoutableAccount.get(); assertThat(routableAccount.accountId()).isEqualTo(ACCOUNT_ID_1); Mockito.verifyNoInteractions(link); Mockito.verify(executorServiceMock).submit(Mockito.<Callable>any()); Mockito.verifyNoMoreInteractions(executorServiceMock); } @Test public void registerCcpEnabledAccountSendTrueReceiveTrue() { final AccountSettings accountSettings = accountSettings(true, true); when(accountSettingsRepositoryMock.findByAccountIdWithConversion(Mockito.any())) .thenReturn(Optional.of(accountSettings)); final Optional<RoutableAccount> optRoutableAccount = defaultRouteBroadcaster .registerCcpEnabledAccount(ACCOUNT_ID_1); assertThat(optRoutableAccount).isNotEmpty(); final RoutableAccount routableAccount = optRoutableAccount.get(); assertThat(routableAccount.accountId()).isEqualTo(ACCOUNT_ID_1); Mockito.verifyNoInteractions(link); Mockito.verify(executorServiceMock).submit(Mockito.<Callable>any()); Mockito.verifyNoMoreInteractions(executorServiceMock); } @Test public void registerCcpEnabledAccountTwiceWithReceiveTrue() { final AccountSettings accountSettings = accountSettings(true, true); when(accountSettingsRepositoryMock.findByAccountIdWithConversion(Mockito.any())) .thenReturn(Optional.of(accountSettings)); Optional<RoutableAccount> optRoutableAccount = defaultRouteBroadcaster.registerCcpEnabledAccount(ACCOUNT_ID_1); assertThat(optRoutableAccount).isNotEmpty(); optRoutableAccount = defaultRouteBroadcaster.registerCcpEnabledAccount(ACCOUNT_ID_1); assertThat(optRoutableAccount).isNotEmpty(); final RoutableAccount routableAccount = optRoutableAccount.get(); assertThat(routableAccount.accountId()).isEqualTo(ACCOUNT_ID_1); Mockito.verifyNoInteractions(link); Mockito.verify(executorServiceMock, times(2)).submit(Mockito.<Callable>any()); Mockito.verifyNoMoreInteractions(executorServiceMock); } @Test public void registerCcpEnabledAccountTwiceWithReceiveFalse() { final AccountSettings accountSettings = accountSettings(true, false); when(accountSettingsRepositoryMock.findByAccountIdWithConversion(Mockito.any())) .thenReturn(Optional.of(accountSettings)); Optional<RoutableAccount> optRoutableAccount = defaultRouteBroadcaster.registerCcpEnabledAccount(ACCOUNT_ID_1); assertThat(optRoutableAccount).isNotEmpty(); optRoutableAccount = defaultRouteBroadcaster.registerCcpEnabledAccount(ACCOUNT_ID_1); assertThat(optRoutableAccount).isNotEmpty(); final RoutableAccount routableAccount = optRoutableAccount.get(); assertThat(routableAccount.accountId()).isEqualTo(ACCOUNT_ID_1); Mockito.verifyNoInteractions(link); Mockito.verifyNoInteractions(executorServiceMock); }
DefaultRouteBroadcaster implements RouteBroadcaster { @Override public Optional<RoutableAccount> getCcpEnabledAccount(final AccountId accountId) { Objects.requireNonNull(accountId); return Optional.ofNullable(this.ccpEnabledAccounts.get(accountId)); } DefaultRouteBroadcaster( final Supplier<ConnectorSettings> connectorSettingsSupplier, final CodecContext ccpCodecContext, final ForwardingRoutingTable<RouteUpdate> outgoingRoutingTable, final AccountSettingsRepository accountSettingsRepository, final LinkManager linkManager, final ExecutorService executorService ); @Override Optional<RoutableAccount> registerCcpEnabledAccount(final AccountId accountId); @Override Optional<RoutableAccount> registerCcpEnabledAccount(final AccountSettings accountSettings); @Override Optional<RoutableAccount> getCcpEnabledAccount(final AccountId accountId); @Override Stream<RoutableAccount> getAllCcpEnabledAccounts(); }
@Test public void getCcpEnabledAccount() { assertThat(defaultRouteBroadcaster.getCcpEnabledAccount(ACCOUNT_ID_1)).isEmpty(); Optional<RoutableAccount> optRoutableAccount = defaultRouteBroadcaster.registerCcpEnabledAccount(ACCOUNT_ID_1); assertThat(optRoutableAccount).isNotEmpty(); assertThat(defaultRouteBroadcaster.getCcpEnabledAccount(ACCOUNT_ID_1)).isEqualTo(optRoutableAccount); }
DefaultRouteBroadcaster implements RouteBroadcaster { @Override public Stream<RoutableAccount> getAllCcpEnabledAccounts() { return this.ccpEnabledAccounts.values().stream(); } DefaultRouteBroadcaster( final Supplier<ConnectorSettings> connectorSettingsSupplier, final CodecContext ccpCodecContext, final ForwardingRoutingTable<RouteUpdate> outgoingRoutingTable, final AccountSettingsRepository accountSettingsRepository, final LinkManager linkManager, final ExecutorService executorService ); @Override Optional<RoutableAccount> registerCcpEnabledAccount(final AccountId accountId); @Override Optional<RoutableAccount> registerCcpEnabledAccount(final AccountSettings accountSettings); @Override Optional<RoutableAccount> getCcpEnabledAccount(final AccountId accountId); @Override Stream<RoutableAccount> getAllCcpEnabledAccounts(); }
@Test public void getAllCcpEnabledAccounts() { assertThat(defaultRouteBroadcaster.getAllCcpEnabledAccounts()).isEmpty(); defaultRouteBroadcaster.registerCcpEnabledAccount(ACCOUNT_ID_1); assertThat(defaultRouteBroadcaster.getAllCcpEnabledAccounts()).hasSize(1); defaultRouteBroadcaster.registerCcpEnabledAccount(ACCOUNT_ID_2); assertThat(defaultRouteBroadcaster.getAllCcpEnabledAccounts()).hasSize(2); defaultRouteBroadcaster.removeAccount(ACCOUNT_ID_1); assertThat(defaultRouteBroadcaster.getCcpEnabledAccount(ACCOUNT_ID_1)).isEmpty(); assertThat(defaultRouteBroadcaster.getCcpEnabledAccount(ACCOUNT_ID_2)).isNotEmpty(); assertThat(defaultRouteBroadcaster.getAllCcpEnabledAccounts()).hasSize(1); defaultRouteBroadcaster.removeAccount(ACCOUNT_ID_2); assertThat(defaultRouteBroadcaster.getCcpEnabledAccount(ACCOUNT_ID_1)).isEmpty(); assertThat(defaultRouteBroadcaster.getCcpEnabledAccount(ACCOUNT_ID_2)).isEmpty(); assertThat(defaultRouteBroadcaster.getAllCcpEnabledAccounts()).isEmpty(); }
InterledgerAddressPrefixMap { public R putEntry(final InterledgerAddressPrefix addressPrefix, final R entry) { Objects.requireNonNull(entry); synchronized (prefixMap) { return prefixMap.put(toTrieKey(addressPrefix), entry); } } InterledgerAddressPrefixMap(); int getNumKeys(); R putEntry(final InterledgerAddressPrefix addressPrefix, final R entry); Optional<R> removeEntry(final InterledgerAddressPrefix addressPrefix); void reset(); Optional<R> getEntry(final InterledgerAddressPrefix addressPrefix); Set<InterledgerAddressPrefix> getKeys(); void forEach(final BiConsumer<? super InterledgerAddressPrefix, R> action); Optional<R> findNextHop(final InterledgerAddress finalDestinationAddress); }
@Test(expected = NullPointerException.class) public void testAddRoutingTableEntryNull() { try { prefixMap.putEntry(null, null); } catch (NullPointerException npe) { assertThat(npe.getMessage()).isNull(); throw npe; } }
DelegatingEncryptionService implements EncryptionService { @Override public <T> T withDecrypted(EncryptedSecret encryptedSecret, Function<byte[], T> callable) { return getDelegate(encryptedSecret.keyMetadata()).withDecrypted(encryptedSecret, callable); } DelegatingEncryptionService(final Set<EncryptionService> encryptionServices); @Override KeyStoreType keyStoreType(); @Override byte[] decrypt(KeyMetadata keyMetadata, EncryptionAlgorithm encryptionAlgorithm, byte[] cipherMessage); @Override EncryptedSecret encrypt(KeyMetadata keyMetadata, EncryptionAlgorithm encryptionAlgorithm, byte[] plainText); @Override T withDecrypted(EncryptedSecret encryptedSecret, Function<byte[], T> callable); }
@Test public void withDecrypted() { DelegatingEncryptionService service = new DelegatingEncryptionService(Sets.newHashSet(mockGcp, mockJks)); assertThat(service.withDecrypted(GCP_SECRET, regurgitate)).isEqualTo(GCP_DECRYPTED); assertThat(service.withDecrypted(JKS_SECRET,regurgitate)).isEqualTo(JKS_DECRYPTED); } @Test public void withDecryptedThrowsExceptionIfNoProvider() { DelegatingEncryptionService service = new DelegatingEncryptionService(Sets.newHashSet(mockJks)); expectedException.expect(RuntimeException.class); service.withDecrypted(GCP_SECRET, regurgitate); }
InterledgerAddressPrefixMap { public Optional<R> getEntry(final InterledgerAddressPrefix addressPrefix) { Objects.requireNonNull(addressPrefix, "addressPrefix must not be null!"); return Optional.ofNullable(this.prefixMap.get(toTrieKey(addressPrefix))); } InterledgerAddressPrefixMap(); int getNumKeys(); R putEntry(final InterledgerAddressPrefix addressPrefix, final R entry); Optional<R> removeEntry(final InterledgerAddressPrefix addressPrefix); void reset(); Optional<R> getEntry(final InterledgerAddressPrefix addressPrefix); Set<InterledgerAddressPrefix> getKeys(); void forEach(final BiConsumer<? super InterledgerAddressPrefix, R> action); Optional<R> findNextHop(final InterledgerAddress finalDestinationAddress); }
@Test(expected = NullPointerException.class) public void testGetRoutingTableEntryNull() { try { prefixMap.getEntry(null); } catch (NullPointerException npe) { assertThat(npe.getMessage()).isEqualTo("addressPrefix must not be null!"); throw npe; } }
InterledgerAddressPrefixMap { public void forEach(final BiConsumer<? super InterledgerAddressPrefix, R> action) { Objects.requireNonNull(action); final BiConsumer<String, R> translatedAction = (ilpPrefixAsString, entry) -> { final String strippedPrefix; if (ilpPrefixAsString.endsWith(".")) { strippedPrefix = ilpPrefixAsString.substring(0, ilpPrefixAsString.length() - 1); } else { strippedPrefix = ilpPrefixAsString; } action.accept(InterledgerAddressPrefix.of(strippedPrefix), entry); }; prefixMap.forEach(translatedAction); } InterledgerAddressPrefixMap(); int getNumKeys(); R putEntry(final InterledgerAddressPrefix addressPrefix, final R entry); Optional<R> removeEntry(final InterledgerAddressPrefix addressPrefix); void reset(); Optional<R> getEntry(final InterledgerAddressPrefix addressPrefix); Set<InterledgerAddressPrefix> getKeys(); void forEach(final BiConsumer<? super InterledgerAddressPrefix, R> action); Optional<R> findNextHop(final InterledgerAddress finalDestinationAddress); }
@Test public void testForEach() { final Route globalRoutingTableEntry = ImmutableRoute.builder() .routePrefix(DEFAULT_TARGET_ADDRESS_PREFIX) .nextHopAccountId(DEFAULT_CONNECTOR_ACCOUNT) .build(); prefixMap.putEntry(globalRoutingTableEntry.routePrefix(), globalRoutingTableEntry); final Route globalRoutingTableEntry2 = ImmutableRoute.builder() .routePrefix(DEFAULT_TARGET_ADDRESS_PREFIX.with("foo")) .nextHopAccountId(DEFAULT_CONNECTOR_ACCOUNT) .build(); prefixMap.putEntry(globalRoutingTableEntry2.routePrefix(), globalRoutingTableEntry2); final AtomicInteger atomicInteger = new AtomicInteger(); prefixMap.forEach((targetAddress, routingTableEntry) -> atomicInteger.getAndIncrement()); assertThat(atomicInteger.get()).isEqualTo(2); }
InterledgerAddressPrefixMap { public Set<InterledgerAddressPrefix> getKeys() { return this.prefixMap.keySet().stream() .map(this::stripTrailingDot) .map(InterledgerAddressPrefix::of) .collect(Collectors.toSet()); } InterledgerAddressPrefixMap(); int getNumKeys(); R putEntry(final InterledgerAddressPrefix addressPrefix, final R entry); Optional<R> removeEntry(final InterledgerAddressPrefix addressPrefix); void reset(); Optional<R> getEntry(final InterledgerAddressPrefix addressPrefix); Set<InterledgerAddressPrefix> getKeys(); void forEach(final BiConsumer<? super InterledgerAddressPrefix, R> action); Optional<R> findNextHop(final InterledgerAddress finalDestinationAddress); }
@Test public void testGetPrefixMapKeys() { this.prefixMap = this.constructPopulatedPrefixMap(); assertThat(this.prefixMap.getKeys().size()).isEqualTo(5); }
InterledgerAddressPrefixMap { public Optional<R> findNextHop(final InterledgerAddress finalDestinationAddress) { Objects.requireNonNull(finalDestinationAddress); return this.findLongestPrefix(InterledgerAddressPrefix.from(finalDestinationAddress)) .map(this::getEntry) .orElse(Optional.empty()); } InterledgerAddressPrefixMap(); int getNumKeys(); R putEntry(final InterledgerAddressPrefix addressPrefix, final R entry); Optional<R> removeEntry(final InterledgerAddressPrefix addressPrefix); void reset(); Optional<R> getEntry(final InterledgerAddressPrefix addressPrefix); Set<InterledgerAddressPrefix> getKeys(); void forEach(final BiConsumer<? super InterledgerAddressPrefix, R> action); Optional<R> findNextHop(final InterledgerAddress finalDestinationAddress); }
@Test public void testGetNextHopRoutingTableEntryWithNoRoutingTableEntrysInMap() { assertThat(prefixMap.findNextHop(DEFAULT_CONNECTOR_ADDRESS.with("bob")).isPresent()).isFalse(); } @Test public void testGetNextHopRoutingTableEntryWithDifferringLengthsInTable() { this.prefixMap = this.constructPopulatedPrefixMap(); assertThat(prefixMap.findNextHop(InterledgerAddress.of("self.me")).isPresent()).isFalse(); assertThat(prefixMap.findNextHop(InterledgerAddress.of("g.1.me")).isPresent()).isTrue(); assertThat(prefixMap.findNextHop(InterledgerAddress.of("g.1.m")).isPresent()).isTrue(); assertThat(prefixMap.findNextHop(InterledgerAddress.of("g.1")).isPresent()).isTrue(); assertThat(prefixMap.findNextHop(InterledgerAddress.of("g.2")).isPresent()).isTrue(); assertThat(prefixMap.findNextHop(InterledgerAddress.of("g.foo.bob")).isPresent()).isTrue(); assertThat(prefixMap.findNextHop(InterledgerAddress.of("g.bar.bob")).isPresent()).isTrue(); assertThat(prefixMap.findNextHop(InterledgerAddress.of("g.baz.boo.alice")).isPresent()).isTrue(); assertThat(prefixMap.findNextHop(InterledgerAddress.of("g.baz.boo.bob")).isPresent()).isTrue(); assertThat(prefixMap.findNextHop(InterledgerAddress.of("g.baz.boo.bar.alice")).isPresent()).isTrue(); assertThat(prefixMap.findNextHop(InterledgerAddress.of("g.baz.boo.bar.bob")).isPresent()).isTrue(); }
InterledgerAddressPrefixMap { @VisibleForTesting protected Optional<InterledgerAddressPrefix> findLongestPrefix( final InterledgerAddressPrefix destinationAddressPrefix ) { Objects.requireNonNull(destinationAddressPrefix, "destinationAddressPrefix must not be null!"); String destinationPrefixKey = toTrieKey(destinationAddressPrefix); final SortedMap<String, R> prefixSubMap = filterLongerPrefixes(destinationPrefixKey, prefixMap.prefixMap(destinationPrefixKey)); if (prefixSubMap.isEmpty() && destinationAddressPrefix.hasPrefix()) { return destinationAddressPrefix.getPrefix() .map(parentPrefix -> { final Optional<InterledgerAddressPrefix> longestMatch = this.findLongestPrefix(parentPrefix); if (longestMatch.isPresent()) { return longestMatch; } else { return this.findLongestPrefix(destinationAddressPrefix.getRootPrefix()); } }) .orElse(Optional.empty()); } else { return prefixSubMap.keySet().stream() .filter(val -> val.length() <= (destinationAddressPrefix.getValue().length() + 1)) .distinct() .map(prefix -> prefix.substring(0, prefix.length() - 1)) .map(InterledgerAddressPrefix::of) .collect(Collectors.reducing((a, b) -> { logger.error( "Routing table has more than one longest-match! This should never happen!" ); return null; }) ); } } InterledgerAddressPrefixMap(); int getNumKeys(); R putEntry(final InterledgerAddressPrefix addressPrefix, final R entry); Optional<R> removeEntry(final InterledgerAddressPrefix addressPrefix); void reset(); Optional<R> getEntry(final InterledgerAddressPrefix addressPrefix); Set<InterledgerAddressPrefix> getKeys(); void forEach(final BiConsumer<? super InterledgerAddressPrefix, R> action); Optional<R> findNextHop(final InterledgerAddress finalDestinationAddress); }
@Test public void testFindLongestPrefixWithNullAddressPrefix() { expectedException.expect(NullPointerException.class); expectedException.expectMessage("destinationAddressPrefix must not be null!"); this.prefixMap = constructPopulatedPrefixMap(); final InterledgerAddressPrefix nullAddress = null; prefixMap.findLongestPrefix(nullAddress); } @Test public void testFindLongestPrefixWithNonPrefix() { expectedException.expect(IllegalArgumentException.class); expectedException.expectMessage("An InterledgerAddressPrefix MUST not end with a period (.) character"); this.prefixMap = constructPopulatedPrefixMap(); prefixMap.findLongestPrefix(InterledgerAddressPrefix.of("g.foo.")); } @Test public void testFindLongestPrefix() { this.prefixMap = constructPopulatedPrefixMap(); assertThat(prefixMap.findLongestPrefix(InterledgerAddressPrefix.of("g.b")).get().getValue()).isEqualTo("g"); assertThat(prefixMap.findLongestPrefix(InterledgerAddressPrefix.of("g.bo")).get().getValue()).isEqualTo("g"); assertThat(prefixMap.findLongestPrefix(InterledgerAddressPrefix.of("g.bob")).get().getValue()).isEqualTo("g"); assertThat(prefixMap.findLongestPrefix(InterledgerAddressPrefix.of("g.b")).get().getValue()).isEqualTo("g"); assertThat(prefixMap.findLongestPrefix(InterledgerAddressPrefix.of("g.f")).get().getValue()).isEqualTo("g"); assertThat(prefixMap.findLongestPrefix(InterledgerAddressPrefix.of("g.fool")).get().getValue()).isEqualTo("g"); assertThat(prefixMap.findLongestPrefix(InterledgerAddressPrefix.of("g.foo.a")).get().getValue()).isEqualTo("g.foo"); assertThat(prefixMap.findLongestPrefix(InterledgerAddressPrefix.of("g.foo.b")).get().getValue()).isEqualTo("g.foo"); assertThat(prefixMap.findLongestPrefix(InterledgerAddressPrefix.of("g.foo.bo")).get().getValue()).isEqualTo("g.foo"); assertThat(prefixMap.findLongestPrefix(InterledgerAddressPrefix.of("g.foo.alice")).get().getValue()).isEqualTo("g.foo"); assertThat(prefixMap.findLongestPrefix(InterledgerAddressPrefix.of("g.foo.bob")).get().getValue()).isEqualTo("g.foo"); assertThat(prefixMap.findLongestPrefix(InterledgerAddressPrefix.of("g.foo.foo")).get().getValue()).isEqualTo("g.foo"); assertThat(prefixMap.findLongestPrefix(InterledgerAddressPrefix.of("g.foo.bar")).get().getValue()).isEqualTo("g.foo"); assertThat(prefixMap.findLongestPrefix(InterledgerAddressPrefix.of("g.foo.fool")).get().getValue()).isEqualTo("g.foo"); assertThat(prefixMap.findLongestPrefix(InterledgerAddressPrefix.of("g.bar.a")).get().getValue()).isEqualTo("g.bar"); assertThat(prefixMap.findLongestPrefix(InterledgerAddressPrefix.of("g.bar.b")).get().getValue()).isEqualTo("g.bar"); assertThat(prefixMap.findLongestPrefix(InterledgerAddressPrefix.of("g.bar.bo")).get().getValue()).isEqualTo("g.bar"); assertThat(prefixMap.findLongestPrefix(InterledgerAddressPrefix.of("g.bar.alice")).get().getValue()).isEqualTo("g.bar"); assertThat(prefixMap.findLongestPrefix(InterledgerAddressPrefix.of("g.bar.bob")).get().getValue()).isEqualTo("g.bar"); assertThat(prefixMap.findLongestPrefix(InterledgerAddressPrefix.of("g.bar.foo")).get().getValue()).isEqualTo("g.bar"); assertThat(prefixMap.findLongestPrefix(InterledgerAddressPrefix.of("g.bart")).get().getValue()).isEqualTo("g"); assertThat(prefixMap.findLongestPrefix(InterledgerAddressPrefix.of("g.baz.boo.a")).get().getValue()).isEqualTo("g.baz.boo"); assertThat(prefixMap.findLongestPrefix(InterledgerAddressPrefix.of("g.baz.boo.b")).get().getValue()).isEqualTo("g.baz.boo"); assertThat(prefixMap.findLongestPrefix(InterledgerAddressPrefix.of("g.baz.boo.bo")).get().getValue()).isEqualTo("g.baz.boo"); assertThat(prefixMap.findLongestPrefix(InterledgerAddressPrefix.of("g.baz.boo.alice")).get().getValue()).isEqualTo("g.baz.boo"); assertThat(prefixMap.findLongestPrefix(InterledgerAddressPrefix.of("g.baz.boo.bob")).get().getValue()).isEqualTo("g.baz.boo"); assertThat(prefixMap.findLongestPrefix(InterledgerAddressPrefix.of("g.baz.boo.foo")).get().getValue()).isEqualTo("g.baz.boo"); assertThat(prefixMap.findLongestPrefix(InterledgerAddressPrefix.of("g.baz.bool")).get().getValue()).isEqualTo("g"); assertThat(prefixMap.findLongestPrefix(InterledgerAddressPrefix.of("g.bazl")).get().getValue()).isEqualTo("g"); assertThat(prefixMap.findLongestPrefix(InterledgerAddressPrefix.of("g.baz.boo.bar.a")).get().getValue()).isEqualTo("g.baz.boo.bar"); assertThat(prefixMap.findLongestPrefix(InterledgerAddressPrefix.of("g.baz.boo.bar.b")).get().getValue()).isEqualTo("g.baz.boo.bar"); assertThat(prefixMap.findLongestPrefix(InterledgerAddressPrefix.of("g.baz.boo.bar.bo")).get().getValue()).isEqualTo("g.baz.boo.bar"); assertThat(prefixMap.findLongestPrefix(InterledgerAddressPrefix.of("g.baz.boo.bar.alice")).get().getValue()).isEqualTo("g.baz.boo.bar"); assertThat(prefixMap.findLongestPrefix(InterledgerAddressPrefix.of("g.baz.boo.bar.bob")).get().getValue()).isEqualTo("g.baz.boo.bar"); assertThat(prefixMap.findLongestPrefix(InterledgerAddressPrefix.of("g.baz.boo.bar.foo")).get().getValue()).isEqualTo("g.baz.boo.bar"); assertThat(prefixMap.findLongestPrefix(InterledgerAddressPrefix.of("g.baz.bool.bart")).get().getValue()).isEqualTo("g"); assertThat(prefixMap.findLongestPrefix(InterledgerAddressPrefix.of("g.bazl.boo.bar")).get().getValue()).isEqualTo("g"); assertThat(prefixMap.findLongestPrefix(InterledgerAddressPrefix.of("g.notfound.a")).get().getValue()).isEqualTo("g"); assertThat(prefixMap.findLongestPrefix(InterledgerAddressPrefix.of("g.notfound.b")).get().getValue()).isEqualTo("g"); assertThat(prefixMap.findLongestPrefix(InterledgerAddressPrefix.of("g.notfound.bo")).get().getValue()).isEqualTo("g"); assertThat(prefixMap.findLongestPrefix(InterledgerAddressPrefix.of("g.notfound.alice")).get().getValue()).isEqualTo("g"); assertThat(prefixMap.findLongestPrefix(InterledgerAddressPrefix.of("g.notfound.bob")).get().getValue()).isEqualTo("g"); assertThat(prefixMap.findLongestPrefix(InterledgerAddressPrefix.of("g.notfound.foo")).get().getValue()).isEqualTo("g"); assertThat(prefixMap.findLongestPrefix(InterledgerAddressPrefix.of("g.1.b")).get().getValue()).isEqualTo("g"); assertThat(prefixMap.findLongestPrefix(InterledgerAddressPrefix.of("g.1.bo")).get().getValue()).isEqualTo("g"); assertThat(prefixMap.findLongestPrefix(InterledgerAddressPrefix.of("g.1.bob")).get().getValue()).isEqualTo("g"); assertThat(prefixMap.findLongestPrefix(InterledgerAddressPrefix.of("g.1.b")).get().getValue()).isEqualTo("g"); assertThat(prefixMap.findLongestPrefix(InterledgerAddressPrefix.of("g.1.f")).get().getValue()).isEqualTo("g"); assertThat(prefixMap.findLongestPrefix(InterledgerAddressPrefix.of("g.1.foo")).get().getValue()).isEqualTo("g"); assertThat(prefixMap.findLongestPrefix(InterledgerAddressPrefix.of("g.11")).get().getValue()).isEqualTo("g"); assertThat(prefixMap.findLongestPrefix(InterledgerAddressPrefix.of("g.22")).get().getValue()).isEqualTo("g"); }
InMemoryRoutingTable implements RoutingTable<R> { @Override public R addRoute(final R route) { Objects.requireNonNull(route); return this.interledgerAddressPrefixMap.putEntry(route.routePrefix(), route); } InMemoryRoutingTable(); InMemoryRoutingTable(final InterledgerAddressPrefixMap interledgerAddressPrefixMap); @Override R addRoute(final R route); @Override Optional<R> removeRoute(final InterledgerAddressPrefix addressPrefix); @Override Optional<R> getRouteByPrefix(final InterledgerAddressPrefix addressPrefix); @Override Iterable<InterledgerAddressPrefix> getAllPrefixes(); @Override void forEach(final BiConsumer<InterledgerAddressPrefix, R> action); @Override Optional<R> findNextHopRoute(final InterledgerAddress interledgerAddress); @Override void reset(); }
@Test(expected = NullPointerException.class) public void testAddRouteNull() { try { this.routingTable.addRoute(null); } catch (NullPointerException e) { throw e; } } @Test public void testAddRoute() { final Route route = this.constructTestRoute(GLOBAL_PREFIX); this.routingTable.addRoute(route); verify(interledgerPrefixMapMock).putEntry(route.routePrefix(), route); verifyNoMoreInteractions(interledgerPrefixMapMock); }
AttractionCollection { public int getHeaderTitle() { return headerTitle; } AttractionCollection(int headerTextResId, List<Attraction> listOfAttractions); int getHeaderTitle(); List<Attraction> getAttractions(); }
@Test public void saveResIdAsHeaderTitle() { assertThat(subject.getHeaderTitle(), is(TEST_HEADER)); }
AttractionRepository { @VisibleForTesting static AttractionCollection buildNightLifeCollection() { ArrayList<Attraction> attractions = new ArrayList<>(); attractions.add(new Attraction( R.drawable.social, R.string.social_title, R.string.creative_cocktails, R.string.social_detailed_desc, R.string.mq_social ) ); attractions.add(new Attraction( R.drawable.mayor_old_town, R.string.mayor_old_town_title, R.string.mayor_great_selction, R.string.mayor_of_old_town_detailed_desc, R.string.mq_mayor_old_town ) ); attractions.add(new Attraction( R.drawable.colorado_room, R.string.colorado_room_title, R.string.colorado_beers_and_spirits, R.string.the_colorado_room_detailed_desc, R.string.mq_the_colorado_room ) ); attractions.add(new Attraction( R.drawable.ace_gilletts, R.string.ace_gilletts_title, R.string.gilletts_crafted_beers, R.string.ace_gilletts_detailed_desc, R.string.mq_ace_gilletts ) ); attractions.add(new Attraction( R.drawable.elliot_martini_bar, R.string.elliots_martini_title, R.string.elliot_martini_variety, R.string.elliot_martini_bar_detailed_desc, R.string.mq_elliot_martini_bar ) ); return new AttractionCollection(R.string.top_bars_nightlife, attractions); } private AttractionRepository(Context context); static AttractionRepository getInstance(Context packageContext); AttractionCollection getCollection(int sectionTitle); List<AttractionCollection> getCollections(); }
@Test public void saveAsAttractionCollection_buildNightLifeCollection() { assertThat(AttractionRepository.buildNightLifeCollection(), instanceOf(AttractionCollection.class)); }
AttractionCollection { public List<Attraction> getAttractions() { return listOfAttractions; } AttractionCollection(int headerTextResId, List<Attraction> listOfAttractions); int getHeaderTitle(); List<Attraction> getAttractions(); }
@Test public void savesAttractionType_getAttractions() { assertThat(subject.getAttractions().get(0), isA(Attraction.class)); } @Test public void returnsAList_getAttractions() { assertThat(subject.getAttractions(), instanceOf(List.class)); }
Attraction implements Parcelable { public int getImageResourceId() { return imageResourceId; } Attraction(int imageResourceId, int titleTextResId, int shortDescTextResId, int longDescTextResId, int mapQueryStrId); protected Attraction(Parcel in); @Override int describeContents(); @Override void writeToParcel(Parcel dest, int flags); int getImageResourceId(); int getTitle(); int getShortDesc(); int getLongDesc(); int getMapQueryStrId(); static final Creator<Attraction> CREATOR; }
@Test public void storesResIdForImage() { assertThat(subject.getImageResourceId(), is(TEST_IMAGE)); }
Attraction implements Parcelable { public int getTitle() { return titleTextResId; } Attraction(int imageResourceId, int titleTextResId, int shortDescTextResId, int longDescTextResId, int mapQueryStrId); protected Attraction(Parcel in); @Override int describeContents(); @Override void writeToParcel(Parcel dest, int flags); int getImageResourceId(); int getTitle(); int getShortDesc(); int getLongDesc(); int getMapQueryStrId(); static final Creator<Attraction> CREATOR; }
@Test public void storesResIdAsTitle() { assertThat(subject.getTitle(), is(TEST_TITLE)); }
Attraction implements Parcelable { public int getShortDesc() { return shortDescTextResId; } Attraction(int imageResourceId, int titleTextResId, int shortDescTextResId, int longDescTextResId, int mapQueryStrId); protected Attraction(Parcel in); @Override int describeContents(); @Override void writeToParcel(Parcel dest, int flags); int getImageResourceId(); int getTitle(); int getShortDesc(); int getLongDesc(); int getMapQueryStrId(); static final Creator<Attraction> CREATOR; }
@Test public void storesResIdAsShortDesc() { assertThat(subject.getShortDesc(), is(TEST_SHORT_DESC)); }
Attraction implements Parcelable { public int getLongDesc() { return longDescTextResId; } Attraction(int imageResourceId, int titleTextResId, int shortDescTextResId, int longDescTextResId, int mapQueryStrId); protected Attraction(Parcel in); @Override int describeContents(); @Override void writeToParcel(Parcel dest, int flags); int getImageResourceId(); int getTitle(); int getShortDesc(); int getLongDesc(); int getMapQueryStrId(); static final Creator<Attraction> CREATOR; }
@Test public void storesResIdAsLongDesc() { assertThat(subject.getLongDesc(), is(TEST_LONG_DESC)); }
AttractionRepository { @VisibleForTesting static AttractionCollection buildActivityCollection() { List<Attraction> attractions = new ArrayList<>(); attractions.add(new Attraction( R.drawable.horsetooth_mountain_park, R.string.horsetooth_mountain_title, R.string.scenic_open_space, R.string.horsetooth_mountain_park_detailed_desc, R.string.mq_horestooth_mountain_park ) ); attractions.add(new Attraction( R.drawable.whitewater_rafting, R.string.mountain_whitewater_title, R.string.white_water_rafting, R.string.mountain_whitewater_descents_detailed_desc, R.string.mq_mountain_whitewater ) ); attractions.add(new Attraction( R.drawable.flower_trail_garden, R.string.flower_trial_garden_title, R.string.horticulture_display, R.string.flower_trail_garden_detailed_desc, R.string.mq_annual_flower_trial_garden ) ); attractions.add(new Attraction( R.drawable.horsetooth_reservoir, R.string.horsetooth_reservoir_title, R.string.best_outdoors, R.string.horsetooth_reservoir_detailed_desc, R.string.mq_horestooth_reservoir ) ); attractions.add(new Attraction( R.drawable.city_park, R.string.city_park_title, R.string.ideal_relaxing_spot, R.string.city_park_detailed_desc, R.string.mq_city_park ) ); return new AttractionCollection(R.string.top_activities, attractions); } private AttractionRepository(Context context); static AttractionRepository getInstance(Context packageContext); AttractionCollection getCollection(int sectionTitle); List<AttractionCollection> getCollections(); }
@Test public void saveAsAttractionCollection_buildActivityCollection() { assertThat(AttractionRepository.buildActivityCollection(), instanceOf(AttractionCollection.class)); }
AttractionRepository { @VisibleForTesting static AttractionCollection buildRestaurantsCollection() { ArrayList<Attraction> attractions = new ArrayList<>(); attractions.add(new Attraction( R.drawable.the_melting_pot, R.string.melting_pot_title, R.string.amazing_fondue, R.string.the_melting_pot_detailed_desc, R.string.mq_the_melting_pot ) ); attractions.add(new Attraction( R.drawable.maza_kabob, R.string.maza_kabob_title, R.string.afghan_specialty, R.string.maza_kabob_detailed_desc, R.string.mq_maza_kabob ) ); attractions.add(new Attraction( R.drawable.rio_grande, R.string.rio_grande_title, R.string.amazing_margarita, R.string.rio_grande_detailed_desc, R.string.mq_rio_grande ) ); attractions.add(new Attraction( R.drawable.star_of_india, R.string.star_of_india_title, R.string.indian_buffet, R.string.star_of_india_detailed_desc, R.string.mq_star_of_india ) ); attractions.add(new Attraction( R.drawable.lucile_creole, R.string.lucile_title, R.string.breakfast_place, R.string.lucile_creole_detailed_desc, R.string.mq_lucile ) ); attractions.add(new Attraction( R.drawable.cafe_athens, R.string.cafe_athens_title, R.string.greek_mediterranean, R.string.cafe_athens_detailed_desc, R.string.mq_cafe_athens ) ); attractions.add(new Attraction( R.drawable.cafe_de_bangkok, R.string.cafe_de_bangkok_title, R.string.traditional_thai, R.string.cafe_de_bangkok_detailed_desc, R.string.mq_cafe_de_bangkok ) ); return new AttractionCollection(R.string.top_restaurants, attractions); } private AttractionRepository(Context context); static AttractionRepository getInstance(Context packageContext); AttractionCollection getCollection(int sectionTitle); List<AttractionCollection> getCollections(); }
@Test public void saveAsAttractionCollection_buildRestaurantsCollection() { assertThat(AttractionRepository.buildRestaurantsCollection(), instanceOf(AttractionCollection.class)); }
AttractionRepository { @VisibleForTesting static AttractionCollection buildBreweriesCollection() { ArrayList<Attraction> attractions = new ArrayList<>(); attractions.add(new Attraction( R.drawable.new_belgium, R.string.new_belgium_title, R.string.new_belgium_free_tours, R.string.new_belgium_detailed_desc, R.string.mq_new_belgium ) ); attractions.add(new Attraction( R.drawable.odell_brewing, R.string.odell_brewing_title, R.string.odell_microbrew, R.string.odell_brewing_detailed_desc, R.string.mq_odell_brewing ) ); attractions.add(new Attraction( R.drawable.anheuser_busch, R.string.anheuser_busch_title, R.string.grand_tour, R.string.anheuser_busch_detailed_desc, R.string.mq_anheuser_busch ) ); attractions.add(new Attraction( R.drawable.coopersmith_brewing, R.string.coopersmith_title, R.string.coopersmith_mixed_desc, R.string.coopersmith_detailed_desc, R.string.mq_coopersmith ) ); return new AttractionCollection(R.string.top_breweries, attractions); } private AttractionRepository(Context context); static AttractionRepository getInstance(Context packageContext); AttractionCollection getCollection(int sectionTitle); List<AttractionCollection> getCollections(); }
@Test public void saveAsAttractionCollection_buildBreweriesCollection() { assertThat(AttractionRepository.buildBreweriesCollection(), instanceOf(AttractionCollection.class)); }
CompositeValidator extends Validator<T> { @Override public void validate(T t) throws CompositeValidationException { List<ValidationException> exceptions = new ArrayList<>(); for (Validator<? super T> validator : validators) { try { validator.validate(t); } catch (ValidationException e) { exceptions.add(e); } } if (!exceptions.isEmpty()) { if (exceptions.size() == 1) { throw exceptions.get(0); } else { throw new CompositeValidationException(exceptions); } } } private CompositeValidator(List<Validator<? super T>> validators); @SafeVarargs static CompositeValidator<T> of(Validator<? super T>... validators); static CompositeValidator<T> of(Iterable<Validator<? super T>> validators); static CompositeValidator<T> of(List<Validator<? super T>> validators); @Override void validate(T t); }
@Test public void concrete_valid() { try { concreteValidator.validate(5); concreteValidator.validate(6); concreteValidator.validate(7); concreteValidator.validate(8); concreteValidator.validate(9); concreteValidator.validate(10); } catch (ValidationException e) { throw new AssertionError("This should be valid!"); } } @Test public void concrete_invalid() { try { concreteValidator.validate(4); throw new AssertionError("This should be invalid!"); } catch (ValidationException e) { assertThat(e).hasMessageThat() .isEqualTo("Was less than 5"); } try { concreteValidator.validate(11); throw new AssertionError("This should be invalid!"); } catch (ValidationException e) { assertThat(e).hasMessageThat() .isEqualTo("Was greater than 10"); } } @Test public void concrete_compositeValidation() { try { concreteValidator.validate(-1); throw new AssertionError("This should be invalid!"); } catch (ValidationException e) { assertThat(e).isInstanceOf(CompositeValidationException.class); CompositeValidationException ce = (CompositeValidationException) e; assertThat(ce.getExceptions()).hasSize(2); assertThat(e).hasMessageThat() .contains("Was less than 5"); assertThat(e).hasMessageThat() .contains("Was negative"); } } @Test public void reflective_valid() { try { reflectiveValidator.validate(new Foo(5)); reflectiveValidator.validate(new Foo(6)); reflectiveValidator.validate(new Foo(7)); reflectiveValidator.validate(new Foo(8)); reflectiveValidator.validate(new Foo(9)); reflectiveValidator.validate(new Foo(10)); } catch (ValidationException e) { throw new AssertionError("This should be valid!"); } } @Test public void reflective_invalid() { try { reflectiveValidator.validate(new Foo(4)); throw new AssertionError("This should be invalid!"); } catch (ValidationException e) { assertThat(e).hasMessageThat() .isEqualTo("Was less than 5"); } try { reflectiveValidator.validate(new Foo(11)); throw new AssertionError("This should be invalid!"); } catch (ValidationException e) { assertThat(e).hasMessageThat() .isEqualTo("Was greater than 10"); } } @Test public void reflective_compositeValidation() { try { reflectiveValidator.validate(new Foo(-1)); throw new AssertionError("This should be invalid!"); } catch (ValidationException e) { assertThat(e).isInstanceOf(CompositeValidationException.class); CompositeValidationException ce = (CompositeValidationException) e; assertThat(ce.getExceptions()).hasSize(2); assertThat(e).hasMessageThat() .contains("Was less than 5"); assertThat(e).hasMessageThat() .contains("Was negative"); } }
Inspector { public <T> Validator<T> validator(Type type) { return validator(type, Util.NO_ANNOTATIONS); } Inspector(Builder builder); Validator<T> validator(Type type); Validator<T> validator(Class<T> type); Validator<T> validator(Type type, Class<? extends Annotation> annotationType); @SuppressWarnings("unchecked") // Factories are required to return only matching Validators. Validator<T> validator(Type type, Set<? extends Annotation> annotations); @SuppressWarnings("unchecked") // Factories are required to return only matching Validators. Validator<T> nextValidator(Validator.Factory skipPast, Type type, Set<? extends Annotation> annotations); Inspector.Builder newBuilder(); }
@Test public void test() { Inspector inspector = new Inspector.Builder() .build(); Data data = new Data(); try { inspector.validator(Data.class).validate(data); fail("No validation was run"); } catch (ValidationException e) { assertThat(e).hasMessageThat().contains("thing() was null"); } List<Data> dataList = Arrays.asList(new Data()); try { inspector.validator(Types.newParameterizedType(List.class, Data.class)).validate(dataList); fail("No validation was run"); } catch (ValidationException e) { assertThat(e).hasMessageThat().contains("thing() was null"); } } @Test public void testSelfValidating() { Inspector inspector = new Inspector.Builder() .build(); SelfValidatingType selfValidatingType = new SelfValidatingType(); try { inspector.validator(SelfValidatingType.class).validate(selfValidatingType); fail("This should throw a validation exception!"); } catch (ValidationException e) { assertThat(e).hasMessageThat().isEqualTo(VALIDATION_MESSAGE); } NestedInheritedSelfValidating nested = new NestedInheritedSelfValidating(); try { inspector.validator(NestedInheritedSelfValidating.class).validate(nested); fail("This should throw a validation exception!"); } catch (ValidationException e) { assertThat(e).hasMessageThat().isEqualTo(VALIDATION_MESSAGE); } }
SPARQLValidator { public Model validate(OntModel toBeValidated, String query) { OntModel model = ModelFactory.createOntologyModel(OntModelSpec.OWL_DL_MEM, ModelFactory.createDefaultModel()); NIFNamespaces.addRLOGPrefix(model); model.setNsPrefix("mylog", logPrefix); QueryExecution qe = QueryExecutionFactory.create(query, toBeValidated); ResultSet rs = qe.execSelect(); for (; rs.hasNext(); ) { QuerySolution qs = rs.next(); Resource relatedResource = qs.getResource("resource"); Resource logLevel = qs.getResource("logLevel"); Literal message = qs.getLiteral("message"); RLOGIndividuals rli; String uri = logLevel.getURI(); if (RLOGIndividuals.FATAL.getUri().equals(uri)) { rli = RLOGIndividuals.FATAL; } else if (RLOGIndividuals.ERROR.getUri().equals(uri)) { rli = RLOGIndividuals.ERROR; } else if (RLOGIndividuals.WARN.getUri().equals(uri)) { rli = RLOGIndividuals.WARN; } else if (RLOGIndividuals.INFO.getUri().equals(uri)) { rli = RLOGIndividuals.INFO; } else if (RLOGIndividuals.DEBUG.getUri().equals(uri)) { rli = RLOGIndividuals.DEBUG; } else if (RLOGIndividuals.TRACE.getUri().equals(uri)) { rli = RLOGIndividuals.TRACE; } else { rli = RLOGIndividuals.ALL; } String m = (message == null) ? "null at " + relatedResource : message.getString(); model.add(RLOGSLF4JBinding.log(logPrefix, m, rli, this.getClass().getCanonicalName(), relatedResource.getURI(), (quiet) ? null : log)); } return model; } SPARQLValidator(OntModel testsuite, String logPrefix); static SPARQLValidator getInstance(); static SPARQLValidator getInstance(String suiteresource); static SPARQLValidator getInstance(File suiteresource); Model validate(OntModel toBeValidated, String query); OntModel validate(OntModel toBeValidated); static String getQuery(String file); static String convertStreamToString(InputStream is); String getLogPrefix(); boolean isQuiet(); void setQuiet(boolean quiet); OntModel getTestsuite(); String getVersion(); List<String> getTests(); String getSparqlPrefix(); }
@Test public void testValidate() { OntModel output = null; OntModel correct = ModelFactory.createOntologyModel(OntModelSpec.OWL_DL_MEM, ModelFactory.createDefaultModel()); correct.read(SPARQLValidator.class.getClassLoader().getResourceAsStream("nif-correct-model.ttl"), "", "Turtle"); output = SPARQLValidator.getInstance().validate(correct); assertTrue(output.isEmpty()); OntModel erroneous = ModelFactory.createOntologyModel(OntModelSpec.OWL_DL_MEM, ModelFactory.createDefaultModel()); erroneous.read(SPARQLValidator.class.getClassLoader().getResourceAsStream("nif-erroneous-model.ttl"), "", "Turtle"); output = SPARQLValidator.getInstance().validate(erroneous); assertFalse(output.isEmpty()); }
ToDoController { @RequestMapping(value = "/", method = RequestMethod.GET, produces = "text/html") public String dashboard() { return "dashboard"; } @RequestMapping(value = "/", method = RequestMethod.GET, produces = "text/html") String dashboard(); @RequestMapping(value = "/todo/listdata", method = RequestMethod.GET, produces = "application/json") @ResponseBody Page<ToDo> listData(Pageable pageable, Authentication authentication); static Predicate constructPredicate(ToDoShareAccount toDoShareAccount); @RequestMapping(value = "/todo/list", method = RequestMethod.GET, produces = "text/html") String list(Model model, Authentication authentication); @RequestMapping(value = "/todo/{toDoId}", method = RequestMethod.GET, produces = "text/html") String edit(@PathVariable("toDoId") @ModelAttribute("toDoForm") ToDoForm toDoForm, Model model); @RequestMapping(value = "/todo/{toDoId}", method = RequestMethod.PUT, produces = "text/html") String update(@Valid ToDoForm toDoForm, BindingResult bindingResult, Authentication authentication, ModelMap model, RedirectAttributes redirectAttributes); @RequestMapping(value = "/todo/", method = RequestMethod.POST, produces = "text/html") String save(@Valid ToDoForm toDoForm, BindingResult bindingResult, Authentication authentication, ModelMap model, RedirectAttributes redirectAttributes); @RequestMapping(value = "/todo/{toDoId}", method = RequestMethod.DELETE, produces = "text/html") String delete(@PathVariable("toDoId") @ModelAttribute("toDoForm") ToDoForm toDoForm, RedirectAttributes redirectAttributes); }
@Test public void testDashboard() throws Exception { mockMvc.perform(get("/")) .andExpect(status().isOk()) .andExpect(view().name("dashboard")); }
ProfileController { @RequestMapping(value = "/profile", method = RequestMethod.GET, produces = "text/html") public String showProfile() { return "profile"; } @RequestMapping(value = "/profile", method = RequestMethod.GET, produces = "text/html") String showProfile(); }
@Test public void testShowProfile() throws Exception { mockMvc.perform(get("/profile")) .andExpect(status().isOk()); }
TracingKafkaUtils { public static void inject(SpanContext spanContext, Headers headers, Tracer tracer) { tracer.inject(spanContext, Format.Builtin.TEXT_MAP, new HeadersMapInjectAdapter(headers)); } static SpanContext extractSpanContext(Headers headers, Tracer tracer); static void inject(SpanContext spanContext, Headers headers, Tracer tracer); static Span buildAndInjectSpan(ProducerRecord<K, V> record, Tracer tracer); static Span buildAndInjectSpan(ProducerRecord<K, V> record, Tracer tracer, BiFunction<String, ProducerRecord, String> producerSpanNameProvider, SpanContext parent); static Span buildAndInjectSpan(ProducerRecord<K, V> record, Tracer tracer, BiFunction<String, ProducerRecord, String> producerSpanNameProvider, SpanContext parent, Collection<SpanDecorator> spanDecorators); static void buildAndFinishChildSpan(ConsumerRecord<K, V> record, Tracer tracer); static void buildAndFinishChildSpan(ConsumerRecord<K, V> record, Tracer tracer, BiFunction<String, ConsumerRecord, String> consumerSpanNameProvider); static void buildAndFinishChildSpan(ConsumerRecord<K, V> record, Tracer tracer, BiFunction<String, ConsumerRecord, String> consumerSpanNameProvider, Collection<SpanDecorator> spanDecorators); static final String TO_PREFIX; static final String FROM_PREFIX; }
@Test public void inject() { MockSpan span = mockTracer.buildSpan("test").start(); Headers headers = new RecordHeaders(); assertEquals(0, headers.toArray().length); TracingKafkaUtils.inject(span.context(), headers, mockTracer); assertTrue(headers.toArray().length > 0); }
TracingKafkaUtils { public static SpanContext extractSpanContext(Headers headers, Tracer tracer) { return tracer .extract(Format.Builtin.TEXT_MAP, new HeadersMapExtractAdapter(headers)); } static SpanContext extractSpanContext(Headers headers, Tracer tracer); static void inject(SpanContext spanContext, Headers headers, Tracer tracer); static Span buildAndInjectSpan(ProducerRecord<K, V> record, Tracer tracer); static Span buildAndInjectSpan(ProducerRecord<K, V> record, Tracer tracer, BiFunction<String, ProducerRecord, String> producerSpanNameProvider, SpanContext parent); static Span buildAndInjectSpan(ProducerRecord<K, V> record, Tracer tracer, BiFunction<String, ProducerRecord, String> producerSpanNameProvider, SpanContext parent, Collection<SpanDecorator> spanDecorators); static void buildAndFinishChildSpan(ConsumerRecord<K, V> record, Tracer tracer); static void buildAndFinishChildSpan(ConsumerRecord<K, V> record, Tracer tracer, BiFunction<String, ConsumerRecord, String> consumerSpanNameProvider); static void buildAndFinishChildSpan(ConsumerRecord<K, V> record, Tracer tracer, BiFunction<String, ConsumerRecord, String> consumerSpanNameProvider, Collection<SpanDecorator> spanDecorators); static final String TO_PREFIX; static final String FROM_PREFIX; }
@Test public void extract_no_context() { Headers headers = new RecordHeaders(); MockSpan.MockContext spanContext = (MockSpan.MockContext) TracingKafkaUtils .extractSpanContext(headers, mockTracer); assertNull(spanContext); }
HeadersMapExtractAdapter implements TextMap { @Override public Iterator<Entry<String, String>> iterator() { return map.entrySet().iterator(); } HeadersMapExtractAdapter(Headers headers); @Override Iterator<Entry<String, String>> iterator(); @Override void put(String key, String value); }
@Test public void verifyNullHeaderHandled() { Headers headers = new RecordHeaders(); headers.add("test_null_header", null); HeadersMapExtractAdapter headersMapExtractAdapter = new HeadersMapExtractAdapter(headers); Entry<String, String> header = headersMapExtractAdapter.iterator().next(); assertNotNull(header); assertEquals(header.getKey(), "test_null_header"); assertNull(header.getValue()); }
TracingCallback implements Callback { @Override public void onCompletion(RecordMetadata metadata, Exception exception) { if (exception != null) { for (SpanDecorator decorator : spanDecorators) { decorator.onError(exception, span); } } try (Scope ignored = tracer.scopeManager().activate(span)) { if (callback != null) { callback.onCompletion(metadata, exception); } } finally { span.finish(); } } TracingCallback(Callback callback, Span span, Tracer tracer); TracingCallback(Callback callback, Span span, Tracer tracer, Collection<SpanDecorator> spanDecorators); @Override void onCompletion(RecordMetadata metadata, Exception exception); }
@Test public void onCompletionWithError() { Span span = mockTracer.buildSpan("test").start(); try (Scope ignored = mockTracer.activateSpan(span)) { TracingCallback callback = new TracingCallback(null, span, mockTracer); callback.onCompletion(null, new RuntimeException("test")); } List<MockSpan> finished = mockTracer.finishedSpans(); assertEquals(1, finished.size()); assertEquals(1, finished.get(0).logEntries().size()); assertEquals(true, finished.get(0).tags().get(Tags.ERROR.getKey())); } @Test public void onCompletionWithCustomErrorDecorators() { Span span = mockTracer.buildSpan("test").start(); try (Scope ignored = mockTracer.activateSpan(span)) { TracingCallback callback = new TracingCallback(null, span, mockTracer, Arrays.asList(SpanDecorator.STANDARD_TAGS, createDecorator())); callback.onCompletion(null, new RuntimeException("test")); } List<MockSpan> finished = mockTracer.finishedSpans(); assertEquals(1, finished.size()); assertEquals(true, finished.get(0).tags().get(Tags.ERROR.getKey())); assertEquals("overwritten", finished.get(0).tags().get("error.of")); assertEquals("error-test", finished.get(0).tags().get("new.error.tag")); } @Test public void onCompletion() { Span span = mockTracer.buildSpan("test").start(); try (Scope ignored = mockTracer.activateSpan(span)) { TracingCallback callback = new TracingCallback(null, span, mockTracer); callback.onCompletion(null, null); } List<MockSpan> finished = mockTracer.finishedSpans(); assertEquals(1, finished.size()); assertEquals(0, finished.get(0).logEntries().size()); assertNull(finished.get(0).tags().get(Tags.ERROR.getKey())); }
RateThisApp { @Deprecated public static void onStart(Context context) { onCreate(context); } static void init(Config config); static void setCallback(Callback callback); static void onCreate(Context context); @Deprecated static void onStart(Context context); static boolean showRateDialogIfNeeded(final Context context); static boolean showRateDialogIfNeeded(final Context context, int themeId); static boolean shouldShowRateDialog(); static void showRateDialog(final Context context); static void showRateDialog(final Context context, int themeId); static void stopRateDialog(final Context context); static int getLaunchCount(final Context context); static final boolean DEBUG; }
@Test public void onStart_isSuccess() { Context context = RuntimeEnvironment.application.getApplicationContext(); RateThisApp.onStart(context); SharedPreferences sharedPreferences = RuntimeEnvironment.application.getSharedPreferences( PREF_NAME, Context.MODE_PRIVATE); long expectedInstallDate = 0L; PackageManager packMan = context.getPackageManager(); try { PackageInfo pkgInfo = packMan.getPackageInfo(context.getPackageName(), 0); expectedInstallDate = new Date(pkgInfo.firstInstallTime).getTime(); } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } Assert.assertEquals(expectedInstallDate, sharedPreferences.getLong(KEY_INSTALL_DATE, 0L)); Assert.assertEquals(1, sharedPreferences.getInt(KEY_LAUNCH_TIMES, 0)); }
RateThisApp { public static void stopRateDialog(final Context context){ setOptOut(context, true); } static void init(Config config); static void setCallback(Callback callback); static void onCreate(Context context); @Deprecated static void onStart(Context context); static boolean showRateDialogIfNeeded(final Context context); static boolean showRateDialogIfNeeded(final Context context, int themeId); static boolean shouldShowRateDialog(); static void showRateDialog(final Context context); static void showRateDialog(final Context context, int themeId); static void stopRateDialog(final Context context); static int getLaunchCount(final Context context); static final boolean DEBUG; }
@Test public void stopRateDialog_IsSuccess() { Context context = RuntimeEnvironment.application.getApplicationContext(); RateThisApp.stopRateDialog(context); SharedPreferences sharedPreferences = RuntimeEnvironment.application.getSharedPreferences( PREF_NAME, Context.MODE_PRIVATE); Assert.assertTrue(sharedPreferences.getBoolean(KEY_OPT_OUT, false)); }
DateTrigger implements Trigger { @Override public Date nextExecutionTime(TriggerContext triggerContext) { Date result = null; if (nextFireDates.size() > 0) { try { result = nextFireDates.remove(0); } catch (IndexOutOfBoundsException e) { logger.debug(e.getMessage()); } } return result; } DateTrigger(Date... dates); @Override Date nextExecutionTime(TriggerContext triggerContext); }
@Test public void testConstructor() { Date epoch = new Date(0); Calendar currentCalendar = Calendar.getInstance(); Date current = currentCalendar.getTime(); currentCalendar.add(Calendar.HOUR, -1); Date past = currentCalendar.getTime(); currentCalendar.add(Calendar.HOUR, 2); Date future = currentCalendar.getTime(); DateTrigger dateTrigger = new DateTrigger(current, epoch, future, past); Date nextExecutionTime = dateTrigger.nextExecutionTime(null); assertNotNull("Should return epoch", nextExecutionTime); assertTrue("Should be epoch", epoch.compareTo(nextExecutionTime) == 0); nextExecutionTime = dateTrigger.nextExecutionTime(null); assertNotNull("Should return past", nextExecutionTime); assertTrue("Should be past", past.compareTo(nextExecutionTime) == 0); nextExecutionTime = dateTrigger.nextExecutionTime(null); assertNotNull("Should return current", nextExecutionTime); assertTrue("Should be current", current.compareTo(nextExecutionTime) == 0); nextExecutionTime = dateTrigger.nextExecutionTime(null); assertNotNull("Should return future", nextExecutionTime); assertTrue("Should be future", future.compareTo(nextExecutionTime) == 0); nextExecutionTime = dateTrigger.nextExecutionTime(null); assertNull("All entries should have been pulled, the nextExecutionTime should have been null.", nextExecutionTime); }
UiUtils { public static String renderParameterInfoDataAsTable(Map<String, String> parameters, boolean withHeader, int lastColumnMaxWidth) { final Table table = new Table(); table.getHeaders().put(COLUMN_1, new TableHeader("Parameter")); final TableHeader tableHeader2 = new TableHeader("Value (Configured or Default)"); tableHeader2.setMaxWidth(lastColumnMaxWidth); table.getHeaders().put(COLUMN_2, tableHeader2); for (Entry<String, String> entry : parameters.entrySet()) { final TableRow tableRow = new TableRow(); table.getHeaders().get(COLUMN_1).updateWidth(entry.getKey().length()); tableRow.addValue(COLUMN_1, entry.getKey()); int width = entry.getValue() != null ? entry.getValue().length() : 0; table.getHeaders().get(COLUMN_2).updateWidth(width); tableRow.addValue(COLUMN_2, entry.getValue()); table.getRows().add(tableRow); } return renderTextTable(table, withHeader); } private UiUtils(); static String renderMapDataAsTable(List<Map<String, Object>> data, List<String> columns); static String renderParameterInfoDataAsTable(Map<String, String> parameters, boolean withHeader, int lastColumnMaxWidth); static String renderParameterInfoDataAsTable(Map<String, String> parameters); static String renderTextTable(Table table); static String renderTextTable(Table table, boolean withHeader); static String getHeaderBorder(Map<Integer, TableHeader> headers); static final String HORIZONTAL_LINE; static final int COLUMN_1; static final int COLUMN_2; static final int COLUMN_3; static final int COLUMN_4; static final int COLUMN_5; static final int COLUMN_6; }
@Test public void testRenderParameterInfoDataAsTableWithMaxWidth() { final Map<String, String> values = new TreeMap<String, String>(); values.put("Key1", "Lorem ipsum dolor sit posuere."); values.put("My super key 2", "Lorem ipsum"); String expectedTableAsString = null; final InputStream inputStream = getClass() .getClassLoader() .getResourceAsStream("testRenderParameterInfoDataAsTableWithMaxWidth.txt"); assertNotNull("The inputstream is null.", inputStream); try { expectedTableAsString = FileCopyUtils.copyToString(new InputStreamReader(inputStream)); } catch (IOException e) { e.printStackTrace(); fail(); } final String tableRenderedAsString = UiUtils.renderParameterInfoDataAsTable(values, false, 20); assertEquals(expectedTableAsString.replaceAll("\r", ""), tableRenderedAsString); }
ShellWordsParser { List<String> parse(String s) { List<String> words = new ArrayList<>(); String field = ""; Matcher matcher = SHELLWORDS.matcher(s); while (matcher.find()) { String word = matcher.group(1); String sq = matcher.group(2); String dq = matcher.group(3); String esc = matcher.group(4); String garbage = matcher.group(5); String sep = matcher.group(6); if (garbage != null) { throw new IllegalArgumentException("Unmatched double quote: " + s); } if (word != null) { field = word; } else if (sq != null) { field = sq; } else if (dq != null) { field = dq.replaceAll("\\\\(?=.)", ""); } else if (esc != null) { field = esc.replaceAll("\\\\(?=.)", ""); } if (sep != null) { words.add(field); field = ""; } } return words; } }
@Test(expected = IllegalArgumentException.class) public void throwsExceptionWhenDoubleQuotedStringsAreMisQuoted() { this.parser.parse("a \"b c d e"); } @Test(expected = IllegalArgumentException.class) public void throwsExceptionWhenSingleQuotedStringsAreMisQuoted() { this.parser.parse("a 'b c d e"); }
MappedAnalytic implements Analytic<I, O> { @Override @SuppressWarnings("unchecked") public O evaluate(I input) { Assert.notNull(input, "input"); MI modelInput = inputMapper.mapInput((A) this, input); MO modelOutput = evaluateInternal(modelInput); O output = outputMapper.mapOutput((A) this, input, modelOutput); return output; } MappedAnalytic(InputMapper<I, A, MI> inputMapper, OutputMapper<I, O, A, MO> outputMapper); @Override @SuppressWarnings("unchecked") O evaluate(I input); }
@Test public void testEvaluateDummyMappedAnalytic() { Tuple input = TupleBuilder.tuple().of("k1", "v1", "k2", "v2"); Tuple output = analytic.evaluate(input); assertNotSame(input, output); assertThat(output.getString("k1"), is("V1")); assertThat(output.getString("k2"), is("V2")); }
AbstractFieldMappingAwareDataMapper implements Mapper { protected Map<String,String> extractFieldNameMappingFrom(List<String> fieldNameMappingPairs){ Assert.notNull(fieldNameMappingPairs, "fieldNameMappingPairs"); Map<String,String> mapping = new LinkedHashMap<String,String>(); for (String fieldNameMapping : fieldNameMappingPairs) { String fieldNameFrom = fieldNameMapping; String fieldNameTo = fieldNameMapping; if (fieldNameMapping.contains(fieldMappingEntrySplitToken)) { String[] fromTo = fieldNameMapping.split(fieldMappingEntrySplitToken); fieldNameFrom = fromTo[0]; fieldNameTo = fromTo[1]; } mapping.put(fieldNameFrom,fieldNameTo); } return mapping; } AbstractFieldMappingAwareDataMapper(); AbstractFieldMappingAwareDataMapper(String fieldMappingEntrySplitToken); String getFieldMappingEntrySplitToken(); static final String DEFAULT_FIELD_NAME_MAPPING_SPLIT_TOKEN; }
@Test public void testExtractMixedFieldNameMappingFromWithDefaultSplitToken() throws Exception { Map<String, String> mapping = mapperWithDefaultSplitToken.extractFieldNameMappingFrom(Arrays.asList("foo:bar", "mambo", "bubu:gaga", "salsa")); assertThat(mapping.size(),is(4)); assertThat(mapping.get("foo"), is("bar")); assertThat(mapping.get("bubu"), is("gaga")); assertThat(mapping.get("mambo"), is("mambo")); assertThat(mapping.get("salsa"), is("salsa")); } @Test public void testExtractFieldNameMappingFromWithDefaultSplitToken() throws Exception { Map<String, String> mapping = mapperWithDefaultSplitToken.extractFieldNameMappingFrom(Arrays.asList("foo:bar", "bubu:gaga")); assertThat(mapping.size(),is(2)); assertThat(mapping.get("foo"), is("bar")); assertThat(mapping.get("bubu"), is("gaga")); } @Test public void testExtractFieldNameMappingFromWithCustomSplitToken() throws Exception { Map<String, String> mapping = mapperWithCustomSplitToken.extractFieldNameMappingFrom(Arrays.asList("foo->bar", "bubu->gaga")); assertThat(mapping.size(),is(2)); assertThat(mapping.get("foo"), is("bar")); assertThat(mapping.get("bubu"), is("gaga")); }
CommonUtils { public static boolean isValidEmail(String emailAddress) { return emailAddress.matches(EMAIL_VALIDATION_REGEX); } private CommonUtils(); static String padRight(String inputString, int size, char paddingChar); static String padRight(String string, int size); static String collectionToCommaDelimitedString(Collection<String> list); static void closeReader(Reader reader); static boolean isValidEmail(String emailAddress); static String maskPassword(String password); static String getLocalTime(Date date, TimeZone timeZone); static String getTimeZoneNameWithOffset(TimeZone timeZone); static final String NOT_AVAILABLE; }
@Test public void testValidEmailAddress() { assertTrue(CommonUtils.isValidEmail("[email protected]")); } @Test public void testInValidEmailAddress() { assertFalse(CommonUtils.isValidEmail("test123")); }
CommonUtils { public static String padRight(String inputString, int size, char paddingChar) { final String stringToPad; if (inputString == null) { stringToPad = ""; } else { stringToPad = inputString; } StringBuilder padded = new StringBuilder(stringToPad); while (padded.length() < size) { padded.append(paddingChar); } return padded.toString(); } private CommonUtils(); static String padRight(String inputString, int size, char paddingChar); static String padRight(String string, int size); static String collectionToCommaDelimitedString(Collection<String> list); static void closeReader(Reader reader); static boolean isValidEmail(String emailAddress); static String maskPassword(String password); static String getLocalTime(Date date, TimeZone timeZone); static String getTimeZoneNameWithOffset(TimeZone timeZone); static final String NOT_AVAILABLE; }
@Test public void testPadRightWithNullString() { assertEquals(" ", CommonUtils.padRight(null, 5)); } @Test public void testPadRightWithEmptyString() { assertEquals(" ", CommonUtils.padRight("", 5)); } @Test public void testPadRight() { assertEquals("foo ", CommonUtils.padRight("foo", 5)); }
CommonUtils { public static String maskPassword(String password) { int lengthOfPassword = password.length(); StringBuilder stringBuilder = new StringBuilder(lengthOfPassword); for (int i = 0; i < lengthOfPassword; i++) { stringBuilder.append('*'); } return stringBuilder.toString(); } private CommonUtils(); static String padRight(String inputString, int size, char paddingChar); static String padRight(String string, int size); static String collectionToCommaDelimitedString(Collection<String> list); static void closeReader(Reader reader); static boolean isValidEmail(String emailAddress); static String maskPassword(String password); static String getLocalTime(Date date, TimeZone timeZone); static String getTimeZoneNameWithOffset(TimeZone timeZone); static final String NOT_AVAILABLE; }
@Test public void testMaskPassword() { assertEquals("******", CommonUtils.maskPassword("foobar")); }
UiUtils { public static String renderTextTable(Table table) { return renderTextTable(table, true); } private UiUtils(); static String renderMapDataAsTable(List<Map<String, Object>> data, List<String> columns); static String renderParameterInfoDataAsTable(Map<String, String> parameters, boolean withHeader, int lastColumnMaxWidth); static String renderParameterInfoDataAsTable(Map<String, String> parameters); static String renderTextTable(Table table); static String renderTextTable(Table table, boolean withHeader); static String getHeaderBorder(Map<Integer, TableHeader> headers); static final String HORIZONTAL_LINE; static final int COLUMN_1; static final int COLUMN_2; static final int COLUMN_3; static final int COLUMN_4; static final int COLUMN_5; static final int COLUMN_6; }
@Test public void testRenderTextTable() { final Table table = new Table(); table.addHeader(1, new TableHeader("Tap Name")) .addHeader(2, new TableHeader("Stream Name")) .addHeader(3, new TableHeader("Tap Definition")); for (int i = 1; i <= 3; i++) { final TableRow row = new TableRow(); row.addValue(1, "tap" + i) .addValue(2, "ticktock") .addValue(3, "tap@ticktock|log"); table.getRows().add(row); } String expectedTableAsString = null; final InputStream inputStream = getClass() .getClassLoader() .getResourceAsStream("testRenderTextTable-expected-output.txt"); assertNotNull("The inputstream is null.", inputStream); try { expectedTableAsString = FileCopyUtils.copyToString(new InputStreamReader(inputStream)); } catch (IOException e) { e.printStackTrace(); fail(); } final String tableRenderedAsString = UiUtils.renderTextTable(table); assertEquals(expectedTableAsString.replaceAll("\r", ""), tableRenderedAsString); } @Test public void testRenderTextTableWithSingleColumn() { final Table table = new Table(); table.addHeader(1, new TableHeader("Gauge name")); final TableRow row = new TableRow(); row.addValue(1, "simplegauge"); table.getRows().add(row); String expectedTableAsString = null; final InputStream inputStream = getClass() .getClassLoader() .getResourceAsStream("testRenderTextTable-single-column-expected-output.txt"); assertNotNull("The inputstream is null.", inputStream); try { expectedTableAsString = FileCopyUtils.copyToString(new InputStreamReader(inputStream)); } catch (IOException e) { e.printStackTrace(); fail(); } final String tableRenderedAsString = UiUtils.renderTextTable(table); assertEquals(expectedTableAsString.replaceAll("\r", ""), tableRenderedAsString); } @Test public void testRenderTextTableWithSingleColumnAndWidthOf4() { final Table table = new Table(); final TableHeader tableHeader = new TableHeader("Gauge name"); tableHeader.setMaxWidth(4); table.addHeader(1, tableHeader); final TableRow row = new TableRow(); row.addValue(1, "simplegauge"); table.getRows().add(row); String expectedTableAsString = null; final InputStream inputStream = getClass() .getClassLoader() .getResourceAsStream("testRenderTextTable-single-column-width4-expected-output.txt"); assertNotNull("The inputstream is null.", inputStream); try { expectedTableAsString = FileCopyUtils.copyToString(new InputStreamReader(inputStream)); } catch (IOException e) { e.printStackTrace(); fail(); } final String tableRenderedAsString = UiUtils.renderTextTable(table); assertEquals(expectedTableAsString.replaceAll("\r", ""), tableRenderedAsString); }
LibreOfficeLauncherHelper { public static String getOperatingSystem(String operatingSystemIndentifier) { if ("linux".equalsIgnoreCase(operatingSystemIndentifier)) { return OS_LINUX; } if (operatingSystemIndentifier != null && operatingSystemIndentifier.toLowerCase().contains("windows")) { return OS_WINDOWS; } else if (operatingSystemIndentifier != null && operatingSystemIndentifier.toLowerCase().contains("mac os x")) { return OS_MACOSX; } else { return OS_UNSUPPORTED; } } static String getOperatingSystem(String operatingSystemIndentifier); static String generateLibreOfficeOpenUrl(String cmisUrl, String repositoryId, String filePath); static final String OS_WINDOWS; static final String OS_LINUX; static final String OS_MACOSX; static final String OS_UNSUPPORTED; }
@Test public void testGetOperatingSystem() { assertEquals(LibreOfficeLauncherHelper.OS_LINUX, LibreOfficeLauncherHelper.getOperatingSystem("linux")); assertEquals(LibreOfficeLauncherHelper.OS_LINUX, LibreOfficeLauncherHelper.getOperatingSystem("Linux")); assertEquals(LibreOfficeLauncherHelper.OS_WINDOWS, LibreOfficeLauncherHelper.getOperatingSystem("Windows XP")); assertEquals(LibreOfficeLauncherHelper.OS_WINDOWS, LibreOfficeLauncherHelper.getOperatingSystem("windows 5.1")); assertEquals(LibreOfficeLauncherHelper.OS_MACOSX, LibreOfficeLauncherHelper.getOperatingSystem("mac os x")); assertEquals(LibreOfficeLauncherHelper.OS_MACOSX, LibreOfficeLauncherHelper.getOperatingSystem("Mac OS X")); assertEquals(LibreOfficeLauncherHelper.OS_UNSUPPORTED, LibreOfficeLauncherHelper.getOperatingSystem("Solaris")); assertEquals(LibreOfficeLauncherHelper.OS_UNSUPPORTED, LibreOfficeLauncherHelper.getOperatingSystem("")); }
LibreOfficeLauncherHelper { public static String generateLibreOfficeOpenUrl(String cmisUrl, String repositoryId, String filePath) throws UnsupportedEncodingException { StringBuilder openUrlSb = new StringBuilder(); openUrlSb.append(LibreOfficeLauncherHelper.LIBREOFFICE_HANDLER); openUrlSb.append(": StringBuilder cmisUrlSb = new StringBuilder(); cmisUrlSb.append(cmisUrl); cmisUrlSb.append("#"); cmisUrlSb.append(repositoryId); String urlEncodedString = URLEncoder.encode(cmisUrlSb.toString(), "UTF-8").replaceAll("\\+", "%20"); openUrlSb.append(urlEncodedString + filePath); return openUrlSb.toString(); } static String getOperatingSystem(String operatingSystemIndentifier); static String generateLibreOfficeOpenUrl(String cmisUrl, String repositoryId, String filePath); static final String OS_WINDOWS; static final String OS_LINUX; static final String OS_MACOSX; static final String OS_UNSUPPORTED; }
@Test public void testGenerateLibreOfficeOpenUrl() throws UnsupportedEncodingException { assertEquals("vnd.libreoffice.cmis: LibreOfficeLauncherHelper.generateLibreOfficeOpenUrl("http: "/Sites/libreoffice-test/documentLibrary/Testdocument.odt")); }
PlatformHADRCrawlerPlugin extends AbstractCrawlerPlugin { public String IsDR(Platform platform) { String activeCloudsListForPlatform = platform.getActiveClouds().toString().toLowerCase(); log.info("activeCloudsListForPlatform: " + activeCloudsListForPlatform.toString()); int i = 0; for (String dataCenter : dataCentersArr) { if (activeCloudsListForPlatform.contains(dataCenter)) { i++; } } if (i >= 2) { return "DR"; } return "Non-DR"; } PlatformHADRCrawlerPlugin(); SearchDal getSearchDal(); void setSearchDal(SearchDal searchDal); void readConfig(); void processEnvironment(Environment env, Map<String, Organization> organizationsMapCache); void processPlatformsInEnv(Environment env, Map<String, Organization> organizationsMapCache); String getOOURL(String path); String parseAssemblyNameFromNsPath(String path); String IsDR(Platform platform); String IsHA(Platform platform); void saveToElasticSearch(PlatformHADRRecord platformHADRRecord, String platformCId); void createIndexInElasticSearch(); PlatformHADRRecord setCloudCategories(PlatformHADRRecord platformHADRRecord, Map<String, Cloud> clouds); Map<String, Object> getPlatformTechDebtForEnvironment(Platform platform, Environment env); boolean isNonProdEnvUsingProdutionClouds(Map<String, Cloud> cloudsMap); boolean prodProfileWithNonProdClouds(Map<String, Cloud> cloudsMap); boolean isHadrPluginEnabled(); boolean isHadrEsEnabled(); String getProdDataCentersList(); String getHadrElasticSearchIndexName(); String[] getDataCentersArr(); void setHadrEsEnabled(boolean isHadrEsEnabled); String getHadrElasticSearchIndexMappings(); String getIsHALabel(); String getIsDRLabel(); String getIsAutoRepairEnabledLabel(); String getIsAutoReplaceEnabledLabel(); String getIsProdCloudInNonProdEnvLabel(); String getIsProdProfileWithNonProdCloudsLabel(); String getEnvironmentProdProfileFilter(); String getDateTimeFormatPattern(); }
@Test(enabled = true) private void test_IsDR() { plugin = new PlatformHADRCrawlerPlugin(); Platform platform = new Platform(); List<String> activeClouds = new ArrayList<String>(); activeClouds.add("dc1-TestCloud1"); activeClouds.add("dc1-TestCloud2"); activeClouds.add("dc2-TestCloud1"); activeClouds.add("dc2-TestCloud2"); platform.setActiveClouds(activeClouds); assertEquals(plugin.IsDR(platform), "DR"); } @Test(enabled = true) private void test_IsNonDR() { plugin = new PlatformHADRCrawlerPlugin(); Platform platform = new Platform(); List<String> activeClouds = new ArrayList<String>(); activeClouds.add("dc1-TestCloud1"); activeClouds.add("dc1-TestCloud2"); platform.setActiveClouds(activeClouds); assertEquals(plugin.IsDR(platform), "Non-DR"); } @Test(enabled = true) private void test_IsNonHA() { plugin = new PlatformHADRCrawlerPlugin(); Platform platform = new Platform(); List<String> activeClouds = new ArrayList<String>(); activeClouds.add("dc1-TestCloud1"); platform.setActiveClouds(activeClouds); assertEquals(plugin.IsDR(platform), "Non-DR"); }
OneOpsYamlReader { public <T> T read(File yamlfile, Class<T> yamlModelClass) throws FileNotFoundException { Yaml yaml = new Yaml(); T yamlmodel = yaml.loadAs(new FileInputStream(yamlfile), yamlModelClass); return yamlmodel; } T read(File yamlfile, Class<T> yamlModelClass); }
@Test public void validateReadingTestYaml() throws Exception { OneOpsYamlReader reader = new OneOpsYamlReader(); TestCase testCaseYaml = reader .read(yaml("src/test/yaml/oo-v2", "testcase.yaml"), TestCase.class); assertEquals("Evaluate optional component add/delete", testCaseYaml.getDescription()); assertEquals("false", testCaseYaml.getRandomcloud()); assertEquals("pulldesign", testCaseYaml.getTags().get(0)); assertTrue(testCaseYaml.getClouds().keySet().contains("cloud0")); List<Cloud> clouds = Lists.newArrayList(testCaseYaml.getClouds().values()); assertEquals(1, clouds.get(0).getDeploymentorder()); assertTrue(testCaseYaml.getTemplates().keySet().contains("template-1.yaml")); List<Template> templates = Lists.newArrayList(testCaseYaml.getTemplates().values()); Template template = templates.get(0); assertEquals("evaluate add of optional component user-temp", template.getAssertions().get("addusercomponent").getMessage()); } @Test public void validateReadingTestOldBooYaml1() throws Exception { OneOpsYamlReader reader = new OneOpsYamlReader(); BooYaml booYaml = reader.read(yaml("src/test/yaml/boo", "assembly.yaml"), BooYaml.class); assertEquals(booYaml.getBoo().getEnvironment_name(), "environment_name"); Map<String, String> tags = Maps.newHashMap(); tags.put("tag-key1", "tag-value1"); tags.put("tag-key2", "tag-value2"); tags.put("tag-key3", "tag-value3"); tags.put("tag-key4", "tag-value4"); assertEquals(booYaml.getAssembly().getTags(), tags); List<BooPlatform> platformList = booYaml.getPlatformList(); BooPlatform booPlatform0 = platformList.get(0); assertEquals(booPlatform0.getName(), "platform-0"); assertEquals(booPlatform0.getPack(), "pack-platform-0"); assertEquals(booPlatform0.getSource(), "source"); Map<String, Map<String, Object>> components = booPlatform0.getComponents(); Map<String, Object> component0 = components.get("component-0"); assertEquals(component0.get("config-0"), "platform-0-config-0-value"); Map<String, BooAttachment> attachments = booPlatform0.getAttachments(); BooAttachment booAttachment = attachments.get("component-0"); assertEquals(booAttachment.getName(), "attachment1"); Map<String, Object> user = components.get("user"); Map<String, String> userComp = Maps.newHashMap(); userComp.put("username", "user1"); userComp.put("authorized_keys", "[\"\"]"); assertEquals(user.get("user1"), userComp); List<BooScale> scaleList = booYaml.getScaleList(); BooScale booScale = scaleList.get(0); assertEquals(booScale.getPlatformName(), "platform-0"); assertEquals(booScale.getComponentName(), "compute"); assertEquals(booScale.getMin(), "2"); assertEquals(booScale.getCurrent(), "2"); List<BooEnvironment> environmentList = booYaml.getEnvironmentList(); BooEnvironment environment0 = environmentList.get(0); assertEquals(environment0.getName(), booYaml.getBoo().getEnvironment_name()); assertEquals(environment0.getProfile(), "DEV"); List<BooCloud> cloudList = environment0.getCloudList(); BooCloud cloud0 = cloudList.get(0); assertEquals(cloud0.getName(), "dev-cdc002"); assertEquals(cloud0.getPriority(), "1"); assertEquals(cloud0.getDpmt_order(), "1"); assertEquals(cloud0.getPct_scale(), "30"); List<BooPlatform> ep0 = environment0.getPlatformList(); BooPlatform ep = ep0.get(0); assertEquals(ep.getName(), "platform-0"); Map<String, String> autoHealing = Maps.newHashMap(); autoHealing.put("autorepair", "false"); autoHealing.put("autoreplace", "true"); autoHealing.put("replace_after_minutes", "60"); autoHealing.put("replace_after_repairs", "4"); assertEquals(ep.getAuto_healing(), autoHealing); Map<String, Map<String, Object>> epc0 = ep.getComponents(); Map<String, Object> lbConfig = epc0.get("lb"); assertEquals(lbConfig.get("ecv_map"), "{\"8080\":\"GET /\"}"); BooModelTransformer bmt = new BooModelTransformer(); OneOps oneops = bmt.convert(booYaml); assertEquals("auth-key", oneops.getApikey()); assertEquals("https: assertEquals("local-org", oneops.getOrganization()); Assembly assembly = oneops.getAssembly(); assertEquals("assembly-name", assembly.getName()); } @Test public void validateReadingTestOldBooYaml2() throws Exception { OneOpsYamlReader reader = new OneOpsYamlReader(); BooYaml booYaml = reader.read(yaml("src/test/yaml/boo", "assembly2.yaml"), BooYaml.class); assertEquals(booYaml.getBoo().getEnvironment_name(), "environment_name"); Map<String, String> tags = Maps.newHashMap(); tags.put("tag-key1", "tag-value1"); tags.put("tag-key2", "tag-value2"); tags.put("tag-key3", "tag-value3"); tags.put("tag-key4", "tag-value4"); assertEquals(booYaml.getAssembly().getTags(), tags); List<BooPlatform> platformList = booYaml.getPlatformList(); BooPlatform booPlatform0 = platformList.get(0); assertEquals(booPlatform0.getName(), "platform-0"); assertEquals(booPlatform0.getPack(), "pack-platform-0"); assertEquals(booPlatform0.getSource(), "source"); Map<String, Map<String, Object>> components = booPlatform0.getComponents(); Map<String, Object> component0 = components.get("component-0"); assertEquals(component0.get("config-0"), "platform-0-config-0-value"); Map<String, Object> user = components.get("user"); Map<String, String> userComp = Maps.newHashMap(); userComp.put("username", "user1"); userComp.put("authorized_keys", "[\"\"]"); assertEquals(user.get("user1"), userComp); List<BooEnvironment> environmentList = booYaml.getEnvironmentList(); BooEnvironment environment0 = environmentList.get(0); assertEquals(environment0.getName(), "dev"); assertEquals(environment0.getAvailability(), "redundant"); List<BooCloud> cloudList = environment0.getCloudList(); BooCloud cloud0 = cloudList.get(0); assertEquals(cloud0.getName(), "stub-dfw2a"); assertEquals(cloud0.getPriority(), "1"); assertEquals(cloud0.getDpmt_order(), "1"); assertEquals(cloud0.getPct_scale(), "100"); List<BooPlatform> ep0 = environment0.getPlatformList(); BooPlatform ep = ep0.get(0); assertEquals(ep.getName(), "platform-0"); Map<String, String> autoHealing = Maps.newHashMap(); autoHealing.put("autorepair", "false"); autoHealing.put("autoreplace", "true"); autoHealing.put("replace_after_minutes", "60"); autoHealing.put("replace_after_repairs", "4"); assertEquals(ep.getAuto_healing(), autoHealing); Map<String, Map<String, Object>> epc0 = ep.getComponents(); Map<String, Object> lbConfig = epc0.get("lb"); assertEquals(lbConfig.get("ecv_map"), "{\"8080\":\"GET /\"}"); List<BooScale> scaleList = ep.getScaleList(); BooScale booScale = scaleList.get(0); assertEquals(booScale.getPlatformName(), "platform-0"); assertEquals(booScale.getComponentName(), "compute"); assertEquals(booScale.getMin(), "1"); assertEquals(booScale.getCurrent(), "3"); BooModelTransformer bmt = new BooModelTransformer(); OneOps oneops = bmt.convert(booYaml); assertEquals("auth-key", oneops.getApikey()); assertEquals("https: assertEquals("local-org", oneops.getOrganization()); Assembly assembly = oneops.getAssembly(); assertEquals("assembly-name", assembly.getName()); } @Test public void validateReadingAssembly() throws Exception { OneOpsYamlReader reader = new OneOpsYamlReader(); OneOps oneops = reader.read(yaml("src/test/yaml/oo-v2", "assembly.yaml"), OneOps.class); assertEquals("auth-key", oneops.getApikey()); assertEquals("https: assertEquals("local-org", oneops.getOrganization()); Assembly assembly = oneops.getAssembly(); assertEquals("assembly-name", assembly.getName()); Map<String, String> variables = assembly.getVariables(); assertEquals("variable-value-0", variables.get("variable-0")); assertEquals("variable-value-1", variables.get("variable-1")); Map<String, String> encryptedVariables = assembly.getEncryptedvariables(); assertEquals("encrypted-variable-value-0", encryptedVariables.get("encrypted-variable-0")); Map<String, String> tags = assembly.getTags(); assertEquals("tag-value-0", tags.get("tag-0")); assertEquals("tag-value-1", tags.get("tag-1")); List<Platform> platforms = assembly.getPlatformList(); Platform p0 = platforms.get(0); assertEquals("platform-0", p0.getName()); assertEquals("source/pack-platform-0", p0.getPack()); assertEquals("1", p0.getPackVersion()); List<String> links = p0.getLinks(); assertEquals("platform-0-link-0", links.get(0)); assertEquals("platform-0-link-1", links.get(1)); Map<String, String> platformVariables = p0.getVariables(); assertEquals("pack-platform-0-variable-0-value", platformVariables.get("pack-platform-variable-0")); assertEquals("pack-platform-0-variable-1-value", platformVariables.get("pack-platform-variable-1")); Map<String, String> encryptedPlatformVariables = p0.getEncryptedvariables(); assertEquals("encrypted-pack-platform-0-variable-0-value", encryptedPlatformVariables.get("encrypted-pack-platform-variable-0")); List<Component> components = p0.getComponentList(); Component c0 = components.get(0); assertEquals("component-0", c0.getId()); Map<String, String> config = c0.getConfiguration(); assertEquals("platform-0-config-0-value", config.get("config-0")); assertEquals("platform-0-config-1-value", config.get("config-1")); assertEquals("platform-1", platforms.get(1).getName()); assertEquals("1", platforms.get(1).getConfiguration().get("version")); List<Component> pcomps = platforms.get(1).getComponentList(); List<Attachment> pAttachments = pcomps.get(0).getAttachmentList(); Attachment pa0 = pAttachments.get(0); assertEquals("attachment1", pa0.getId()); Map<String, String> paconfig0 = pa0.getConfiguration(); assertEquals("before-add,before-update,before-replace", paconfig0.get("run_on")); List<Environment> environments = assembly.getEnvironmentList(); Environment e0 = environments.get(0); assertEquals("environment-0", e0.getName()); assertTrue(e0.isGlobaldns()); assertEquals("redundant", e0.getAvailability()); assertEquals("variable-new-value-0", e0.getVariables().get("variable-0")); assertEquals("encrypted-variable-new-value-0", e0.getEncryptedvariables().get("encrypted-variable-0")); List<Platform> environmentPlatforms = e0.getPlatformList(); Platform ep0 = environmentPlatforms.get(0); assertEquals("platform-1", ep0.getName()); assertEquals("false", ep0.getEnable()); Map<String, String> ep0config = ep0.getConfiguration(); assertEquals("redundant", ep0config.get("availability")); assertEquals("false", ep0config.get("autorepair")); assertEquals("true", ep0config.get("autoreplace")); assertEquals("55", ep0config.get("replace_after_minutes")); assertEquals("4", ep0config.get("replace_after_repairs")); Map<String, Map<String, String>> scale = ep0.getScale(); Map<String, String> computeScale = scale.get("compute"); assertEquals("3", computeScale.get("current")); assertEquals("1", computeScale.get("min")); assertEquals("5", computeScale.get("max")); assertEquals("pack-platform-0-variable-0-new-value", ep0.getVariables().get("pack-platform-variable-0")); List<Component> environmentComponents = ep0.getComponentList(); Component epc0 = environmentComponents.get(0); assertEquals("component-0", epc0.getId()); assertEquals("component-0-type", epc0.getType()); assertEquals("true", epc0.getTouch()); Map<String, String> config0 = epc0.getConfiguration(); assertEquals("platform-1-config-0-value", config0.get("config-2")); assertEquals("platform-1-config-1-value", config0.get("config-3")); List<Attachment> epAttachments = epc0.getAttachmentList(); Attachment epa0 = epAttachments.get(0); assertEquals("attachment1", epa0.getId()); Map<String, String> epaconfig0 = epa0.getConfiguration(); assertEquals("before-add,before-update,before-replace", epaconfig0.get("run_on")); List<Cloud> clouds = e0.getCloudList(); Cloud cloud = clouds.get(0); assertEquals(1, cloud.getPriority()); assertEquals(1, cloud.getDeploymentorder()); assertEquals(100, cloud.getScalepercentage()); }
NotificationMessage implements Serializable { public String getPayloadString(String name) { return payload.get(name) == null ? null : String.valueOf(payload.get(name)); } static String buildSubjectPrefix(String nsPath); Map<String, Object> getPayload(); String getPayloadString(String name); void putPayloadEntry(String name, Object value); void putPayloadEntries(Map<String, Object> payloadEntries); String getNsPath(); void setNsPath(String nsPath); String getSource(); void setSource(String source); long getTimestamp(); void setTimestamp(long timestamp); long getCmsId(); void setCmsId(long cmsId); NotificationSeverity getSeverity(); void setSeverity(NotificationSeverity severity); NotificationType getType(); void setType(NotificationType type); String getSubject(); void setSubject(String subject); String getTemplateName(); void setTemplateName(String templateName); String getTemplateParams(); void setTemplateParams(String templateParams); String getText(); void setText(String text); String getEnvironmentProfileName(); void setEnvironmentProfileName(String envProfile); String getAdminStatus(); void setAdminStatus(String adminStatus); long getManifestCiId(); void setManifestCiId(long manifestCiId); String getCloudName(); void setCloudName(String cloudName); void appendText(String notes); String asString(); List<CmsCISimple> getCis(); void setCis(List<CmsCISimple> cis); }
@Test public void testGetPayloadStringForNull() { assertNull(new NotificationMessage().getPayloadString(ENTRY_NAME)); }
CmsCryptoDES implements CmsCrypto { public void init() throws IOException, GeneralSecurityException { Security.addProvider(new BouncyCastleProvider()); this.secretKeyFile = System.getenv("CMS_DES_PEM"); if (this.secretKeyFile == null) { this.secretKeyFile = System.getProperty("com.kloopz.crypto.cms_des_pem"); } if (this.secretKeyFile == null) { logger.error(">>>>>>>>>>>>>>Failed to init DES Encryptor/Decryptor no key faile is set, use CMS_DES_PEM env var to set location!"); throw new FileNotFoundException("Failed to init DES Encryptor/Decryptor no key faile is set, use CMS_DES_PEM env var to set location!"); } initEncryptorDecryptor(); } @Override String encrypt(String instr); @Override String decrypt(String instr); @Override String decryptVars(String instr); void init(); static void generateDESKey(String file); static void main(String[] args); void setSecretKeyFile(String secretKeyFile); void init(String secretKeyFile); }
@Test(expectedExceptions = CmsException.class) public void badDESEnvTest() throws Exception { CmsCryptoDES crypto1 = new CmsCryptoDES(); try { crypto1.init(); } catch (FileNotFoundException e) { throw new CmsException(33, "File not found, likely a devbox, throwing CmsException"); } } @Test(expectedExceptions = IOException.class) public void badFileTest() throws Exception { CmsCryptoDES crypto1 = new CmsCryptoDES(); crypto1.init("this-is-not-a-key-file"); }
CmsCryptoDES implements CmsCrypto { @Override public String decrypt(String instr) throws GeneralSecurityException { if (instr.startsWith(ENC_PREFIX)) { instr = instr.substring(ENC_PREFIX.length()); } return decryptStr(instr); } @Override String encrypt(String instr); @Override String decrypt(String instr); @Override String decryptVars(String instr); void init(); static void generateDESKey(String file); static void main(String[] args); void setSecretKeyFile(String secretKeyFile); void init(String secretKeyFile); }
@Test(threadPoolSize = 10, invocationCount = 3, timeOut = 10000) public void testDecrypt() throws Exception { String decryptedUUID = crypto.decrypt(encryptedString); Assert.assertTrue(rawString.equals(decryptedUUID)); } @Test public void testEmptyString() throws Exception { String decryptedText = crypto.decrypt(CmsCrypto.ENC_PREFIX); Assert.assertTrue(StringUtils.EMPTY.equals(decryptedText)); }
ListUtils { public <V> Map<K, V> toMap(List<V> list, String keyField) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { String accessor = convertFieldToAccessor(keyField); Map<K, V> map = new HashMap<K, V>(); for(V obj : list) { Method method = obj.getClass().getMethod(accessor); @SuppressWarnings("unchecked") K key = (K)method.invoke(obj); map.put(key, obj); } return map; } Map<K, V> toMap(List<V> list, String keyField); Map<K, List<V>> toMapOfList(List<V> list, String keyField); }
@Test public void testList1() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { List<MyBean> listOfBeans = new ArrayList<MyBean>(LIST_SIZE); for (int i = 1; i <= LIST_SIZE; i++) { MyBean m = new MyBean(String.valueOf(i)); listOfBeans.add(m); } Map<String, MyBean> outMap = util.toMap(listOfBeans, KEY_FIELD); assertEquals(LIST_SIZE, outMap.size()); for(MyBean listMember : listOfBeans){ assertEquals(listMember, outMap.get(listMember.getSpecialValue())); } System.out.println(outMap); }