src_fm_fc_ms_ff
stringlengths 43
86.8k
| target
stringlengths 20
276k
|
---|---|
WMAIndicator extends CachedIndicator<Num> { @Override protected Num calculate(int index) { if (index == 0) { return indicator.getValue(0); } Num value = numOf(0); if (index - barCount < 0) { for (int i = index + 1; i > 0; i--) { value = value.plus(numOf(i).multipliedBy(indicator.getValue(i - 1))); } return value.dividedBy(numOf(((index + 1) * (index + 2)) / 2)); } int actualIndex = index; for (int i = barCount; i > 0; i--) { value = value.plus(numOf(i).multipliedBy(indicator.getValue(actualIndex))); actualIndex--; } return value.dividedBy(numOf((barCount * (barCount + 1)) / 2)); } WMAIndicator(Indicator<Num> indicator, int barCount); @Override String toString(); } | @Test public void calculate() { MockBarSeries series = new MockBarSeries(numFunction, 1d, 2d, 3d, 4d, 5d, 6d); Indicator<Num> close = new ClosePriceIndicator(series); Indicator<Num> wmaIndicator = new WMAIndicator(close, 3); assertNumEquals(1, wmaIndicator.getValue(0)); assertNumEquals(1.6667, wmaIndicator.getValue(1)); assertNumEquals(2.3333, wmaIndicator.getValue(2)); assertNumEquals(3.3333, wmaIndicator.getValue(3)); assertNumEquals(4.3333, wmaIndicator.getValue(4)); assertNumEquals(5.3333, wmaIndicator.getValue(5)); } |
AroonDownIndicator extends CachedIndicator<Num> { @Override public String toString() { return getClass().getSimpleName() + " barCount: " + barCount; } AroonDownIndicator(Indicator<Num> minValueIndicator, int barCount); AroonDownIndicator(BarSeries series, int barCount); @Override String toString(); } | @Test public void onlyNaNValues() { BarSeries series = new BaseBarSeriesBuilder().withNumTypeOf(numFunction).withName("NaN test").build(); for (long i = 0; i <= 1000; i++) { series.addBar(ZonedDateTime.now().plusDays(i), NaN, NaN, NaN, NaN, NaN); } AroonDownIndicator aroonDownIndicator = new AroonDownIndicator(series, 5); for (int i = series.getBeginIndex(); i <= series.getEndIndex(); i++) { assertEquals(NaN.toString(), aroonDownIndicator.getValue(i).toString()); } }
@Test public void naNValuesInIntervall() { BarSeries series = new BaseBarSeriesBuilder().withNumTypeOf(numFunction).withName("NaN test").build(); for (long i = 10; i >= 0; i--) { Num minPrice = i % 2 == 0 ? series.numOf(i) : NaN; series.addBar(ZonedDateTime.now().plusDays(10 - i), NaN, NaN, minPrice, NaN, NaN); } series.addBar(ZonedDateTime.now().plusDays(11), NaN, NaN, series.numOf(10), NaN, NaN); AroonDownIndicator aroonDownIndicator = new AroonDownIndicator(series, 5); for (int i = series.getBeginIndex(); i <= series.getEndIndex(); i++) { if (i % 2 != 0 && i < 11) { assertEquals(NaN.toString(), aroonDownIndicator.getValue(i).toString()); } else if (i < 11) assertNumEquals(series.numOf(100).toString(), aroonDownIndicator.getValue(i)); else assertNumEquals(series.numOf(80).toString(), aroonDownIndicator.getValue(i)); } } |
BollingerBandsLowerIndicator extends CachedIndicator<Num> { public Num getK() { return k; } BollingerBandsLowerIndicator(BollingerBandsMiddleIndicator bbm, Indicator<Num> indicator); BollingerBandsLowerIndicator(BollingerBandsMiddleIndicator bbm, Indicator<Num> indicator, Num k); Num getK(); @Override String toString(); } | @Test public void bollingerBandsLowerUsingSMAAndStandardDeviation() { BollingerBandsMiddleIndicator bbmSMA = new BollingerBandsMiddleIndicator(sma); StandardDeviationIndicator standardDeviation = new StandardDeviationIndicator(closePrice, barCount); BollingerBandsLowerIndicator bblSMA = new BollingerBandsLowerIndicator(bbmSMA, standardDeviation); assertNumEquals(2, bblSMA.getK()); assertNumEquals(1, bblSMA.getValue(0)); assertNumEquals(0.5, bblSMA.getValue(1)); assertNumEquals(0.367, bblSMA.getValue(2)); assertNumEquals(1.367, bblSMA.getValue(3)); assertNumEquals(2.3905, bblSMA.getValue(4)); assertNumEquals(2.7239, bblSMA.getValue(5)); assertNumEquals(2.367, bblSMA.getValue(6)); BollingerBandsLowerIndicator bblSMAwithK = new BollingerBandsLowerIndicator(bbmSMA, standardDeviation, numFunction.apply(1.5)); assertNumEquals(1.5, bblSMAwithK.getK()); assertNumEquals(1, bblSMAwithK.getValue(0)); assertNumEquals(0.75, bblSMAwithK.getValue(1)); assertNumEquals(0.7752, bblSMAwithK.getValue(2)); assertNumEquals(1.7752, bblSMAwithK.getValue(3)); assertNumEquals(2.6262, bblSMAwithK.getValue(4)); assertNumEquals(2.9595, bblSMAwithK.getValue(5)); assertNumEquals(2.7752, bblSMAwithK.getValue(6)); } |
BollingerBandsUpperIndicator extends CachedIndicator<Num> { public Num getK() { return k; } BollingerBandsUpperIndicator(BollingerBandsMiddleIndicator bbm, Indicator<Num> deviation); BollingerBandsUpperIndicator(BollingerBandsMiddleIndicator bbm, Indicator<Num> deviation, Num k); Num getK(); @Override String toString(); } | @Test public void bollingerBandsUpperUsingSMAAndStandardDeviation() { BollingerBandsMiddleIndicator bbmSMA = new BollingerBandsMiddleIndicator(sma); StandardDeviationIndicator standardDeviation = new StandardDeviationIndicator(closePrice, barCount); BollingerBandsUpperIndicator bbuSMA = new BollingerBandsUpperIndicator(bbmSMA, standardDeviation); assertNumEquals(2, bbuSMA.getK()); assertNumEquals(1, bbuSMA.getValue(0)); assertNumEquals(2.5, bbuSMA.getValue(1)); assertNumEquals(3.633, bbuSMA.getValue(2)); assertNumEquals(4.633, bbuSMA.getValue(3)); assertNumEquals(4.2761, bbuSMA.getValue(4)); assertNumEquals(4.6094, bbuSMA.getValue(5)); assertNumEquals(5.633, bbuSMA.getValue(6)); assertNumEquals(5.2761, bbuSMA.getValue(7)); assertNumEquals(5.633, bbuSMA.getValue(8)); assertNumEquals(4.2761, bbuSMA.getValue(9)); BollingerBandsUpperIndicator bbuSMAwithK = new BollingerBandsUpperIndicator(bbmSMA, standardDeviation, numFunction.apply(1.5)); assertNumEquals(1.5, bbuSMAwithK.getK()); assertNumEquals(1, bbuSMAwithK.getValue(0)); assertNumEquals(2.25, bbuSMAwithK.getValue(1)); assertNumEquals(3.2247, bbuSMAwithK.getValue(2)); assertNumEquals(4.2247, bbuSMAwithK.getValue(3)); assertNumEquals(4.0404, bbuSMAwithK.getValue(4)); assertNumEquals(4.3737, bbuSMAwithK.getValue(5)); assertNumEquals(5.2247, bbuSMAwithK.getValue(6)); assertNumEquals(5.0404, bbuSMAwithK.getValue(7)); assertNumEquals(5.2247, bbuSMAwithK.getValue(8)); assertNumEquals(4.0404, bbuSMAwithK.getValue(9)); } |
KeltnerChannelUpperIndicator extends CachedIndicator<Num> { public KeltnerChannelUpperIndicator(KeltnerChannelMiddleIndicator keltnerMiddleIndicator, double ratio, int barCountATR) { super(keltnerMiddleIndicator); this.ratio = numOf(ratio); this.keltnerMiddleIndicator = keltnerMiddleIndicator; averageTrueRangeIndicator = new ATRIndicator(keltnerMiddleIndicator.getBarSeries(), barCountATR); } KeltnerChannelUpperIndicator(KeltnerChannelMiddleIndicator keltnerMiddleIndicator, double ratio,
int barCountATR); } | @Test public void keltnerChannelUpperIndicatorTest() { KeltnerChannelMiddleIndicator km = new KeltnerChannelMiddleIndicator(new ClosePriceIndicator(data), 14); KeltnerChannelUpperIndicator ku = new KeltnerChannelUpperIndicator(km, 2, 14); assertNumEquals(11971.9132, ku.getValue(13)); assertNumEquals(12002.3402, ku.getValue(14)); assertNumEquals(12024.4032, ku.getValue(15)); assertNumEquals(12040.3933, ku.getValue(16)); assertNumEquals(12052.8572, ku.getValue(17)); assertNumEquals(12067.9050, ku.getValue(18)); assertNumEquals(12099.5025, ku.getValue(19)); assertNumEquals(12110.5722, ku.getValue(20)); assertNumEquals(12130.8675, ku.getValue(21)); assertNumEquals(12147.7344, ku.getValue(22)); assertNumEquals(12175.5937, ku.getValue(23)); assertNumEquals(12208.1327, ku.getValue(24)); assertNumEquals(12233.9032, ku.getValue(25)); assertNumEquals(12256.9596, ku.getValue(26)); assertNumEquals(12285.9094, ku.getValue(27)); assertNumEquals(12301.1108, ku.getValue(28)); assertNumEquals(12313.2042, ku.getValue(29)); } |
KeltnerChannelLowerIndicator extends CachedIndicator<Num> { public KeltnerChannelLowerIndicator(KeltnerChannelMiddleIndicator keltnerMiddleIndicator, double ratio, int barCountATR) { super(keltnerMiddleIndicator); this.ratio = numOf(ratio); this.keltnerMiddleIndicator = keltnerMiddleIndicator; averageTrueRangeIndicator = new ATRIndicator(keltnerMiddleIndicator.getBarSeries(), barCountATR); } KeltnerChannelLowerIndicator(KeltnerChannelMiddleIndicator keltnerMiddleIndicator, double ratio,
int barCountATR); } | @Test public void keltnerChannelLowerIndicatorTest() { KeltnerChannelMiddleIndicator km = new KeltnerChannelMiddleIndicator(new ClosePriceIndicator(data), 14); KeltnerChannelLowerIndicator kl = new KeltnerChannelLowerIndicator(km, 2, 14); assertNumEquals(11556.5468, kl.getValue(13)); assertNumEquals(11583.7971, kl.getValue(14)); assertNumEquals(11610.8331, kl.getValue(15)); assertNumEquals(11639.5955, kl.getValue(16)); assertNumEquals(11667.0877, kl.getValue(17)); assertNumEquals(11660.5619, kl.getValue(18)); assertNumEquals(11675.8782, kl.getValue(19)); assertNumEquals(11705.9497, kl.getValue(20)); assertNumEquals(11726.7208, kl.getValue(21)); assertNumEquals(11753.4154, kl.getValue(22)); assertNumEquals(11781.8375, kl.getValue(23)); assertNumEquals(11817.1476, kl.getValue(24)); assertNumEquals(11851.9771, kl.getValue(25)); assertNumEquals(11878.6139, kl.getValue(26)); assertNumEquals(11904.4570, kl.getValue(27)); assertNumEquals(11935.3907, kl.getValue(28)); assertNumEquals(11952.2012, kl.getValue(29)); } |
KeltnerChannelMiddleIndicator extends CachedIndicator<Num> { public KeltnerChannelMiddleIndicator(BarSeries series, int barCountEMA) { this(new TypicalPriceIndicator(series), barCountEMA); } KeltnerChannelMiddleIndicator(BarSeries series, int barCountEMA); KeltnerChannelMiddleIndicator(Indicator<Num> indicator, int barCountEMA); } | @Test public void keltnerChannelMiddleIndicatorTest() { KeltnerChannelMiddleIndicator km = new KeltnerChannelMiddleIndicator(new ClosePriceIndicator(data), 14); assertNumEquals(11764.23, km.getValue(13)); assertNumEquals(11793.0687, km.getValue(14)); assertNumEquals(11817.6182, km.getValue(15)); assertNumEquals(11839.9944, km.getValue(16)); assertNumEquals(11859.9725, km.getValue(17)); assertNumEquals(11864.2335, km.getValue(18)); assertNumEquals(11887.6903, km.getValue(19)); assertNumEquals(11908.2609, km.getValue(20)); assertNumEquals(11928.7941, km.getValue(21)); assertNumEquals(11950.5749, km.getValue(22)); assertNumEquals(11978.7156, km.getValue(23)); assertNumEquals(12012.6402, km.getValue(24)); assertNumEquals(12042.9401, km.getValue(25)); assertNumEquals(12067.7868, km.getValue(26)); assertNumEquals(12095.1832, km.getValue(27)); assertNumEquals(12118.2508, km.getValue(28)); assertNumEquals(12132.7027, km.getValue(29)); } |
BarSeriesManager { public TradingRecord run(Strategy strategy) { return run(strategy, OrderType.BUY); } BarSeriesManager(); BarSeriesManager(BarSeries barSeries); BarSeriesManager(BarSeries barSeries, CostModel transactionCostModel, CostModel holdingCostModel); void setBarSeries(BarSeries barSeries); BarSeries getBarSeries(); TradingRecord run(Strategy strategy); TradingRecord run(Strategy strategy, int startIndex, int finishIndex); TradingRecord run(Strategy strategy, OrderType orderType); TradingRecord run(Strategy strategy, OrderType orderType, int startIndex, int finishIndex); TradingRecord run(Strategy strategy, OrderType orderType, Num amount); TradingRecord run(Strategy strategy, OrderType orderType, Num amount, int startIndex, int finishIndex); } | @Test public void runOnSeries() { List<Trade> trades = manager.run(strategy).getTrades(); assertEquals(2, trades.size()); assertEquals(Order.buyAt(2, seriesForRun.getBar(2).getClosePrice(), numOf(1)), trades.get(0).getEntry()); assertEquals(Order.sellAt(4, seriesForRun.getBar(4).getClosePrice(), numOf(1)), trades.get(0).getExit()); assertEquals(Order.buyAt(6, seriesForRun.getBar(6).getClosePrice(), numOf(1)), trades.get(1).getEntry()); assertEquals(Order.sellAt(7, seriesForRun.getBar(7).getClosePrice(), numOf(1)), trades.get(1).getExit()); }
@Test public void runWithOpenEntryBuyLeft() { Strategy aStrategy = new BaseStrategy(new FixedRule(1), new FixedRule(3)); List<Trade> trades = manager.run(aStrategy, 0, 3).getTrades(); assertEquals(1, trades.size()); assertEquals(Order.buyAt(1, seriesForRun.getBar(1).getClosePrice(), numOf(1)), trades.get(0).getEntry()); assertEquals(Order.sellAt(3, seriesForRun.getBar(3).getClosePrice(), numOf(1)), trades.get(0).getExit()); }
@Test public void runWithOpenEntrySellLeft() { Strategy aStrategy = new BaseStrategy(new FixedRule(1), new FixedRule(3)); List<Trade> trades = manager.run(aStrategy, OrderType.SELL, 0, 3).getTrades(); assertEquals(1, trades.size()); assertEquals(Order.sellAt(1, seriesForRun.getBar(1).getClosePrice(), numOf(1)), trades.get(0).getEntry()); assertEquals(Order.buyAt(3, seriesForRun.getBar(3).getClosePrice(), numOf(1)), trades.get(0).getExit()); }
@Test public void runBetweenIndexes() { List<Trade> trades = manager.run(strategy, 0, 3).getTrades(); assertEquals(1, trades.size()); assertEquals(Order.buyAt(2, seriesForRun.getBar(2).getClosePrice(), numOf(1)), trades.get(0).getEntry()); assertEquals(Order.sellAt(4, seriesForRun.getBar(4).getClosePrice(), numOf(1)), trades.get(0).getExit()); trades = manager.run(strategy, 4, 4).getTrades(); assertTrue(trades.isEmpty()); trades = manager.run(strategy, 5, 8).getTrades(); assertEquals(1, trades.size()); assertEquals(Order.buyAt(6, seriesForRun.getBar(6).getClosePrice(), numOf(1)), trades.get(0).getEntry()); assertEquals(Order.sellAt(7, seriesForRun.getBar(7).getClosePrice(), numOf(1)), trades.get(0).getExit()); } |
FixedRule extends AbstractRule { @Override public boolean isSatisfied(int index, TradingRecord tradingRecord) { boolean satisfied = false; for (int idx : indexes) { if (idx == index) { satisfied = true; break; } } traceIsSatisfied(index, satisfied); return satisfied; } FixedRule(int... indexes); @Override boolean isSatisfied(int index, TradingRecord tradingRecord); } | @Test public void isSatisfied() { FixedRule fixedRule = new FixedRule(); assertFalse(fixedRule.isSatisfied(0)); assertFalse(fixedRule.isSatisfied(1)); assertFalse(fixedRule.isSatisfied(2)); assertFalse(fixedRule.isSatisfied(9)); fixedRule = new FixedRule(1, 2, 3); assertFalse(fixedRule.isSatisfied(0)); assertTrue(fixedRule.isSatisfied(1)); assertTrue(fixedRule.isSatisfied(2)); assertTrue(fixedRule.isSatisfied(3)); assertFalse(fixedRule.isSatisfied(4)); assertFalse(fixedRule.isSatisfied(5)); assertFalse(fixedRule.isSatisfied(6)); assertFalse(fixedRule.isSatisfied(7)); assertFalse(fixedRule.isSatisfied(8)); assertFalse(fixedRule.isSatisfied(9)); assertFalse(fixedRule.isSatisfied(10)); } |
Returns implements Indicator<Num> { public int getSize() { return barSeries.getBarCount() - 1; } Returns(BarSeries barSeries, Trade trade, ReturnType type); Returns(BarSeries barSeries, TradingRecord tradingRecord, ReturnType type); List<Num> getValues(); @Override Num getValue(int index); @Override BarSeries getBarSeries(); @Override Num numOf(Number number); int getSize(); void calculate(Trade trade); void calculate(Trade trade, int finalIndex); } | @Test public void returnSize() { for (Returns.ReturnType type : Returns.ReturnType.values()) { BarSeries sampleBarSeries = new MockBarSeries(numFunction, 1d, 2d, 3d, 4d, 5d); Returns returns = new Returns(sampleBarSeries, new BaseTradingRecord(), type); assertEquals(4, returns.getSize()); } } |
Returns implements Indicator<Num> { @Override public Num getValue(int index) { return values.get(index); } Returns(BarSeries barSeries, Trade trade, ReturnType type); Returns(BarSeries barSeries, TradingRecord tradingRecord, ReturnType type); List<Num> getValues(); @Override Num getValue(int index); @Override BarSeries getBarSeries(); @Override Num numOf(Number number); int getSize(); void calculate(Trade trade); void calculate(Trade trade, int finalIndex); } | @Test public void singleReturnTradeArith() { BarSeries sampleBarSeries = new MockBarSeries(numFunction, 1d, 2d); TradingRecord tradingRecord = new BaseTradingRecord(Order.buyAt(0, sampleBarSeries), Order.sellAt(1, sampleBarSeries)); Returns return1 = new Returns(sampleBarSeries, tradingRecord, Returns.ReturnType.ARITHMETIC); assertNumEquals(NaN.NaN, return1.getValue(0)); assertNumEquals(1.0, return1.getValue(1)); }
@Test public void returnsWithSellAndBuyOrders() { BarSeries sampleBarSeries = new MockBarSeries(numFunction, 2, 1, 3, 5, 6, 3, 20); TradingRecord tradingRecord = new BaseTradingRecord(Order.buyAt(0, sampleBarSeries), Order.sellAt(1, sampleBarSeries), Order.buyAt(3, sampleBarSeries), Order.sellAt(4, sampleBarSeries), Order.sellAt(5, sampleBarSeries), Order.buyAt(6, sampleBarSeries)); Returns strategyReturns = new Returns(sampleBarSeries, tradingRecord, Returns.ReturnType.ARITHMETIC); assertNumEquals(NaN.NaN, strategyReturns.getValue(0)); assertNumEquals(-0.5, strategyReturns.getValue(1)); assertNumEquals(0, strategyReturns.getValue(2)); assertNumEquals(0, strategyReturns.getValue(3)); assertNumEquals(1d / 5, strategyReturns.getValue(4)); assertNumEquals(0, strategyReturns.getValue(5)); assertNumEquals(1 - (20d / 3), strategyReturns.getValue(6)); }
@Test public void returnsWithGaps() { BarSeries sampleBarSeries = new MockBarSeries(numFunction, 1d, 2d, 3d, 4d, 5d, 6d, 7d, 8d, 9d, 10d, 11d, 12d); TradingRecord tradingRecord = new BaseTradingRecord(Order.sellAt(2, sampleBarSeries), Order.buyAt(5, sampleBarSeries), Order.buyAt(8, sampleBarSeries), Order.sellAt(10, sampleBarSeries)); Returns returns = new Returns(sampleBarSeries, tradingRecord, Returns.ReturnType.LOG); assertNumEquals(NaN.NaN, returns.getValue(0)); assertNumEquals(0, returns.getValue(1)); assertNumEquals(0, returns.getValue(2)); assertNumEquals(-0.28768207245178085, returns.getValue(3)); assertNumEquals(-0.22314355131420976, returns.getValue(4)); assertNumEquals(-0.1823215567939546, returns.getValue(5)); assertNumEquals(0, returns.getValue(6)); assertNumEquals(0, returns.getValue(7)); assertNumEquals(0, returns.getValue(8)); assertNumEquals(0.10536051565782635, returns.getValue(9)); assertNumEquals(0.09531017980432493, returns.getValue(10)); assertNumEquals(0, returns.getValue(11)); }
@Test public void returnsWithNoTrades() { BarSeries sampleBarSeries = new MockBarSeries(numFunction, 3d, 2d, 5d, 4d, 7d, 6d, 7d, 8d, 5d, 6d); Returns returns = new Returns(sampleBarSeries, new BaseTradingRecord(), Returns.ReturnType.LOG); assertNumEquals(NaN.NaN, returns.getValue(0)); assertNumEquals(0, returns.getValue(4)); assertNumEquals(0, returns.getValue(7)); assertNumEquals(0, returns.getValue(9)); } |
CashFlow implements Indicator<Num> { public int getSize() { return barSeries.getBarCount(); } CashFlow(BarSeries barSeries, Trade trade); CashFlow(BarSeries barSeries, TradingRecord tradingRecord); CashFlow(BarSeries barSeries, TradingRecord tradingRecord, int finalIndex); @Override Num getValue(int index); @Override BarSeries getBarSeries(); @Override Num numOf(Number number); int getSize(); } | @Test public void cashFlowSize() { BarSeries sampleBarSeries = new MockBarSeries(numFunction, 1d, 2d, 3d, 4d, 5d); CashFlow cashFlow = new CashFlow(sampleBarSeries, new BaseTradingRecord()); assertEquals(5, cashFlow.getSize()); } |
CashFlow implements Indicator<Num> { @Override public Num getValue(int index) { return values.get(index); } CashFlow(BarSeries barSeries, Trade trade); CashFlow(BarSeries barSeries, TradingRecord tradingRecord); CashFlow(BarSeries barSeries, TradingRecord tradingRecord, int finalIndex); @Override Num getValue(int index); @Override BarSeries getBarSeries(); @Override Num numOf(Number number); int getSize(); } | @Test public void cashFlowBuyWithOnlyOneTrade() { BarSeries sampleBarSeries = new MockBarSeries(numFunction, 1d, 2d); TradingRecord tradingRecord = new BaseTradingRecord(Order.buyAt(0, sampleBarSeries), Order.sellAt(1, sampleBarSeries)); CashFlow cashFlow = new CashFlow(sampleBarSeries, tradingRecord); assertNumEquals(1, cashFlow.getValue(0)); assertNumEquals(2, cashFlow.getValue(1)); }
@Test public void cashFlowWithSellAndBuyOrders() { BarSeries sampleBarSeries = new MockBarSeries(numFunction, 2, 1, 3, 5, 6, 3, 20); TradingRecord tradingRecord = new BaseTradingRecord(Order.buyAt(0, sampleBarSeries), Order.sellAt(1, sampleBarSeries), Order.buyAt(3, sampleBarSeries), Order.sellAt(4, sampleBarSeries), Order.sellAt(5, sampleBarSeries), Order.buyAt(6, sampleBarSeries)); CashFlow cashFlow = new CashFlow(sampleBarSeries, tradingRecord); assertNumEquals(1, cashFlow.getValue(0)); assertNumEquals("0.5", cashFlow.getValue(1)); assertNumEquals("0.5", cashFlow.getValue(2)); assertNumEquals("0.5", cashFlow.getValue(3)); assertNumEquals("0.6", cashFlow.getValue(4)); assertNumEquals("0.6", cashFlow.getValue(5)); assertNumEquals("-2.8", cashFlow.getValue(6)); }
@Test public void cashFlowSell() { BarSeries sampleBarSeries = new MockBarSeries(numFunction, 1, 2, 4, 8, 16, 32); TradingRecord tradingRecord = new BaseTradingRecord(Order.sellAt(2, sampleBarSeries), Order.buyAt(3, sampleBarSeries)); CashFlow cashFlow = new CashFlow(sampleBarSeries, tradingRecord); assertNumEquals(1, cashFlow.getValue(0)); assertNumEquals(1, cashFlow.getValue(1)); assertNumEquals(1, cashFlow.getValue(2)); assertNumEquals(0, cashFlow.getValue(3)); assertNumEquals(0, cashFlow.getValue(4)); assertNumEquals(0, cashFlow.getValue(5)); }
@Test public void cashFlowShortSell() { BarSeries sampleBarSeries = new MockBarSeries(numFunction, 1, 2, 4, 8, 16, 32); TradingRecord tradingRecord = new BaseTradingRecord(Order.buyAt(0, sampleBarSeries), Order.sellAt(2, sampleBarSeries), Order.sellAt(2, sampleBarSeries), Order.buyAt(4, sampleBarSeries), Order.buyAt(4, sampleBarSeries), Order.sellAt(5, sampleBarSeries)); CashFlow cashFlow = new CashFlow(sampleBarSeries, tradingRecord); assertNumEquals(1, cashFlow.getValue(0)); assertNumEquals(2, cashFlow.getValue(1)); assertNumEquals(4, cashFlow.getValue(2)); assertNumEquals(0, cashFlow.getValue(3)); assertNumEquals(-8, cashFlow.getValue(4)); assertNumEquals(-8, cashFlow.getValue(5)); }
@Test public void cashFlowValueWithOnlyOneTradeAndAGapBefore() { BarSeries sampleBarSeries = new MockBarSeries(numFunction, 1d, 1d, 2d); TradingRecord tradingRecord = new BaseTradingRecord(Order.buyAt(1, sampleBarSeries), Order.sellAt(2, sampleBarSeries)); CashFlow cashFlow = new CashFlow(sampleBarSeries, tradingRecord); assertNumEquals(1, cashFlow.getValue(0)); assertNumEquals(1, cashFlow.getValue(1)); assertNumEquals(2, cashFlow.getValue(2)); }
@Test public void cashFlowValueWithTwoTradesAndLongTimeWithoutOrders() { BarSeries sampleBarSeries = new MockBarSeries(numFunction, 1d, 2d, 4d, 8d, 16d, 32d); TradingRecord tradingRecord = new BaseTradingRecord(Order.buyAt(1, sampleBarSeries), Order.sellAt(2, sampleBarSeries), Order.buyAt(4, sampleBarSeries), Order.sellAt(5, sampleBarSeries)); CashFlow cashFlow = new CashFlow(sampleBarSeries, tradingRecord); assertNumEquals(1, cashFlow.getValue(0)); assertNumEquals(1, cashFlow.getValue(1)); assertNumEquals(2, cashFlow.getValue(2)); assertNumEquals(2, cashFlow.getValue(3)); assertNumEquals(2, cashFlow.getValue(4)); assertNumEquals(4, cashFlow.getValue(5)); }
@Test public void cashFlowValue() { BarSeries sampleBarSeries = new MockBarSeries(numFunction, 3d, 2d, 5d, 1000d, 5000d, 0.0001d, 4d, 7d, 6d, 7d, 8d, 5d, 6d); TradingRecord tradingRecord = new BaseTradingRecord(Order.buyAt(0, sampleBarSeries), Order.sellAt(2, sampleBarSeries), Order.buyAt(6, sampleBarSeries), Order.sellAt(8, sampleBarSeries), Order.buyAt(9, sampleBarSeries), Order.sellAt(11, sampleBarSeries)); CashFlow cashFlow = new CashFlow(sampleBarSeries, tradingRecord); assertNumEquals(1, cashFlow.getValue(0)); assertNumEquals(2d / 3, cashFlow.getValue(1)); assertNumEquals(5d / 3, cashFlow.getValue(2)); assertNumEquals(5d / 3, cashFlow.getValue(3)); assertNumEquals(5d / 3, cashFlow.getValue(4)); assertNumEquals(5d / 3, cashFlow.getValue(5)); assertNumEquals(5d / 3, cashFlow.getValue(6)); assertNumEquals(5d / 3 * 7d / 4, cashFlow.getValue(7)); assertNumEquals(5d / 3 * 6d / 4, cashFlow.getValue(8)); assertNumEquals(5d / 3 * 6d / 4, cashFlow.getValue(9)); assertNumEquals(5d / 3 * 6d / 4 * 8d / 7, cashFlow.getValue(10)); assertNumEquals(5d / 3 * 6d / 4 * 5d / 7, cashFlow.getValue(11)); assertNumEquals(5d / 3 * 6d / 4 * 5d / 7, cashFlow.getValue(12)); sampleBarSeries = new MockBarSeries(numFunction, 5d, 6d, 3d, 7d, 8d, 6d, 10d, 15d, 6d); tradingRecord = new BaseTradingRecord(Order.buyAt(4, sampleBarSeries), Order.sellAt(5, sampleBarSeries), Order.buyAt(6, sampleBarSeries), Order.sellAt(8, sampleBarSeries)); CashFlow flow = new CashFlow(sampleBarSeries, tradingRecord); assertNumEquals(1, flow.getValue(0)); assertNumEquals(1, flow.getValue(1)); assertNumEquals(1, flow.getValue(2)); assertNumEquals(1, flow.getValue(3)); assertNumEquals(1, flow.getValue(4)); assertNumEquals("0.75", flow.getValue(5)); assertNumEquals("0.75", flow.getValue(6)); assertNumEquals("1.125", flow.getValue(7)); assertNumEquals("0.45", flow.getValue(8)); }
@Test public void cashFlowValueWithNoTrades() { BarSeries sampleBarSeries = new MockBarSeries(numFunction, 3d, 2d, 5d, 4d, 7d, 6d, 7d, 8d, 5d, 6d); CashFlow cashFlow = new CashFlow(sampleBarSeries, new BaseTradingRecord()); assertNumEquals(1, cashFlow.getValue(4)); assertNumEquals(1, cashFlow.getValue(7)); assertNumEquals(1, cashFlow.getValue(9)); }
@Test public void reallyLongCashFlow() { int size = 1000000; BarSeries sampleBarSeries = new MockBarSeries(Collections.nCopies(size, new MockBar(10, numFunction))); TradingRecord tradingRecord = new BaseTradingRecord(Order.buyAt(0, sampleBarSeries), Order.sellAt(size - 1, sampleBarSeries)); CashFlow cashFlow = new CashFlow(sampleBarSeries, tradingRecord); assertNumEquals(1, cashFlow.getValue(size - 1)); } |
IsLowestRule extends AbstractRule { @Override public boolean isSatisfied(int index, TradingRecord tradingRecord) { LowestValueIndicator lowest = new LowestValueIndicator(ref, barCount); Num lowestVal = lowest.getValue(index); Num refVal = ref.getValue(index); final boolean satisfied = !refVal.isNaN() && !lowestVal.isNaN() && refVal.equals(lowestVal); traceIsSatisfied(index, satisfied); return satisfied; } IsLowestRule(Indicator<Num> ref, int barCount); @Override boolean isSatisfied(int index, TradingRecord tradingRecord); } | @Test public void isSatisfied() { assertTrue(rule.isSatisfied(0)); assertTrue(rule.isSatisfied(1)); assertFalse(rule.isSatisfied(2)); assertTrue(rule.isSatisfied(3)); assertFalse(rule.isSatisfied(4)); assertTrue(rule.isSatisfied(5)); assertFalse(rule.isSatisfied(6)); assertFalse(rule.isSatisfied(7)); assertFalse(rule.isSatisfied(8)); assertTrue(rule.isSatisfied(9)); } |
NumberOfLosingTradesCriterion extends AbstractAnalysisCriterion { @Override public Num calculate(BarSeries series, TradingRecord tradingRecord) { long numberOfLosingTrades = tradingRecord.getTrades().stream().filter(Trade::isClosed) .filter(trade -> isLosingTrade(series, trade)).count(); return series.numOf(numberOfLosingTrades); } @Override Num calculate(BarSeries series, TradingRecord tradingRecord); @Override Num calculate(BarSeries series, Trade trade); @Override boolean betterThan(Num criterionValue1, Num criterionValue2); } | @Test public void calculateWithNoTrades() { MockBarSeries series = new MockBarSeries(numFunction, 100, 105, 110, 100, 95, 105); assertNumEquals(0, getCriterion().calculate(series, new BaseTradingRecord())); }
@Test public void calculateWithTwoTrades() { MockBarSeries series = new MockBarSeries(numFunction, 100, 105, 110, 100, 95, 105); TradingRecord tradingRecord = new BaseTradingRecord(Order.buyAt(1, series), Order.sellAt(3, series), Order.buyAt(3, series), Order.sellAt(4, series)); assertNumEquals(2, getCriterion().calculate(series, tradingRecord)); }
@Test public void calculateWithOneTrade() { MockBarSeries series = new MockBarSeries(numFunction, 100, 105, 110, 100, 95, 105); Trade trade = new Trade(Order.buyAt(1, series), Order.sellAt(3, series)); assertNumEquals(1, getCriterion().calculate(series, trade)); } |
NumberOfLosingTradesCriterion extends AbstractAnalysisCriterion { @Override public boolean betterThan(Num criterionValue1, Num criterionValue2) { return criterionValue1.isLessThan(criterionValue2); } @Override Num calculate(BarSeries series, TradingRecord tradingRecord); @Override Num calculate(BarSeries series, Trade trade); @Override boolean betterThan(Num criterionValue1, Num criterionValue2); } | @Test public void betterThan() { AnalysisCriterion criterion = getCriterion(); assertTrue(criterion.betterThan(numOf(3), numOf(6))); assertFalse(criterion.betterThan(numOf(7), numOf(4))); } |
VersusBuyAndHoldCriterion extends AbstractAnalysisCriterion { @Override public Num calculate(BarSeries series, TradingRecord tradingRecord) { TradingRecord fakeRecord = new BaseTradingRecord(); fakeRecord.enter(series.getBeginIndex()); fakeRecord.exit(series.getEndIndex()); return criterion.calculate(series, tradingRecord).dividedBy(criterion.calculate(series, fakeRecord)); } VersusBuyAndHoldCriterion(AnalysisCriterion criterion); @Override Num calculate(BarSeries series, TradingRecord tradingRecord); @Override Num calculate(BarSeries series, Trade trade); @Override boolean betterThan(Num criterionValue1, Num criterionValue2); } | @Test public void calculateOnlyWithGainTrades() { MockBarSeries series = new MockBarSeries(numFunction, 100, 105, 110, 100, 95, 105); TradingRecord tradingRecord = new BaseTradingRecord(Order.buyAt(0, series), Order.sellAt(2, series), Order.buyAt(3, series), Order.sellAt(5, series)); AnalysisCriterion buyAndHold = getCriterion(new TotalProfitCriterion()); assertNumEquals(1.10 * 1.05 / 1.05, buyAndHold.calculate(series, tradingRecord)); }
@Test public void calculateOnlyWithLossTrades() { MockBarSeries series = new MockBarSeries(numFunction, 100, 95, 100, 80, 85, 70); TradingRecord tradingRecord = new BaseTradingRecord(Order.buyAt(0, series), Order.sellAt(1, series), Order.buyAt(2, series), Order.sellAt(5, series)); AnalysisCriterion buyAndHold = getCriterion(new TotalProfitCriterion()); assertNumEquals(0.95 * 0.7 / 0.7, buyAndHold.calculate(series, tradingRecord)); }
@Test public void calculateWithOnlyOneTrade() { MockBarSeries series = new MockBarSeries(numFunction, 100, 95, 100, 80, 85, 70); Trade trade = new Trade(Order.buyAt(0, series), Order.sellAt(1, series)); AnalysisCriterion buyAndHold = getCriterion(new TotalProfitCriterion()); assertNumEquals((100d / 70) / (100d / 95), buyAndHold.calculate(series, trade)); }
@Test public void calculateWithNoTrades() { MockBarSeries series = new MockBarSeries(numFunction, 100, 95, 100, 80, 85, 70); AnalysisCriterion buyAndHold = getCriterion(new TotalProfitCriterion()); assertNumEquals(1 / 0.7, buyAndHold.calculate(series, new BaseTradingRecord())); }
@Test public void calculateWithAverageProfit() { MockBarSeries series = new MockBarSeries(numFunction, 100, 95, 100, 80, 85, 130); TradingRecord tradingRecord = new BaseTradingRecord(Order.buyAt(0, NaN, NaN), Order.sellAt(1, NaN, NaN), Order.buyAt(2, NaN, NaN), Order.sellAt(5, NaN, NaN)); AnalysisCriterion buyAndHold = getCriterion(new AverageProfitCriterion()); assertNumEquals(Math.pow(95d / 100 * 130d / 100, 1d / 6) / Math.pow(130d / 100, 1d / 6), buyAndHold.calculate(series, tradingRecord)); }
@Test public void calculateWithNumberOfBars() { MockBarSeries series = new MockBarSeries(numFunction, 100, 95, 100, 80, 85, 130); TradingRecord tradingRecord = new BaseTradingRecord(Order.buyAt(0, series), Order.sellAt(1, series), Order.buyAt(2, series), Order.sellAt(5, series)); AnalysisCriterion buyAndHold = getCriterion(new NumberOfBarsCriterion()); assertNumEquals(6d / 6d, buyAndHold.calculate(series, tradingRecord)); } |
VersusBuyAndHoldCriterion extends AbstractAnalysisCriterion { @Override public boolean betterThan(Num criterionValue1, Num criterionValue2) { return criterionValue1.isGreaterThan(criterionValue2); } VersusBuyAndHoldCriterion(AnalysisCriterion criterion); @Override Num calculate(BarSeries series, TradingRecord tradingRecord); @Override Num calculate(BarSeries series, Trade trade); @Override boolean betterThan(Num criterionValue1, Num criterionValue2); } | @Test public void betterThan() { AnalysisCriterion criterion = getCriterion(new TotalProfitCriterion()); assertTrue(criterion.betterThan(numOf(2.0), numOf(1.5))); assertFalse(criterion.betterThan(numOf(1.5), numOf(2.0))); } |
NumberOfWinningTradesCriterion extends AbstractAnalysisCriterion { @Override public Num calculate(BarSeries series, TradingRecord tradingRecord) { long numberOfLosingTrades = tradingRecord.getTrades().stream().filter(Trade::isClosed) .filter(trade -> isWinningTrade(series, trade)).count(); return series.numOf(numberOfLosingTrades); } @Override Num calculate(BarSeries series, TradingRecord tradingRecord); @Override Num calculate(BarSeries series, Trade trade); @Override boolean betterThan(Num criterionValue1, Num criterionValue2); } | @Test public void calculateWithNoTrades() { MockBarSeries series = new MockBarSeries(numFunction, 100, 105, 110, 100, 95, 105); assertNumEquals(0, getCriterion().calculate(series, new BaseTradingRecord())); }
@Test public void calculateWithTwoTrades() { MockBarSeries series = new MockBarSeries(numFunction, 100, 105, 110, 100, 95, 105); TradingRecord tradingRecord = new BaseTradingRecord(Order.buyAt(0, series), Order.sellAt(2, series), Order.buyAt(3, series), Order.sellAt(5, series)); assertNumEquals(2, getCriterion().calculate(series, tradingRecord)); }
@Test public void calculateWithOneTrade() { MockBarSeries series = new MockBarSeries(numFunction, 100, 105, 110, 100, 95, 105); Trade trade = new Trade(Order.buyAt(0, series), Order.sellAt(2, series)); assertNumEquals(1, getCriterion().calculate(series, trade)); } |
NotRule extends AbstractRule { @Override public boolean isSatisfied(int index, TradingRecord tradingRecord) { final boolean satisfied = !ruleToNegate.isSatisfied(index, tradingRecord); traceIsSatisfied(index, satisfied); return satisfied; } NotRule(Rule ruleToNegate); @Override boolean isSatisfied(int index, TradingRecord tradingRecord); Rule getRuleToNegate(); } | @Test public void isSatisfied() { assertFalse(satisfiedRule.negation().isSatisfied(0)); assertTrue(unsatisfiedRule.negation().isSatisfied(0)); assertFalse(satisfiedRule.negation().isSatisfied(10)); assertTrue(unsatisfiedRule.negation().isSatisfied(10)); } |
NumberOfWinningTradesCriterion extends AbstractAnalysisCriterion { @Override public boolean betterThan(Num criterionValue1, Num criterionValue2) { return criterionValue1.isLessThan(criterionValue2); } @Override Num calculate(BarSeries series, TradingRecord tradingRecord); @Override Num calculate(BarSeries series, Trade trade); @Override boolean betterThan(Num criterionValue1, Num criterionValue2); } | @Test public void betterThan() { AnalysisCriterion criterion = getCriterion(); assertTrue(criterion.betterThan(numOf(3), numOf(6))); assertFalse(criterion.betterThan(numOf(7), numOf(4))); } |
BuyAndHoldCriterion extends AbstractAnalysisCriterion { @Override public Num calculate(BarSeries series, TradingRecord tradingRecord) { return series.getBar(series.getEndIndex()).getClosePrice() .dividedBy(series.getBar(series.getBeginIndex()).getClosePrice()); } @Override Num calculate(BarSeries series, TradingRecord tradingRecord); @Override Num calculate(BarSeries series, Trade trade); @Override boolean betterThan(Num criterionValue1, Num criterionValue2); } | @Test public void calculateOnlyWithGainTrades() { MockBarSeries series = new MockBarSeries(numFunction, 100, 105, 110, 100, 95, 105); TradingRecord tradingRecord = new BaseTradingRecord(Order.buyAt(0, series), Order.sellAt(2, series), Order.buyAt(3, series), Order.sellAt(5, series)); AnalysisCriterion buyAndHold = getCriterion(); assertNumEquals(1.05, buyAndHold.calculate(series, tradingRecord)); }
@Test public void calculateOnlyWithLossTrades() { MockBarSeries series = new MockBarSeries(numFunction, 100, 95, 100, 80, 85, 70); TradingRecord tradingRecord = new BaseTradingRecord(Order.buyAt(0, series), Order.sellAt(1, series), Order.buyAt(2, series), Order.sellAt(5, series)); AnalysisCriterion buyAndHold = getCriterion(); assertNumEquals(0.7, buyAndHold.calculate(series, tradingRecord)); }
@Test public void calculateWithNoTrades() { MockBarSeries series = new MockBarSeries(numFunction, 100, 95, 100, 80, 85, 70); AnalysisCriterion buyAndHold = getCriterion(); assertNumEquals(0.7, buyAndHold.calculate(series, new BaseTradingRecord())); }
@Test public void calculateWithOneTrade() { MockBarSeries series = new MockBarSeries(numFunction, 100, 105); Trade trade = new Trade(Order.buyAt(0, series), Order.sellAt(1, series)); AnalysisCriterion buyAndHold = getCriterion(); assertNumEquals(105d / 100, buyAndHold.calculate(series, trade)); } |
BuyAndHoldCriterion extends AbstractAnalysisCriterion { @Override public boolean betterThan(Num criterionValue1, Num criterionValue2) { return criterionValue1.isGreaterThan(criterionValue2); } @Override Num calculate(BarSeries series, TradingRecord tradingRecord); @Override Num calculate(BarSeries series, Trade trade); @Override boolean betterThan(Num criterionValue1, Num criterionValue2); } | @Test public void betterThan() { AnalysisCriterion criterion = getCriterion(); assertTrue(criterion.betterThan(numOf(1.3), numOf(1.1))); assertFalse(criterion.betterThan(numOf(0.6), numOf(0.9))); } |
NumberOfBarsCriterion extends AbstractAnalysisCriterion { @Override public Num calculate(BarSeries series, TradingRecord tradingRecord) { return tradingRecord.getTrades().stream().filter(Trade::isClosed).map(t -> calculate(series, t)) .reduce(series.numOf(0), Num::plus); } @Override Num calculate(BarSeries series, TradingRecord tradingRecord); @Override Num calculate(BarSeries series, Trade trade); @Override boolean betterThan(Num criterionValue1, Num criterionValue2); } | @Test public void calculateWithNoTrades() { MockBarSeries series = new MockBarSeries(numFunction, 100, 105, 110, 100, 95, 105); AnalysisCriterion numberOfBars = getCriterion(); assertNumEquals(0, numberOfBars.calculate(series, new BaseTradingRecord())); }
@Test public void calculateWithTwoTrades() { MockBarSeries series = new MockBarSeries(numFunction, 100, 105, 110, 100, 95, 105); TradingRecord tradingRecord = new BaseTradingRecord(Order.buyAt(0, series), Order.sellAt(2, series), Order.buyAt(3, series), Order.sellAt(5, series)); AnalysisCriterion numberOfBars = getCriterion(); assertNumEquals(6, numberOfBars.calculate(series, tradingRecord)); }
@Test public void calculateWithOneTrade() { MockBarSeries series = new MockBarSeries(numFunction, 100, 95, 100, 80, 85, 70); Trade t = new Trade(Order.buyAt(2, series), Order.sellAt(5, series)); AnalysisCriterion numberOfBars = getCriterion(); assertNumEquals(4, numberOfBars.calculate(series, t)); } |
AndRule extends AbstractRule { @Override public boolean isSatisfied(int index, TradingRecord tradingRecord) { final boolean satisfied = rule1.isSatisfied(index, tradingRecord) && rule2.isSatisfied(index, tradingRecord); traceIsSatisfied(index, satisfied); return satisfied; } AndRule(Rule rule1, Rule rule2); @Override boolean isSatisfied(int index, TradingRecord tradingRecord); Rule getRule1(); Rule getRule2(); } | @Test public void isSatisfied() { assertFalse(satisfiedRule.and(BooleanRule.FALSE).isSatisfied(0)); assertFalse(BooleanRule.FALSE.and(satisfiedRule).isSatisfied(0)); assertFalse(unsatisfiedRule.and(BooleanRule.FALSE).isSatisfied(0)); assertFalse(BooleanRule.FALSE.and(unsatisfiedRule).isSatisfied(0)); assertTrue(satisfiedRule.and(BooleanRule.TRUE).isSatisfied(10)); assertTrue(BooleanRule.TRUE.and(satisfiedRule).isSatisfied(10)); assertFalse(unsatisfiedRule.and(BooleanRule.TRUE).isSatisfied(10)); assertFalse(BooleanRule.TRUE.and(unsatisfiedRule).isSatisfied(10)); } |
RESTService extends Service { @Override public final String getAlias() { try { String pathPrefix = null; for (Annotation classAnnotation : this.getClass().getAnnotations()) { if (classAnnotation instanceof ServicePath) { pathPrefix = ((ServicePath) classAnnotation).value(); break; } } if (pathPrefix == null) { throw new Exception("ServicePath annotation for service class is required!"); } pathPrefix = pathPrefix.trim(); pathPrefix = pathPrefix.replaceAll("(^/)|(/$)", ""); if (pathPrefix.length() == 0) { throw new Exception("ServicePath annotation for service class is required!"); } return pathPrefix; } catch (Exception e) { } return null; } RESTService(); final RESTResponse handle(URI baseUri, URI requestUri, String method, byte[] body,
Map<String, List<String>> headers); final String getSwagger(); @Override final String getAlias(); } | @Test public void testAlias() { assertEquals("service1", testee.getAlias()); } |
LocalNode extends Node { public void storeAgent(Agent agent) throws AgentException { storeAgent((AgentImpl) agent); } LocalNode(LocalNodeManager localNodeManager); LocalNode(LocalNodeManager localNodeManager, ClassManager classManager); @Override Long getNodeId(); @Override void shutDown(); @Override void registerReceiver(MessageReceiver receiver); @Override void sendMessage(Message message, MessageResultListener listener, SendMode mode); @Override void sendMessage(Message message, Object atNodeId, MessageResultListener listener); @Deprecated @Override EnvelopeVersion fetchArtifact(long id); @Deprecated @Override void storeArtifact(EnvelopeVersion envelope); @Deprecated @Override void removeArtifact(long id, byte[] signature); @Override Object[] findRegisteredAgent(String agentId, int hintOfExpectedCount); @Override AgentImpl getAgent(String id); void storeAgent(Agent agent); @Override void storeAgent(AgentImpl agent); @Deprecated @Override void updateAgent(AgentImpl agent); @Override Object[] getOtherKnownNodes(); @Override NodeInformation getNodeInformation(Object nodeId); @Override EnvelopeVersion createEnvelope(String identifier, PublicKey authorPubKey, Serializable content,
AgentImpl... reader); @Override EnvelopeVersion createEnvelope(EnvelopeVersion previousVersion, Serializable content); @Override EnvelopeVersion createEnvelope(EnvelopeVersion previousVersion, Serializable content, AgentImpl... reader); @Override void storeEnvelope(EnvelopeVersion envelope, AgentImpl author); @Override EnvelopeVersion fetchEnvelope(String identifier); @Override EnvelopeVersion createEnvelope(String identifier, PublicKey authorPubKey, Serializable content,
Collection<?> readers); @Override EnvelopeVersion createEnvelope(EnvelopeVersion previousVersion, Serializable content, Collection<?> readers); @Override EnvelopeVersion createUnencryptedEnvelope(String identifier, PublicKey authorPubKey, Serializable content); @Override EnvelopeVersion createUnencryptedEnvelope(EnvelopeVersion previousVersion, Serializable content); @Override void storeEnvelope(EnvelopeVersion envelope, AgentImpl author, long timeoutMs); @Override void storeEnvelopeAsync(EnvelopeVersion envelope, AgentImpl author, StorageStoreResultHandler resultHandler,
StorageCollisionHandler collisionHandler, StorageExceptionHandler exceptionHandler); @Override EnvelopeVersion fetchEnvelope(String identifier, long timeoutMs); @Override void fetchEnvelopeAsync(String identifier, StorageEnvelopeHandler envelopeHandler,
StorageExceptionHandler exceptionHandler); @Override void removeEnvelope(String identifier); @Override EnvelopeVersion fetchArtifact(String identifier); } | @Test public void testStartupAgents() { try { LocalNode testee = new LocalNodeManager().newNode(); UserAgentImpl adam = MockAgentFactory.getAdam(); adam.unlock("adamspass"); testee.storeAgent(adam); testee.launch(); UserAgentImpl abel = MockAgentFactory.getAbel(); try { testee.storeAgent(abel); fail("AgentLockedException expected"); } catch (AgentLockedException e) { } abel.unlock("abelspass"); testee.storeAgent(abel); } catch (Exception e) { e.printStackTrace(); Assert.fail(e.toString()); } }
@Test public void testSimpleInvocation() { try { String serviceClass = "i5.las2peer.api.TestService"; LocalNode testee = new LocalNodeManager().launchNode(); UserAgentImpl eve = MockAgentFactory.getEve(); eve.unlock("evespass"); testee.storeAgent(eve); ServiceAgentImpl testService = testee.startService(ServiceNameVersion.fromString(serviceClass + "@1.0"), "a passphrase"); Serializable result = testee.invokeLocally(eve, testService, "inc", new Serializable[] { new Integer(10) }); assertEquals(12, result); } catch (Exception e) { e.printStackTrace(); Assert.fail(e.toString()); } }
@Test public void testUserRegistry() { try { UserAgentImpl a = UserAgentImpl.createUserAgent("a"); UserAgentImpl b = UserAgentImpl.createUserAgent("b"); a.unlock("a"); b.unlock("b"); a.setLoginName("alpha"); b.setLoginName("beta"); LocalNode testee = new LocalNodeManager().launchNode(); testee.storeAgent(a); testee.storeAgent(b); assertEquals(a.getIdentifier(), testee.getUserManager().getAgentIdByLogin("alpha")); assertEquals(b.getIdentifier(), testee.getUserManager().getAgentIdByLogin("beta")); try { testee.getUserManager().getAgentIdByLogin("bla"); fail("AgentNotFoundException expected"); } catch (AgentNotFoundException e) { } } catch (Exception e) { e.printStackTrace(); Assert.fail(e.toString()); } }
@Test public void testUserRegDistribution() { try { LocalNodeManager manager = new LocalNodeManager(); LocalNode testee1 = manager.launchNode(); for (int i = 0; i < 11; i++) { UserAgentImpl a = UserAgentImpl.createUserAgent("pass" + i); a.unlock("pass" + i); a.setLoginName("login_" + i); testee1.storeAgent(a); } LocalNode testee2 = manager.launchNode(); testee2.getUserManager().getAgentIdByLogin("login_2"); } catch (Exception e) { e.printStackTrace(); Assert.fail(e.toString()); } }
@Test public void testStoreAnonymousAgent() { try { LocalNode testNode = new LocalNodeManager().launchNode(); AnonymousAgentImpl anonymous = AnonymousAgentImpl.getInstance(); testNode.storeAgent(anonymous); Assert.fail("Exception expected"); } catch (AgentException e) { } catch (Exception e) { e.printStackTrace(); Assert.fail(e.toString()); } } |
ServiceAliasManager { public AliasResolveResponse resolvePathToServiceName(String path) throws AliasNotFoundException { List<String> split = splitPath(path); int level = 0; String currentKey = null; while (level < split.size() && level < MAX_PATH_LEVEL) { if (currentKey == null) { currentKey = split.get(level); } else { currentKey += SEPERATOR + split.get(level); } String currentEntry = null; try { currentEntry = getEntry(currentKey); } catch (EnvelopeException | CryptoException | AgentAccessDeniedException | SerializationException e) { throw new AliasNotFoundException("Path does not exist.", e); } if (!currentEntry.equals(BLANK)) { return new AliasResolveResponse(currentEntry, level + 1); } level++; } if (level == MAX_PATH_LEVEL) { throw new AliasNotFoundException("Given path is too long."); } throw new AliasNotFoundException("Given path does not fit any alias."); } ServiceAliasManager(Node node); void registerServiceAlias(ServiceAgentImpl agent, String alias); AliasResolveResponse resolvePathToServiceName(String path); } | @Test public void testIntegration() throws CryptoException, InternalSecurityException, AgentAlreadyRegisteredException, AgentException, AliasNotFoundException, AgentAccessDeniedException { LocalNode node = new LocalNodeManager().launchNode(); node.startService(ServiceNameVersion.fromString("[email protected]"), "asdf"); assertEquals("i5.las2peer.api.TestService", node.getServiceAliasManager().resolvePathToServiceName("test").getServiceName()); } |
NodeServiceCache { public ServiceInstance getServiceAgentInstance(ServiceNameVersion service, boolean exact, boolean localOnly, AgentImpl acting) throws AgentNotRegisteredException { ServiceInstance local = null, global = null; if (exact) { synchronized (localServices) { if (localServices.containsKey(service.getName()) && localServices.get(service.getName()).containsKey(service.getVersion())) { local = localServices.get(service.getName()).get(service.getVersion()); } } } else { synchronized (localServices) { if (localServices.containsKey(service.getName())) { for (Map.Entry<ServiceVersion, ServiceInstance> e : localServices.get(service.getName()) .entrySet()) { if (e.getKey().fits(service.getVersion())) { local = e.getValue(); break; } } } } } if (!localOnly && (local == null || runningAt.isBusy())) { if (exact) { ServiceInstance instance = getBestGlobalInstanceOfVersion(service.getName(), service.getVersion()); if (instance == null) { try { update(service, true, acting); } catch (Exception e) { if (e instanceof TimeoutException) { logger.log(Level.INFO, "Timeout while updating service cache. " + e.toString()); } else { logger.log(Level.INFO, "Could not update service cache", e); } if (local == null) { throw new AgentNotRegisteredException( "Could not retrieve service information from the network.", e); } } instance = getBestGlobalInstanceOfVersion(service.getName(), service.getVersion()); } if (instance != null) { global = instance; } } else { ServiceInstance instance = getBestGlobalInstanceFitsVersion(service.getName(), service.getVersion()); if (instance != null) { global = instance; } if (instance == null) { try { update(service, false, acting); } catch (Exception e) { if (e instanceof TimeoutException) { logger.log(Level.INFO, "Timeout while updating service cache. " + e.toString()); } else { logger.log(Level.INFO, "Could not update service cache", e); } if (local == null) { throw new AgentNotRegisteredException( "Could not retrieve service information from the network.", e); } } instance = getBestGlobalInstanceFitsVersion(service.getName(), service.getVersion()); } if (instance != null) { global = instance; } } } if (local != null && (!runningAt.isBusy() || global == null)) { return local; } else if (global != null) { return global; } throw new AgentNotRegisteredException("Could not find any agent for this service on the network!"); } NodeServiceCache(Node parent, long lifeTime, int resultCount); void setWaitForResults(int c); void setLifeTimeSeconds(int c); void setTimeoutMs(int timeoutMs); void clear(); ServiceInstance getServiceAgentInstance(ServiceNameVersion service, boolean exact, boolean localOnly,
AgentImpl acting); void removeGlobalServiceInstance(ServiceInstance instance); void registerLocalService(ServiceAgentImpl agent); void unregisterLocalService(ServiceAgentImpl agent); ServiceAgentImpl getLocalService(ServiceNameVersion service); List<String> getLocalServiceNames(); List<ServiceVersion> getLocalServiceVersions(String serviceName); } | @Test public void testIntegration() { try { ServiceNameVersion serviceNameVersion = ServiceNameVersion .fromString("[email protected]"); LocalNode serviceNode = new LocalNodeManager().newNode("export/jars/"); serviceNode.launch(); ServiceAgentImpl serviceAgent = serviceNode.startService(serviceNameVersion, "a pass"); ServiceAgentImpl localServiceAgent = serviceNode.getNodeServiceCache() .getServiceAgentInstance(serviceNameVersion, true, true, null).getServiceAgent(); assertSame(serviceAgent, localServiceAgent); serviceNode.stopService(serviceAgent); try { serviceNode.getNodeServiceCache().getServiceAgentInstance(serviceNameVersion, true, true, null); fail("AgentNotRegisteredException exptected!"); } catch (AgentNotRegisteredException e) { } } catch (Exception e) { e.printStackTrace(); Assert.fail(e.toString()); } } |
MessageEnvelope implements Message { public String getContent() { return content; } MessageEnvelope(NodeHandle sendingNode, String content); MessageEnvelope(NodeHandle sendingNode, i5.las2peer.communication.Message content); NodeHandle getSendingNode(); String getContent(); i5.las2peer.communication.Message getContainedMessage(); @Override int getPriority(); } | @Test public void testSimpleContent() { try { String data = "some data to test"; MessageEnvelope testee = new MessageEnvelope(null, data); byte[] serialized = SerializeTools.serialize(testee); MessageEnvelope andBack = (MessageEnvelope) SerializeTools.deserialize(serialized); assertEquals(data, andBack.getContent()); } catch (Exception e) { e.printStackTrace(); Assert.fail(e.toString()); } } |
PastryNodeImpl extends Node { @Override public synchronized void shutDown() { this.setStatus(NodeStatus.CLOSING); super.shutDown(); if (threadpool != null) { threadpool.shutdownNow(); } if (pastryNode != null) { pastryNode.destroy(); pastryNode = null; } if (pastryEnvironment != null) { pastryEnvironment.destroy(); pastryEnvironment = null; } this.setStatus(NodeStatus.CLOSED); } PastryNodeImpl(String bootstrap, STORAGE_MODE storageMode, String storageDir, Long nodeIdSeed); PastryNodeImpl(ClassManager classManager, boolean useMonitoringObserver, InetAddress pastryBindAddress,
Integer pastryPort, List<String> bootstrap, STORAGE_MODE storageMode, String storageDir, Long nodeIdSeed); PastryNode getPastryNode(); @Override synchronized void shutDown(); @Override synchronized void registerReceiver(MessageReceiver receiver); @Override synchronized void unregisterReceiver(MessageReceiver receiver); @Override synchronized void registerReceiverToTopic(MessageReceiver receiver, long topic); @Override synchronized void unregisterReceiverFromTopic(MessageReceiver receiver, long topic); @Override void sendMessage(Message message, MessageResultListener listener, SendMode mode); @Override void sendMessage(Message message, Object atNodeId, MessageResultListener listener); @Deprecated @Override EnvelopeVersion fetchArtifact(long id); @Deprecated @Override EnvelopeVersion fetchArtifact(String identifier); @Deprecated @Override void storeArtifact(EnvelopeVersion envelope); @Deprecated @Override void removeArtifact(long id, byte[] signature); @Override Object[] findRegisteredAgent(String agentId, int hintOfExpectedCount); NodeApplication getApplication(); @Override AgentImpl getAgent(String id); @Override void storeAgent(AgentImpl agent); @Deprecated @Override void updateAgent(AgentImpl agent); @Override Serializable getNodeId(); InetAddress getBindAddress(); int getPort(); @Override Object[] getOtherKnownNodes(); @Override NodeInformation getNodeInformation(Object nodeId); long getLocalStorageSize(); long getLocalMaxStorageSize(); @Override void storeEnvelope(EnvelopeVersion envelope, AgentImpl author); @Override EnvelopeVersion fetchEnvelope(String identifier); @Override EnvelopeVersion createEnvelope(String identifier, PublicKey authorPubKey, Serializable content,
AgentImpl... reader); @Override EnvelopeVersion createEnvelope(String identifier, PublicKey authorPubKey, Serializable content,
Collection<?> readers); @Override EnvelopeVersion createEnvelope(EnvelopeVersion previousVersion, Serializable content); @Override EnvelopeVersion createEnvelope(EnvelopeVersion previousVersion, Serializable content, AgentImpl... reader); @Override EnvelopeVersion createEnvelope(EnvelopeVersion previousVersion, Serializable content, Collection<?> readers); @Override EnvelopeVersion createUnencryptedEnvelope(String identifier, PublicKey authorPubKey, Serializable content); @Override EnvelopeVersion createUnencryptedEnvelope(EnvelopeVersion previousVersion, Serializable content); @Override void storeEnvelope(EnvelopeVersion envelope, AgentImpl author, long timeoutMs); @Override void storeEnvelopeAsync(EnvelopeVersion envelope, AgentImpl author, StorageStoreResultHandler resultHandler,
StorageCollisionHandler collisionHandler, StorageExceptionHandler exceptionHandler); @Override EnvelopeVersion fetchEnvelope(String identifier, long timeoutMs); @Override void fetchEnvelopeAsync(String identifier, StorageEnvelopeHandler envelopeHandler,
StorageExceptionHandler exceptionHandler); @Override void removeEnvelope(String identifier); void storeHashedContentAsync(byte[] content, StorageStoreResultHandler resultHandler,
StorageExceptionHandler exceptionHandler); void storeHashedContent(byte[] content); void storeHashedContent(byte[] content, long timeoutMs); void fetchHashedContentAsync(byte[] hash, StorageArtifactHandler artifactHandler,
StorageExceptionHandler exceptionHandler); byte[] fetchHashedContent(byte[] hash); byte[] fetchHashedContent(byte[] hash, long timeoutMs); static final int DEFAULT_BOOTSTRAP_PORT; } | @Test public void testNodeRestart() { PastryNodeImpl testNode = null; try { testNode = TestSuite.launchNetwork(1).get(0); testNode.shutDown(); testNode.launch(); testNode.shutDown(); } catch (Exception e) { e.printStackTrace(); Assert.fail(e.toString()); } finally { testNode.shutDown(); System.out.println("Node stopped"); } } |
ServiceClassLoader extends ClassLoader { public LoadedLibrary getLibrary() { return library; } ServiceClassLoader(LoadedLibrary lib, ClassLoader parent, ClassLoaderPolicy policy); LoadedLibrary getLibrary(); @Override URL getResource(String resourceName); } | @Test public void test() throws IllegalArgumentException, IOException { LoadedLibrary lib = LoadedJarLibrary .createFromJar("export/jars/i5.las2peer.classLoaders.testPackage2-1.0.jar"); ServiceClassLoader testee = new ServiceClassLoader(lib, null, new DefaultPolicy()); assertEquals("i5.las2peer.classLoaders.testPackage2", testee.getLibrary().getIdentifier().getName()); assertEquals("1.0", testee.getLibrary().getIdentifier().getVersion().toString()); } |
RESTService extends Service { public final RESTResponse handle(URI baseUri, URI requestUri, String method, byte[] body, Map<String, List<String>> headers) { final ResponseWriter responseWriter = new ResponseWriter(); final ContainerRequest requestContext = new ContainerRequest(baseUri, requestUri, method, getSecurityContext(), new MapPropertiesDelegate()); requestContext.setEntityStream(new ByteArrayInputStream(body)); requestContext.getHeaders().putAll(headers); requestContext.setWriter(responseWriter); try { appHandler.handle(requestContext); } finally { responseWriter.commit(); } return responseWriter.getResponse(); } RESTService(); final RESTResponse handle(URI baseUri, URI requestUri, String method, byte[] body,
Map<String, List<String>> headers); final String getSwagger(); @Override final String getAlias(); } | @Test public void testHandle() throws URISyntaxException { RESTResponse response = invoke(testee, "GET", "hello", ""); assertEquals(200, response.getHttpCode()); assertEquals("Hello World!", new String(response.getBody())); } |
ServiceClassLoader extends ClassLoader { @Override protected synchronized Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException { Logger.logLoading(this, name, null); Class<?> c = findLoadedClass(name); if (c == null && this.policy.canLoad(name)) { try { if (parent != null) { c = parent.loadClass(name); } else { c = getSystemClassLoader().loadClass(name); } } catch (ClassNotFoundException e) { } } if (c == null) { try { c = findClass(name); } catch (ClassNotFoundException e) { Logger.logLoading(this, name, false); throw e; } } if (resolve) { resolveClass(c); } Logger.logLoading(this, name, true); return c; } ServiceClassLoader(LoadedLibrary lib, ClassLoader parent, ClassLoaderPolicy policy); LoadedLibrary getLibrary(); @Override URL getResource(String resourceName); } | @Test public void testClassLoading() throws IllegalArgumentException, IOException, ClassNotFoundException, SecurityException, NoSuchMethodException, IllegalAccessException, InvocationTargetException { LoadedLibrary lib = LoadedJarLibrary .createFromJar("export/jars/i5.las2peer.classLoaders.testPackage1-1.0.jar"); ServiceClassLoader testee = new ServiceClassLoader(lib, null, new DefaultPolicy()); Class<?> cl = testee.loadClass("i5.las2peer.classLoaders.testPackage1.CounterClass", false); Method inc = cl.getDeclaredMethod("inc"); Method counter = cl.getDeclaredMethod("getCounter"); inc.invoke(null); Object res = counter.invoke(null); assertEquals(1, ((Integer) res).intValue()); assertSame(testee, cl.getClassLoader()); try { testee.loadClass("some.not.existing.class"); fail("ClassNotFoundException should have been thrown"); } catch (ClassNotFoundException e) { } }
@Test public void testLoaderBehaviour() throws ClassNotFoundException, IllegalArgumentException, IOException { LoadedLibrary lib = LoadedJarLibrary .createFromJar("export/jars/i5.las2peer.classLoaders.testPackage1-1.0.jar"); ServiceClassLoader testee1 = new ServiceClassLoader(lib, null, new DefaultPolicy()); ServiceClassLoader testee2 = new ServiceClassLoader(lib, null, new DefaultPolicy()); Class<?> test1 = testee1.loadClass("i5.las2peer.classLoaders.testPackage1.CounterClass", false); Class<?> test2 = testee2.loadClass("i5.las2peer.classLoaders.testPackage1.CounterClass", false); assertNotSame(test1, test2); assertSame(testee1, test1.getClassLoader()); assertSame(testee2, test2.getClassLoader()); test2 = testee1.loadClass("i5.las2peer.classLoaders.testPackage1.CounterClass"); assertEquals(test1, test2); assertSame(testee1, test2.getClassLoader()); }
@Test public void testPackages() throws IllegalArgumentException, IOException, ClassNotFoundException { LoadedLibrary lib = LoadedJarLibrary .createFromJar("export/jars/i5.las2peer.classLoaders.testPackage1-1.0.jar"); ServiceClassLoader testee = new ServiceClassLoader(lib, null, new DefaultPolicy()); Class<?> cl = testee.loadClass("i5.las2peer.classLoaders.testPackage1.CounterClass", false); assertSame(testee, cl.getClassLoader()); assertNotNull(cl.getPackage()); assertEquals(cl.getPackage().getName(), "i5.las2peer.classLoaders.testPackage1"); }
@Test public void testPolicy() throws IllegalArgumentException, IOException, ClassNotFoundException, NoSuchMethodException, SecurityException, IllegalAccessException, InvocationTargetException { LoadedLibrary lib = LoadedJarLibrary .createFromJar("export/jars/i5.las2peer.classLoaders.evilService-1.0.jar"); ServiceClassLoader testee = new ServiceClassLoader(lib, null, new RestrictivePolicy()); Class<?> cl = testee.loadClass("i5.las2peer.classLoaders.evilService.EvilService", false); Method notEvil = cl.getDeclaredMethod("notEvil"); Method accessNode = cl.getDeclaredMethod("accessNode"); Method createThread = cl.getDeclaredMethod("createThread"); notEvil.invoke(null); try { accessNode.invoke(null); fail("NoClassDefFoundError expected"); } catch (InvocationTargetException e) { System.out.print(e.getTargetException()); if (!(e.getTargetException() instanceof NoClassDefFoundError)) { fail("NoClassDefFoundError expected"); } } try { createThread.invoke(null); fail("NoClassDefFoundError expected"); } catch (InvocationTargetException e) { if (!(e.getTargetException() instanceof NoClassDefFoundError)) { fail("NoClassDefFoundError expected"); } } } |
ServiceClassLoader extends ClassLoader { URL getResource(String resourceName, boolean lookUp) { Logger.logGetResource(this, resourceName, null, lookUp); URL res; try { res = library.getResourceAsUrl(resourceName); } catch (ResourceNotFoundException e) { if (lookUp && parent != null) { URL result = parent.getResource(resourceName); if (result != null) { return result; } else { Logger.logGetResource(this, resourceName, false, null); return null; } } else { Logger.logGetResource(this, resourceName, false, null); return null; } } if (res != null) { Logger.logGetResource(this, resourceName, true, null); return res; } else { return null; } } ServiceClassLoader(LoadedLibrary lib, ClassLoader parent, ClassLoaderPolicy policy); LoadedLibrary getLibrary(); @Override URL getResource(String resourceName); } | @Test public void testResources() throws IllegalArgumentException, IOException { LoadedLibrary lib = LoadedJarLibrary .createFromJar("export/jars/i5.las2peer.classLoaders.testPackage1-1.0.jar"); ServiceClassLoader testee = new ServiceClassLoader(lib, null, new DefaultPolicy()); Properties properties = new Properties(); properties.load(testee.getResourceAsStream("i5/las2peer/classLoaders/testPackage1/test.properties")); assertEquals("123", properties.getProperty("integer")); assertEquals("value", properties.getProperty("attribute")); URL test = testee.getResource("does/not/exist"); assertNull(test); } |
ClassManager { public static final String getPackageName(String className) { if (className.indexOf('.') < 0) { throw new IllegalArgumentException("this class is not contained in a package!"); } return className.substring(0, className.lastIndexOf('.')); } ClassManager(Repository repository, ClassLoader platformLoader, ClassLoaderPolicy policy); ClassManager(Repository[] repositories, ClassLoader platformLoader, ClassLoaderPolicy policy); ClassManager(List<Repository> repositories, ClassLoader platformLoader, ClassLoaderPolicy policy); void registerService(ServiceNameVersion serviceIdentifier); void unregisterService(ServiceNameVersion service); Class<?> getServiceClass(ServiceNameVersion service); static final String getPackageName(String className); void addRepository(Repository repository); } | @Test public void testPackageName() { assertEquals("my.package", ClassManager.getPackageName("my.package.Class")); try { ClassManager.getPackageName("teststring"); fail("IllegalArgumentException should have been thrown"); } catch (IllegalArgumentException e) { } } |
ClassManager { public Class<?> getServiceClass(ServiceNameVersion service) throws ClassLoaderException { ServiceClassLoader cl = registeredLoaders.get(service); if (cl == null) { try { registerService(service); cl = registeredLoaders.get(service); } catch (LibraryNotFoundException e) { System.err.println("No library found for " + service + "! Trying default classpath. This should not happen in a productive environment!"); try { return this.platformLoader.loadClass(service.getName()); } catch (ClassNotFoundException e2) { throw e; } } } try { return cl.loadClass(service.getName()); } catch (ClassNotFoundException e) { throw new LibraryNotFoundException( "The library for " + service + " could be loaded, but the class is not available!", e); } } ClassManager(Repository repository, ClassLoader platformLoader, ClassLoaderPolicy policy); ClassManager(Repository[] repositories, ClassLoader platformLoader, ClassLoaderPolicy policy); ClassManager(List<Repository> repositories, ClassLoader platformLoader, ClassLoaderPolicy policy); void registerService(ServiceNameVersion serviceIdentifier); void unregisterService(ServiceNameVersion service); Class<?> getServiceClass(ServiceNameVersion service); static final String getPackageName(String className); void addRepository(Repository repository); } | @Test public void testServiceClassLoading() throws ClassLoaderException, SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException { ClassManager testee = new ClassManager(new FileSystemRepository("export/jars/"), ClassLoader.getSystemClassLoader(), new DefaultPolicy()); Class<?> cl = testee.getServiceClass(ServiceNameVersion.fromString("[email protected]")); assertFalse(cl.getClassLoader().equals(ClassLoader.getSystemClassLoader())); Method m = cl.getDeclaredMethod("countCalls"); Object result = m.invoke(null); result = m.invoke(null); assertEquals(-2, ((Integer) result).intValue()); Class<?> cl1 = testee.getServiceClass(new ServiceNameVersion("i5.las2peer.testServices.testPackage1.TestService", "1.0")); Class<?> cl2 = testee.getServiceClass(new ServiceNameVersion("i5.las2peer.testServices.testPackage1.TestService", "1.1")); Method m1 = cl1.getDeclaredMethod("getVersionStatic"); Method m2 = cl2.getDeclaredMethod("getVersionStatic"); assertEquals(m1.invoke(null), 100); assertEquals(m2.invoke(null), 110); }
@Test public void testMultipleServiceClassLoading() throws ClassLoaderException, SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException { ClassManager testee = new ClassManager(new FileSystemRepository("export/jars/"), ClassLoader.getSystemClassLoader(), new DefaultPolicy()); Class<?> cl1 = testee.getServiceClass(new ServiceNameVersion("i5.las2peer.classLoaders.testPackage2.UsingCounter", "1.0")); Class<?> cl2 = testee.getServiceClass(new ServiceNameVersion("i5.las2peer.classLoaders.testPackage2.UsingCounter", "1.0")); assertFalse(cl1.getClassLoader().equals(ClassLoader.getSystemClassLoader())); assertFalse(cl2.getClassLoader().equals(ClassLoader.getSystemClassLoader())); assertSame(cl1, cl2); } |
ClassLoaderPolicy { public boolean canLoad(String className) { if (deniedPaths.contains("")) { return false; } String[] split = className.split("\\."); String current = ""; for (String part : split) { current += (current.equals("")) ? part : ("." + part); if (deniedPaths.contains(current)) { return false; } } if (allowedPaths.contains("")) { return true; } current = ""; for (String part : split) { current += (current.equals("")) ? part : ("." + part); if (allowedPaths.contains(current)) { return true; } } return false; } boolean canLoad(String className); } | @Test public void test() { ClassLoaderPolicy policy = new TestPolicy(); assertFalse(policy.canLoad("notallowed")); assertTrue(policy.canLoad("package")); assertTrue(policy.canLoad("package.sub")); assertFalse(policy.canLoad("package2")); assertTrue(policy.canLoad("package2.sub")); assertTrue(policy.canLoad("package3.sub1")); assertTrue(policy.canLoad("package3.sub1.sub")); assertFalse(policy.canLoad("package3.sub")); assertFalse(policy.canLoad("package3.sub.sub")); ClassLoaderPolicy policy2 = new TestPolicy2(); assertTrue(policy2.canLoad("package2")); assertFalse(policy2.canLoad("package")); } |
LibraryVersion { public boolean equals(LibraryVersion v) { return v.toString().equals(this.toString()); } LibraryVersion(String version); LibraryVersion(int major, int minor, int sub, int build); LibraryVersion(int major, int minor, int sub); LibraryVersion(int major, int minor); LibraryVersion(int major); boolean equals(LibraryVersion v); @Override boolean equals(Object o); @Override int hashCode(); int getMinor(); int getMajor(); int getSub(); int getBuild(); @Override String toString(); } | @Test public void testEquality() { LibraryVersion testee1 = new LibraryVersion("10.0.1-1234"); LibraryVersion testee2 = new LibraryVersion(10, 0, 1, 1234); assertTrue(testee1.equals(testee2)); assertEquals(testee1, testee2); assertFalse(new LibraryVersion("10.1.1-1234").equals(new LibraryVersion(10, 1, 1, 123))); assertFalse(new LibraryVersion("10.1.1-1234").equals(new LibraryVersion(10, 1, 1))); assertEquals(new LibraryVersion("10.0.1-1234"), "10.0.1-1234"); } |
RESTService extends Service { public final String getSwagger() throws JsonProcessingException { Swagger swagger = new Reader(new Swagger()).read(this.application.getClasses()); return Json.mapper().writeValueAsString(swagger); } RESTService(); final RESTResponse handle(URI baseUri, URI requestUri, String method, byte[] body,
Map<String, List<String>> headers); final String getSwagger(); @Override final String getAlias(); } | @Test public void testSwagger() throws JsonProcessingException { String response = testee.getSwagger(); assertTrue(response.contains("getHello")); } |
LibraryVersion { @Override public String toString() { String result = "" + major; if (minor != null) { result += "." + minor; if (sub != null) result += "." + sub; } if (build != null) result += "-" + build; return result; } LibraryVersion(String version); LibraryVersion(int major, int minor, int sub, int build); LibraryVersion(int major, int minor, int sub); LibraryVersion(int major, int minor); LibraryVersion(int major); boolean equals(LibraryVersion v); @Override boolean equals(Object o); @Override int hashCode(); int getMinor(); int getMajor(); int getSub(); int getBuild(); @Override String toString(); } | @Test public void testStringRepresentation() { assertEquals("10.0.1-1234", new LibraryVersion(10, 0, 1, 1234).toString()); assertEquals("10.0-1234", new LibraryVersion("10.0-1234").toString()); assertEquals("10-1234", new LibraryVersion("10-1234").toString()); assertEquals("10.0.1", new LibraryVersion(10, 0, 1).toString()); assertEquals("10.1", new LibraryVersion(10, 1).toString()); assertEquals("10", new LibraryVersion(10).toString()); } |
LibraryIdentifier { public boolean equals(LibraryIdentifier i) { return this.toString().equals(i.toString()); } LibraryIdentifier(String name); LibraryIdentifier(String name, String version); LibraryIdentifier(String name, LibraryVersion version); static LibraryIdentifier fromFilename(String filename); LibraryVersion getVersion(); String getName(); @Override String toString(); boolean equals(LibraryIdentifier i); @Override boolean equals(Object o); @Override int hashCode(); static final String MANIFEST_LIBRARY_NAME_ATTRIBUTE; static final String MANIFEST_LIBRARY_VERSION_ATTRIBUTE; } | @Test public void testEquality() { assertEquals(new LibraryIdentifier("testname;version=\"1.0.1-22\""), "testname;version=\"1.0.1-22\""); assertFalse(new LibraryIdentifier("testname;version=\"1.0.1-22\"").equals("tstname;version=\"1.0.1-22\"")); } |
LibraryIdentifier { public static LibraryIdentifier fromFilename(String filename) { String fileNameWithOutExt = new File(filename).getName().replaceFirst("[.][^.]+$", ""); Pattern versionPattern = Pattern.compile("-[0-9]+(?:.[0-9]+(?:.[0-9]+)?)?(?:-[0-9]+)?$"); Matcher m = versionPattern.matcher(fileNameWithOutExt); String sName = null; String sVersion = null; if (m.find()) { sName = fileNameWithOutExt.substring(0, m.start()); sVersion = m.group().substring(1); return new LibraryIdentifier(sName, sVersion); } else { sName = fileNameWithOutExt; return new LibraryIdentifier(sName, (LibraryVersion) null); } } LibraryIdentifier(String name); LibraryIdentifier(String name, String version); LibraryIdentifier(String name, LibraryVersion version); static LibraryIdentifier fromFilename(String filename); LibraryVersion getVersion(); String getName(); @Override String toString(); boolean equals(LibraryIdentifier i); @Override boolean equals(Object o); @Override int hashCode(); static final String MANIFEST_LIBRARY_NAME_ATTRIBUTE; static final String MANIFEST_LIBRARY_VERSION_ATTRIBUTE; } | @Test public void testFromFilename() { try { LibraryIdentifier testFull = LibraryIdentifier .fromFilename("service/i5.las2peer.services.testService-4.2.jar"); Assert.assertEquals("i5.las2peer.services.testService", testFull.getName()); Assert.assertEquals("4.2", testFull.getVersion().toString()); LibraryIdentifier testTripleVersion = LibraryIdentifier .fromFilename("i5.las2peer.services.testService-4.2.0.jar"); Assert.assertEquals("i5.las2peer.services.testService", testTripleVersion.getName()); Assert.assertEquals("4.2.0", testTripleVersion.getVersion().toString()); LibraryIdentifier testDoubleVersion = LibraryIdentifier .fromFilename("i5.las2peer.services.testService-4.2.jar"); Assert.assertEquals("i5.las2peer.services.testService", testDoubleVersion.getName()); Assert.assertEquals("4.2", testDoubleVersion.getVersion().toString()); LibraryIdentifier testSingleVersion = LibraryIdentifier .fromFilename("i5.las2peer.services.testService-4.jar"); Assert.assertEquals("i5.las2peer.services.testService", testSingleVersion.getName()); Assert.assertEquals("4", testSingleVersion.getVersion().toString()); LibraryIdentifier testNoVersion = LibraryIdentifier.fromFilename("i5.las2peer.services.testService.jar"); Assert.assertEquals("i5.las2peer.services.testService", testNoVersion.getName()); Assert.assertNull(testNoVersion.getVersion()); } catch (Exception e) { e.printStackTrace(); Assert.fail(e.toString()); } } |
LoadedJarLibrary extends LoadedLibrary { public static LoadedJarLibrary createFromJar(String filename) throws IllegalArgumentException, IOException { JarFile jfFile = new JarFile(filename); String sName = jfFile.getManifest().getMainAttributes() .getValue(LibraryIdentifier.MANIFEST_LIBRARY_NAME_ATTRIBUTE); String sVersion = jfFile.getManifest().getMainAttributes() .getValue(LibraryIdentifier.MANIFEST_LIBRARY_VERSION_ATTRIBUTE); if (sName == null || sVersion == null) { LibraryIdentifier tmpId = LibraryIdentifier.fromFilename(filename); if (sName == null) { sName = tmpId.getName(); } if (sVersion == null) { sVersion = tmpId.getVersion().toString(); } } jfFile.close(); return new LoadedJarLibrary(filename, new LibraryIdentifier(sName, sVersion)); } LoadedJarLibrary(String filename, LibraryIdentifier ident); @Override URL getResourceAsUrl(String name); String[] getContainedClasses(); String[] getContainedResources(); LinkedList<String> getContainedFiles(); String getJarFileName(); static LoadedJarLibrary createFromJar(String filename); } | @Test public void testStringGetter() throws IOException, LibraryNotFoundException, ResourceNotFoundException { LoadedJarLibrary testee = LoadedJarLibrary .createFromJar("export/jars/i5.las2peer.classLoaders.testPackage1-1.1.jar"); String test = testee.getResourceAsString("i5/las2peer/classLoaders/testPackage1/test.properties"); test = test.replace("\n", "").replace("\r", ""); assertEquals("attribute=otherValueinteger=987", test); }
@Test public void testBinaryContent() throws IOException, LibraryNotFoundException, ResourceNotFoundException { LoadedJarLibrary testee = LoadedJarLibrary .createFromJar("export/jars/i5.las2peer.classLoaders.testPackage1-1.1.jar"); byte[] result = testee.getResourceAsBinary("i5/las2peer/classLoaders/testPackage1/test.properties"); assertNotNull(result); assertTrue(result.length > 0); result = testee.getResourceAsBinary("i5/las2peer/classLoaders/testPackage1/CounterClass.class"); assertNotNull(result); assertTrue(result.length > 0); } |
LoadedLibrary { public static String resourceToClassName(String entryName) { if (!entryName.endsWith(".class")) { throw new IllegalArgumentException("This is not a class file!"); } return entryName.replace('/', '.').substring(0, entryName.length() - 6); } LoadedLibrary(String libraryIdentifier); LoadedLibrary(LibraryIdentifier lib); LibraryIdentifier getLibraryIdentifier(); abstract URL getResourceAsUrl(String name); String getResourceAsString(String resourceName); byte[] getResourceAsBinary(String resourceName); LibraryIdentifier getIdentifier(); static String classToResourceName(String className); static String resourceToClassName(String entryName); } | @Test public void testResourceToClassName() { assertEquals("test.bla.Class", LoadedLibrary.resourceToClassName("test/bla/Class.class")); try { LoadedLibrary.resourceToClassName("test.clas"); fail("IllegalArgumentException should have been thrown"); } catch (IllegalArgumentException e) { } } |
LoadedLibrary { public static String classToResourceName(String className) { return className.replace('.', '/') + ".class"; } LoadedLibrary(String libraryIdentifier); LoadedLibrary(LibraryIdentifier lib); LibraryIdentifier getLibraryIdentifier(); abstract URL getResourceAsUrl(String name); String getResourceAsString(String resourceName); byte[] getResourceAsBinary(String resourceName); LibraryIdentifier getIdentifier(); static String classToResourceName(String className); static String resourceToClassName(String entryName); } | @Test public void testClassToResourceName() { assertEquals("test/bla/Class.class", LoadedLibrary.classToResourceName("test.bla.Class")); assertEquals("Class.class", LoadedLibrary.classToResourceName("Class")); } |
FileSystemRepository implements Repository { public static long getLastModified(File dir, boolean recursive) { File[] files = dir.listFiles(); if (files == null || files.length == 0) { return dir.lastModified(); } long lastModified = 0; for (File f : files) { if (f.isDirectory() && recursive) { long ll = getLastModified(f, recursive); if (lastModified < ll) { lastModified = ll; } } else { if (lastModified < f.lastModified()) { lastModified = f.lastModified(); } } } return lastModified; } FileSystemRepository(String directory); FileSystemRepository(String directory, boolean recursive); FileSystemRepository(String[] directories); FileSystemRepository(String[] directories, boolean recursive); FileSystemRepository(Iterable<String> directories, boolean recursive); @Override LoadedLibrary findLibrary(String name); @Override LoadedLibrary findLibrary(LibraryIdentifier lib); String[] getAvailableVersions(String libraryName); Collection<LibraryVersion> getAvailableVersionSet(String libraryName); String[] getAllLibraries(); Collection<String> getLibraryCollection(); static long getLastModified(File dir, boolean recursive); @Override String toString(); } | @Test public void testGetLastModified() throws InterruptedException { File f = new File("export" + File.separator + "jars" + File.separator); long date1 = FileSystemRepository.getLastModified(f, true); assertTrue(date1 > 0); Thread.sleep(2000); new File("export" + File.separator + "jars" + File.separator + "i5.las2peer.classLoaders.testPackage1-1.0.jar") .setLastModified(System.currentTimeMillis()); long date2 = FileSystemRepository.getLastModified(f, true); assertTrue(date1 < date2); long date3 = FileSystemRepository.getLastModified(f, true); assertTrue(date2 == date3); } |
L2pLogger extends Logger implements NodeObserver { public static L2pLogger getInstance(Class<?> cls) throws ClassCastException { return getInstance(cls.getCanonicalName()); } protected L2pLogger(String name, String resourceBundleName); synchronized void printStackTrace(Throwable e); static void setGlobalLogDirectory(String directory); synchronized void setLogDirectory(String directory); static void setGlobalLogfilePrefix(String prefix); synchronized void setLogfilePrefix(String prefix); static void setGlobalConsoleLevel(Level level); synchronized void setConsoleLevel(Level level); static void setGlobalLogfileLevel(Level level); synchronized void setLogfileLevel(Level level); @Override void log(LogRecord record); @Deprecated static void logEvent(MonitoringEvent event, String message); @Deprecated static void logEvent(MonitoringEvent event, Agent actingUser, String message); @Deprecated static void logEvent(Object from, MonitoringEvent event, String message); @Deprecated static void logEvent(Object from, MonitoringEvent event, String message, Agent serviceAgent,
Agent actingUser); @Deprecated static void logEvent(Node node, Object from, MonitoringEvent event, String message, Agent serviceAgent,
Agent actingUser); void log(MonitoringEvent event); void log(MonitoringEvent event, String remarks); void log(MonitoringEvent event, String sourceAgentId, String destinationAgentId, String remarks); @Deprecated @Override void log(Long timestamp, MonitoringEvent event, String sourceNode, String sourceAgentId,
String destinationNode, String destinationAgentId, String remarks); static Formatter getGlobalConsoleFormatter(); static Formatter getGlobalLogfileFormatter(); static L2pLogger getInstance(Class<?> cls); static L2pLogger getInstance(String name); static final String GLOBAL_NAME; static final int DEFAULT_LIMIT_BYTES; static final int DEFAULT_LIMIT_FILES; static final String DEFAULT_ENCODING; static final String DEFAULT_LOG_DIRECTORY; static final String DEFAULT_LOGFILE_PREFIX; static final Level DEFAULT_CONSOLE_LEVEL; static final Level DEFAULT_LOGFILE_LEVEL; static final Level DEFAULT_OBSERVER_LEVEL; static final SimpleDateFormat DEFAULT_DATE_FORMAT; } | @Test public void testParent2() { L2pLogger logger = L2pLogger.getInstance(L2pLoggerTest.class.getName()); assertTrue(logger instanceof L2pLogger); Logger parent = logger.getParent(); assertNotNull(parent); assertTrue(parent instanceof L2pLogger); } |
UserAgentManager { public String getAgentIdByLogin(String name) throws AgentNotFoundException, AgentOperationFailedException { if (name.equalsIgnoreCase(AnonymousAgent.LOGIN_NAME)) { return AnonymousAgentImpl.getInstance().getIdentifier(); } try { EnvelopeVersion env = node.fetchEnvelope(PREFIX_USER_NAME + name.toLowerCase()); return (String) env.getContent(); } catch (EnvelopeNotFoundException e) { throw new AgentNotFoundException("Username not found!", e); } catch (EnvelopeException | SerializationException | CryptoException e) { throw new AgentOperationFailedException("Could not read agent id from storage"); } } UserAgentManager(Node node); void registerUserAgent(UserAgent agent); void registerOIDCSub(UserAgentImpl agent, String sub); String getAgentId(String prefixedIdentifier); String getAgentIdByLogin(String name); String getAgentIdByEmail(String email); String getAgentIdByOIDCSub(String sub); } | @Test public void testLogin() { try { Node node = new LocalNodeManager().launchNode(); UserAgentManager l = node.getUserManager(); UserAgentImpl a = UserAgentImpl.createUserAgent("pass"); a.unlock("pass"); a.setLoginName("login"); node.storeAgent(a); assertEquals(a.getIdentifier(), l.getAgentIdByLogin("login")); UserAgentImpl b = UserAgentImpl.createUserAgent("pass"); b.unlock("pass"); b.setLoginName("login"); try { node.storeAgent(b); fail("LoginNameAlreadyTakenException expected"); } catch (LoginNameAlreadyTakenException e) { } b.setLoginName("login2"); node.storeAgent(b); assertEquals(b.getIdentifier(), l.getAgentIdByLogin("login2")); b.setLoginName("LOGIN"); try { node.storeAgent(b); fail("LoginNameAlreadyTakenException expected"); } catch (LoginNameAlreadyTakenException e) { } assertEquals(a.getIdentifier(), l.getAgentIdByLogin("LOGIN")); try { l.getAgentIdByLogin("fdewfue"); fail("AgentNotFoundException expected"); } catch (AgentNotFoundException e) { } } catch (Exception e) { e.printStackTrace(); } } |
ServiceAgentGenerator { public static void main(String argv[]) { if (argv.length != 2) { System.err.println( "usage: java i5.las2peer.tools.ServiceAgentGenerator [service class]@[service version] [passphrase]"); return; } else if (argv[0].length() < PW_MIN_LENGTH) { System.err.println("the password needs to be at least " + PW_MIN_LENGTH + " signs long, but only " + argv[0].length() + " given"); return; } try { ServiceAgentImpl agent = ServiceAgentImpl.createServiceAgent(ServiceNameVersion.fromString(argv[0]), argv[1]); System.out.print(agent.toXmlString()); } catch (Exception e) { System.err.println("unable to generate new agent: " + e); } } static void main(String argv[]); } | @Test public void testMainUsage() { ServiceAgentGenerator.main(new String[0]); assertTrue(("" + standardError.toString()).contains("usage:")); assertEquals("", standardOut.toString()); }
@Test public void testMainNormal() { String className = "[email protected]"; ServiceAgentGenerator.main(new String[] { className, "mypass" }); assertEquals("", standardError.toString()); String output = standardOut.toString(); assertTrue(output.contains("serviceclass=\"" + className + "\"")); } |
UserAgentManager { public String getAgentIdByEmail(String email) throws AgentNotFoundException, AgentOperationFailedException { try { EnvelopeVersion env = node.fetchEnvelope(PREFIX_USER_MAIL + email.toLowerCase()); return (String) env.getContent(); } catch (EnvelopeNotFoundException e) { throw new AgentNotFoundException("Email not found!", e); } catch (EnvelopeException | SerializationException | CryptoException e) { throw new AgentOperationFailedException("Could not read email from storage"); } } UserAgentManager(Node node); void registerUserAgent(UserAgent agent); void registerOIDCSub(UserAgentImpl agent, String sub); String getAgentId(String prefixedIdentifier); String getAgentIdByLogin(String name); String getAgentIdByEmail(String email); String getAgentIdByOIDCSub(String sub); } | @Test public void testEmail() { try { Node node = new LocalNodeManager().launchNode(); UserAgentManager l = node.getUserManager(); UserAgentImpl a = UserAgentImpl.createUserAgent("pass"); a.unlock("pass"); a.setEmail("[email protected]"); node.storeAgent(a); assertEquals(a.getIdentifier(), l.getAgentIdByEmail("[email protected]")); UserAgentImpl b = UserAgentImpl.createUserAgent("pass"); b.unlock("pass"); b.setEmail("[email protected]"); try { node.storeAgent(b); fail("EmailAlreadyTakenException expected"); } catch (EmailAlreadyTakenException e) { } b.setEmail("[email protected]"); try { node.storeAgent(b); fail("EmailAlreadyTakenException expected"); } catch (EmailAlreadyTakenException e) { } b.setEmail("[email protected]"); node.storeAgent(b); assertEquals(b.getIdentifier(), l.getAgentIdByEmail("[email protected]")); b.setEmail("[email protected]"); node.storeAgent(b); assertEquals(b.getIdentifier(), l.getAgentIdByEmail("[email protected]")); assertEquals(b.getIdentifier(), l.getAgentIdByEmail("[email protected]")); try { l.getAgentIdByEmail("fdewfue"); fail("AgentNotFoundException expected"); } catch (AgentNotFoundException e) { } } catch (Exception e) { e.printStackTrace(); } } |
UserAgentImpl extends PassphraseAgentImpl implements UserAgent { public static UserAgentImpl createUserAgent(String passphrase) throws CryptoException, AgentOperationFailedException { byte[] salt = CryptoTools.generateSalt(); return new UserAgentImpl(CryptoTools.generateKeyPair(), passphrase, salt); } protected UserAgentImpl(KeyPair pair, String passphrase, byte[] salt); protected UserAgentImpl(PublicKey pubKey, byte[] encryptedPrivate, byte[] salt); @Override String getLoginName(); @Override boolean hasLoginName(); @Override void setLoginName(String loginName); @Override void setEmail(String email); @Override String toXmlString(); static UserAgentImpl createFromXml(String xml); static UserAgentImpl createUserAgent(String passphrase); static UserAgentImpl createFromXml(Element root); @Override void receiveMessage(Message message, AgentContext context); @Override void notifyUnregister(); @Override String getEmail(); @Override boolean hasEmail(); } | @Test public void testUnlocking() throws NoSuchAlgorithmException, CryptoException, AgentAccessDeniedException, InternalSecurityException, AgentLockedException, AgentOperationFailedException { String passphrase = "A passphrase to unlock"; UserAgentImpl a = UserAgentImpl.createUserAgent(passphrase); try { a.decryptSymmetricKey(null); fail("AgentLockedException should have been thrown"); } catch (AgentLockedException e) { } catch (SerializationException e) { fail("SecurityException should have been thrown"); e.printStackTrace(); } try { a.unlock("bad passphrase"); fail("SecurityException should have been thrown"); } catch (AgentAccessDeniedException e) { } try { a.decryptSymmetricKey(null); fail("AgentLockedException should have been thrown"); } catch (AgentLockedException e) { } catch (SerializationException e) { fail("AgentLockedException should have been thrown"); e.printStackTrace(); } a.unlock(passphrase); try { a.decryptSymmetricKey(null); } catch (IllegalArgumentException e) { } catch (SerializationException e) { fail("Illegal argument exception should have been thrown"); e.printStackTrace(); } }
@Test public void testPassphraseChange() throws NoSuchAlgorithmException, InternalSecurityException, CryptoException, AgentAccessDeniedException, AgentLockedException, AgentOperationFailedException { String passphrase = "a passphrase"; UserAgentImpl a = UserAgentImpl.createUserAgent(passphrase); String sndPass = "ein anderes Passphrase"; try { a.changePassphrase(sndPass); fail("AgentLockedException expected"); } catch (AgentLockedException e) { } a.unlock(passphrase); a.changePassphrase(sndPass); a.lockPrivateKey(); try { a.unlock(passphrase); fail("AgentAccessDeniedException expected"); } catch (AgentAccessDeniedException e) { } a.unlock(sndPass); } |
Mediator implements MessageReceiver { @Override public void receiveMessage(Message message, AgentContext c) throws MessageException { if (!message.getRecipientId().equalsIgnoreCase(myAgent.getIdentifier())) { throw new MessageException("I'm not responsible for the receiver (something went very wrong)!"); } try { message.open(myAgent, c); if (getMyNode() != null && !message.getContent().equals("thank you")) { try { Message response = new Message(message, "thank you"); response.setSendingNodeId(getMyNode().getNodeId()); getMyNode().sendMessage(response, null); } catch (EncodingFailedException e) { throw new MessageException("Unable to send response ", e); } catch (SerializationException e) { throw new MessageException("Unable to send response ", e); } } } catch (InternalSecurityException e) { throw new MessageException("Unable to open message because of security problems! ", e); } catch (AgentNotFoundException e) { throw new MessageException( "Sender unkown (since this is the receiver). Has the sending node gone offline? ", e); } catch (AgentException e) { throw new MessageException("Could not read the sender agent", e); } if (!workOnMessage(message, c)) { pending.add(message); } } Mediator(Node n, AgentImpl a); Message getNextMessage(); boolean hasMessages(); @Override void receiveMessage(Message message, AgentContext c); boolean workOnMessage(Message message, AgentContext context); boolean isRegistered(); @Override String getResponsibleForAgentSafeId(); AgentImpl getAgent(); @Override void notifyRegistrationTo(Node node); @Override void notifyUnregister(); @Deprecated Serializable invoke(String service, String method, Serializable[] parameters, boolean localOnly); Serializable invoke(ServiceNameVersion serviceNameVersion, String method, Serializable[] parameters,
boolean localOnly); int getNumberOfWaiting(); void registerMessageHandler(MessageHandler handler); void unregisterMessageHandler(MessageHandler handler); int unregisterMessageHandlerClass(Class<?> cls); int unregisterMessageHandlerClass(String classname); boolean hasMessageHandler(MessageHandler handler); boolean hasMessageHandlerClass(Class<?> cls); } | @Test public void testWrongRecipient() { try { UserAgentImpl eve = MockAgentFactory.getEve(); eve.unlock("evespass"); UserAgentImpl adam = MockAgentFactory.getAdam(); adam.unlock("adamspass"); Mediator testee = new Mediator(null, eve); Message m = new Message(eve, adam, "a message"); try { testee.receiveMessage(m, null); fail("MessageException expected!"); } catch (MessageException e) { assertTrue(e.getMessage().contains("not responsible")); } } catch (Exception e) { e.printStackTrace(); Assert.fail(e.toString()); } } |
ServiceAgentImpl extends PassphraseAgentImpl implements ServiceAgent { public static long serviceNameToTopicId(String service) { return SimpleTools.longHash(service); } protected ServiceAgentImpl(ServiceNameVersion service, KeyPair pair, String passphrase, byte[] salt); protected ServiceAgentImpl(ServiceNameVersion service, PublicKey pubKey, byte[] encodedPrivate, byte[] salt); @Override ServiceNameVersion getServiceNameVersion(); @Override String toXmlString(); @Override void receiveMessage(Message m, AgentContext c); @Override void notifyUnregister(); @Deprecated static ServiceAgentImpl generateNewAgent(String forService, String passPhrase); static ServiceAgentImpl createServiceAgent(ServiceNameVersion service, String passphrase); @Deprecated static ServiceAgentImpl createServiceAgent(String serviceName, String passphrase); static ServiceAgentImpl createFromXml(String xml); static ServiceAgentImpl createFromXml(Element rootElement); @Override void notifyRegistrationTo(Node node); static long serviceNameToTopicId(String service); boolean isRunning(); Object invoke(String method, Object[] parameters); Serializable handle(RMITask task, AgentContext agentContext); Service getServiceInstance(); } | @Test public void testServiceDiscovery() throws CryptoException, InternalSecurityException, AgentAlreadyRegisteredException, AgentException, MalformedXMLException, IOException, EncodingFailedException, SerializationException, InterruptedException, TimeoutException, AgentAccessDeniedException { LocalNode node = new LocalNodeManager().launchNode(); node.startService(ServiceNameVersion.fromString("[email protected]"), "a pass"); node.startService(ServiceNameVersion.fromString("[email protected]"), "a pass"); node.startService(ServiceNameVersion.fromString("[email protected]"), "a pass"); node.startService(ServiceNameVersion.fromString("[email protected]"), "a pass"); PassphraseAgentImpl userAgent = MockAgentFactory.getAdam(); userAgent.unlock("adamspass"); node.registerReceiver(userAgent); Message request = new Message(userAgent, ServiceAgentImpl.serviceNameToTopicId("i5.las2peer.api.TestService"), new ServiceDiscoveryContent(ServiceNameVersion.fromString("i5.las2peer.api.TestService@1"), false), 30000); Message[] answers = node.sendMessageAndCollectAnswers(request, 4); assertEquals(2, answers.length); boolean found10 = false, found11 = false; for (Message m : answers) { m.open(userAgent, node); ServiceDiscoveryContent c = (ServiceDiscoveryContent) m.getContent(); if (c.getService().getVersion().toString().equals("1.0")) { found10 = true; } else if (c.getService().getVersion().toString().equals("1.1")) { found11 = true; } } assertTrue(found10); assertTrue(found11); request = new Message(userAgent, ServiceAgentImpl.serviceNameToTopicId("i5.las2peer.api.TestService"), new ServiceDiscoveryContent(ServiceNameVersion.fromString("[email protected]"), true), 30000); answers = node.sendMessageAndCollectAnswers(request, 4); assertEquals(1, answers.length); answers[0].open(userAgent, node); ServiceDiscoveryContent c = (ServiceDiscoveryContent) answers[0].getContent(); assertTrue(c.getService().getVersion().toString().equals("1.1")); } |
AgentContext implements AgentStorage { public Agent requestAgent(String agentId) throws AgentAccessDeniedException, AgentNotFoundException, AgentOperationFailedException { if (agentId.equalsIgnoreCase(getMainAgent().getIdentifier())) { return getMainAgent(); } else { try { return requestGroupAgent(agentId); } catch (AgentAccessDeniedException e) { throw new AgentAccessDeniedException("Access to agent denied!", e); } } } AgentContext(Node localNode, AgentImpl mainAgent); void unlockMainAgent(String passphrase); AgentImpl getMainAgent(); GroupAgentImpl requestGroupAgent(String groupId); Agent requestAgent(String agentId); boolean hasAccess(String agentId); boolean isMemberRecursive(GroupAgentImpl groupAgent, String agentId); Node getLocalNode(); void touch(); long getLastUsageTimestamp(); @Override AgentImpl getAgent(String id); @Override boolean hasAgent(String id); static AgentContext getCurrent(); } | @Test public void testRequestAgent() throws MalformedXMLException, IOException, InternalSecurityException, CryptoException, SerializationException, AgentException, NodeException, AgentAccessDeniedException { LocalNode node = new LocalNodeManager().newNode(); UserAgentImpl adam = MockAgentFactory.getAdam(); adam.unlock("adamspass"); GroupAgentImpl group1 = MockAgentFactory.getGroup1(); group1.unlock(adam); GroupAgentImpl groupA = MockAgentFactory.getGroupA(); groupA.unlock(adam); GroupAgentImpl groupSuper = GroupAgentImpl.createGroupAgent(new AgentImpl[] { group1, groupA }); groupSuper.unlock(group1); try { node.storeAgent(group1); } catch (AgentAlreadyRegisteredException e) { } try { node.storeAgent(groupA); } catch (AgentAlreadyRegisteredException e) { } node.storeAgent(groupSuper); node.launch(); UserAgentImpl eve = MockAgentFactory.getEve(); eve.unlock("evespass"); AgentContext context = new AgentContext(node, eve); try { GroupAgentImpl a = (GroupAgentImpl) context.requestAgent(group1.getIdentifier()); assertEquals(a.getIdentifier(), group1.getIdentifier()); } catch (Exception e) { e.printStackTrace(); fail("exception thrown: " + e); } try { context.requestAgent(groupA.getIdentifier()); fail("exception expected"); } catch (Exception e) { } try { GroupAgentImpl a = (GroupAgentImpl) context.requestAgent(groupSuper.getIdentifier()); assertEquals(a.getIdentifier(), groupSuper.getIdentifier()); } catch (Exception e) { e.printStackTrace(); fail("exception thrown: " + e); } } |
AgentContext implements AgentStorage { public boolean hasAccess(String agentId) throws AgentNotFoundException { if (agent.getIdentifier().equals(agentId)) { return true; } AgentImpl a; try { a = getAgent(agentId); } catch (AgentException e) { throw new AgentNotFoundException("Agent could not be found!", e); } if (a instanceof GroupAgentImpl) { return isMemberRecursive((GroupAgentImpl) a, agent.getIdentifier()); } return false; } AgentContext(Node localNode, AgentImpl mainAgent); void unlockMainAgent(String passphrase); AgentImpl getMainAgent(); GroupAgentImpl requestGroupAgent(String groupId); Agent requestAgent(String agentId); boolean hasAccess(String agentId); boolean isMemberRecursive(GroupAgentImpl groupAgent, String agentId); Node getLocalNode(); void touch(); long getLastUsageTimestamp(); @Override AgentImpl getAgent(String id); @Override boolean hasAgent(String id); static AgentContext getCurrent(); } | @Test public void testHasAccess() throws MalformedXMLException, IOException, InternalSecurityException, CryptoException, SerializationException, AgentException, NodeException, AgentAccessDeniedException { LocalNode node = new LocalNodeManager().newNode(); UserAgentImpl adam = MockAgentFactory.getAdam(); adam.unlock("adamspass"); GroupAgentImpl group1 = MockAgentFactory.getGroup1(); group1.unlock(adam); GroupAgentImpl groupA = MockAgentFactory.getGroupA(); groupA.unlock(adam); GroupAgentImpl groupSuper = GroupAgentImpl.createGroupAgent(new AgentImpl[] { group1, groupA }); groupSuper.unlock(group1); try { node.storeAgent(group1); } catch (AgentAlreadyRegisteredException e) { } try { node.storeAgent(groupA); } catch (AgentAlreadyRegisteredException e) { } node.storeAgent(groupSuper); node.launch(); UserAgentImpl eve = MockAgentFactory.getEve(); eve.unlock("evespass"); AgentContext context = new AgentContext(node, eve); try { boolean result = context.hasAccess(group1.getIdentifier()); assertTrue(result); } catch (Exception e) { e.printStackTrace(); fail("exception thrown: " + e); } try { boolean result = context.hasAccess(groupA.getIdentifier()); assertFalse(result); } catch (Exception e) { e.printStackTrace(); fail("exception thrown: " + e); } try { boolean result = context.hasAccess(groupSuper.getIdentifier()); assertTrue(result); } catch (Exception e) { e.printStackTrace(); fail("exception thrown: " + e); } } |
AnonymousAgentImpl extends AgentImpl implements AnonymousAgent { @Override public boolean isLocked() { return false; } private AnonymousAgentImpl(); static AnonymousAgentImpl getInstance(); @Override String toXmlString(); @Override void receiveMessage(Message message, AgentContext c); @Override void unlockPrivateKey(SecretKey key); @Override void encryptPrivateKey(SecretKey key); @Override boolean isLocked(); @Override String getIdentifier(); @Override PublicKey getPublicKey(); @Override SecretKey decryptSymmetricKey(byte[] crypted); @Override Signature createSignature(); @Override byte[] signContent(byte[] plainData); @Override boolean equals(Object other); } | @Test public void testCreation() { assertFalse(anonymousAgent.isLocked()); } |
AnonymousAgentImpl extends AgentImpl implements AnonymousAgent { @Override public String getIdentifier() { return AnonymousAgent.IDENTIFIER; } private AnonymousAgentImpl(); static AnonymousAgentImpl getInstance(); @Override String toXmlString(); @Override void receiveMessage(Message message, AgentContext c); @Override void unlockPrivateKey(SecretKey key); @Override void encryptPrivateKey(SecretKey key); @Override boolean isLocked(); @Override String getIdentifier(); @Override PublicKey getPublicKey(); @Override SecretKey decryptSymmetricKey(byte[] crypted); @Override Signature createSignature(); @Override byte[] signContent(byte[] plainData); @Override boolean equals(Object other); } | @Test public void testOperations() throws AgentNotFoundException, AgentException, InternalSecurityException { AnonymousAgent a = (AnonymousAgent) node.getAgent(AnonymousAgent.IDENTIFIER); assertEquals(a.getIdentifier(), AnonymousAgent.IDENTIFIER); a = (AnonymousAgent) node.getAgent(AnonymousAgent.LOGIN_NAME); assertEquals(a.getIdentifier(), AnonymousAgent.IDENTIFIER); try { node.storeAgent(anonymousAgent); fail("Exception expected"); } catch (AgentException e) { } } |
EnvelopeVersion implements Serializable, XmlAble { @Override public String toString() { return identifier + "#" + version; } private EnvelopeVersion(String identifier, long version, PublicKey authorPubKey,
HashMap<PublicKey, byte[]> readerKeys, HashSet<String> readerGroupIds, byte[] rawContent); protected EnvelopeVersion(String identifier, PublicKey authorPubKey, Serializable content, Collection<?> readers); protected EnvelopeVersion(EnvelopeVersion previousVersion, Serializable content); protected EnvelopeVersion(EnvelopeVersion previousVersion, Serializable content, Collection<?> readers); protected EnvelopeVersion(String identifier, long version, PublicKey authorPubKey, Serializable content,
Collection<?> readers, Set<String> readerGroups); static String getAgentIdentifier(String agentId); String getIdentifier(); long getVersion(); PublicKey getAuthorPublicKey(); @Override String toString(); boolean isEncrypted(); HashMap<PublicKey, byte[]> getReaderKeys(); Set<String> getReaderGroupIds(); Serializable getContent(); Serializable getContent(AgentContext context); @Override String toXmlString(); static EnvelopeVersion createFromXml(Element rootElement); static EnvelopeVersion createFromXml(String xml); static final long LATEST_VERSION; static final long NULL_VERSION; static final long START_VERSION; static final long MAX_UPDATE_CYCLES; } | @Test public void testCollisionWithoutCollisionManager() { try { PastryNodeImpl node1 = nodes.get(0); UserAgentImpl smith = MockAgentFactory.getAdam(); smith.unlock("adamspass"); EnvelopeVersion envelope1 = node1.createUnencryptedEnvelope("test", smith.getPublicKey(), "Hello World 1!"); EnvelopeVersion envelope2 = node1.createUnencryptedEnvelope("test", smith.getPublicKey(), "Hello World 2!"); node1.storeEnvelopeAsync(envelope1, smith, new StorageStoreResultHandler() { @Override public void onResult(Serializable serializable, int successfulOperations) { System.out.println("Successfully stored artifact " + successfulOperations + " times"); node1.storeEnvelopeAsync(envelope2, smith, new StorageStoreResultHandler() { @Override public void onResult(Serializable serializable, int successfulOperations) { Assert.fail("Exception expected!"); } }, null, new StorageExceptionHandler() { private boolean testComplete = false; @Override public void onException(Exception e) { synchronized (this) { if (e instanceof EnvelopeAlreadyExistsException) { System.out.println("Expected exception '" + e.toString() + "' received."); testComplete = true; asyncTestState = true; } else if (!testComplete) { storageExceptionHandler.onException(e); } } } }); } }, null, storageExceptionHandler); System.out.println("Waiting ..."); for (int n = 1; n <= 100; n++) { if (asyncTestState) { return; } Thread.sleep(100); } Assert.fail("No collision occurred!"); } catch (Exception e) { e.printStackTrace(); Assert.fail(e.toString()); } }
@Test public void testCollisionWithMergeCancelation() { try { PastryNodeImpl node1 = nodes.get(0); UserAgentImpl smith = MockAgentFactory.getAdam(); smith.unlock("adamspass"); EnvelopeVersion envelope1 = node1.createUnencryptedEnvelope("test", smith.getPublicKey(), "Hello World 1!"); EnvelopeVersion envelope2 = node1.createUnencryptedEnvelope("test", smith.getPublicKey(), "Hello World 2!"); node1.storeEnvelopeAsync(envelope1, smith, new StorageStoreResultHandler() { @Override public void onResult(Serializable serializable, int successfulOperations) { System.out.println("Successfully stored artifact " + successfulOperations + " times"); node1.storeEnvelopeAsync(envelope2, smith, new StorageStoreResultHandler() { @Override public void onResult(Serializable serializable, int successfulOperations) { Assert.fail("Exception expected!"); } }, new StorageCollisionHandler() { @Override public String onCollision(EnvelopeVersion toStore, EnvelopeVersion inNetwork, long numberOfCollisions) throws StopMergingException { throw new StopMergingException(); } @Override public Set<PublicKey> mergeReaders(Set<PublicKey> toStoreReaders, Set<PublicKey> inNetworkReaders) { return new HashSet<>(); } @Override public Set<String> mergeGroups(Set<String> toStoreGroups, Set<String> inNetworkGroups) { return new HashSet<>(); } }, new StorageExceptionHandler() { @Override public void onException(Exception e) { if (e instanceof StopMergingException) { System.out.println("Expected exception '" + e.toString() + "' received."); asyncTestState = true; } else { storageExceptionHandler.onException(e); } } }); } }, null, storageExceptionHandler); System.out.println("Waiting ..."); for (int n = 1; n <= 100; n++) { if (asyncTestState) { return; } Thread.sleep(100); } Assert.fail("No collision occurred!"); } catch (Exception e) { e.printStackTrace(); Assert.fail(e.toString()); } }
@Test public void testFetchNonExisting() { try { PastryNodeImpl node1 = nodes.get(0); System.out.println("Fetching artifact ..."); node1.fetchEnvelopeAsync("testtesttest", new StorageEnvelopeHandler() { @Override public void onEnvelopeReceived(EnvelopeVersion envelope) { Assert.fail("Unexpected result (" + envelope.toString() + ")!"); } }, new StorageExceptionHandler() { @Override public void onException(Exception e) { if (e instanceof EnvelopeNotFoundException) { System.out.println("Expected exception '" + e.toString() + "' received."); asyncTestState = true; } else { Assert.fail("Unexpected exception (" + e.toString() + ")!"); } } }); System.out.println("Waiting ..."); for (int n = 1; n <= 100; n++) { if (asyncTestState) { return; } Thread.sleep(100); } Assert.fail("Exception expected!"); } catch (Exception e) { e.printStackTrace(); Assert.fail(e.toString()); } }
@Test public void testChangeContentType() { try { PastryNodeImpl node1 = nodes.get(0); UserAgentImpl smith = MockAgentFactory.getAdam(); smith.unlock("adamspass"); EnvelopeVersion envelope1 = node1.createUnencryptedEnvelope("test", smith.getPublicKey(), "Hello World!"); node1.storeEnvelope(envelope1, smith); EnvelopeVersion envelope2 = node1.createUnencryptedEnvelope(envelope1, 123456789); node1.storeEnvelope(envelope2, smith); } catch (Exception e) { e.printStackTrace(); Assert.fail(e.toString()); } }
@Test public void testStoreAnonymous() { try { PastryNodeImpl node = nodes.get(0); AnonymousAgentImpl anonymous = AnonymousAgentImpl.getInstance(); node.storeAgent(anonymous); Assert.fail("Exception expected"); } catch (AgentException e) { } catch (Exception e) { e.printStackTrace(); Assert.fail(e.toString()); } } |
Message implements XmlAble, Cloneable { public void open(AgentStorage storage) throws InternalSecurityException, AgentException { open(null, storage); } Message(); Message(AgentImpl from, AgentImpl to, Serializable data); Message(AgentImpl from, AgentImpl to, Serializable data, long timeOutMs); Message(AgentImpl from, AgentImpl to, XmlAble data); Message(AgentImpl from, AgentImpl to, XmlAble data, long timeoutMs); Message(AgentImpl from, long topic, Serializable data); Message(AgentImpl from, long topic, Serializable data, long timeoutMs); Message(Message responseTo, XmlAble data, long timeoutMs); Message(Message responseTo, XmlAble data); Message(Message responseTo, Serializable data, long timeoutMs); Message(Message responseTo, Serializable data); AgentImpl getSender(); String getSenderId(); AgentImpl getRecipient(); String getRecipientId(); Long getTopicId(); boolean isTopic(); long getId(); Long getResponseToId(); boolean isResponse(); Object getContent(); void open(AgentStorage storage); void open(AgentImpl unlockedRecipient, AgentStorage storage); void open(AgentImpl unlockedRecipient, AgentStorage storage, ClassLoader contentClsLoader); void verifySignature(); void close(); boolean isOpen(); long getValidMs(); long getTimestamp(); Date getTimestampDate(); Date getTimeoutDate(); long getTimeoutTs(); boolean isExpired(); @Override String toXmlString(); void setStateFromXml(String xml); void setSendingNodeId(NodeHandle handle); void setSendingNodeId(Long id); void setRecipientId(String id); void setSendingNodeId(Object id); Serializable getSendingNodeId(); static Message createFromXml(String xml); @Override Message clone(); static final long DEFAULT_TIMEOUT; } | @Test public void testOpen() { try { UserAgentImpl a = UserAgentImpl.createUserAgent("passa"); UserAgentImpl b = UserAgentImpl.createUserAgent("passb"); BasicAgentStorage storage = new BasicAgentStorage(); storage.registerAgents(a, b); a.unlock("passa"); Message testee = new Message(a, b, "some content"); assertNull(testee.getSender()); assertNull(testee.getRecipient()); assertTrue(b.getIdentifier().equalsIgnoreCase(testee.getRecipientId())); assertEquals(a.getIdentifier(), testee.getSenderId()); b.unlock("passb"); testee.open(b, storage); assertNotSame(a, testee.getSender()); assertEquals(b, testee.getRecipient()); assertEquals(a.getIdentifier(), testee.getSender().getIdentifier()); } catch (Exception e) { e.printStackTrace(); Assert.fail(e.toString()); } } |
Message implements XmlAble, Cloneable { @Override public String toXmlString() { String response = ""; if (responseToId != null) { response = " responseTo=\"" + responseToId + "\""; } String sending = ""; if (sendingNodeId != null) { if (sendingNodeId instanceof Long || sendingNodeId instanceof NodeHandle) { try { sending = "\t<sendingNode encoding=\"base64\">" + SerializeTools.serializeToBase64(sendingNodeId) + "</sendingNode>\n"; } catch (SerializationException e) { } } } String base64ContentKey = ""; if (baContentKey != null) { base64ContentKey = Base64.getEncoder().encodeToString(baContentKey); } String receiver; String contentKey = ""; String encryption = ""; if (!isTopic()) { receiver = "to=\"" + recipientId + "\""; encryption = " encryption=\"" + CryptoTools.getSymmetricAlgorithm() + "\""; contentKey = "\t<contentKey encryption=\"" + CryptoTools.getAsymmetricAlgorithm() + "\" encoding=\"base64\">" + base64ContentKey + "</contentKey>\n"; } else { receiver = "topic=\"" + topicId + "\""; } String base64Signature = ""; if (baSignature != null) { base64Signature = Base64.getEncoder().encodeToString(baSignature); } return "<las2peer:message" + " id=\"" + id + "\"" + response + " from=\"" + senderId + "\" " + receiver + " generated=\"" + timestampMs + "\" timeout=\"" + validMs + "\">\n" + sending + "\t<content" + encryption + " encoding=\"base64\">" + Base64.getEncoder().encodeToString(baEncryptedContent) + "</content>\n" + contentKey + "\t<signature encoding=\"base64\" method=\"" + CryptoTools.getSignatureMethod() + "\">" + base64Signature + "</signature>\n" + "</las2peer:message>\n"; } Message(); Message(AgentImpl from, AgentImpl to, Serializable data); Message(AgentImpl from, AgentImpl to, Serializable data, long timeOutMs); Message(AgentImpl from, AgentImpl to, XmlAble data); Message(AgentImpl from, AgentImpl to, XmlAble data, long timeoutMs); Message(AgentImpl from, long topic, Serializable data); Message(AgentImpl from, long topic, Serializable data, long timeoutMs); Message(Message responseTo, XmlAble data, long timeoutMs); Message(Message responseTo, XmlAble data); Message(Message responseTo, Serializable data, long timeoutMs); Message(Message responseTo, Serializable data); AgentImpl getSender(); String getSenderId(); AgentImpl getRecipient(); String getRecipientId(); Long getTopicId(); boolean isTopic(); long getId(); Long getResponseToId(); boolean isResponse(); Object getContent(); void open(AgentStorage storage); void open(AgentImpl unlockedRecipient, AgentStorage storage); void open(AgentImpl unlockedRecipient, AgentStorage storage, ClassLoader contentClsLoader); void verifySignature(); void close(); boolean isOpen(); long getValidMs(); long getTimestamp(); Date getTimestampDate(); Date getTimeoutDate(); long getTimeoutTs(); boolean isExpired(); @Override String toXmlString(); void setStateFromXml(String xml); void setSendingNodeId(NodeHandle handle); void setSendingNodeId(Long id); void setRecipientId(String id); void setSendingNodeId(Object id); Serializable getSendingNodeId(); static Message createFromXml(String xml); @Override Message clone(); static final long DEFAULT_TIMEOUT; } | @Test public void testPrintMessage() { try { UserAgentImpl eve = MockAgentFactory.getEve(); UserAgentImpl adam = MockAgentFactory.getAdam(); eve.unlock("evespass"); Message m = new Message(eve, adam, "a simple content string"); String xml = m.toXmlString(); System.out.println("------ XML message output ------"); System.out.println(xml); System.out.println("------ / XML message output ------"); } catch (Exception e) { e.printStackTrace(); Assert.fail(e.toString()); } } |
ExecutionContext implements Context { @Override public void storeAgent(Agent agent) throws AgentAccessDeniedException, AgentAlreadyExistsException, AgentOperationFailedException, AgentLockedException { if (agent.isLocked()) { throw new AgentLockedException(); } else if (agent instanceof AnonymousAgent) { throw new AgentAccessDeniedException("Anonymous agent must not be stored"); } else if (agent instanceof GroupAgentImpl) { ((GroupAgentImpl) agent).apply(); } try { node.storeAgent((AgentImpl) agent); } catch (AgentAlreadyExistsException | AgentLockedException | AgentAccessDeniedException | AgentOperationFailedException e) { throw e; } catch (AgentException e) { throw new AgentOperationFailedException(e); } } ExecutionContext(ServiceAgentImpl agent, AgentContext context, Node node); static ExecutionContext getCurrent(); AgentContext getCallerContext(); @Override ClassLoader getServiceClassLoader(); @Override ExecutorService getExecutor(); @Override Service getService(); @SuppressWarnings("unchecked") @Override T getService(Class<T> serviceType); @Override ServiceAgent getServiceAgent(); @Override Agent getMainAgent(); @Override Serializable invoke(String service, String method, Serializable... parameters); @Override Serializable invoke(ServiceNameVersion service, String method, Serializable... parameters); @Override Serializable invokeInternally(String service, String method, Serializable... parameters); @Override Serializable invokeInternally(ServiceNameVersion service, String method, Serializable... parameters); @Override void monitorEvent(String message); @Override void monitorEvent(MonitoringEvent event, String message); @Override void monitorEvent(Object from, MonitoringEvent event, String message); @Override void monitorEvent(Object from, MonitoringEvent event, String message, boolean includeActingUser); @Override UserAgent createUserAgent(String passphrase); @Override GroupAgent createGroupAgent(Agent[] members); @Override Agent fetchAgent(String agentId); @Override Agent requestAgent(String agentId, Agent using); @Override Agent requestAgent(String agentId); @Override void storeAgent(Agent agent); @Override boolean hasAccess(String agentId, Agent using); @Override boolean hasAccess(String agentId); @Override String getUserAgentIdentifierByLoginName(String loginName); @Override String getUserAgentIdentifierByEmail(String emailAddress); @Override void registerReceiver(MessageReceiver receiver); @Override Logger getLogger(Class<?> cls); @Override Envelope requestEnvelope(String identifier, Agent using); @Override Envelope requestEnvelope(String identifier); @Override void storeEnvelope(Envelope env, Agent using); @Override void storeEnvelope(Envelope env); @Override void storeEnvelope(Envelope env, EnvelopeCollisionHandler handler, Agent using); @Override void storeEnvelope(Envelope env, EnvelopeCollisionHandler handler); @Override void reclaimEnvelope(String identifier, Agent using); @Override void reclaimEnvelope(String identifier); @Override Envelope createEnvelope(String identifier, Agent using); @Override Envelope createEnvelope(String identifier); } | @Test public void testStoreAnonymous() { try { AnonymousAgentImpl anonymous = AnonymousAgentImpl.getInstance(); context.storeAgent(anonymous); Assert.fail("Exception expected"); } catch (AgentAccessDeniedException e) { } catch (Exception e) { e.printStackTrace(); Assert.fail(e.toString()); } } |
ServiceHelper { public static Object execute(Service service, String method) throws ServiceMethodNotFoundException, IllegalArgumentException, IllegalAccessException, InvocationTargetException { return execute(service, method, new Object[0]); } static Class<?> getWrapperClass(Class<?> c); static boolean isWrapperClass(Class<?> c); static boolean isSubclass(Class<?> subClass, Class<?> superClass); static Class<?> getUnwrappedClass(Class<?> c); static Object execute(Service service, String method); static Object execute(Service service, String method, Object... parameters); static Method searchMethod(Class<? extends Service> serviceClass, String methodName, Object[] params); static String getParameterString(Object[] params); } | @Test public void testInvocation() throws SecurityException, IllegalArgumentException, ServiceMethodNotFoundException, IllegalAccessException, InvocationTargetException, InternalSecurityException { TestService testee = new TestService(); assertEquals(10, ServiceHelper.execute(testee, "getInt")); assertEquals(4, ServiceHelper.execute(testee, "inc", 2)); assertEquals(4, ServiceHelper.execute(testee, "inc", new Integer(2))); }
@Test public void testSubclassParam() throws SecurityException, IllegalArgumentException, IllegalAccessException, InvocationTargetException, InternalSecurityException, ServiceMethodNotFoundException { TestService testee = new TestService(); assertEquals("testnachricht", ServiceHelper.execute(testee, "subclass", new SecurityException("testnachricht"))); }
@Test public void testExceptions() throws SecurityException, IllegalArgumentException, IllegalAccessException, InvocationTargetException, InternalSecurityException { TestService testee = new TestService(); try { ServiceHelper.execute(testee, "privateMethod"); fail("ServiceMethodNotFoundException expected"); } catch (ServiceMethodNotFoundException e) { } try { ServiceHelper.execute(testee, "protectedMethod"); fail("ServiceMethodNotFoundException expected"); } catch (ServiceMethodNotFoundException e) { } try { ServiceHelper.execute(testee, "staticMethod"); fail("ServiceMethodNotFoundException expected"); } catch (ServiceMethodNotFoundException e) { } } |
SimpleTools { public static String join(Object[] objects, String glue) { if (objects == null) { return ""; } return SimpleTools.join(Arrays.asList(objects), glue); } static long longHash(String s); static String createRandomString(int length); static String join(Object[] objects, String glue); static String join(Iterable<?> objects, String glue); static String repeat(String string, int count); static String repeat(Object o, int count); static byte[] toByteArray(InputStream is); static String byteToHexString(byte[] bytes); static int getSystemDefinedPort(); static final String sRandomStringCharSet; } | @Test public void testJoin() { assertEquals("", SimpleTools.join((Object[]) null, "abc")); assertEquals("", SimpleTools.join(new Object[0], "dkefde")); assertEquals("a, b, c", SimpleTools.join(new Object[] { "a", 'b', "c" }, ", ")); assertEquals("10.20.30", SimpleTools.join(new Integer[] { 10, 20, 30 }, ".")); } |
WebConnector extends Connector { public String getHttpEndpoint() { return "http: } WebConnector(); WebConnector(boolean http, int httpPort, boolean https, int httpsPort); WebConnector(Integer httpPort); void setLogFile(String filename); void setHttpPort(Integer port); void setHttpsPort(Integer port); void enableHttpHttps(boolean http, boolean https); @Deprecated void setSocketTimeout(int timeoutInMs); void setLogStream(OutputStream stream); void setSslKeyPassword(String password); void setSslKeystore(String keystore); void setCrossOriginResourceDomain(String cord); String getCrossOriginResourceDomain(); void setCrossOriginResourceMaxAge(int maxAge); int getCrossOriginResourceMaxAge(); void setCrossOriginResourceSharing(boolean enable); boolean isCrossOriginResourceSharing(); void setPreferLocalServices(boolean enable); @Override void start(Node node); String getRootCAFilename(); String getMyHostname(); String getHttpsEndpoint(); String getHttpEndpoint(); @Override synchronized void stop(); Node getL2pNode(); void logMessage(String message); void logError(String message, Throwable throwable); void logError(String message); NameLock getLockOidc(); String getOidcClientId(); String getOidcClientSecret(); int getHttpPort(); int getHttpsPort(); X509Certificate getCACertificate(); AgentImpl authenticateAgent(MultivaluedMap<String, String> requestHeaders, String accessTokenQueryParam); AgentSession getOrCreateSession(PassphraseAgentImpl agent); AgentSession getSessionById(String sessionid); void destroySession(String sessionId); String generateToken(); static final int DEFAULT_HTTP_PORT; static final String WEB_CONNECTOR; static final int DEFAULT_HTTPS_PORT; static final boolean DEFAULT_START_HTTP; static final boolean DEFAULT_START_HTTPS; static final String DEFAULT_CROSS_ORIGIN_RESOURCE_DOMAIN; static final int DEFAULT_CROSS_ORIGIN_RESOURCE_MAX_AGE; static final boolean DEFAULT_ENABLE_CROSS_ORIGIN_RESOURCE_SHARING; static final boolean DEFAULT_ONLY_LOCAL_SERVICES; static final String SESSION_COOKIE; static final String DEFAULT_DEFAULT_OIDC_PROVIDER; public String defaultOIDCProvider; public ArrayList<String> oidcProviders; static final int DEFAULT_MAX_CONNECTIONS; static final String COOKIE_SESSIONID_KEY; static final int DEFAULT_SESSION_TIMEOUT; static final int DEFAULT_MAX_THREADS; static final int DEFAULT_MAX_REQUEST_BODY_SIZE; static final String SSL_INSTANCE_NAME; public Map<String, JSONObject> oidcProviderInfos; } | @Test public void testNotMethodService() { try { MiniClient c = new MiniClient(); c.setConnectorEndpoint(connector.getHttpEndpoint()); c.setLogin(testAgent.getIdentifier(), testPass); ClientResponse response = c.sendRequest("GET", "service1/asdag", ""); Assert.assertEquals(404, response.getHttpCode()); } catch (Exception e) { Assert.fail("Not existing service caused wrong exception"); } }
@Test public void testLogin() { MiniClient c = new MiniClient(); c.setConnectorEndpoint(connector.getHttpEndpoint()); try { c.setLogin(testAgent.getIdentifier(), testPass); ClientResponse result = c.sendRequest("get", "test/ok", ""); Assert.assertEquals("OK", result.getResponse().trim()); } catch (Exception e) { e.printStackTrace(); Assert.fail("Exception: " + e); } try { c.setLogin("adam", testPass); ClientResponse result = c.sendRequest("GET", "test/ok", ""); Assert.assertEquals("OK", result.getResponse().trim()); } catch (Exception e) { e.printStackTrace(); Assert.fail("Exception: " + e); } try { c.setLogin(testAgent.getIdentifier(), "aaaaaaaaaaaaa"); ClientResponse result = c.sendRequest("GET", "test/ok", ""); Assert.assertEquals(401, result.getHttpCode()); } catch (Exception e) { e.printStackTrace(); Assert.fail("Exception: " + e); } try { c.setLogin(Long.toString(65464), "aaaaaaaaaaaaa"); ClientResponse result = c.sendRequest("GET", "test/ok", ""); Assert.assertEquals(401, result.getHttpCode()); } catch (Exception e) { e.printStackTrace(); Assert.fail("Exception: " + e); } try { c = new MiniClient(); c.setConnectorEndpoint(connector.getHttpEndpoint()); c.setLogin(Long.toString(65464), "aaaaaaaaaaaaa"); ClientResponse result = c.sendRequest("GET", "test/ok", ""); Assert.assertEquals(401, result.getHttpCode()); } catch (Exception e) { e.printStackTrace(); Assert.fail("Exception: " + e); } }
@Test public void testExceptions() { try { MiniClient c = new MiniClient(); c.setConnectorEndpoint(connector.getHttpEndpoint()); c.setLogin(testAgent.getIdentifier(), testPass); ClientResponse result = c.sendRequest("GET", "doesNotExist", ""); Assert.assertEquals(404, result.getHttpCode()); result = c.sendRequest("GET", "test/exception", ""); Assert.assertEquals(500, result.getHttpCode()); } catch (Exception e) { e.printStackTrace(); Assert.fail("Exception: " + e); } }
@Test public void testCrossOriginHeader() { try { MiniClient c = new MiniClient(); c.setConnectorEndpoint(connector.getHttpEndpoint()); c.setLogin(testAgent.getIdentifier(), testPass); ClientResponse response = c.sendRequest("GET", "asdag", ""); Assert.assertEquals(connector.crossOriginResourceDomain, response.getHeader("Access-Control-Allow-Origin")); Assert.assertEquals(String.valueOf(connector.crossOriginResourceMaxAge), response.getHeader("Access-Control-Max-Age")); } catch (Exception e) { Assert.fail("Not existing service caused wrong exception"); } }
@Test public void testPath() { try { MiniClient c = new MiniClient(); c.setConnectorEndpoint(connector.getHttpEndpoint()); c.setLogin(testAgent.getIdentifier(), testPass); ClientResponse result = c.sendRequest("GET", "version/path", ""); Assert.assertEquals(Status.OK.getStatusCode(), result.getHttpCode()); Assert.assertTrue(result.getResponse().trim().endsWith("version/")); result = c.sendRequest("GET", "version/v1/path", ""); Assert.assertEquals(Status.OK.getStatusCode(), result.getHttpCode()); Assert.assertTrue(result.getResponse().trim().endsWith("version/v1/")); result = c.sendRequest("GET", "VERSION/path", ""); Assert.assertEquals(Status.OK.getStatusCode(), result.getHttpCode()); Assert.assertTrue(result.getResponse().trim().endsWith("VERSION/")); result = c.sendRequest("GET", "UPPERCASE/test", ""); Assert.assertEquals(Status.OK.getStatusCode(), result.getHttpCode()); Assert.assertEquals("success", result.getResponse().trim()); result = c.sendRequest("GET", "uppercase/test", ""); Assert.assertEquals(Status.OK.getStatusCode(), result.getHttpCode()); Assert.assertEquals("success", result.getResponse().trim()); } catch (Exception e) { e.printStackTrace(); Assert.fail("Exception: " + e); } }
@Test public void testSwagger() { MiniClient c = new MiniClient(); c.setConnectorEndpoint(connector.getHttpEndpoint()); try { c.setLogin(testAgent.getIdentifier(), testPass); ClientResponse result = c.sendRequest("GET", "swaggertest/swagger.json", ""); Assert.assertTrue(result.getResponse().trim().contains("createSomething")); Assert.assertTrue(result.getResponse().trim().contains("subresource/content")); } catch (Exception e) { e.printStackTrace(); Assert.fail("Exception: " + e); } }
@Test public void testResponseCode() { try { MiniClient c = new MiniClient(); c.setConnectorEndpoint(connector.getHttpEndpoint()); c.setLogin(testAgent.getIdentifier(), testPass); ClientResponse result = c.sendRequest("PUT", "swaggertest/create/notfound", ""); Assert.assertEquals(404, result.getHttpCode()); result = c.sendRequest("PUT", "swaggertest/create/asdf", ""); Assert.assertEquals(200, result.getHttpCode()); } catch (Exception e) { e.printStackTrace(); Assert.fail("Exception: " + e); } }
@Test public void testSubresource() { try { MiniClient c = new MiniClient(); c.setConnectorEndpoint(connector.getHttpEndpoint()); c.setLogin(testAgent.getIdentifier(), testPass); ClientResponse result = c.sendRequest("GET", "swaggertest/subresource/content", ""); Assert.assertEquals(200, result.getHttpCode()); Assert.assertEquals("test", result.getResponse().trim()); } catch (Exception e) { e.printStackTrace(); Assert.fail("Exception: " + e); } }
@Test public void testUploadLimit() { try { MiniClient c = new MiniClient(); c.setConnectorEndpoint(connector.getHttpEndpoint()); c.setLogin(testAgent.getIdentifier(), testPass); byte[] testContent = new byte[WebConnector.DEFAULT_MAX_REQUEST_BODY_SIZE]; new Random().nextBytes(testContent); String base64 = Base64.getEncoder().encodeToString(testContent); ClientResponse result = c.sendRequest("POST", "test", base64); Assert.assertEquals(HttpURLConnection.HTTP_ENTITY_TOO_LARGE, result.getHttpCode()); } catch (Exception e) { e.printStackTrace(); Assert.fail("Exception: " + e); } }
@Test public void testSecurityContextIntegration() { try { MiniClient c = new MiniClient(); c.setConnectorEndpoint(connector.getHttpEndpoint()); ClientResponse result = c.sendRequest("GET", "security/name", ""); System.out.println("RESPONSE: " + result.getResponse()); Assert.assertEquals("no principal", result.getResponse().trim()); Assert.assertEquals(403, result.getHttpCode()); result = c.sendRequest("GET", "security/authenticated", ""); Assert.assertEquals(403, result.getHttpCode()); result = c.sendRequest("GET", "security/anonymous", ""); Assert.assertEquals(200, result.getHttpCode()); c.setLogin(testAgent.getIdentifier(), testPass); result = c.sendRequest("GET", "security/name", ""); Assert.assertEquals(200, result.getHttpCode()); Assert.assertEquals("adam", result.getResponse().trim()); result = c.sendRequest("GET", "security/authenticated", ""); Assert.assertEquals(200, result.getHttpCode()); result = c.sendRequest("GET", "security/anonymous", ""); Assert.assertEquals(200, result.getHttpCode()); result = c.sendRequest("GET", "security/bot", ""); Assert.assertEquals(403, result.getHttpCode()); } catch (Exception e) { e.printStackTrace(); Assert.fail("Exception: " + e); } }
@Test public void testClassLoading() { try { MiniClient c = new MiniClient(); c.setConnectorEndpoint(connector.getHttpEndpoint()); c.setLogin(testAgent.getIdentifier(), testPass); ClientResponse result = c.sendRequest("GET", "classloader/test", ""); Assert.assertEquals(200, result.getHttpCode()); Assert.assertEquals("OK", result.getResponse().trim()); } catch (Exception e) { e.printStackTrace(); Assert.fail("Exception: " + e); } }
@Test public void testEmptyResponse() { try { MiniClient c = new MiniClient(); c.setConnectorEndpoint(connector.getHttpEndpoint()); c.setLogin(testAgent.getIdentifier(), testPass); ClientResponse result = c.sendRequest("GET", "test/empty", ""); Assert.assertEquals(200, result.getHttpCode()); } catch (Exception e) { e.printStackTrace(); Assert.fail("Exception: " + e); } }
@Test public void testAuthParamSanitization() { try { MiniClient c = new MiniClient(); c.setConnectorEndpoint(connector.getHttpEndpoint()); c.setLogin(testAgent.getIdentifier(), testPass); ClientResponse result = c.sendRequest("GET", "test/requesturi?param1=sadf&access-token=secret", ""); Assert.assertEquals(200, result.getHttpCode()); Assert.assertTrue(result.getResponse().contains("param1")); Assert.assertFalse(result.getResponse().contains("secret")); Assert.assertFalse(result.getResponse().contains("access-token")); HashMap<String, String> headers = new HashMap<>(); headers.put("param1", "asdf"); result = c.sendRequest("GET", "test/headers", "", headers); Assert.assertEquals(200, result.getHttpCode()); Assert.assertTrue(result.getResponse().toLowerCase().contains("param1")); Assert.assertFalse(result.getResponse().toLowerCase().contains("authorization")); } catch (Exception e) { e.printStackTrace(); Assert.fail("Exception: " + e); } }
@Test public void testEncoding() { try { MiniClient c = new MiniClient(); c.setConnectorEndpoint(connector.getHttpEndpoint()); c.setLogin(testAgent.getIdentifier(), testPass); ClientResponse result = c.sendRequest("GET", "test/encoding", ""); Assert.assertEquals(200, result.getHttpCode()); final String header = result.getHeader(HttpHeaders.CONTENT_TYPE); System.out.println("header is: " + header); Assert.assertNotNull(header); Assert.assertTrue(header.toLowerCase().contains("charset=utf-8")); final String response = result.getResponse(); System.out.println("response is: " + response); Assert.assertNotNull(response); Assert.assertTrue(response.contains("☺")); } catch (Exception e) { e.printStackTrace(); Assert.fail("Exception: " + e); } }
@Test public void testBody() { try { MiniClient c = new MiniClient(); c.setConnectorEndpoint(connector.getHttpEndpoint()); c.setLogin(testAgent.getIdentifier(), testPass); String body = "This is a test."; ClientResponse result = c.sendRequest("POST", "test/body", body); Assert.assertEquals(200, result.getHttpCode()); Assert.assertTrue(result.getResponse().trim().equals(body)); } catch (Exception e) { e.printStackTrace(); Assert.fail("Exception: " + e); } }
@Test public void testPathResolve() { try { MiniClient c = new MiniClient(); c.setConnectorEndpoint(connector.getHttpEndpoint()); c.setLogin(testAgent.getIdentifier(), testPass); ClientResponse result = c.sendRequest("GET", "deep/path/test", ""); Assert.assertEquals(200, result.getHttpCode()); Assert.assertTrue(result.getResponse().trim().endsWith("deep/path/")); result = c.sendRequest("GET", "deep/path/v1/test", ""); Assert.assertEquals(200, result.getHttpCode()); Assert.assertTrue(result.getResponse().trim().endsWith("deep/path/v1/")); result = c.sendRequest("GET", "deep/path", ""); Assert.assertEquals(200, result.getHttpCode()); Assert.assertTrue(result.getResponse().trim().endsWith("deep/path/")); result = c.sendRequest("GET", "deep/path/v1", ""); Assert.assertEquals(200, result.getHttpCode()); Assert.assertTrue(result.getResponse().trim().endsWith("deep/path/v1/")); } catch (Exception e) { e.printStackTrace(); Assert.fail("Exception: " + e); } }
@Test public void testFavicon() { try { MiniClient c = new MiniClient(); c.setConnectorEndpoint(connector.getHttpEndpoint()); c.setLogin(testAgent.getIdentifier(), testPass); ClientResponse result = c.sendRequest("GET", "favicon.ico", ""); Assert.assertEquals(200, result.getHttpCode()); Assert.assertArrayEquals(SimpleTools.toByteArray(getClass().getResourceAsStream("/favicon.ico")), result.getRawResponse()); } catch (Exception e) { e.printStackTrace(); Assert.fail("Exception: " + e); } } |
SimpleTools { public static String repeat(String string, int count) { if (string == null) { return null; } else if (string.isEmpty() || count <= 0) { return ""; } StringBuffer result = new StringBuffer(); for (int i = 0; i < count; i++) { result.append(string); } return result.toString(); } static long longHash(String s); static String createRandomString(int length); static String join(Object[] objects, String glue); static String join(Iterable<?> objects, String glue); static String repeat(String string, int count); static String repeat(Object o, int count); static byte[] toByteArray(InputStream is); static String byteToHexString(byte[] bytes); static int getSystemDefinedPort(); static final String sRandomStringCharSet; } | @Test public void testRepeat() { assertEquals("", SimpleTools.repeat("", 11)); assertEquals("", SimpleTools.repeat("adwdw", 0)); assertEquals("", SimpleTools.repeat("adwdw", -10)); assertNull(SimpleTools.repeat(null, 100)); assertEquals("xxxx", SimpleTools.repeat("x", 4)); assertEquals("101010", SimpleTools.repeat(10, 3)); } |
LocalNode extends Node { @Override public void sendMessage(Message message, MessageResultListener listener, SendMode mode) { message.setSendingNodeId(this.getNodeId()); registerAnswerListener(message.getId(), listener); try { switch (mode) { case ANYCAST: if (!message.isTopic()) { localNodeManager.localSendMessage(localNodeManager.findFirstNodeWithAgent(message.getRecipientId()), message); } else { Long[] ids = localNodeManager.findAllNodesWithTopic(message.getTopicId()); if (ids.length == 0) { listener.collectException( new MessageException("No agent listening to topic " + message.getTopicId())); } else { localNodeManager.localSendMessage(ids[0], message); } } break; case BROADCAST: if (!message.isTopic()) { Long[] ids = localNodeManager.findAllNodesWithAgent(message.getRecipientId()); if (ids.length == 0) { listener.collectException(new AgentNotRegisteredException(message.getRecipientId())); } else { listener.addRecipients(ids.length - 1); for (long id : ids) { localNodeManager.localSendMessage(id, message); } } } else { Long[] ids = localNodeManager.findAllNodesWithTopic(message.getTopicId()); if (ids.length == 0) { listener.collectException( new MessageException("No agent listening to topic " + message.getTopicId())); } else { listener.addRecipients(ids.length - 1); for (long id : ids) { localNodeManager.localSendMessage(id, message); } } } } } catch (AgentNotRegisteredException e) { localNodeManager.storeMessage(message, listener); } } LocalNode(LocalNodeManager localNodeManager); LocalNode(LocalNodeManager localNodeManager, ClassManager classManager); @Override Long getNodeId(); @Override void shutDown(); @Override void registerReceiver(MessageReceiver receiver); @Override void sendMessage(Message message, MessageResultListener listener, SendMode mode); @Override void sendMessage(Message message, Object atNodeId, MessageResultListener listener); @Deprecated @Override EnvelopeVersion fetchArtifact(long id); @Deprecated @Override void storeArtifact(EnvelopeVersion envelope); @Deprecated @Override void removeArtifact(long id, byte[] signature); @Override Object[] findRegisteredAgent(String agentId, int hintOfExpectedCount); @Override AgentImpl getAgent(String id); void storeAgent(Agent agent); @Override void storeAgent(AgentImpl agent); @Deprecated @Override void updateAgent(AgentImpl agent); @Override Object[] getOtherKnownNodes(); @Override NodeInformation getNodeInformation(Object nodeId); @Override EnvelopeVersion createEnvelope(String identifier, PublicKey authorPubKey, Serializable content,
AgentImpl... reader); @Override EnvelopeVersion createEnvelope(EnvelopeVersion previousVersion, Serializable content); @Override EnvelopeVersion createEnvelope(EnvelopeVersion previousVersion, Serializable content, AgentImpl... reader); @Override void storeEnvelope(EnvelopeVersion envelope, AgentImpl author); @Override EnvelopeVersion fetchEnvelope(String identifier); @Override EnvelopeVersion createEnvelope(String identifier, PublicKey authorPubKey, Serializable content,
Collection<?> readers); @Override EnvelopeVersion createEnvelope(EnvelopeVersion previousVersion, Serializable content, Collection<?> readers); @Override EnvelopeVersion createUnencryptedEnvelope(String identifier, PublicKey authorPubKey, Serializable content); @Override EnvelopeVersion createUnencryptedEnvelope(EnvelopeVersion previousVersion, Serializable content); @Override void storeEnvelope(EnvelopeVersion envelope, AgentImpl author, long timeoutMs); @Override void storeEnvelopeAsync(EnvelopeVersion envelope, AgentImpl author, StorageStoreResultHandler resultHandler,
StorageCollisionHandler collisionHandler, StorageExceptionHandler exceptionHandler); @Override EnvelopeVersion fetchEnvelope(String identifier, long timeoutMs); @Override void fetchEnvelopeAsync(String identifier, StorageEnvelopeHandler envelopeHandler,
StorageExceptionHandler exceptionHandler); @Override void removeEnvelope(String identifier); @Override EnvelopeVersion fetchArtifact(String identifier); } | @Test public void testTwoNodes() { try { UserAgentImpl adam = MockAgentFactory.getAdam(); UserAgentImpl eve = MockAgentFactory.getEve(); adam.unlock("adamspass"); eve.unlock("evespass"); LocalNodeManager manager = new LocalNodeManager(); LocalNode testee1 = manager.launchAgent(adam); manager.launchAgent(eve); assertTrue(manager.findAllNodesWithAgent(adam.getIdentifier()).length > 0); assertTrue(manager.findAllNodesWithAgent(eve.getIdentifier()).length > 0); MessageResultListener l = new MessageResultListener(10000); Message m = new Message(adam, eve, new PingPongContent()); testee1.sendMessage(m, l); l.waitForAllAnswers(); assertEquals(1, l.getNumberOfExpectedResults()); assertTrue(l.isFinished()); assertTrue(l.isSuccess()); } catch (Exception e) { e.printStackTrace(); Assert.fail(e.toString()); } }
@Test public void testTimeout() { try { UserAgentImpl adam = MockAgentFactory.getAdam(); adam.unlock("adamspass"); UserAgentImpl eve = MockAgentFactory.getEve(); LocalNodeManager manager = new LocalNodeManager(); LocalNode testee1 = manager.launchAgent(adam); MessageResultListener l = new MessageResultListener(2000) { @Override public void notifyTimeout() { LocalNodeTest.testTimeoutVariable = true; } }; Message m = new Message(adam, eve, new PingPongContent(), 1000); manager.setPendingTimeOut(1000); testee1.sendMessage(m, l); Thread.sleep(30000); assertFalse(l.isSuccess()); assertTrue(l.isTimedOut()); assertEquals(0, l.getResults().length); assertTrue(testTimeoutVariable); } catch (Exception e) { e.printStackTrace(); Assert.fail(e.toString()); } }
@Test public void testPending() { try { UserAgentImpl adam = MockAgentFactory.getAdam(); adam.unlock("adamspass"); UserAgentImpl eve = MockAgentFactory.getEve(); eve.unlock("evespass"); LocalNodeManager manager = new LocalNodeManager(); LocalNode node1 = manager.launchAgent(adam); MessageResultListener resultListener = new MessageResultListener(8000) { @Override public void notifySuccess() { LocalNodeTest.testPendingVariable = true; } }; Message msg = new Message(adam, eve, new PingPongContent()); node1.sendMessage(msg, resultListener); Thread.sleep(5000); assertFalse(testPendingVariable); assertFalse(resultListener.isSuccess()); assertFalse(resultListener.isFinished()); manager.launchAgent(eve); Thread.sleep(manager.getMaxMessageWait() + 6000); assertTrue(resultListener.isSuccess()); assertTrue(resultListener.isFinished()); assertTrue(testPendingVariable); } catch (Exception e) { e.printStackTrace(); Assert.fail(e.toString()); } } |
Utils { public static void print(String title, String message, int type) { switch (type) { case Log.DEBUG: Log.d("EntireNews (" + title + ")", message); break; case Log.ERROR: Log.e("EntireNews (" + title + ")", message); break; case Log.INFO: Log.i("EntireNews (" + title + ")", message); break; case Log.VERBOSE: Log.v("EntireNews (" + title + ")", message); break; case Log.WARN: Log.w("EntireNews (" + title + ")", message); break; default: Log.d("EntireNews (" + title + ")", message); } } static void print(String title, String message, int type); static void print(final String title, final int message); static void print(final String title, final String message); static void showSnackbar(final CoordinatorLayout layout, final Context context, final String message); static void showSnackbar(final CoordinatorLayout layout, final Context context, final String message, final boolean isError); static void showSnackbar(final CoordinatorLayout layout, final Context context, final int message); static void showSnackbar(final CoordinatorLayout layout, final Context context, final int message, final boolean isError); static void showSnackbar(final CoordinatorLayout layout, final Context context, final String message, final int action); static void showSnackbar(final CoordinatorLayout layout, final Context context, final int message, final int action); static String createSlug(final String slug); static boolean isNavBarOnBottom(@NonNull Context context); static @CheckResult @ColorInt int modifyAlpha(@ColorInt int color, @IntRange(from = 0, to = 255) int alpha); static @CheckResult @ColorInt int modifyAlpha(@ColorInt int color, @FloatRange(from = 0f, to = 1f) float alpha); static String getDateAgo(final Context context, final String isoDate); static boolean isInternetConnected(final Context context); @SuppressLint("PrivateApi") static Boolean hasNavigationBar(final String TAG, final Resources resources); static void share(final String TAG, final Context context, final String name, final String title, final String url); } | @Test public void print() { } |
Utils { public static String createSlug(final String slug) { return slug.replaceAll("[^\\w\\s]", "").trim().toLowerCase().replaceAll("\\W+", "-"); } static void print(String title, String message, int type); static void print(final String title, final int message); static void print(final String title, final String message); static void showSnackbar(final CoordinatorLayout layout, final Context context, final String message); static void showSnackbar(final CoordinatorLayout layout, final Context context, final String message, final boolean isError); static void showSnackbar(final CoordinatorLayout layout, final Context context, final int message); static void showSnackbar(final CoordinatorLayout layout, final Context context, final int message, final boolean isError); static void showSnackbar(final CoordinatorLayout layout, final Context context, final String message, final int action); static void showSnackbar(final CoordinatorLayout layout, final Context context, final int message, final int action); static String createSlug(final String slug); static boolean isNavBarOnBottom(@NonNull Context context); static @CheckResult @ColorInt int modifyAlpha(@ColorInt int color, @IntRange(from = 0, to = 255) int alpha); static @CheckResult @ColorInt int modifyAlpha(@ColorInt int color, @FloatRange(from = 0f, to = 1f) float alpha); static String getDateAgo(final Context context, final String isoDate); static boolean isInternetConnected(final Context context); @SuppressLint("PrivateApi") static Boolean hasNavigationBar(final String TAG, final Resources resources); static void share(final String TAG, final Context context, final String name, final String title, final String url); } | @Test public void createSlug() { String input = "This is a title"; String expected = "this-is-a-title"; String output = Utils.createSlug(input); assertEquals(expected,output); } |
PlaygroundApplication { public static void main(String[] args) { SpringApplication.run(PlaygroundApplication.class, args); } static void main(String[] args); } | @Test public void main() throws Exception { PlaygroundApplication playgroundApplication = new PlaygroundApplication(); playgroundApplication.main(new String[]{}); } |
ProductService { public TdBProduct getProductInfo(Long productId) { TdBProduct tdBProduct = tdBProductRepository.findOne(productId); if (tdBProduct == null) { throw new ResourceNotFoundException(String.format("不存在 productId=%s", productId)); } return tdBProduct; } TdBProduct getProductInfo(Long productId); } | @Test public void getProductInfo() throws Exception { Long productId = 99999830L; given(tdBProductRepository.findOne(productId)).willReturn(mockDiscnt(productId)); TdBProduct productInfo = productService.getProductInfo(99999830L); assertThat(productInfo.getProductId()).isEqualTo(productId); }
@Test(expected = ResourceNotFoundException.class) public void getProductInfoResourceNotFoundException() throws Exception { Long productId = 1L; productService.getProductInfo(99999830L); } |
RootController { @RequestMapping(value = {"/"}, method = RequestMethod.GET) public String rootRedirect() { return "index"; } @RequestMapping(value = {"/"}, method = RequestMethod.GET) String rootRedirect(); } | @Test public void rootRedirect() throws Exception { ResponseEntity<String> result = restTemplate.exchange("/", HttpMethod.GET, new HttpEntity(null), String.class); logger.info(result.toString()); assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK); } |
ProductController { @Cacheable("getProductInfo") @HystrixCommand( fallbackMethod = "", ignoreExceptions = {Exception.class} ) @ApiOperation(value = "查询产品配置") @RequestMapping(value = "/{productId}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE) public ProductDTO getProductInfo(@ApiParam(value = "产品编码", defaultValue = "99999830", required = true) @PathVariable Long productId) { TdBProduct productInfo = productService.getProductInfo(productId); return staticModelMapperComponent.productEntityToDTO(productInfo); } @Cacheable("getProductInfo") @HystrixCommand( fallbackMethod = "", // Use Exception Handler ignoreExceptions = {Exception.class} ) @ApiOperation(value = "查询产品配置") @RequestMapping(value = "/{productId}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE) ProductDTO getProductInfo(@ApiParam(value = "产品编码", defaultValue = "99999830", required = true)
@PathVariable Long productId); } | @Test public void getProductInfo() throws Exception { ResponseEntity<ProductDTO> result = restTemplate.getForEntity(baseurl + "/products/99999830", ProductDTO.class); logger.info(result.toString()); assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(result.getBody().getProductId()).isEqualTo(99999830L); } |
SemanticVersion implements Comparable<SemanticVersion>, Serializable { @Override public String toString() { StringBuilder ret = new StringBuilder(); ret.append(major); ret.append('.'); ret.append(minor); ret.append('.'); ret.append(patch); if (qualifier != null) { ret.append('-'); ret.append(qualifier); } return ret.toString(); } SemanticVersion(); SemanticVersion(int major, int minor, int patch); SemanticVersion(int major, int minor, int patch, String qualifier); SemanticVersion(String version); boolean isUpdateFor(SemanticVersion v); boolean isSameOrNewer(SemanticVersion v); boolean isSame(SemanticVersion v); boolean isCompatibleUpdateFor(SemanticVersion v); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object other); @Override int compareTo(SemanticVersion v); String getAsString(); void setAsString(String version); public int major; public int minor; public int patch; public String qualifier; } | @Test public void testParsePlain() throws ParseException { SemanticVersion v = new SemanticVersion("1.2.3"); assertEquals(1, v.major); assertEquals(2, v.minor); assertEquals(3, v.patch); assertEquals("1.2.3", v.toString()); v = new SemanticVersion("11.22.33"); assertEquals(11, v.major); assertEquals(22, v.minor); assertEquals(33, v.patch); assertEquals("11.22.33", v.toString()); v = new SemanticVersion("11.22.33-SNAPSHOT"); assertEquals(11, v.major); assertEquals(22, v.minor); assertEquals(33, v.patch); assertEquals("SNAPSHOT", v.qualifier); assertEquals("11.22.33-SNAPSHOT", v.toString()); } |
Newznab extends Indexer<Xml> { protected SearchResultItem createSearchResultItem(NewznabXmlItem item) throws NzbHydraException { SearchResultItem searchResultItem = new SearchResultItem(); String link = getEnclosureUrl(item); searchResultItem.setLink(link); if (item.getRssGuid().isPermaLink()) { searchResultItem.setDetails(item.getRssGuid().getGuid()); Matcher matcher = GUID_PATTERN.matcher(item.getRssGuid().getGuid()); if (matcher.matches()) { searchResultItem.setIndexerGuid(matcher.group(2)); } else { searchResultItem.setIndexerGuid(item.getRssGuid().getGuid()); } } else { searchResultItem.setIndexerGuid(item.getRssGuid().getGuid()); } if (!Strings.isNullOrEmpty(item.getComments()) && Strings.isNullOrEmpty(searchResultItem.getDetails())) { searchResultItem.setDetails(item.getComments().replace("#comments", "")); } searchResultItem.setFirstFound(Instant.now()); searchResultItem.setIndexer(this); searchResultItem.setTitle(cleanUpTitle(item.getTitle())); searchResultItem.setSize(item.getEnclosure().getLength()); searchResultItem.setPubDate(item.getPubDate()); searchResultItem.setIndexerScore(config.getScore()); searchResultItem.setGuid(SearchResultIdCalculator.calculateSearchResultId(searchResultItem)); searchResultItem.setAgePrecise(true); searchResultItem.setDescription(item.getDescription()); searchResultItem.setDownloadType(DownloadType.NZB); searchResultItem.setCommentsLink(item.getComments()); searchResultItem.setOriginalCategory(item.getCategory()); parseAttributes(item, searchResultItem); return searchResultItem; } @Override NfoResult getNfo(String guid); } | @Test public void shouldGetDetailsLinkFromCommentsIfNotSetFromRssGuid() throws Exception { NewznabXmlItem rssItem = buildBasicRssItem(); rssItem.setRssGuid(new NewznabXmlGuid("someguid", false)); rssItem.setComments("http: SearchResultItem item = testee.createSearchResultItem(rssItem); assertThat(item.getDetails(), is("http: }
@Test public void shouldNotSetGroupOrPosterIfNotAvailable() throws Exception { NewznabXmlItem rssItem = buildBasicRssItem(); rssItem.getNewznabAttributes().clear(); rssItem.getNewznabAttributes().add(new NewznabAttribute("group", "not available")); rssItem.getNewznabAttributes().add(new NewznabAttribute("poster", "not available")); SearchResultItem item = testee.createSearchResultItem(rssItem); assertThat(item.getGroup().isPresent(), is(false)); assertThat(item.getPoster().isPresent(), is(false)); }
@Test public void shouldReadGroupFromDescription() throws Exception { NewznabXmlItem rssItem = buildBasicRssItem(); rssItem.setDescription("<b>Group:</b> alt.binaries.tun<br />"); assertThat(testee.createSearchResultItem(rssItem).getGroup().get(), is("alt.binaries.tun")); }
@Test public void shouldRemoveTrailingWords() throws Exception { baseConfig.getSearching().setRemoveTrailing(Arrays.asList("English", "-Obfuscated", " spanish")); NewznabXmlItem rssItem = buildBasicRssItem(); rssItem.setTitle("Some title English"); assertThat(testee.createSearchResultItem(rssItem).getTitle(), is("Some title")); rssItem.setTitle("Some title-Obfuscated"); assertThat(testee.createSearchResultItem(rssItem).getTitle(), is("Some title")); rssItem.setTitle("Some title Spanish"); assertThat(testee.createSearchResultItem(rssItem).getTitle(), is("Some title")); }
@Test public void shouldCreateSearchResultItem() throws Exception { NewznabXmlItem rssItem = buildBasicRssItem(); rssItem.getNewznabAttributes().add(new NewznabAttribute("password", "0")); rssItem.getNewznabAttributes().add(new NewznabAttribute("group", "group")); rssItem.getNewznabAttributes().add(new NewznabAttribute("poster", "poster")); rssItem.getNewznabAttributes().add(new NewznabAttribute("files", "10")); rssItem.getNewznabAttributes().add(new NewznabAttribute("grabs", "20")); rssItem.getNewznabAttributes().add(new NewznabAttribute("comments", "30")); rssItem.getNewznabAttributes().add(new NewznabAttribute("usenetdate", new JaxbPubdateAdapter().marshal(Instant.ofEpochSecond(6666666)))); rssItem.getNewznabAttributes().add(new NewznabAttribute("category", "5000")); rssItem.getNewznabAttributes().add(new NewznabAttribute("category", "5050")); SearchResultItem item = testee.createSearchResultItem(rssItem); assertThat(item.getLink(), is("http: assertThat(item.getIndexerGuid(), is("123")); assertThat(item.getSize(), is(456L)); assertThat(item.getDescription(), is("description")); assertThat(item.getPubDate(), is(Instant.ofEpochSecond(5555555))); assertThat(item.getCommentsLink(), is("http: assertThat(item.getDetails(), is("http: assertThat(item.isAgePrecise(), is(true)); assertThat(item.getUsenetDate().get(), is(Instant.ofEpochSecond(6666666))); assertThat(item.getDownloadType(), is(DownloadType.NZB)); assertThat(item.isPassworded(), is(false)); assertThat(item.getGroup().get(), is("group")); assertThat(item.getPoster().get(), is("poster")); assertThat(item.getFiles(), is(10)); assertThat(item.getGrabs(), is(20)); assertThat(item.getCommentsCount(), is(30)); verify(categoryProviderMock, times(1)).fromResultNewznabCategories(Arrays.asList(5000, 5050)); rssItem.setRssGuid(new NewznabXmlGuid("123", false)); rssItem.getNewznabAttributes().clear(); rssItem.getNewznabAttributes().add(new NewznabAttribute("password", "1")); rssItem.getNewznabAttributes().add(new NewznabAttribute("nfo", "1")); item = testee.createSearchResultItem(rssItem); assertThat(item.getIndexerGuid(), is("123")); assertThat(item.isPassworded(), is(true)); assertThat(item.getHasNfo(), is(HasNfo.YES)); }
@Test public void shouldGetDetailsLinkFromRssGuidIfPermalink() throws Exception { NewznabXmlItem rssItem = buildBasicRssItem(); rssItem.setRssGuid(new NewznabXmlGuid("detailsLink", true)); rssItem.setComments("http: SearchResultItem item = testee.createSearchResultItem(rssItem); assertThat(item.getDetails(), is("detailsLink")); } |
Newznab extends Indexer<Xml> { protected void computeCategory(SearchResultItem searchResultItem, List<Integer> newznabCategories) { if (!newznabCategories.isEmpty()) { Integer mostSpecific = newznabCategories.stream().max(Integer::compareTo).get(); IndexerCategoryConfig mapping = config.getCategoryMapping(); Category category; if (mapping == null) { category = categoryProvider.fromSearchNewznabCategories(newznabCategories, categoryProvider.getNotAvailable()); searchResultItem.setOriginalCategory(categoryProvider.getNotAvailable().getName()); } else { category = idToCategory.computeIfAbsent(mostSpecific, x -> { Optional<Category> categoryOptional = Optional.empty(); if (mapping.getAnime().isPresent() && Objects.equals(mapping.getAnime().get(), mostSpecific)) { categoryOptional = categoryProvider.fromSubtype(Subtype.ANIME); } else if (mapping.getAudiobook().isPresent() && Objects.equals(mapping.getAudiobook().get(), mostSpecific)) { categoryOptional = categoryProvider.fromSubtype(Subtype.AUDIOBOOK); } else if (mapping.getEbook().isPresent() && Objects.equals(mapping.getEbook().get(), mostSpecific)) { categoryOptional = categoryProvider.fromSubtype(Subtype.EBOOK); } else if (mapping.getComic().isPresent() && Objects.equals(mapping.getComic().get(), mostSpecific)) { categoryOptional = categoryProvider.fromSubtype(Subtype.COMIC); } else if (mapping.getMagazine().isPresent() && Objects.equals(mapping.getMagazine().get(), mostSpecific)) { categoryOptional = categoryProvider.fromSubtype(Subtype.MAGAZINE); } return categoryOptional.orElse(categoryProvider.fromResultNewznabCategories(newznabCategories)); }); searchResultItem.setOriginalCategory(mapping.getNameFromId(mostSpecific)); } if (category == null) { searchResultItem.setCategory(categoryProvider.getNotAvailable()); } else { searchResultItem.setCategory(category); } } else { searchResultItem.setCategory(categoryProvider.getNotAvailable()); } } @Override NfoResult getNfo(String guid); } | @Test public void shouldComputeCategory() throws Exception { when(categoryProviderMock.fromResultNewznabCategories(any())).thenReturn(otherCategory); testee.config.getCategoryMapping().setAnime(1010); SearchResultItem item = new SearchResultItem(); testee.computeCategory(item, Arrays.asList(1000, 1010)); assertThat(item.getCategory(), is(animeCategory)); testee.computeCategory(item, Arrays.asList(3030)); assertThat(item.getCategory(), is(otherCategory)); } |
NzbGeek extends Newznab { @Override protected String cleanupQuery(String query) { String[] split = query.split(" "); if (query.split(" ").length > 6) { query = Joiner.on(" ").join(Arrays.copyOfRange(split, 0, 6)); } return query.replace("\"", ""); } } | @Test public void shouldNotUseMoreThan6WordsForNzbGeek() throws Exception { String query = "1 2 3 4 5 6 7 8 9"; assertThat(testee.cleanupQuery(query), is("1 2 3 4 5 6")); } |
IndexerStatusesCleanupTask { @HydraTask(configId = "cleanUpIndexerStatuses", name = "Clean up indexer statuses", interval = MINUTE) public void cleanup() { boolean anyChanges = false; for (IndexerConfig config : configProvider.getBaseConfig().getIndexers()) { if (config.getState() == IndexerConfig.State.DISABLED_SYSTEM_TEMPORARY && config.getDisabledUntil() != null && Instant.ofEpochMilli(config.getDisabledUntil()).isBefore(Instant.now())) { logger.debug("Setting indexer {} back to enabled after having been temporarily disabled until {}", config.getName(), Instant.ofEpochMilli(config.getDisabledUntil())); config.setState(IndexerConfig.State.ENABLED); config.setDisabledUntil(null); config.setLastError(null); anyChanges = true; } } if (anyChanges) { configProvider.getBaseConfig().save(false); } } @Autowired IndexerStatusesCleanupTask(ConfigProvider configProvider); @HydraTask(configId = "cleanUpIndexerStatuses", name = "Clean up indexer statuses", interval = MINUTE) void cleanup(); } | @Test public void shouldCleanup() { testee.cleanup(); assertThat(indexerConfigDisabledTempOutsideTimeWindow.getState()).isEqualTo(IndexerConfig.State.ENABLED); assertThat(indexerConfigDisabledTempOutsideTimeWindow.getDisabledUntil()).isNull(); assertThat(indexerConfigDisabledTempOutsideTimeWindow.getLastError()).isNull(); assertThat(indexerConfigDisabledTempOutsideTimeWindow.getDisabledLevel()).isEqualTo(1); assertThat(indexerConfigDisabledTempInTimeWindow.getState()).isEqualTo(IndexerConfig.State.DISABLED_SYSTEM_TEMPORARY); assertThat(indexerConfigDisabledTempInTimeWindow.getDisabledUntil()).isNotNull(); assertThat(indexerConfigDisabledTempInTimeWindow.getLastError()).isEqualTo("someerror"); assertThat(indexerConfigDisabledTempInTimeWindow.getDisabledLevel()).isEqualTo(1); assertThat(indexerConfigEnabled.getState()).isEqualTo(IndexerConfig.State.ENABLED); assertThat(indexerConfigUserDisabled.getState()).isEqualTo(IndexerConfig.State.DISABLED_USER); assertThat(indexerConfigDisabledSystem.getState()).isEqualTo(IndexerConfig.State.DISABLED_SYSTEM); } |
IndexerWebAccess { @SuppressWarnings("unchecked") public <T> T get(URI uri, IndexerConfig indexerConfig) throws IndexerAccessException { return get(uri, indexerConfig, null); } @SuppressWarnings("unchecked") T get(URI uri, IndexerConfig indexerConfig); @SuppressWarnings("unchecked") T get(URI uri, IndexerConfig indexerConfig, Class responseType); } | @Test public void shouldUseIndexerUserAgent() throws Exception{ testee.get(new URI("http: Map<String, String> headers = headersCaptor.getValue(); assertThat(headers).contains(entry("User-Agent", "indexerUa")); }
@Test public void shouldUseGlobalUserAgentIfNoIndexerUaIsSet() throws Exception{ indexerConfig.setUserAgent(null); testee.get(new URI("http: Map<String, String> headers = headersCaptor.getValue(); assertThat(headers).contains(entry("User-Agent", "globalUa")); }
@Test public void shouldUseIndexerTimeout() throws Exception{ testee.get(new URI("http: assertThat(timeoutCaptor.getValue()).isEqualTo(10); }
@Test public void shouldUseGlobalTimeoutNoIndexerTimeoutIsSet() throws Exception{ indexerConfig.setTimeout(null); testee.get(new URI("http: assertThat(timeoutCaptor.getValue()).isEqualTo(100); } |
IndexerForSearchSelector { protected boolean checkIndexerHitLimit(Indexer indexer) { Stopwatch stopwatch = Stopwatch.createStarted(); IndexerConfig indexerConfig = indexer.getConfig(); if (!indexerConfig.getHitLimit().isPresent() && !indexerConfig.getDownloadLimit().isPresent()) { return true; } LocalDateTime comparisonTime; LocalDateTime now = LocalDateTime.now(clock); if (indexerConfig.getHitLimitResetTime().isPresent()) { comparisonTime = now.with(ChronoField.HOUR_OF_DAY, indexerConfig.getHitLimitResetTime().get()); if (comparisonTime.isAfter(now)) { comparisonTime = comparisonTime.minus(1, ChronoUnit.DAYS); } } else { comparisonTime = now.minus(1, ChronoUnit.DAYS); } if (indexerConfig.getHitLimit().isPresent()) { boolean limitExceeded = checkIfHitLimitIsExceeded(indexer, indexerConfig, comparisonTime, IndexerApiAccessType.SEARCH, indexerConfig.getHitLimit().get(), "API hit"); if (limitExceeded) { return false; } } if (indexerConfig.getDownloadLimit().isPresent()) { boolean limitExceeded = checkIfHitLimitIsExceeded(indexer, indexerConfig, comparisonTime, IndexerApiAccessType.NZB, indexerConfig.getDownloadLimit().get(), "download"); if (limitExceeded) { return false; } } logger.debug(LoggingMarkers.PERFORMANCE, "Detection that hit limits were not reached for indexer {} took {}ms", indexer.getName(), stopwatch.elapsed(TimeUnit.MILLISECONDS)); return true; } IndexerForSearchSelection pickIndexers(SearchRequest searchRequest); static final Pattern SCHEDULER_PATTERN; } | @Test public void shouldIgnoreHitLimitIfNotYetReached() { indexerConfigMock.setHitLimit(10); when(queryMock.getResultList()).thenReturn(Collections.emptyList()); boolean result = testee.checkIndexerHitLimit(indexer); assertTrue(result); verify(entityManagerMock).createNativeQuery(anyString()); }
@Test public void shouldFollowApiHitLimit() { indexerConfigMock.setHitLimit(1); when(queryMock.getResultList()).thenReturn(Arrays.asList(Timestamp.from(Instant.now().minus(10, ChronoUnit.MILLIS)))); boolean result = testee.checkIndexerHitLimit(indexer); assertFalse(result); verify(entityManagerMock).createNativeQuery(anyString()); }
@Test public void shouldIgnoreDownloadLimitIfNotYetReached() { indexerConfigMock.setDownloadLimit(10); when(queryMock.getResultList()).thenReturn(Arrays.asList(Timestamp.from(Instant.now().minus(10, ChronoUnit.MILLIS)))); boolean result = testee.checkIndexerHitLimit(indexer); assertTrue(result); }
@Test public void shouldIgnoreHitAndDownloadLimitIfNoneAreSet() { indexerConfigMock.setHitLimit(null); indexerConfigMock.setDownloadLimit(null); testee.checkIndexerHitLimit(indexer); verify(nzbDownloadRepository, never()).findBySearchResultIndexerOrderByTimeDesc(any(), any()); verify(indexerApiAccessRepository, never()).findByIndexerOrderByTimeDesc(any(), any()); } |
UrlCalculator { protected UriComponentsBuilder buildLocalBaseUriBuilder(HttpServletRequest request) { String scheme; String host; int port = -1; String path; if (request.isSecure()) { logger.debug(LoggingMarkers.URL_CALCULATION, "Using scheme HTTPS because request is deemed secure"); scheme = "https"; } else if (Boolean.parseBoolean(environment.getProperty("server.ssl.enabled"))) { logger.debug(LoggingMarkers.URL_CALCULATION, "Using scheme HTTPS because header x-forwarded-proto is not set and built-in SSL is enabled"); scheme = "https"; } else { logger.debug(LoggingMarkers.URL_CALCULATION, "Using scheme HTTP because header x-forwarded-proto is not set and built-in SSL is disabled"); scheme = "http"; } String hostHeader = request.getHeader("host"); if (hostHeader == null) { host = request.getServerName(); logger.warn("Header host not set. Using {}. Please change your reverse proxy configuration. See https: } else { String[] split = hostHeader.split(":"); host = split[0]; if (split.length > 1) { port = Integer.parseInt(split[1]); logger.debug(LoggingMarkers.URL_CALCULATION, "Using host {} and port {} from host header {}", host, port, hostHeader); } else { logger.debug(LoggingMarkers.URL_CALCULATION, "Using host {} from host header", hostHeader); } } if (port == -1) { port = request.getServerPort(); logger.debug(LoggingMarkers.URL_CALCULATION, "Using port {} ", port); } path = request.getContextPath(); if (!Strings.isNullOrEmpty(path)) { logger.debug(LoggingMarkers.URL_CALCULATION, "Using context path {} as path", path); } else { logger.debug(LoggingMarkers.URL_CALCULATION, "Not using any context path"); } return UriComponentsBuilder.newInstance() .scheme(scheme) .host(host) .port(port) .path(path); } UriComponentsBuilder getRequestBasedUriBuilder(); @JsonIgnore UriComponentsBuilder getLocalBaseUriBuilder(); } | @Test public void shouldBuildCorrectlyForLocalAccessWithHttp() { prepareConfig(false, false, "/"); prepareHeaders("127.0.0.1:5076", null, null, null); prepareServlet("http: UriComponentsBuilder builder = testee.buildLocalBaseUriBuilder(requestMock); assertThat(builder.build().getScheme()).isEqualTo("http"); assertThat(builder.build().getHost()).isEqualTo("127.0.0.1"); assertThat(builder.build().getPort()).isEqualTo(5076); assertThat(builder.build().getPath()).isEqualTo("/"); }
@Test public void shouldBuildCorrectlyForLocalAccessWithContextPath() { prepareConfig(false, false, "/nzbhydra2"); prepareHeaders("127.0.0.1:5076", null, null, null); prepareServlet("http: UriComponentsBuilder builder = testee.buildLocalBaseUriBuilder(requestMock); assertThat(builder.build().getScheme()).isEqualTo("http"); assertThat(builder.build().getHost()).isEqualTo("127.0.0.1"); assertThat(builder.build().getPort()).isEqualTo(5076); assertThat(builder.build().getPath()).isEqualTo("/nzbhydra2"); }
@Test public void shouldBuildCorrectlyForLocalAccessWithBindAllAccessedViaLocalhost() { prepareConfig(false, true, "/"); prepareHeaders("127.0.0.1:5076", null, null, null); prepareServlet("http: UriComponentsBuilder builder = testee.buildLocalBaseUriBuilder(requestMock); assertThat(builder.build().getScheme()).isEqualTo("http"); assertThat(builder.build().getHost()).isEqualTo("127.0.0.1"); assertThat(builder.build().getPort()).isEqualTo(5076); assertThat(builder.build().getPath()).isEqualTo("/"); }
@Test public void shouldBuildCorrectlyForLocalAccessWithBindAllAccessedViaNetworkAddress() { prepareConfig(false, true, "/"); prepareHeaders("192.168.1.111:5076", null, null, null); prepareServlet("http: UriComponentsBuilder builder = testee.buildLocalBaseUriBuilder(requestMock); assertThat(builder.build().getScheme()).isEqualTo("http"); assertThat(builder.build().getHost()).isEqualTo("192.168.1.111"); assertThat(builder.build().getPort()).isEqualTo(5076); assertThat(builder.build().getPath()).isEqualTo("/"); }
@Test public void shouldBuildCorrectlyForReverseProxyWithHttpAccessedViaLocalhost() { prepareConfig(false, false, "/nzbhydra2"); prepareHeaders("127.0.0.1", "127.0.0.1:4001", null, null); prepareServlet("http: UriComponentsBuilder builder = testee.buildLocalBaseUriBuilder(requestMock); assertThat(builder.build().getScheme()).isEqualTo("http"); assertThat(builder.build().getHost()).isEqualTo("127.0.0.1"); assertThat(builder.build().getPort()).isEqualTo(4001); assertThat(builder.build().getPath()).isEqualTo("/nzbhydra2"); }
@Test public void shouldBuildCorrectlyForReverseProxyWithHttpAccessedViaNetworkAddress() { prepareConfig(false, false, "/nzbhydra2"); prepareHeaders("192.168.1.111", "192.168.1.111:4001", null, null); prepareServlet("192.168.1.111:4001", "192.168.1.111", 80, "http", "/nzbhydra2"); UriComponentsBuilder builder = testee.buildLocalBaseUriBuilder(requestMock); assertThat(builder.build().getScheme()).isEqualTo("http"); assertThat(builder.build().getHost()).isEqualTo("192.168.1.111"); assertThat(builder.build().getPort()).isEqualTo(4001); assertThat(builder.build().getPath()).isEqualTo("/nzbhydra2"); }
@Test public void shouldBuildCorrectlyForReverseProxySendingForwardedPort() { prepareConfig(false, false, "/nzbhydra2"); prepareHeaders("192.168.1.111", "192.168.1.111", null, "4001"); prepareServlet("192.168.1.111:4001", "192.168.1.111", 80, "http", "/nzbhydra2"); UriComponentsBuilder builder = testee.buildLocalBaseUriBuilder(requestMock); assertThat(builder.build().getScheme()).isEqualTo("http"); assertThat(builder.build().getHost()).isEqualTo("192.168.1.111"); assertThat(builder.build().getPort()).isEqualTo(4001); assertThat(builder.build().getPath()).isEqualTo("/nzbhydra2"); }
@Test public void shouldBuildCorrectlyForReverseProxyWithHttpsAccessedViaLocalhost() { prepareConfig(false, false, "/nzbhydra2"); prepareHeaders("127.0.0.1:4001", "127.0.0.1:4001", "https", null); prepareServlet("http: UriComponentsBuilder builder = testee.buildLocalBaseUriBuilder(requestMock); assertThat(builder.build().getScheme()).isEqualTo("https"); assertThat(builder.build().getHost()).isEqualTo("127.0.0.1"); assertThat(builder.build().getPort()).isEqualTo(4001); assertThat(builder.build().getPath()).isEqualTo("/nzbhydra2"); }
@Test public void shouldBuildCorrectlyForReverseProxyWithHttpsAccessedViaNetworkAddress() { prepareConfig(false, false, "/nzbhydra2"); prepareHeaders("192.168.1.111:4001", "192.168.1.111:4001", "https", null); prepareServlet("192.168.1.111:4001", "192.168.1.111", 80, "http", "/nzbhydra2"); UriComponentsBuilder builder = testee.buildLocalBaseUriBuilder(requestMock); assertThat(builder.build().getScheme()).isEqualTo("https"); assertThat(builder.build().getHost()).isEqualTo("192.168.1.111"); assertThat(builder.build().getPort()).isEqualTo(4001); assertThat(builder.build().getPath()).isEqualTo("/nzbhydra2"); }
@Test public void shouldBuildCorrectlyForReverseProxyWithHttpsOnPort443() { prepareConfig(false, false, "/nzbhydra2"); prepareHeaders("localhost", "localhost", "https", null); prepareServlet("localhost", "localhost", 443, "http", "/nzbhydra2"); UriComponentsBuilder builder = testee.buildLocalBaseUriBuilder(requestMock); assertThat(builder.build().getScheme()).isEqualTo("https"); assertThat(builder.build().getHost()).isEqualTo("localhost"); assertThat(builder.build().getPort()).isEqualTo(-1); assertThat(builder.build().getPath()).isEqualTo("/nzbhydra2"); }
@Test public void shouldBuildCorrectlyForReverseProxyWithHttpOnPort80AndNoPath() { prepareConfig(false, false, "/"); prepareHeaders("localhost", "localhost", "http", null); prepareServlet("localhost", "localhost", 80, "http", "/"); UriComponentsBuilder builder = testee.buildLocalBaseUriBuilder(requestMock); assertThat(builder.build().getScheme()).isEqualTo("http"); assertThat(builder.build().getHost()).isEqualTo("localhost"); assertThat(builder.build().getPort()).isEqualTo(-1); assertThat(builder.build().getPath()).isEqualTo("/"); } |
InfoProvider { public boolean canConvert(MediaIdType from, MediaIdType to) { return canConvertMap.get(from).contains(to); } boolean canConvert(MediaIdType from, MediaIdType to); static Set<MediaIdType> getConvertibleFrom(MediaIdType from); boolean canConvertAny(Set<MediaIdType> from, Set<MediaIdType> to); MediaInfo convert(Map<MediaIdType, String> identifiers); @Cacheable(cacheNames = "infos", sync = true) //sync=true is currently apparently not supported by Caffeine. synchronizing by method is good enough because we'll likely rarely hit this method concurrently with different parameters synchronized MediaInfo convert(String value, MediaIdType fromType); TvInfo findTvInfoInDatabase(Map<MediaIdType, String> ids); MovieInfo findMovieInfoInDatabase(Map<MediaIdType, String> ids); @Cacheable(cacheNames = "titles", sync = true) List<MediaInfo> search(String title, MediaIdType titleType); static Set<MediaIdType> TV_ID_TYPES; static Set<MediaIdType> MOVIE_ID_TYPES; static Set<MediaIdType> REAL_ID_TYPES; } | @Test public void canConvert() throws Exception { for (MediaIdType type : Arrays.asList(MediaIdType.IMDB, MediaIdType.TMDB, MediaIdType.MOVIETITLE)) { for (MediaIdType type2 : Arrays.asList(MediaIdType.IMDB, MediaIdType.TMDB, MediaIdType.MOVIETITLE)) { assertTrue(testee.canConvert(type, type2)); } } for (MediaIdType type : Arrays.asList(MediaIdType.TVMAZE, MediaIdType.TVDB, MediaIdType.TVRAGE, MediaIdType.TVTITLE, MediaIdType.TVIMDB)) { for (MediaIdType type2 : Arrays.asList(MediaIdType.TVMAZE, MediaIdType.TVDB, MediaIdType.TVRAGE, MediaIdType.TVTITLE, MediaIdType.TVIMDB)) { assertTrue("Should be able to convert " + type + " to " + type2, testee.canConvert(type, type2)); } } } |
InfoProvider { public boolean canConvertAny(Set<MediaIdType> from, Set<MediaIdType> to) { return from.stream().anyMatch(x -> canConvertMap.containsKey(x) && canConvertMap.get(x).stream().anyMatch(to::contains)); } boolean canConvert(MediaIdType from, MediaIdType to); static Set<MediaIdType> getConvertibleFrom(MediaIdType from); boolean canConvertAny(Set<MediaIdType> from, Set<MediaIdType> to); MediaInfo convert(Map<MediaIdType, String> identifiers); @Cacheable(cacheNames = "infos", sync = true) //sync=true is currently apparently not supported by Caffeine. synchronizing by method is good enough because we'll likely rarely hit this method concurrently with different parameters synchronized MediaInfo convert(String value, MediaIdType fromType); TvInfo findTvInfoInDatabase(Map<MediaIdType, String> ids); MovieInfo findMovieInfoInDatabase(Map<MediaIdType, String> ids); @Cacheable(cacheNames = "titles", sync = true) List<MediaInfo> search(String title, MediaIdType titleType); static Set<MediaIdType> TV_ID_TYPES; static Set<MediaIdType> MOVIE_ID_TYPES; static Set<MediaIdType> REAL_ID_TYPES; } | @Test public void canConvertAny() throws Exception { assertTrue(testee.canConvertAny(Sets.newSet(MediaIdType.TVMAZE, MediaIdType.TVDB), Sets.newSet(MediaIdType.TVRAGE))); assertTrue(testee.canConvertAny(Sets.newSet(MediaIdType.TVMAZE, MediaIdType.TVDB), Sets.newSet(MediaIdType.TVMAZE))); assertTrue(testee.canConvertAny(Sets.newSet(MediaIdType.TVMAZE), Sets.newSet(MediaIdType.TVMAZE, MediaIdType.TVDB))); assertFalse(testee.canConvertAny(Sets.newSet(), Sets.newSet(MediaIdType.TVMAZE, MediaIdType.TVDB))); assertFalse(testee.canConvertAny(Sets.newSet(MediaIdType.TVMAZE, MediaIdType.TVDB), Sets.newSet())); assertFalse(testee.canConvertAny(Sets.newSet(MediaIdType.TVMAZE, MediaIdType.TVDB), Sets.newSet(MediaIdType.TMDB))); } |
InfoProvider { public MediaInfo convert(Map<MediaIdType, String> identifiers) throws InfoProviderException { for (MediaIdType idType : REAL_ID_TYPES) { if (identifiers.containsKey(idType) && identifiers.get(idType) != null) { return convert(identifiers.get(idType), idType); } } throw new InfoProviderException("Unable to find any convertable IDs"); } boolean canConvert(MediaIdType from, MediaIdType to); static Set<MediaIdType> getConvertibleFrom(MediaIdType from); boolean canConvertAny(Set<MediaIdType> from, Set<MediaIdType> to); MediaInfo convert(Map<MediaIdType, String> identifiers); @Cacheable(cacheNames = "infos", sync = true) //sync=true is currently apparently not supported by Caffeine. synchronizing by method is good enough because we'll likely rarely hit this method concurrently with different parameters synchronized MediaInfo convert(String value, MediaIdType fromType); TvInfo findTvInfoInDatabase(Map<MediaIdType, String> ids); MovieInfo findMovieInfoInDatabase(Map<MediaIdType, String> ids); @Cacheable(cacheNames = "titles", sync = true) List<MediaInfo> search(String title, MediaIdType titleType); static Set<MediaIdType> TV_ID_TYPES; static Set<MediaIdType> MOVIE_ID_TYPES; static Set<MediaIdType> REAL_ID_TYPES; } | @Test public void shouldCatchUnexpectedError() throws Exception { when(tvMazeHandlerMock.getInfos(anyString(), eq(MediaIdType.TVDB))).thenThrow(IllegalArgumentException.class); try { testee.convert("", MediaIdType.TVDB); fail("Should've failed"); } catch (Exception e) { assertEquals(InfoProviderException.class, e.getClass()); } }
@Test public void shouldCallTvMaze() throws Exception { ArgumentCaptor<TvInfo> tvInfoArgumentCaptor = ArgumentCaptor.forClass(TvInfo.class); for (MediaIdType type : Arrays.asList(MediaIdType.TVMAZE, MediaIdType.TVDB, MediaIdType.TVRAGE, MediaIdType.TVTITLE, MediaIdType.TVIMDB)) { reset(tvMazeHandlerMock); when(tvMazeHandlerMock.getInfos(anyString(), any(MediaIdType.class))).thenReturn(new TvMazeSearchResult("tvmazeId", "tvrageId", "tvdbId", "imdbId", "title", 0, "posterUrl")); testee.convert("value", type); verify(tvMazeHandlerMock).getInfos("value", type); } verify(tvInfoRepositoryMock).findByTvdbId("value"); verify(tvInfoRepositoryMock).findByTvrageId("value"); verify(tvInfoRepositoryMock).findByTvmazeId("value"); verify(tvInfoRepositoryMock).findByImdbId("ttvalue"); verify(tvInfoRepositoryMock, times(5)).save(tvInfoArgumentCaptor.capture()); assertEquals(5, tvInfoArgumentCaptor.getAllValues().size()); assertEquals("title", tvInfoArgumentCaptor.getValue().getTitle()); assertEquals("tvdbId", tvInfoArgumentCaptor.getValue().getTvdbId().get()); assertEquals("tvmazeId", tvInfoArgumentCaptor.getValue().getTvmazeId().get()); assertEquals("tvrageId", tvInfoArgumentCaptor.getValue().getTvrageId().get()); assertEquals("ttimdbId", tvInfoArgumentCaptor.getValue().getImdbId().get()); assertEquals(Integer.valueOf(0), tvInfoArgumentCaptor.getValue().getYear()); } |
InfoProvider { @Cacheable(cacheNames = "titles", sync = true) public List<MediaInfo> search(String title, MediaIdType titleType) throws InfoProviderException { try { List<MediaInfo> infos; switch (titleType) { case TVTITLE: { List<TvMazeSearchResult> results = tvMazeHandler.search(title); infos = results.stream().map(MediaInfo::new).collect(Collectors.toList()); for (MediaInfo mediaInfo : infos) { TvInfo tvInfo = new TvInfo(mediaInfo); if (tvInfoRepository.findByTvrageIdOrTvmazeIdOrTvdbIdOrImdbId(tvInfo.getTvrageId().orElse("-1"), tvInfo.getTvmazeId().orElse("-1"), tvInfo.getTvdbId().orElse("-1"), tvInfo.getImdbId().orElse("-1")) == null) { tvInfoRepository.save(tvInfo); } } break; } case MOVIETITLE: { List<TmdbSearchResult> results = tmdbHandler.search(title, null); infos = results.stream().map(MediaInfo::new).collect(Collectors.toList()); break; } default: throw new IllegalArgumentException("Wrong IdType"); } return infos; } catch (Exception e) { logger.error("Error while searching for " + titleType + " " + title, e); Throwables.throwIfInstanceOf(e, InfoProviderException.class); throw new InfoProviderException("Unexpected error while converting infos", e); } } boolean canConvert(MediaIdType from, MediaIdType to); static Set<MediaIdType> getConvertibleFrom(MediaIdType from); boolean canConvertAny(Set<MediaIdType> from, Set<MediaIdType> to); MediaInfo convert(Map<MediaIdType, String> identifiers); @Cacheable(cacheNames = "infos", sync = true) //sync=true is currently apparently not supported by Caffeine. synchronizing by method is good enough because we'll likely rarely hit this method concurrently with different parameters synchronized MediaInfo convert(String value, MediaIdType fromType); TvInfo findTvInfoInDatabase(Map<MediaIdType, String> ids); MovieInfo findMovieInfoInDatabase(Map<MediaIdType, String> ids); @Cacheable(cacheNames = "titles", sync = true) List<MediaInfo> search(String title, MediaIdType titleType); static Set<MediaIdType> TV_ID_TYPES; static Set<MediaIdType> MOVIE_ID_TYPES; static Set<MediaIdType> REAL_ID_TYPES; } | @Test public void shouldSearch() throws Exception { testee.search("title", MediaIdType.TVTITLE); verify(tvMazeHandlerMock).search("title"); testee.search("title", MediaIdType.MOVIETITLE); verify(tmdbHandlerMock).search("title", null); } |
InfoProvider { public TvInfo findTvInfoInDatabase(Map<MediaIdType, String> ids) { Collection<TvInfo> matchingInfos = tvInfoRepository.findByTvrageIdOrTvmazeIdOrTvdbIdOrImdbId(ids.getOrDefault(TVRAGE, "-1"), ids.getOrDefault(TVMAZE, "-1"), ids.getOrDefault(TVDB, "-1"), ids.getOrDefault(IMDB, "-1")); return matchingInfos.stream().max(TvInfo::compareTo).orElse(null); } boolean canConvert(MediaIdType from, MediaIdType to); static Set<MediaIdType> getConvertibleFrom(MediaIdType from); boolean canConvertAny(Set<MediaIdType> from, Set<MediaIdType> to); MediaInfo convert(Map<MediaIdType, String> identifiers); @Cacheable(cacheNames = "infos", sync = true) //sync=true is currently apparently not supported by Caffeine. synchronizing by method is good enough because we'll likely rarely hit this method concurrently with different parameters synchronized MediaInfo convert(String value, MediaIdType fromType); TvInfo findTvInfoInDatabase(Map<MediaIdType, String> ids); MovieInfo findMovieInfoInDatabase(Map<MediaIdType, String> ids); @Cacheable(cacheNames = "titles", sync = true) List<MediaInfo> search(String title, MediaIdType titleType); static Set<MediaIdType> TV_ID_TYPES; static Set<MediaIdType> MOVIE_ID_TYPES; static Set<MediaIdType> REAL_ID_TYPES; } | @Test public void shouldGetInfoWithMostIds() { TvInfo mostInfo = new TvInfo("abc", "abc", "abc", null, null, null, null); when(tvInfoRepositoryMock.findByTvrageIdOrTvmazeIdOrTvdbIdOrImdbId(anyString(), anyString(), anyString(), anyString())).thenReturn(Arrays.asList( mostInfo, new TvInfo("abc", "abc", null, null, null, null, null), new TvInfo("abc", null, null, null, null, null, null) )); TvInfo info = testee.findTvInfoInDatabase(new HashMap<>()); assertEquals(mostInfo, info); } |
TmdbHandler { public TmdbSearchResult getInfos(String value, MediaIdType idType) throws InfoProviderException { if (idType == MediaIdType.MOVIETITLE) { return fromTitle(value, null); } if (idType == MediaIdType.IMDB) { return fromImdb(value); } if (idType == MediaIdType.TMDB) { return fromTmdb(value); } throw new IllegalArgumentException("Unable to get infos from " + idType); } TmdbSearchResult getInfos(String value, MediaIdType idType); List<TmdbSearchResult> search(String title, Integer year); } | @Test public void imdbToTmdb() throws Exception { TmdbSearchResult result = testee.getInfos("tt5895028", MediaIdType.IMDB); assertThat(result.getTmdbId(), is("407806")); assertThat(result.getTitle(), is("13th")); }
@Test public void tmdbToImdb() throws Exception { TmdbSearchResult result = testee.getInfos("407806", MediaIdType.TMDB); assertThat(result.getImdbId(), is("tt5895028")); assertThat(result.getTitle(), is("13th")); } |
TmdbHandler { TmdbSearchResult fromTitle(String title, Integer year) throws InfoProviderException { Movie movie = getMovieByTitle(title, year); TmdbSearchResult result = getSearchResultFromMovie(movie); return result; } TmdbSearchResult getInfos(String value, MediaIdType idType); List<TmdbSearchResult> search(String title, Integer year); } | @Test public void fromTitle() throws Exception { TmdbSearchResult result = testee.getInfos("gladiator", MediaIdType.MOVIETITLE); assertThat(result.getImdbId(), is("tt0172495")); result = testee.fromTitle("gladiator", 1992); assertThat(result.getImdbId(), is("tt0104346")); } |
HydraOkHttp3ClientHttpRequestFactory implements ClientHttpRequestFactory, AsyncClientHttpRequestFactory { protected boolean isUriToBeIgnoredByProxy(String host) { MainConfig mainConfig = configProvider.getBaseConfig().getMain(); if (mainConfig.isProxyIgnoreLocal()) { Boolean ipToLong = isHostInLocalNetwork(host); if (ipToLong != null) { return ipToLong; } } if (mainConfig.getProxyIgnoreDomains() == null || mainConfig.getProxyIgnoreDomains().isEmpty()) { return false; } return mainConfig.getProxyIgnoreDomains().stream().anyMatch(x -> isSameHost(x, host)); } @PostConstruct void init(); @EventListener void handleConfigChangedEvent(ConfigChangedEvent event); @Override ClientHttpRequest createRequest(URI uri, HttpMethod httpMethod); @Override AsyncClientHttpRequest createAsyncRequest(URI uri, HttpMethod httpMethod); Builder getOkHttpClientBuilder(URI requestUri); static long ipToLong(InetAddress ip); } | @Test public void shouldRecognizeLocalIps() { assertThat(testee.isUriToBeIgnoredByProxy("localhost"), is(true)); assertThat(testee.isUriToBeIgnoredByProxy("127.0.0.1"), is(true)); assertThat(testee.isUriToBeIgnoredByProxy("192.168.1.1"), is(true)); assertThat(testee.isUriToBeIgnoredByProxy("192.168.240.3"), is(true)); assertThat(testee.isUriToBeIgnoredByProxy("10.0.240.3"), is(true)); assertThat(testee.isUriToBeIgnoredByProxy("8.8.8.8"), is(false)); }
@Test public void shouldRecognizeIgnoredDomains() { assertThat(testee.isUriToBeIgnoredByProxy("mydomain.com"), is(true)); assertThat(testee.isUriToBeIgnoredByProxy("github.com"), is(true)); assertThat(testee.isUriToBeIgnoredByProxy("subdomain.otherdomain.net"), is(true)); assertThat(testee.isUriToBeIgnoredByProxy("subdomain.otherDOmain.NET"), is(true)); assertThat(testee.isUriToBeIgnoredByProxy("subdomain.otherdomain.ORG"), is(false)); assertThat(testee.isUriToBeIgnoredByProxy("somedomain.com"), is(false)); } |
HydraOkHttp3ClientHttpRequestFactory implements ClientHttpRequestFactory, AsyncClientHttpRequestFactory { public Builder getOkHttpClientBuilder(URI requestUri) { Builder builder = getBaseBuilder(); configureBuilderForSsl(requestUri, builder); MainConfig main = configProvider.getBaseConfig().getMain(); if (main.getProxyType() == ProxyType.NONE) { return builder; } if (isUriToBeIgnoredByProxy(requestUri.getHost())) { logger.debug("Not using proxy for request to {}", requestUri.getHost()); return builder; } if (main.getProxyType() == ProxyType.SOCKS) { return builder.socketFactory(sockProxySocketFactory); } else if (main.getProxyType() == ProxyType.HTTP) { builder = builder.proxy(new Proxy(Type.HTTP, new InetSocketAddress(main.getProxyHost(), main.getProxyPort()))).proxyAuthenticator((Route route, Response response) -> { if (response.request().header("Proxy-Authorization") != null) { logger.warn("Authentication with proxy failed"); return null; } String credential = Credentials.basic(main.getProxyUsername(), main.getProxyPassword()); return response.request().newBuilder() .header("Proxy-Authorization", credential).build(); }); } return builder; } @PostConstruct void init(); @EventListener void handleConfigChangedEvent(ConfigChangedEvent event); @Override ClientHttpRequest createRequest(URI uri, HttpMethod httpMethod); @Override AsyncClientHttpRequest createAsyncRequest(URI uri, HttpMethod httpMethod); Builder getOkHttpClientBuilder(URI requestUri); static long ipToLong(InetAddress ip); } | @Test public void shouldNotUseProxyIfNotConfigured() throws URISyntaxException { baseConfig.getMain().setProxyType(ProxyType.NONE); OkHttpClient client = testee.getOkHttpClientBuilder(new URI("http: assertThat(client.socketFactory() instanceof SockProxySocketFactory, is(false)); assertThat(client.proxy(), is(nullValue())); }
@Test public void shouldUseHttpProxyIfConfigured() throws URISyntaxException { baseConfig.getMain().setProxyType(ProxyType.HTTP); baseConfig.getMain().setProxyHost("proxyhost"); baseConfig.getMain().setProxyPort(1234); OkHttpClient client = testee.getOkHttpClientBuilder(new URI("http: assertThat(client.proxy().address(), equalTo(new InetSocketAddress("proxyhost", 1234))); } |
UpdateManager implements InitializingBean { public boolean isUpdateAvailable() { try { return getLatestVersion().isUpdateFor(currentVersion) && !latestVersionIgnored() && !latestVersionBlocked() && latestVersionFinalOrPreEnabled(); } catch (UpdateException e) { logger.error("Error while checking if new version is available", e); return false; } } UpdateManager(); boolean isUpdateAvailable(); boolean latestVersionFinalOrPreEnabled(); boolean latestVersionIgnored(); boolean latestVersionBlocked(); String getLatestVersionString(); String getCurrentVersionString(); void ignore(String version); List<ChangelogVersionEntry> getChangesSinceCurrentVersion(); List<ChangelogVersionEntry> getAllVersionChangesUpToCurrentVersion(); List<ChangelogVersionEntry> getAutomaticUpdateVersionHistory(); void installUpdate(boolean isAutomaticUpdate); void exitWithReturnCode(final int returnCode); @Override void afterPropertiesSet(); PackageInfo getPackageInfo(); static final int SHUTDOWN_RETURN_CODE; static final int UPDATE_RETURN_CODE; static final int RESTART_RETURN_CODE; static final int RESTORE_RETURN_CODE; static final String KEY; } | @Test public void testThatChecksForUpdateAvailable() throws Exception { assertTrue(testee.isUpdateAvailable()); testee.currentVersion = new SemanticVersion("v2.0.0"); assertFalse(testee.isUpdateAvailable()); }
@Test public void testThatChecksForUpdateAvailableWithPrerelease() throws Exception { assertTrue(testee.isUpdateAvailable()); configProviderMock.getBaseConfig().getMain().setUpdateToPrereleases(true); testee.currentVersion = new SemanticVersion("v2.3.4"); assertFalse(testee.isUpdateAvailable()); } |
UpdateManager implements InitializingBean { public String getLatestVersionString() throws UpdateException { return getLatestVersion().toString(); } UpdateManager(); boolean isUpdateAvailable(); boolean latestVersionFinalOrPreEnabled(); boolean latestVersionIgnored(); boolean latestVersionBlocked(); String getLatestVersionString(); String getCurrentVersionString(); void ignore(String version); List<ChangelogVersionEntry> getChangesSinceCurrentVersion(); List<ChangelogVersionEntry> getAllVersionChangesUpToCurrentVersion(); List<ChangelogVersionEntry> getAutomaticUpdateVersionHistory(); void installUpdate(boolean isAutomaticUpdate); void exitWithReturnCode(final int returnCode); @Override void afterPropertiesSet(); PackageInfo getPackageInfo(); static final int SHUTDOWN_RETURN_CODE; static final int UPDATE_RETURN_CODE; static final int RESTART_RETURN_CODE; static final int RESTORE_RETURN_CODE; static final String KEY; } | @Test public void shouldGetLatestReleaseFromGithub() throws Exception { String latestVersionString = testee.getLatestVersionString(); assertEquals("2.0.0", latestVersionString); testee.getLatestVersionString(); } |
UpdateManager implements InitializingBean { public List<ChangelogVersionEntry> getChangesSinceCurrentVersion() throws UpdateException { if (latestVersion == null) { getLatestVersion(); } List<ChangelogVersionEntry> allChanges; try { String response = webAccess.callUrl(changelogUrl); allChanges = objectMapper.readValue(response, new TypeReference<List<ChangelogVersionEntry>>() { }); } catch (IOException e) { throw new UpdateException("Error while getting changelog: " + e.getMessage()); } final Optional<ChangelogVersionEntry> newestFinalUpdate = allChanges.stream().filter(x -> x.isFinal() && new SemanticVersion(x.getVersion()).isUpdateFor(currentVersion)).max(Comparator.naturalOrder()); List<ChangelogVersionEntry> collectedVersionChanges = allChanges.stream().filter(x -> { if (!new SemanticVersion(x.getVersion()).isUpdateFor(currentVersion)) { return false; } if (x.isFinal()) { return true; } else { if (configProvider.getBaseConfig().getMain().isUpdateToPrereleases()) { return true; } else { return newestFinalUpdate.isPresent() && newestFinalUpdate.get().getSemanticVersion().isUpdateFor(x.getSemanticVersion()); } } } ).sorted(Comparator.reverseOrder()).collect(Collectors.toList()); return collectedVersionChanges.stream() .sorted(Comparator.reverseOrder()) .collect(Collectors.toList()); } UpdateManager(); boolean isUpdateAvailable(); boolean latestVersionFinalOrPreEnabled(); boolean latestVersionIgnored(); boolean latestVersionBlocked(); String getLatestVersionString(); String getCurrentVersionString(); void ignore(String version); List<ChangelogVersionEntry> getChangesSinceCurrentVersion(); List<ChangelogVersionEntry> getAllVersionChangesUpToCurrentVersion(); List<ChangelogVersionEntry> getAutomaticUpdateVersionHistory(); void installUpdate(boolean isAutomaticUpdate); void exitWithReturnCode(final int returnCode); @Override void afterPropertiesSet(); PackageInfo getPackageInfo(); static final int SHUTDOWN_RETURN_CODE; static final int UPDATE_RETURN_CODE; static final int RESTART_RETURN_CODE; static final int RESTORE_RETURN_CODE; static final String KEY; } | @Test public void shouldGetAllChangesIncludingPrereleaseWhenRunningFinal() throws Exception { when(webAccessMock.callUrl(eq("http:/127.0.0.1:7070/changelog"))).thenReturn( objectMapper.writeValueAsString(Arrays.asList( new ChangelogVersionEntry("2.0.1", null, false, Arrays.asList(new ChangelogChangeEntry("note", "this is a newer prerelease"))), new ChangelogVersionEntry("2.0.0", null, true, Arrays.asList(new ChangelogChangeEntry("note", "Next final release"))), new ChangelogVersionEntry("1.0.1", null, false, Arrays.asList(new ChangelogChangeEntry("note", "A betal release"))), new ChangelogVersionEntry("1.0.0", null, true, Arrays.asList(new ChangelogChangeEntry("note", "Initial final release"))) ))); List<ChangelogVersionEntry> changesSince = testee.getChangesSinceCurrentVersion(); assertEquals(2, changesSince.size()); assertEquals("2.0.0", changesSince.get(0).getVersion()); assertEquals("1.0.1", changesSince.get(1).getVersion()); }
@Test public void shouldGetAllChangesIncludingPrereleaseWhenInstallingPrereleases() throws Exception { baseConfig.getMain().setUpdateToPrereleases(true); when(webAccessMock.callUrl(eq("http:/127.0.0.1:7070/changelog"))).thenReturn( objectMapper.writeValueAsString(Arrays.asList( new ChangelogVersionEntry("2.0.1", null, false, Arrays.asList(new ChangelogChangeEntry("note", "this is a newer prerelease"))), new ChangelogVersionEntry("2.0.0", null, true, Arrays.asList(new ChangelogChangeEntry("note", "Next final release"))), new ChangelogVersionEntry("1.0.1", null, false, Arrays.asList(new ChangelogChangeEntry("note", "A betal release"))), new ChangelogVersionEntry("1.0.0", null, true, Arrays.asList(new ChangelogChangeEntry("note", "Initial final release"))) ))); List<ChangelogVersionEntry> changesSince = testee.getChangesSinceCurrentVersion(); assertEquals(3, changesSince.size()); assertEquals("2.0.1", changesSince.get(0).getVersion()); assertEquals("2.0.0", changesSince.get(1).getVersion()); assertEquals("1.0.1", changesSince.get(2).getVersion()); }
@Test public void shouldGetAllChangesWithoutPrerelease() throws Exception { when(webAccessMock.callUrl(eq("http:/127.0.0.1:7070/changelog"))).thenReturn( objectMapper.writeValueAsString(Arrays.asList( new ChangelogVersionEntry("2.0.1", null, false, Arrays.asList(new ChangelogChangeEntry("note", "this is a newer prerelease"))), new ChangelogVersionEntry("2.0.0", null, true, Arrays.asList(new ChangelogChangeEntry("note", "Next final release"))), new ChangelogVersionEntry("1.0.0", null, true, Arrays.asList(new ChangelogChangeEntry("note", "Initial final release"))) ))); List<ChangelogVersionEntry> changesSince = testee.getChangesSinceCurrentVersion(); assertEquals(1, changesSince.size()); assertEquals("2.0.0", changesSince.get(0).getVersion()); } |
IndexerForSearchSelector { LocalDateTime calculateNextPossibleHit(IndexerConfig indexerConfig, Instant firstInWindowAccessTime) { LocalDateTime nextPossibleHit; if (indexerConfig.getHitLimitResetTime().isPresent()) { LocalDateTime now = LocalDateTime.now(clock); nextPossibleHit = now.with(ChronoField.HOUR_OF_DAY, indexerConfig.getHitLimitResetTime().get()).with(ChronoField.MINUTE_OF_HOUR, 0); if (nextPossibleHit.isBefore(now)) { nextPossibleHit = nextPossibleHit.plus(1, ChronoUnit.DAYS); } } else { nextPossibleHit = LocalDateTime.ofInstant(firstInWindowAccessTime, ZoneOffset.UTC).plus(1, ChronoUnit.DAYS); } return nextPossibleHit; } IndexerForSearchSelection pickIndexers(SearchRequest searchRequest); static final Pattern SCHEDULER_PATTERN; } | @Test public void shouldCalculateNextHitWithRollingTimeWindows() throws Exception { indexerConfigMock.setHitLimitResetTime(null); Instant firstInWindow = Instant.now().minus(12, ChronoUnit.HOURS); LocalDateTime nextHit = testee.calculateNextPossibleHit(indexerConfigMock, firstInWindow); assertEquals(LocalDateTime.ofInstant(firstInWindow, ZoneOffset.UTC).plus(24, ChronoUnit.HOURS), nextHit); }
@Test public void shouldCalculateNextHitWithFixedResetTime() { Instant currentTime = Instant.ofEpochSecond(1518500323); testee.clock = Clock.fixed(currentTime, ZoneId.of("UTC")); indexerConfigMock.setHitLimitResetTime(10); LocalDateTime nextHit = testee.calculateNextPossibleHit(indexerConfigMock, currentTime); assertThat(nextHit.getHour()).isEqualTo(10); assertThat(nextHit.getDayOfYear()).isEqualTo(LocalDateTime.ofInstant(currentTime, ZoneId.of("UTC")).get(ChronoField.DAY_OF_YEAR)); currentTime = Instant.ofEpochSecond(1518500323); testee.clock = Clock.fixed(currentTime, ZoneId.of("UTC")); indexerConfigMock.setHitLimitResetTime(4); nextHit = testee.calculateNextPossibleHit(indexerConfigMock, currentTime); assertThat(nextHit.getHour()).isEqualTo(4); assertThat(nextHit.getDayOfYear()).isEqualTo(LocalDateTime.ofInstant(currentTime, ZoneId.of("UTC")).get(ChronoField.DAY_OF_YEAR) + 1); } |
IndexerForSearchSelector { protected boolean checkTorznabOnlyUsedForTorrentOrInternalSearches(Indexer indexer) { if (searchRequest.getDownloadType() == DownloadType.TORRENT && indexer.getConfig().getSearchModuleType() != SearchModuleType.TORZNAB) { String message = String.format("Not using %s because a torrent search is requested", indexer.getName()); return handleIndexerNotSelected(indexer, message, "No torrent search"); } if (searchRequest.getDownloadType() == DownloadType.NZB && indexer.getConfig().getSearchModuleType() == SearchModuleType.TORZNAB && searchRequest.getSource() == SearchSource.API) { String message = String.format("Not using %s because torznab indexers cannot be used by API NZB searches", indexer.getName()); return handleIndexerNotSelected(indexer, message, "NZB API search"); } return true; } IndexerForSearchSelection pickIndexers(SearchRequest searchRequest); static final Pattern SCHEDULER_PATTERN; } | @Test public void shouldOnlyUseTorznabIndexersForTorrentSearches() throws Exception { indexerConfigMock.setSearchModuleType(SearchModuleType.NEWZNAB); when(searchRequest.getDownloadType()).thenReturn(org.nzbhydra.searching.dtoseventsenums.DownloadType.TORRENT); assertFalse("Only torznab indexers should be used for torrent searches", testee.checkTorznabOnlyUsedForTorrentOrInternalSearches(indexer)); indexerConfigMock.setSearchModuleType(SearchModuleType.TORZNAB); when(searchRequest.getDownloadType()).thenReturn(org.nzbhydra.searching.dtoseventsenums.DownloadType.TORRENT); assertTrue("Torznab indexers should be used for torrent searches", testee.checkTorznabOnlyUsedForTorrentOrInternalSearches(indexer)); indexerConfigMock.setSearchModuleType(SearchModuleType.TORZNAB); when(searchRequest.getSource()).thenReturn(SearchSource.INTERNAL); when(searchRequest.getDownloadType()).thenReturn(org.nzbhydra.searching.dtoseventsenums.DownloadType.NZB); assertTrue("Torznab indexers should be selected for internal NZB searches", testee.checkTorznabOnlyUsedForTorrentOrInternalSearches(indexer)); indexerConfigMock.setSearchModuleType(SearchModuleType.TORZNAB); when(searchRequest.getSource()).thenReturn(SearchSource.API); when(searchRequest.getDownloadType()).thenReturn(DownloadType.NZB); assertFalse("Torznab indexers should not be selected for API NZB searches", testee.checkTorznabOnlyUsedForTorrentOrInternalSearches(indexer)); } |
CategoryProvider implements InitializingBean { public Category fromSearchNewznabCategories(String cats) { if (StringUtils.isEmpty(cats)) { return getNotAvailable(); } try { return fromSearchNewznabCategories(Arrays.stream(cats.split(",")).map(Integer::valueOf).collect(Collectors.toList()), getNotAvailable()); } catch (NumberFormatException e) { logger.error("Unable to parse categories string '{}'", cats); return getNotAvailable(); } } CategoryProvider(); @Override void afterPropertiesSet(); @org.springframework.context.event.EventListener void handleNewConfigEvent(ConfigChangedEvent newConfig); List<Category> getCategories(); void setCategories(List<Category> categories); Category getByInternalName(String name); Category getNotAvailable(); Category fromSearchNewznabCategories(String cats); Optional<Category> fromSubtype(Subtype subtype); Category fromSearchNewznabCategories(List<Integer> cats, Category defaultCategory); Category fromResultNewznabCategories(List<Integer> cats); static boolean checkCategoryMatchingMainCategory(int cat, int possibleMainCat); Category getMatchingCategoryOrMatchingMainCategory(List<Integer> cats, Category defaultCategory); static final Category naCategory; } | @Test public void shouldConvertSearchNewznabCategoriesToInternalCategory() throws Exception { assertThat(testee.fromSearchNewznabCategories(Arrays.asList(3000), CategoriesConfig.allCategory).getName(), is("3000,3030")); assertThat(testee.fromSearchNewznabCategories(Arrays.asList(3030), CategoriesConfig.allCategory).getName(), is("3000,3030")); assertThat(testee.fromSearchNewznabCategories(Arrays.asList(7020), CategoriesConfig.allCategory).getName(), is("7020,8010")); assertThat(testee.fromSearchNewznabCategories(Arrays.asList(7000, 7020), CategoriesConfig.allCategory).getName(), is("7020,8010")); assertThat(testee.fromSearchNewznabCategories(Arrays.asList(7020, 8010), CategoriesConfig.allCategory).getName(), is("7020,8010")); assertThat(testee.fromSearchNewznabCategories(Arrays.asList(4000), CategoriesConfig.allCategory).getName(), is("4000")); assertThat(testee.fromSearchNewznabCategories(Arrays.asList(4020), CategoriesConfig.allCategory).getName(), is("4000")); assertThat(testee.fromSearchNewznabCategories(Arrays.asList(4090), CategoriesConfig.allCategory).getName(), is("4090")); assertThat(testee.fromSearchNewznabCategories(Arrays.asList(4000, 4090), CategoriesConfig.allCategory).getName(), is("4000")); assertThat(testee.fromSearchNewznabCategories(Arrays.asList(7090), CategoriesConfig.allCategory).getName(), is("All")); assertThat(testee.fromSearchNewznabCategories("4000").getName(), is("4000")); assertThat(testee.fromSearchNewznabCategories("7020,8010").getName(), is("7020,8010")); assertThat(testee.fromSearchNewznabCategories(Collections.emptyList(), CategoriesConfig.allCategory).getName(), is("All")); assertThat(testee.fromSearchNewznabCategories("").getName(), is("N/A")); assertThat(testee.fromSearchNewznabCategories(Arrays.asList(4030, 4090), CategoriesConfig.allCategory).getName(), is("4000")); assertThat(testee.fromSearchNewznabCategories(Arrays.asList(3000, 4000), CategoriesConfig.allCategory).getName(), is("4000")); } |
CategoryProvider implements InitializingBean { public Category fromResultNewznabCategories(List<Integer> cats) { if (cats == null || cats.size() == 0) { return naCategory; } cats.sort((o1, o2) -> Integer.compare(o2, o1)); return getMatchingCategoryOrMatchingMainCategory(cats, naCategory); } CategoryProvider(); @Override void afterPropertiesSet(); @org.springframework.context.event.EventListener void handleNewConfigEvent(ConfigChangedEvent newConfig); List<Category> getCategories(); void setCategories(List<Category> categories); Category getByInternalName(String name); Category getNotAvailable(); Category fromSearchNewznabCategories(String cats); Optional<Category> fromSubtype(Subtype subtype); Category fromSearchNewznabCategories(List<Integer> cats, Category defaultCategory); Category fromResultNewznabCategories(List<Integer> cats); static boolean checkCategoryMatchingMainCategory(int cat, int possibleMainCat); Category getMatchingCategoryOrMatchingMainCategory(List<Integer> cats, Category defaultCategory); static final Category naCategory; } | @Test public void shouldConvertIndexerNewznabCategoriesToInternalCategory() throws Exception { assertThat(testee.fromResultNewznabCategories(Collections.emptyList()).getName(), is("N/A")); assertThat(testee.fromResultNewznabCategories(Arrays.asList(4000, 4090)).getName(), is("4090")); assertThat(testee.fromResultNewznabCategories(Arrays.asList(4000, 4090, 10_000)).getName(), is("4090")); assertThat(testee.fromResultNewznabCategories(Arrays.asList(4000, 10_000)).getName(), is("4000")); assertThat(testee.fromResultNewznabCategories(Arrays.asList(4090, 11_000)).getName(), is("4090&11_000")); assertThat(testee.fromResultNewznabCategories(Arrays.asList(6060)).getName(), is("6060+9090&99_000")); assertThat(testee.fromResultNewznabCategories(Arrays.asList(6060, 99_000)).getName(), is("6060+9090&99_000")); assertThat(testee.fromResultNewznabCategories(Arrays.asList(7070, 88_000)).getName(), is("N/A")); assertThat(testee.fromResultNewznabCategories(Arrays.asList(10_000, 20_000, 30_000)).getName(), is("10_000&20_000&30_000")); assertThat(testee.fromResultNewznabCategories(Arrays.asList(10_000, 20_000)).getName(), is("N/A")); assertThat(testee.fromResultNewznabCategories(Arrays.asList(4020)).getName(), is("4000")); assertThat(testee.fromResultNewznabCategories(Arrays.asList(9999)).getName(), is("N/A")); } |
CategoryProvider implements InitializingBean { public static boolean checkCategoryMatchingMainCategory(int cat, int possibleMainCat) { return possibleMainCat % 1000 == 0 && cat / 1000 == possibleMainCat / 1000; } CategoryProvider(); @Override void afterPropertiesSet(); @org.springframework.context.event.EventListener void handleNewConfigEvent(ConfigChangedEvent newConfig); List<Category> getCategories(); void setCategories(List<Category> categories); Category getByInternalName(String name); Category getNotAvailable(); Category fromSearchNewznabCategories(String cats); Optional<Category> fromSubtype(Subtype subtype); Category fromSearchNewznabCategories(List<Integer> cats, Category defaultCategory); Category fromResultNewznabCategories(List<Integer> cats); static boolean checkCategoryMatchingMainCategory(int cat, int possibleMainCat); Category getMatchingCategoryOrMatchingMainCategory(List<Integer> cats, Category defaultCategory); static final Category naCategory; } | @Test public void testcheckCategoryMatchingMainCategory() { assertThat(testee.checkCategoryMatchingMainCategory(5030, 5000), is(true)); assertThat(testee.checkCategoryMatchingMainCategory(5000, 5000), is(true)); assertThat(testee.checkCategoryMatchingMainCategory(4030, 5000), is(false)); assertThat(testee.checkCategoryMatchingMainCategory(4000, 5000), is(false)); assertThat(testee.checkCategoryMatchingMainCategory(4030, 4030), is(false)); } |
CategoryProvider implements InitializingBean { public Optional<Category> fromSubtype(Subtype subtype) { return categories.stream().filter(x -> x.getSubtype() == subtype).findFirst(); } CategoryProvider(); @Override void afterPropertiesSet(); @org.springframework.context.event.EventListener void handleNewConfigEvent(ConfigChangedEvent newConfig); List<Category> getCategories(); void setCategories(List<Category> categories); Category getByInternalName(String name); Category getNotAvailable(); Category fromSearchNewznabCategories(String cats); Optional<Category> fromSubtype(Subtype subtype); Category fromSearchNewznabCategories(List<Integer> cats, Category defaultCategory); Category fromResultNewznabCategories(List<Integer> cats); static boolean checkCategoryMatchingMainCategory(int cat, int possibleMainCat); Category getMatchingCategoryOrMatchingMainCategory(List<Integer> cats, Category defaultCategory); static final Category naCategory; } | @Test public void shouldFindBySubtype() { Optional<Category> animeOptional = testee.fromSubtype(Subtype.ANIME); assertThat(animeOptional.isPresent(), is(true)); assertThat(animeOptional.get().getName(), is("7020,8010")); Optional<Category> magazineOptional = testee.fromSubtype(Subtype.MAGAZINE); assertThat(magazineOptional.isPresent(), is(false)); } |
NewznabParameters { @Override public int hashCode() { return Objects.hashCode(apikey, t, q, cat, rid, tvdbid, tvmazeid, traktId, imdbid, tmdbid, season, ep, author, title, offset, limit, minage, maxage, minsize, maxsize, id, raw, o, cachetime, genre, attrs, extended, password); } @Override String toString(); @Override boolean equals(Object o1); @Override int hashCode(); int cacheKey(NewznabResponse.SearchType searchType); } | @Test public void testHashCode() throws Exception { NewznabParameters testee1 = new NewznabParameters(); testee1.setQ("q"); NewznabParameters testee2 = new NewznabParameters(); testee2.setQ("q"); assertEquals(testee1.cacheKey(NewznabResponse.SearchType.TORZNAB), testee2.cacheKey(NewznabResponse.SearchType.TORZNAB)); assertNotEquals(testee1.cacheKey(NewznabResponse.SearchType.TORZNAB), testee2.cacheKey(NewznabResponse.SearchType.NEWZNAB)); testee2.setQ("anotherQ"); assertNotEquals(testee1.cacheKey(NewznabResponse.SearchType.TORZNAB), testee2.cacheKey(NewznabResponse.SearchType.TORZNAB)); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.