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.divide... | @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))... |
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, ... |
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... |
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... |
KeltnerChannelUpperIndicator extends CachedIndicator<Num> { public KeltnerChannelUpperIndicator(KeltnerChannelMiddleIndicator keltnerMiddleIndicator, double ratio, int barCountATR) { super(keltnerMiddleIndicator); this.ratio = numOf(ratio); this.keltnerMiddleIndicator = keltnerMiddleIndicator; averageTrueRangeIndicator... | @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.getV... |
KeltnerChannelLowerIndicator extends CachedIndicator<Num> { public KeltnerChannelLowerIndicator(KeltnerChannelMiddleIndicator keltnerMiddleIndicator, double ratio, int barCountATR) { super(keltnerMiddleIndicator); this.ratio = numOf(ratio); this.keltnerMiddleIndicator = keltnerMiddleIndicator; averageTrueRangeIndicator... | @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.getV... |
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 ba... | @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.9... |
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 getBar... | @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... |
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 isSat... | @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(fixed... |
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 getBarSe... | @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 BarSerie... | @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.ARITHM... |
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... | @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 ind... | @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(... |
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.isNa... | @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.i... |
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(numberOfLos... | @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, 11... |
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... | @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, tradingRec... | @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 = getC... |
VersusBuyAndHoldCriterion extends AbstractAnalysisCriterion { @Override public boolean betterThan(Num criterionValue1, Num criterionValue2) { return criterionValue1.isGreaterThan(criterionValue2); } VersusBuyAndHoldCriterion(AnalysisCriterion criterion); @Override Num calculate(BarSeries series, TradingRecord tradingRe... | @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(numberOfL... | @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, 11... |
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, TradingRec... | @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, Trad... | @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... | @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 = getC... |
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)... | @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, Tra... | @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 serie... |
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 b... | @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(satisfi... |
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 ne... | @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 registerRece... | @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("AgentLockedExcepti... |
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 ... | @Test public void testIntegration() throws CryptoException, InternalSecurityException, AgentAlreadyRegisteredException, AgentException, AliasNotFoundException, AgentAccessDeniedException { LocalNode node = new LocalNodeManager().launchNode(); node.startService(ServiceNameVersion.fromString("i5.las2peer.api.TestService@... |
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())... | @Test public void testIntegration() { try { ServiceNameVersion serviceNameVersion = ServiceNameVersion .fromString("i5.las2peer.testServices.testPackage2.UsingService@1.0"); LocalNode serviceNode = new LocalNodeManager().newNode("export/jars/"); serviceNode.launch(); ServiceAgentImpl serviceAgent = serviceNode.startSer... |
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 getContain... | @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()); }... |
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(); pas... | @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.testPackage... |
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, getSecurityCo... | @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.loadCla... | @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"); Servi... |
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(re... | @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();... |
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, C... | @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 fo... | @Test public void testServiceClassLoading() throws ClassLoaderException, SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException { ClassManager testee = new ClassManager(new FileSystemRepository("export/jars/"), ClassLoader.getSystemClassLoader(), new Defaul... |
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 (allow... | @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.su... |
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 ... | @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))); asser... |
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[]... | @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); Lib... | @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).toStrin... |
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... | @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); St... | @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 test... |
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 sVers... | @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.prop... |
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(Library... | @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(... | @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 = getLastModifie... | @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... |
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(S... | @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.toLower... | @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")); UserAg... |
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... | @Test public void testMainUsage() { ServiceAgentGenerator.main(new String[0]); assertTrue(("" + standardError.toString()).contains("usage:")); assertEquals("", standardOut.toString()); }
@Test public void testMainNormal() { String className = "a.test.package.WithAService@1.0"; ServiceAgentGenerator.main(new String[] { ... |
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 AgentNotFoundExcepti... | @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@example.com"); node.storeAgent(a); assertEquals(a.getIdentifier(), l.getAgentIdByEmail("email@ex... |
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 UserAg... | @Test public void testUnlocking() throws NoSuchAlgorithmException, CryptoException, AgentAccessDeniedException, InternalSecurityException, AgentLockedException, AgentOperationFailedException { String passphrase = "A passphrase to unlock"; UserAgentImpl a = UserAgentImpl.createUserAgent(passphrase); try { a.decryptSymme... |
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 { messag... | @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... |
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 s... | @Test public void testServiceDiscovery() throws CryptoException, InternalSecurityException, AgentAlreadyRegisteredException, AgentException, MalformedXMLException, IOException, EncodingFailedException, SerializationException, InterruptedException, TimeoutException, AgentAccessDeniedException { LocalNode node = new Loca... |
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 (Ag... | @Test public void testRequestAgent() throws MalformedXMLException, IOException, InternalSecurityException, CryptoException, SerializationException, AgentException, NodeException, AgentAccessDeniedException { LocalNode node = new LocalNodeManager().newNode(); UserAgentImpl adam = MockAgentFactory.getAdam(); adam.unlock(... |
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 ins... | @Test public void testHasAccess() throws MalformedXMLException, IOException, InternalSecurityException, CryptoException, SerializationException, AgentException, NodeException, AgentAccessDeniedException { LocalNode node = new LocalNodeManager().newNode(); UserAgentImpl adam = MockAgentFactory.getAdam(); adam.unlock("ad... |
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(S... | @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... | @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); assertEqu... |
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 Envelope... | @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 = node... |
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 fro... | @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(te... |
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 { sendi... | @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... |
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 Agen... | @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(... | @Test public void testInvocation() throws SecurityException, IllegalArgumentException, ServiceMethodNotFoundException, IllegalAccessException, InvocationTargetException, InternalSecurityException { TestService testee = new TestService(); assertEquals(10, ServiceHelper.execute(testee, "getInt")); assertEquals(4, Service... |
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(Itera... | @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 enableHttpH... | @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 (Excepti... |
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... | @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, ... |
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(loca... | @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); assertTru... |
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... | @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 me... | @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 = ResourceN... |
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(v... | @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(999998... |
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.to... | @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); asser... |
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.setDet... | @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(... |
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 c... | @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(ite... |
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... | @Test public void shouldCleanup() { testee.cleanup(); assertThat(indexerConfigDisabledTempOutsideTimeWindow.getState()).isEqualTo(IndexerConfig.State.ENABLED); assertThat(indexerConfigDisabledTempOutsideTimeWindow.getDisabledUntil()).isNull(); assertThat(indexerConfigDisabledTempOutsideTimeWindow.getLastError()).isNull... |
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 indexe... | @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(... |
IndexerForSearchSelector { protected boolean checkIndexerHitLimit(Indexer indexer) { Stopwatch stopwatch = Stopwatch.createStarted(); IndexerConfig indexerConfig = indexer.getConfig(); if (!indexerConfig.getHitLimit().isPresent() && !indexerConfig.getDownloadLimit().isPresent()) { return true; } LocalDateTime compariso... | @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 shoul... |
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 (Boolea... | @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(... |
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 co... | @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 ty... |
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(MediaIdT... | @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... |
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 t... | @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.getCl... |
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(M... | @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... | @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,... |
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 Illeg... | @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", Med... |
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 t... | @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 (i... | @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)); ... |
HydraOkHttp3ClientHttpRequestFactory implements ClientHttpRequestFactory, AsyncClientHttpRequestFactory { public Builder getOkHttpClientBuilder(URI requestUri) { Builder builder = getBaseBuilder(); configureBuilderForSsl(requestUri, builder); MainConfig main = configProvider.getBaseConfig().getMain(); if (main.getProxy... | @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(... |
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 avail... | @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.isUpda... |
UpdateManager implements InitializingBean { public String getLatestVersionString() throws UpdateException { return getLatestVersion().toString(); } UpdateManager(); boolean isUpdateAvailable(); boolean latestVersionFinalOrPreEnabled(); boolean latestVersionIgnored(); boolean latestVersionBlocked(); String getLatestVers... | @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(... | @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 ... |
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, index... | @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.ofIns... |
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 i... | @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 torr... |
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 (... | @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).get... |
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(); @Overrid... | @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.fromResultNewzna... |
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 v... | @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.checkCategory... |
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(Con... | @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(magazineOpti... |
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... | @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)); as... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.