method2testcases
stringlengths
118
6.63k
### Question: 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); }### Answer: @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")); }
### Question: 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(); }### Answer: @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"); }
### Question: 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(); }### Answer: @Test public void testSwagger() throws JsonProcessingException { String response = testee.getSwagger(); assertTrue(response.contains("getHello")); }
### Question: 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(); }### Answer: @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()); }
### Question: 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; }### Answer: @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\"")); }
### Question: 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; }### Answer: @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()); } }
### Question: 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); }### Answer: @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); }
### Question: 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); }### Answer: @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) { } }
### Question: 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); }### Answer: @Test public void testClassToResourceName() { assertEquals("test/bla/Class.class", LoadedLibrary.classToResourceName("test.bla.Class")); assertEquals("Class.class", LoadedLibrary.classToResourceName("Class")); }
### Question: 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(); }### Answer: @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); }
### Question: 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; }### Answer: @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); }
### Question: 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); }### Answer: @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(); } }
### Question: 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[]); }### Answer: @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 + "\"")); }
### Question: 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); }### Answer: @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(); } }
### Question: 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(); }### Answer: @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); }
### Question: 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); }### Answer: @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()); } }
### Question: 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(); }### Answer: @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")); }
### Question: 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(); }### Answer: @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); } }
### Question: 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(); }### Answer: @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); } }
### Question: 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); }### Answer: @Test public void testCreation() { assertFalse(anonymousAgent.isLocked()); }
### Question: 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); }### Answer: @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) { } }
### Question: 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; }### Answer: @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()); } }
### Question: 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; }### Answer: @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()); } }
### Question: 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); }### Answer: @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()); } }
### Question: 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); }### Answer: @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) { } }
### Question: 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; }### Answer: @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 }, ".")); }
### Question: 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; }### Answer: @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)); }
### Question: 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); }### Answer: @Test public void print() { }
### Question: 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); }### Answer: @Test public void createSlug() { String input = "This is a title"; String expected = "this-is-a-title"; String output = Utils.createSlug(input); assertEquals(expected,output); }
### Question: PlaygroundApplication { public static void main(String[] args) { SpringApplication.run(PlaygroundApplication.class, args); } static void main(String[] args); }### Answer: @Test public void main() throws Exception { PlaygroundApplication playgroundApplication = new PlaygroundApplication(); playgroundApplication.main(new String[]{}); }
### Question: 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); }### Answer: @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); }
### Question: RootController { @RequestMapping(value = {"/"}, method = RequestMethod.GET) public String rootRedirect() { return "index"; } @RequestMapping(value = {"/"}, method = RequestMethod.GET) String rootRedirect(); }### Answer: @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); }
### Question: 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); }### Answer: @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); }
### Question: 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; }### Answer: @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()); }
### Question: 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); }### Answer: @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)); }
### Question: 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("\"", ""); } }### Answer: @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")); }
### Question: 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(); }### Answer: @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); }
### Question: 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); }### Answer: @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); }
### Question: 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; }### Answer: @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()); }
### Question: 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; }### Answer: @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)); } } }
### Question: 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; }### Answer: @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))); }
### Question: 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; }### Answer: @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()); }
### Question: 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; }### Answer: @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); }
### Question: 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; }### Answer: @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); }
### Question: 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); }### Answer: @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")); }
### Question: 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); }### Answer: @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")); }
### Question: 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); }### Answer: @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)); }
### Question: 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); }### Answer: @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))); }
### Question: 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; }### Answer: @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()); }
### Question: 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; }### Answer: @Test public void shouldGetLatestReleaseFromGithub() throws Exception { String latestVersionString = testee.getLatestVersionString(); assertEquals("2.0.0", latestVersionString); testee.getLatestVersionString(); }
### Question: 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; }### Answer: @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); }
### Question: 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; }### Answer: @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)); }
### Question: 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; }### Answer: @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")); }
### Question: 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; }### Answer: @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")); }
### Question: 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; }### Answer: @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)); }
### Question: 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; }### Answer: @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)); }
### Question: 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); }### Answer: @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)); }
### Question: DuplicateDetector { protected boolean testForDuplicateAge(SearchResultItem result1, SearchResultItem result2, float duplicateAgeThreshold) { Instant date1 = result1.getBestDate(); Instant date2 = result2.getBestDate(); if (date1 == null || date2 == null) { logger.debug(LoggingMarkers.DUPLICATES, "At least one result has no usenet date and no pub date"); return false; } boolean isSameAge = Math.abs(date1.getEpochSecond() - date2.getEpochSecond()) / (60 * 60) <= duplicateAgeThreshold; logger.debug(LoggingMarkers.DUPLICATES, "Same age: {}", isSameAge); return isSameAge; } DuplicateDetectionResult detectDuplicates(Set<SearchResultItem> results); }### Answer: @Test public void shouldUseUsenetDateForComparison() throws Exception { SearchResultItem item1 = new SearchResultItem(); setValues(item1, "1", "poster1", "group", Instant.now()); item1.setPubDate(Instant.now().minus(100, ChronoUnit.DAYS)); SearchResultItem item2 = new SearchResultItem(); setValues(item2, "2", "poster1", "group", Instant.now()); item2.setPubDate(Instant.now().minus(300, ChronoUnit.DAYS)); item1.setUsenetDate(Instant.now()); item2.setUsenetDate(Instant.now()); assertThat(testee.testForDuplicateAge(item1, item2, 1F)).isTrue(); item2.setUsenetDate(null); assertThat(testee.testForDuplicateAge(item1, item2, 1F)).isFalse(); }
### Question: InternalSearchResultProcessor { protected SearchResultWebTOBuilder setSearchResultDateRelatedValues(SearchResultWebTOBuilder builder, SearchResultItem item) { Instant date = item.getBestDate(); long ageInDays = date.until(Instant.now(), ChronoUnit.DAYS); if (ageInDays > 0) { builder.age(ageInDays + "d"); } else { long ageInHours = date.until(Instant.now(), ChronoUnit.HOURS); if (ageInHours > 0) { builder.age(ageInHours + "h"); } else { long ageInMinutes = date.until(Instant.now(), ChronoUnit.MINUTES); builder.age(ageInMinutes + "m"); } } builder = builder .age_precise(item.isAgePrecise()) .date(LocalDateTime.ofInstant(date, ZoneId.of("UTC")).format(item.isAgePrecise() ? DATE_TIME_FORMATTER : DATE_FORMATTER)) .epoch(date.getEpochSecond()); return builder; } SearchResponse createSearchResponse(org.nzbhydra.searching.SearchResult searchResult); }### Answer: @Test public void setSearchResultDateRelatedValues() { SearchResultWebTOBuilder builder = SearchResultWebTO.builder(); SearchResultItem item = new SearchResultItem(); item.setPubDate(Instant.now().minus(100, ChronoUnit.DAYS)); item.setUsenetDate(Instant.now().minus(10, ChronoUnit.DAYS)); builder = testee.setSearchResultDateRelatedValues(builder, item); assertThat(builder.build().getAge()).isEqualTo("10d"); item.setUsenetDate(Instant.now().minus(10, ChronoUnit.HOURS)); builder = testee.setSearchResultDateRelatedValues(builder, item); assertThat(builder.build().getAge()).isEqualTo("10h"); item.setUsenetDate(Instant.now().minus(10, ChronoUnit.MINUTES)); builder = testee.setSearchResultDateRelatedValues(builder, item); assertThat(builder.build().getAge()).isEqualTo("10m"); item.setUsenetDate(null); builder = testee.setSearchResultDateRelatedValues(builder, item); assertThat(builder.build().getAge()).isEqualTo("100d"); }
### Question: DownloadStatusUpdater { @EventListener public void onNzbDownloadEvent(FileDownloadEvent downloadEvent) { if (!configProvider.getBaseConfig().getMain().isKeepHistory()) { return; } lastDownload = Instant.now(); queueCheckEnabled = true; historyCheckEnabled = true; logger.debug(LoggingMarkers.DOWNLOAD_STATUS_UPDATE, "Received download event. Will enable status updates for the next {} minutes", (MIN_SECONDS_SINCE_LAST_DOWNLOAD_TO_CHECK_STATUSES / 60)); } @HydraTask(configId = "downloadHistoryCheck", name = "Download history check", interval = TEN_MINUTES_MS) @Transactional void checkHistoryStatus(); @HydraTask(configId = "downloadQueueCheck", name = "Download queue check", interval = TEN_SECONDS_MS) @Transactional void checkQueueStatus(); @EventListener void onNzbDownloadEvent(FileDownloadEvent downloadEvent); }### Answer: @Test public void shouldSetEnabledOnDownloadEvent() { testee.queueCheckEnabled = false; testee.lastDownload = null; testee.onNzbDownloadEvent(new FileDownloadEvent(new FileDownloadEntity(), new SearchResultEntity())); assertThat(testee.queueCheckEnabled).isTrue(); assertThat(testee.lastDownload).isNotNull(); }
### Question: RssItemBuilder { public static RssItemBuilder builder() { RssItemBuilder builder = new RssItemBuilder(); return builder; } private RssItemBuilder(); static RssItemBuilder builder(); static RssItemBuilder builder(String title); RssItemBuilder title(String title); RssItemBuilder link(String link); RssItemBuilder size(long size); RssItemBuilder pubDate(Instant pubDate); RssItemBuilder rssGuid(NewznabXmlGuid rssGuid); RssItemBuilder description(String description); RssItemBuilder comments(String comments); RssItemBuilder category(String category); RssItemBuilder grabs(Integer grabs); RssItemBuilder newznabAttributes(List<NewznabAttribute> newznabAttributes); RssItemBuilder torznabAttributes(List<NewznabAttribute> torznabAttributes); RssItemBuilder enclosure(NewznabXmlEnclosure enclosure); RssItemBuilder hasNfo(boolean hasNfo); RssItemBuilder poster(String poster); RssItemBuilder group(String group); RssItemBuilder linksFromBaseUrl(String baseUrl); RssItemBuilder categoryNewznab(String... categories); NewznabXmlItem build(); }### Answer: @Test public void testBuilder() { NewznabXmlItem item = RssItemBuilder.builder("title") .group("group") .poster("poster") .size(1000L) .category("category") .categoryNewznab("5000") .description("desc") .link("link") .hasNfo(true) .grabs(10).build(); Map<String, String> attributes = item.getNewznabAttributes().stream().collect(Collectors.toMap(NewznabAttribute::getName, NewznabAttribute::getValue)); assertEquals("group", attributes.get("group")); assertEquals("poster", attributes.get("poster")); assertEquals("5000", attributes.get("category")); assertEquals("1", attributes.get("nfo")); assertEquals(Long.valueOf(1000), item.getEnclosure().getLength()); assertEquals("desc", item.getDescription()); assertEquals("category", item.getCategory()); assertEquals("link", item.getEnclosure().getUrl()); }
### Question: DownloaderStatus { public List<Long> getDownloadingRatesInKilobytes() { if (downloadingRatesInKilobytes.isEmpty() || downloadingRatesInKilobytes.size() < 5) { return downloadingRatesInKilobytes; } if (downloadingRatesInKilobytes.get(downloadingRatesInKilobytes.size() - 1) / (float) 10 > downloadingRatesInKilobytes.get(downloadingRatesInKilobytes.size() - 2)) { if (downloadingRatesInKilobytes.get(downloadingRatesInKilobytes.size() - 1) / (float) 10 > downloadingRatesInKilobytes.get(downloadingRatesInKilobytes.size() - 3)) { return downloadingRatesInKilobytes.subList(0, downloadingRatesInKilobytes.size() - 1); } } return downloadingRatesInKilobytes; } Long getLastDownloadRate(); String getDownloadRateFormatted(); String getRemainingSizeFormatted(); List<Long> getDownloadingRatesInKilobytes(); }### Answer: @Test public void getDownloadingRatesInKilobytes() { List<Long> list = new ArrayList<>(Arrays.asList(100L, 100L, 100L, 100L, 100L, 100L, 100L)); testee.setDownloadingRatesInKilobytes(list); assertThat(testee.getDownloadingRatesInKilobytes()).containsExactlyElementsOf(list); list = new ArrayList<>(Arrays.asList(100L, 100L, 100L, 100L, 100L, 100L, 100L, 50000L)); testee.setDownloadingRatesInKilobytes(list); assertThat(testee.getDownloadingRatesInKilobytes()).containsExactly(100L, 100L, 100L, 100L, 100L, 100L, 100L); list = new ArrayList<>(Arrays.asList(100L, 100L, 100L, 100L, 100L, 100L, 100L, 50000L, 50000L)); testee.setDownloadingRatesInKilobytes(list); assertThat(testee.getDownloadingRatesInKilobytes()).containsExactlyElementsOf(list); }
### Question: OutOfMemoryDetector implements ProblemDetector { @Override public void executeCheck() { try { AtomicReference<State> state = new AtomicReference<>(); state.set(State.LOOKING_FOR_OOM); AtomicReference<String> lastTimeStampLine = new AtomicReference<>(); Files.lines(logContentProvider.getCurrentLogfile(false).toPath()).forEach(line -> { if (line.matches("\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}.*")) { if (state.get() == State.LOOKING_FOR_OOM) { lastTimeStampLine.set(line); } if (state.get() == State.LOOKING_FOR_OOM_END) { state.set(State.LOOKING_FOR_OOM); } return; } if (line.contains("java.lang.OutOfMemoryError")) { if (state.get() == State.LOOKING_FOR_OOM) { String key = "outOfMemoryDetected-" + lastTimeStampLine.get(); boolean alreadyDetected = genericStorage.get(key, String.class).isPresent(); if (!alreadyDetected) { logger.warn("The log indicates that the process ran out of memory. Please increase the XMX value in the main config and restart."); genericStorage.save(key, true); genericStorage.save("outOfMemoryDetected", true); } state.set(State.LOOKING_FOR_OOM_END); } } }); } catch (IOException e) { logger.warn("Unable to read log file: " + e.getMessage()); } catch (Exception e) { logger.warn("Unable to detect problems in log file", e); } } @Override void executeCheck(); }### Answer: @Ignore @Test public void executeCheck() throws Exception { MockitoAnnotations.initMocks(this); final Path tempFile = Files.createTempFile("nzbhydra", ".log"); try { tempFile.toFile().delete(); Files.copy(getClass().getResourceAsStream("logWithOom.log"), tempFile); } catch (Exception e) { return; } when(logContentProviderMock.getCurrentLogfile(false)).thenReturn(tempFile.toFile()); testee.executeCheck(); verify(genericStorageMock, times(4)).save(stringArgumentCaptor.capture(), objectArgumentCaptor.capture()); assertThat(stringArgumentCaptor.getAllValues().get(0)).isEqualTo("outOfMemoryDetected-2018-11-09 00:17:46 database: close"); assertThat(stringArgumentCaptor.getAllValues().get(1)).isEqualTo("outOfMemoryDetected"); assertThat(stringArgumentCaptor.getAllValues().get(2)).isEqualTo("outOfMemoryDetected-2018-11-09 11:11:46 database: close"); assertThat(stringArgumentCaptor.getAllValues().get(3)).isEqualTo("outOfMemoryDetected"); assertThat(objectArgumentCaptor.getAllValues().get(0)).isEqualTo(true); assertThat(objectArgumentCaptor.getAllValues().get(1)).isEqualTo(true); }
### Question: SensitiveDataRemovingPatternLayoutEncoder extends PatternLayoutEncoder { protected String removeSensitiveData(String txt) { return txt.replaceAll("(?i)(username|apikey|password)(=|:|%3D)([^&\\s]{2,})", "$1$2<$1>") .replaceAll("(\"name\" ?: ?\"apiKey\",(\\s*\"label\": ?\".*\",)?\\s*\"value\" ?: \")([^\"\\s*]*)", "$1<apikey>") .replaceAll("(\"name\" ?: ?\"baseUrl\",(\\s*\"label\": ?\".*\",)?\\s*\"value\" ?: \")([^\"\\s*]*)", "$1<url>") ; } Charset getCharset(); void setCharset(Charset charset); byte[] encode(ILoggingEvent event); }### Answer: @Test public void shouldRemoveSensitiveData() { SensitiveDataRemovingPatternLayoutEncoder encoder = new SensitiveDataRemovingPatternLayoutEncoder(); String result = encoder.removeSensitiveData("https: assertThat(result).isEqualTo("https: result = encoder.removeSensitiveData("https: assertThat(result).isEqualTo("https: result = encoder.removeSensitiveData("http: assertThat(result).isEqualTo("http: result = encoder.removeSensitiveData("https: assertThat(result).isEqualTo("https: result = encoder.removeSensitiveData("https: assertThat(result).isEqualTo("https: result = encoder.removeSensitiveData("https: assertThat(result).isEqualTo("https: result = encoder.removeSensitiveData("https: assertThat(result).isEqualTo("https: result = encoder.removeSensitiveData("https: assertThat(result).isEqualTo("https: final String darrApiKeyField = " \"name\": \"apiKey\",\n" + " \"label\": \"API Key\",\n" + " \"value\": \"12345678\","; result = encoder.removeSensitiveData(darrApiKeyField); assertThat(result).isEqualTo(darrApiKeyField.replace("12345678", "<apikey>")); final String darrUrlField = " \"name\": \"baseUrl\",\n" + " \"label\": \"URL\",\n" + " \"value\": \"http: result = encoder.removeSensitiveData(darrUrlField); assertThat(result).isEqualTo(darrUrlField.replace("http: final String darrUrlField2 = "\"name\" : \"baseUrl\",\n" + " \"value\" : \"http: result = encoder.removeSensitiveData(darrUrlField2); assertThat(result).isEqualTo(darrUrlField2.replace("http: final String darrUrlField3 = "\"name\" : \"baseUrl\",\n" + " \"value\" : \"http: result = encoder.removeSensitiveData(darrUrlField3); assertThat(result).isEqualTo(darrUrlField3.replace("http: }
### Question: IndexerForSearchSelector { protected boolean checkIndexerSelectedByUser(Indexer indexer) { boolean indexerNotSelectedByUser = (searchRequest.getIndexers().isPresent() && !searchRequest.getIndexers().get().isEmpty()) && !searchRequest.getIndexers().get().contains(indexer.getName()); if (indexerNotSelectedByUser) { logger.info(String.format("Not using %s because it was not selected by the user", indexer.getName())); notSelectedIndersWithReason.put(indexer, "Not selected by the user"); return false; } return true; } IndexerForSearchSelection pickIndexers(SearchRequest searchRequest); static final Pattern SCHEDULER_PATTERN; }### Answer: @Test public void shouldCheckIfSelectedByUser() { when(searchModuleProviderMock.getIndexers()).thenReturn(Arrays.asList(indexer)); when(searchRequest.getSource()).thenReturn(SearchSource.INTERNAL); when(searchRequest.getIndexers()).thenReturn(Optional.of(Sets.newSet("anotherIndexer"))); assertFalse(testee.checkIndexerSelectedByUser(indexer)); when(searchRequest.getSource()).thenReturn(SearchSource.API); assertFalse(testee.checkIndexerSelectedByUser(indexer)); when(searchRequest.getIndexers()).thenReturn(Optional.of(Sets.newSet("indexer"))); when(searchRequest.getSource()).thenReturn(SearchSource.INTERNAL); assertTrue(testee.checkIndexerSelectedByUser(indexer)); when(searchRequest.getSource()).thenReturn(SearchSource.API); assertTrue(testee.checkIndexerSelectedByUser(indexer)); }
### Question: CategoryConverter implements AttributeConverter<Category, String> { @Override public String convertToDatabaseColumn(Category category) { if (category == null) { return null; } return category.getName(); } @Autowired void setCategoryProvider(CategoryProvider categoryProvider); @Override String convertToDatabaseColumn(Category category); @Override Category convertToEntityAttribute(String categoryName); }### Answer: @Test public void convertToDatabaseColumn() throws Exception { Category category = new Category(); category.setName("name"); assertThat(testee.convertToDatabaseColumn(category), is("name")); }
### Question: CategoryConverter implements AttributeConverter<Category, String> { @Override public Category convertToEntityAttribute(String categoryName) { return categoryProvider.getByInternalName(categoryName); } @Autowired void setCategoryProvider(CategoryProvider categoryProvider); @Override String convertToDatabaseColumn(Category category); @Override Category convertToEntityAttribute(String categoryName); }### Answer: @Test public void convertToEntityAttribute() throws Exception { Category category = new Category(); when(categoryProviderMock.getByInternalName("name")).thenReturn(category); assertThat(testee.convertToEntityAttribute("name"), is(category)); }
### Question: NewznabXmlTransformer { NewznabXmlItem buildRssItem(SearchResultItem searchResultItem, boolean isNzb) { NewznabXmlItem rssItem = new NewznabXmlItem(); String link = nzbHandler.getDownloadLinkForResults(searchResultItem.getSearchResultId(), false, isNzb ? DownloadType.NZB : DownloadType.TORRENT); rssItem.setLink(link); rssItem.setTitle(searchResultItem.getTitle()); rssItem.setRssGuid(new NewznabXmlGuid(String.valueOf(searchResultItem.getGuid()), false)); rssItem.setSize(searchResultItem.getSize()); if (searchResultItem.getPubDate() != null) { rssItem.setPubDate(searchResultItem.getPubDate()); } else { rssItem.setPubDate(searchResultItem.getBestDate()); } searchResultItem.getAttributes().put("guid", String.valueOf(searchResultItem.getSearchResultId())); List<NewznabAttribute> newznabAttributes = searchResultItem.getAttributes().entrySet().stream().map(attribute -> new NewznabAttribute(attribute.getKey(), attribute.getValue())).sorted(Comparator.comparing(NewznabAttribute::getName)).collect(Collectors.toList()); if (searchResultItem.getIndexer() != null) { newznabAttributes.add(new NewznabAttribute("hydraIndexerScore", String.valueOf(searchResultItem.getIndexer().getConfig().getScore()))); newznabAttributes.add(new NewznabAttribute("hydraIndexerHost", getIndexerHost(searchResultItem))); newznabAttributes.add(new NewznabAttribute("hydraIndexerName", String.valueOf(searchResultItem.getIndexer().getName()))); } String resultType; if (isNzb) { rssItem.setNewznabAttributes(newznabAttributes); resultType = APPLICATION_TYPE_NZB; } else { rssItem.setTorznabAttributes(newznabAttributes); resultType = APPLICATION_TYPE_TORRENT; } rssItem.setEnclosure(new NewznabXmlEnclosure(link, searchResultItem.getSize(), resultType)); rssItem.setComments(searchResultItem.getCommentsLink()); rssItem.setDescription(searchResultItem.getDescription()); rssItem.setCategory(configProvider.getBaseConfig().getSearching().isUseOriginalCategories() ? searchResultItem.getOriginalCategory() : searchResultItem.getCategory().getName()); return rssItem; } }### Answer: @Test public void shouldUseCorrectApplicationType() { SearchRequest searchRequest = new SearchRequest(SearchSource.INTERNAL, SearchType.SEARCH, 0, 100); SearchResultItem searchResultItem = new SearchResultItem(); searchResultItem.setIndexer(indexerMock); searchResultItem.setCategory(new Category()); searchRequest.setDownloadType(DownloadType.NZB); NewznabXmlItem item = testee.buildRssItem(searchResultItem, searchRequest.getDownloadType() == DownloadType.NZB); assertThat(item.getEnclosure().getType()).isEqualTo("application/x-nzb"); searchRequest.setDownloadType(DownloadType.TORRENT); item = testee.buildRssItem(searchResultItem, searchRequest.getDownloadType() == DownloadType.NZB); assertThat(item.getEnclosure().getType()).isEqualTo("application/x-bittorrent"); }
### Question: IndexerForSearchSelector { protected boolean checkIndexerStatus(Indexer indexer) { if (indexer.getConfig().getState() == IndexerConfig.State.DISABLED_SYSTEM_TEMPORARY) { if (indexer.getConfig().getDisabledUntil() == null || Instant.ofEpochMilli(indexer.getConfig().getDisabledUntil()).isBefore(clock.instant())) { return true; } String message = String.format("Not using %s because it's disabled until %s due to a previous error ", indexer.getName(), Instant.ofEpochMilli(indexer.getConfig().getDisabledUntil())); return handleIndexerNotSelected(indexer, message, "Disabled temporarily because of previous errors"); } if (indexer.getConfig().getState() == IndexerConfig.State.DISABLED_SYSTEM) { String message = String.format("Not using %s because it's disabled due to a previous unrecoverable error", indexer.getName()); return handleIndexerNotSelected(indexer, message, "Disabled permanently because of previous unrecoverable error"); } return true; } IndexerForSearchSelection pickIndexers(SearchRequest searchRequest); static final Pattern SCHEDULER_PATTERN; }### Answer: @Test public void shouldCheckIfDisabledBySystem() { when(searchingConfig.isIgnoreTemporarilyDisabled()).thenReturn(false); indexerConfigMock.setState(IndexerConfig.State.ENABLED); indexerConfigMock.setDisabledUntil(null); assertTrue(testee.checkIndexerStatus(indexer)); indexerConfigMock.setState(IndexerConfig.State.DISABLED_SYSTEM_TEMPORARY); indexerConfigMock.setDisabledUntil(Instant.now().plus(1, ChronoUnit.DAYS).toEpochMilli()); assertFalse(testee.checkIndexerStatus(indexer)); indexerConfigMock.setState(IndexerConfig.State.DISABLED_SYSTEM); assertFalse(testee.checkIndexerStatus(indexer)); }
### Question: ConfigMigration { public Map<String, Object> migrate(Map<String, Object> map) { int foundConfigVersion = (int) ((Map<String, Object>) map.get("main")).get("configVersion"); if (foundConfigVersion > expectedConfigVersion) { throw new RuntimeException("The existing config file has version " + foundConfigVersion + " but the program expects version " + expectedConfigVersion + ". You might be trying to use an older code base with settings created by a newer version of the program"); } for (ConfigMigrationStep step : steps) { if (foundConfigVersion <= step.forVersion()) { logger.info("Migrating config from version {}", step.forVersion()); map = step.migrate(map); foundConfigVersion = step.forVersion() + 1; } ((Map<String, Object>) map.get("main")).put("configVersion", foundConfigVersion); } if (foundConfigVersion != expectedConfigVersion) { throw new RuntimeException(String.format("Expected the config after migration to be at version %d but it's at version %d", expectedConfigVersion, foundConfigVersion)); } return map; } ConfigMigration(); Map<String, Object> migrate(Map<String, Object> map); }### Answer: @Test public void shouldMigrate() { BaseConfig input = new BaseConfig(); input.getMain().setConfigVersion(1); BaseConfig afterMigration = new BaseConfig(); afterMigration.getMain().setConfigVersion(2); Map<String, Object> map = objectMapper.convertValue(input, typeRef); when(configMigrationStepMock.forVersion()).thenReturn(1); when(configMigrationStepMock.migrate(any())).thenReturn(map); testee.steps = Arrays.asList(configMigrationStepMock); testee.expectedConfigVersion = 2; Map<String, Object> result = testee.migrate(map); input = objectMapper.convertValue(result, BaseConfig.class); verify(configMigrationStepMock).migrate(map); assertThat(input.getMain().getConfigVersion()).isEqualTo(2); } @Test(expected = RuntimeException.class) public void shouldThrowExceptionIfWrongConfigVersionAfterMigration() { BaseConfig input = new BaseConfig(); input.getMain().setConfigVersion(1); Map<String, Object> map = objectMapper.convertValue(input, typeRef); testee.steps = Collections.emptyList(); testee.expectedConfigVersion = 2; testee.migrate(map); }
### Question: ConfigMigration { protected static List<ConfigMigrationStep> getMigrationSteps() { ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false); provider.addIncludeFilter(new AssignableTypeFilter(ConfigMigrationStep.class)); Set<BeanDefinition> candidates = provider.findCandidateComponents(ConfigMigrationStep.class.getPackage().getName()); List<ConfigMigrationStep> steps = new ArrayList<>(); for (BeanDefinition beanDefinition : candidates) { try { ConfigMigrationStep instance = (ConfigMigrationStep) Class.forName(beanDefinition.getBeanClassName()).getConstructor().newInstance(); steps.add(instance); } catch (Exception e) { logger.error("Unable to instantiate migration step from class " + beanDefinition.getBeanClassName(), e); } } Collections.sort(steps); return steps; } ConfigMigration(); Map<String, Object> migrate(Map<String, Object> map); }### Answer: @Test public void shouldFindMigrationStepsForAllPossibleConfigVersions() { Integer currentConfigVersion = new MainConfig().getConfigVersion(); List<ConfigMigrationStep> steps = ConfigMigration.getMigrationSteps(); for (int i = 3; i < currentConfigVersion; i++) { int finalI = i; assertThat(steps.stream().anyMatch(x -> x.forVersion() == finalI)).isTrue(); } }
### Question: ConfigMigrationStep005to006 implements ConfigMigrationStep { @Override public Map<String, Object> migrate(Map<String, Object> toMigrate) { Map<String, Object> categoriesConfig = getFromMap(toMigrate, "categoriesConfig"); List<Map<String, Object>> categories = getListFromMap(categoriesConfig, "categories"); for (Map<String, Object> category : categories) { List<Integer> existingNumbers = (List<Integer>) category.get("newznabCategories"); category.put("newznabCategories", existingNumbers.stream().map(Object::toString).collect(Collectors.toList())); } return toMigrate; } @Override int forVersion(); @Override Map<String, Object> migrate(Map<String, Object> toMigrate); }### Answer: @Test public void migrate() throws Exception { String yaml = Resources.toString(ConfigMigrationStep005to006Test.class.getResource("migrate5to6.yaml"), Charset.defaultCharset()); Map<String, Object> map = Jackson.YAML_MAPPER.readValue(yaml, ConfigReaderWriter.MAP_TYPE_REFERENCE); Map<String, Object> migrated = testee.migrate(map); String newYaml = Jackson.YAML_MAPPER.writeValueAsString(migrated); BaseConfig baseConfig = Jackson.YAML_MAPPER.readValue(newYaml, BaseConfig.class); assertThat(baseConfig.getCategoriesConfig().getCategories().get(0).getNewznabCategories().get(0).get(0)).isEqualTo(1000); assertThat(baseConfig.getCategoriesConfig().getCategories().get(1).getNewznabCategories().get(0).get(0)).isEqualTo(3000); assertThat(baseConfig.getCategoriesConfig().getCategories().get(1).getNewznabCategories().get(1).get(0)).isEqualTo(3030); }
### Question: NewsProvider { public List<NewsEntry> getNews() throws IOException { if (Instant.now().minus(2, ChronoUnit.HOURS).isAfter(lastCheckedForNews)) { newsEntries = webAccess.callUrl(newsUrl, new TypeReference<List<NewsEntry>>() { }); newsEntries.sort(Comparator.comparing(NewsEntry::getShowForVersion).reversed()); lastCheckedForNews = Instant.now(); } return newsEntries; } List<NewsEntry> getNews(); void saveShownForCurrentVersion(); List<NewsEntry> getNewsForCurrentVersionAndAfter(); }### Answer: @Test public void getNews() throws Exception { List<NewsEntry> entries = testee.getNews(); assertThat(entries.size(), is(3)); assertThat(entries.get(0).getNewsAsMarkdown(), is("news3.0.0")); assertThat(entries.get(0).getShowForVersion().major, is(3)); }
### Question: NewsProvider { public List<NewsEntry> getNewsForCurrentVersionAndAfter() throws IOException { List<ShownNews> shownNews = shownNewsRepository.findAll(); if (shownNews == null || shownNews.isEmpty()) { return Collections.emptyList(); } SemanticVersion from = shownNews.size() == 1 ? new SemanticVersion(shownNews.get(0).getVersion()) : null; SemanticVersion to = new SemanticVersion(updateManager.getCurrentVersionString()); List<NewsEntry> news = getNews(); return news.stream() .filter(x -> isShowNewsEntry(from, to, x)) .collect(Collectors.toList()); } List<NewsEntry> getNews(); void saveShownForCurrentVersion(); List<NewsEntry> getNewsForCurrentVersionAndAfter(); }### Answer: @Test public void shouldOnlyGetNewsNewerThanShownButNotNewerThanCurrentVersion() throws Exception { when(updateManagerMock.getCurrentVersionString()).thenReturn("2.0.0"); when(shownNewsRepositoryMock.findAll()).thenReturn(Collections.singletonList(new ShownNews("1.0.0"))); List<NewsEntry> entries = testee.getNewsForCurrentVersionAndAfter(); assertThat(entries.size(), is(1)); assertThat(entries.get(0).getNewsAsMarkdown(), is("news2.0.0")); } @Test public void shouldOnlyGetNewstNotNewerThanCurrentVersion() throws Exception { when(updateManagerMock.getCurrentVersionString()).thenReturn("2.0.0"); when(shownNewsRepositoryMock.findAll()).thenReturn(Collections.singletonList(new ShownNews("0.0.1"))); List<NewsEntry> entries = testee.getNewsForCurrentVersionAndAfter(); assertThat(entries.size(), is(2)); assertThat(entries.get(0).getNewsAsMarkdown(), is("news2.0.0")); assertThat(entries.get(1).getNewsAsMarkdown(), is("news1.0.0")); } @Test public void shouldNoNewsWhenNewInstall() throws Exception { when(updateManagerMock.getCurrentVersionString()).thenReturn("2.0.0"); when(shownNewsRepositoryMock.findAll()).thenReturn(Collections.emptyList()); List<NewsEntry> entries = testee.getNewsForCurrentVersionAndAfter(); assertThat(entries.size(), is(0)); } @Test public void shouldNotGetNewsWhenAlreadyShown() throws Exception { when(updateManagerMock.getCurrentVersionString()).thenReturn("3.0.0"); when(shownNewsRepositoryMock.findAll()).thenReturn(Collections.singletonList(new ShownNews("3.0.0"))); List<NewsEntry> entries = testee.getNewsForCurrentVersionAndAfter(); assertThat(entries.size(), is(0)); }
### Question: IndexerForSearchSelector { protected boolean checkDisabledForCategory(Indexer indexer) { if (searchRequest.getCategory().getSubtype().equals(Subtype.ALL)) { return true; } boolean indexerDisabledForThisCategory = !indexer.getConfig().getEnabledCategories().isEmpty() && !indexer.getConfig().getEnabledCategories().contains(searchRequest.getCategory().getName()); if (indexerDisabledForThisCategory) { String message = String.format("Not using %s because it's disabled for category %s", indexer.getName(), searchRequest.getCategory().getName()); return handleIndexerNotSelected(indexer, message, "Disabled for category"); } return true; } IndexerForSearchSelection pickIndexers(SearchRequest searchRequest); static final Pattern SCHEDULER_PATTERN; }### Answer: @Test public void shouldCheckForCategory() { when(searchRequest.getCategory()).thenReturn(category); indexerConfigMock.setEnabledCategories(Collections.emptyList()); assertTrue(testee.checkDisabledForCategory(indexer)); indexerConfigMock.setEnabledCategories(Arrays.asList("anotherCategory")); assertFalse(testee.checkDisabledForCategory(indexer)); indexerConfigMock.setEnabledCategories(Arrays.asList(("category"))); assertTrue(testee.checkDisabledForCategory(indexer)); }
### Question: Binsearch extends Indexer<String> { @SuppressWarnings("ConstantConditions") @Override protected List<SearchResultItem> getSearchResultItems(String searchRequestResponse, SearchRequest searchRequest) throws IndexerParsingException { List<SearchResultItem> items = new ArrayList<>(); Document doc = Jsoup.parse(searchRequestResponse); if (doc.text().contains("No results in most popular groups")) { return Collections.emptyList(); } Elements mainTables = doc.select("table#r2"); if (mainTables.size() == 0) { throw new IndexerParsingException("Unable to find main table in binsearch page. This happens sometimes ;-)"); } Element mainTable = mainTables.get(0); Elements rows = mainTable.select("tr"); for (int i = 1; i < rows.size(); i++) { Element row = rows.get(i); SearchResultItem item = parseRow(row); if (item == null) { continue; } items.add(item); } debug("Finished parsing {} of {} rows", items.size(), rows.size()); return items; } @Override NfoResult getNfo(String guid); }### Answer: @Test public void shouldParseResultsCorrectly() throws Exception { String html = Resources.toString(Resources.getResource(BinsearchTest.class, "/org/nzbhydra/mapping/binsearch.html"), Charsets.UTF_8); List<SearchResultItem> searchResultItems = testee.getSearchResultItems(html, new SearchRequest()); assertThat(searchResultItems.size(), is(1)); SearchResultItem item = searchResultItems.get(0); assertThat(item.getTitle(), is("testtitle. 3D.TOPBOT.TrueFrench.1080p.X264.AC3.5.1-JKF.mkv")); assertThat(item.getLink(), is("https: assertThat(item.getDetails(), is("https: assertThat(item.getSize(), is(12209999872L)); assertThat(item.getIndexerGuid(), is("176073735")); assertThat(item.getPubDate(), is(Instant.ofEpochSecond(1443312000))); assertThat(item.isAgePrecise(), is(false)); assertThat(item.getPoster().get(), is("[email protected] (Clown_nez)")); assertThat(item.getGroup().get(), is("alt.binaries.movies.mkv")); } @Test public void shouldParseOtherResultsCorrectly() throws Exception { String html = Resources.toString(Resources.getResource(BinsearchTest.class, "/org/nzbhydra/mapping/binsearch_randm.html"), Charsets.UTF_8); List<SearchResultItem> searchResultItems = testee.getSearchResultItems(html, new SearchRequest()); assertThat(searchResultItems.size(), is(41)); } @Test public void shouldRecognizeWhenNoResultsFound() throws Exception { String html = Resources.toString(Resources.getResource(BinsearchTest.class, "/org/nzbhydra/mapping/binsearch_noresults.html"), Charsets.UTF_8); List<SearchResultItem> searchResultItems = testee.getSearchResultItems(html, new SearchRequest()); assertThat(searchResultItems, is(empty())); }
### Question: Binsearch extends Indexer<String> { @Override protected void completeIndexerSearchResult(String response, IndexerSearchResult indexerSearchResult, AcceptorResult acceptorResult, SearchRequest searchRequest, int offset, Integer limit) { Document doc = Jsoup.parse(response); if (doc.select("table.xMenuT").size() > 0) { Element navigationTable = doc.select("table.xMenuT").get(1); Elements pageLinks = navigationTable.select("a"); boolean hasMore = !pageLinks.isEmpty() && pageLinks.last().text().equals(">"); boolean totalKnown = false; indexerSearchResult.setOffset(searchRequest.getOffset()); int total = searchRequest.getOffset() + 100; if (!hasMore) { total = searchRequest.getOffset() + indexerSearchResult.getSearchResultItems().size(); totalKnown = true; } indexerSearchResult.setHasMoreResults(hasMore); indexerSearchResult.setTotalResults(total); indexerSearchResult.setTotalResultsKnown(totalKnown); } else { indexerSearchResult.setHasMoreResults(false); indexerSearchResult.setTotalResults(0); indexerSearchResult.setTotalResultsKnown(true); } indexerSearchResult.setLimit(limit); indexerSearchResult.setOffset(offset); } @Override NfoResult getNfo(String guid); }### Answer: @Test public void shouldRecognizeIfSingleResultPage() throws Exception { SearchRequest searchRequest = new SearchRequest(SearchSource.INTERNAL, SearchType.SEARCH, 0, 100); String html = Resources.toString(Resources.getResource(BinsearchTest.class, "/org/nzbhydra/mapping/binsearch_singlepage.html"), Charsets.UTF_8); IndexerSearchResult indexerSearchResult = new IndexerSearchResult(testee, ""); List<SearchResultItem> items = new ArrayList<>(); for (int i = 0; i < 24; i++) { SearchResultItem searchResultItem = new SearchResultItem(); searchResultItem.setPubDate(Instant.now()); items.add(searchResultItem); } indexerSearchResult.setSearchResultItems(items); testee.completeIndexerSearchResult(html, indexerSearchResult, null, searchRequest, 0, 100); assertThat(indexerSearchResult.getOffset(), is(0)); assertThat(indexerSearchResult.getLimit(), is(100)); assertThat(indexerSearchResult.getTotalResults(), is(24)); assertThat(indexerSearchResult.isTotalResultsKnown(), is(true)); assertThat(indexerSearchResult.isHasMoreResults(), is(false)); } @Test public void shouldRecognizeIfMoreResultsAvailable() throws Exception { SearchRequest searchRequest = new SearchRequest(SearchSource.INTERNAL, SearchType.SEARCH, 0, 100); String html = Resources.toString(Resources.getResource(BinsearchTest.class, "/org/nzbhydra/mapping/binsearch.html"), Charsets.UTF_8); IndexerSearchResult indexerSearchResult = new IndexerSearchResult(testee, ""); testee.completeIndexerSearchResult(html, indexerSearchResult, null, searchRequest, 0, 100); assertThat(indexerSearchResult.isTotalResultsKnown(), is(false)); assertThat(indexerSearchResult.isHasMoreResults(), is(true)); }
### Question: Binsearch extends Indexer<String> { @Override protected UriComponentsBuilder buildSearchUrl(SearchRequest searchRequest, Integer offset, Integer limit) throws IndexerSearchAbortedException { String query = super.generateQueryIfApplicable(searchRequest, ""); query = addRequiredWordsToQuery(searchRequest, query); if (Strings.isNullOrEmpty(query)) { throw new IndexerSearchAbortedException("Binsearch cannot search without a query"); } query = cleanupQuery(query); return UriComponentsBuilder.fromHttpUrl("https: } @Override NfoResult getNfo(String guid); }### Answer: @Test public void shouldBuildSimpleQuery() throws IndexerSearchAbortedException { SearchRequest searchRequest = new SearchRequest(SearchSource.INTERNAL, SearchType.SEARCH, 0, 100); searchRequest.setQuery("query"); UriComponentsBuilder builder = testee.buildSearchUrl(searchRequest, 0, 100); assertThat(builder.toUriString(), is("https: } @Test public void shouldAddRequiredWords() throws IndexerSearchAbortedException { SearchRequest searchRequest = new SearchRequest(SearchSource.INTERNAL, SearchType.SEARCH, 0, 100); searchRequest.getInternalData().setRequiredWords(Arrays.asList("a", "b")); searchRequest.setQuery("query"); UriComponentsBuilder builder = testee.buildSearchUrl(searchRequest, 0, 100); assertThat(builder.build().toString(), is("https: } @Test(expected = IndexerSearchAbortedException.class) public void shouldAbortIfSearchNotPossible() throws IndexerSearchAbortedException { SearchRequest searchRequest = new SearchRequest(SearchSource.INTERNAL, SearchType.SEARCH, 0, 100); testee.buildSearchUrl(searchRequest, 0, 100); }
### Question: IndexerForSearchSelector { protected boolean checkLoadLimiting(Indexer indexer) { boolean preventedByLoadLimiting = indexer.getConfig().getLoadLimitOnRandom().isPresent() && random.nextInt(indexer.getConfig().getLoadLimitOnRandom().get()) + 1 != 1; if (preventedByLoadLimiting) { boolean loadLimitIgnored = configProvider.getBaseConfig().getSearching().isIgnoreLoadLimitingForInternalSearches() && searchRequest.getSource() == SearchSource.INTERNAL; if (loadLimitIgnored) { logger.debug("Ignoring load limiting for internal search"); return true; } String message = String.format("Not using %s because load limiting prevented it. Chances of it being picked: 1/%d", indexer.getName(), indexer.getConfig().getLoadLimitOnRandom().get()); return handleIndexerNotSelected(indexer, message, "Load limiting"); } return true; } IndexerForSearchSelection pickIndexers(SearchRequest searchRequest); static final Pattern SCHEDULER_PATTERN; }### Answer: @Test public void shouldCheckForLoadLimiting() { indexerConfigMock.setLoadLimitOnRandom(null); assertTrue(testee.checkLoadLimiting(indexer)); indexerConfigMock.setLoadLimitOnRandom(1); for (int i = 0; i < 50; i++) { assertTrue(testee.checkLoadLimiting(indexer)); } indexerConfigMock.setLoadLimitOnRandom(2); int countNotPicked = 0; for (int i = 0; i < 500; i++) { countNotPicked += testee.checkLoadLimiting(indexer) ? 0 : 1; } assertTrue(countNotPicked > 0); }
### Question: Binsearch extends Indexer<String> { @Override protected String getAndStoreResultToDatabase(URI uri, IndexerApiAccessType apiAccessType) throws IndexerAccessException { return Failsafe.with(retry503policy) .onFailedAttempt(throwable -> logger.warn("Encountered 503 error. Will retry")) .get(() -> getAndStoreResultToDatabase(uri, String.class, apiAccessType)); } @Override NfoResult getNfo(String guid); }### Answer: @Test(expected = FailsafeException.class) public void shouldRetryOn503() throws Exception { testee = spy(testee); doThrow(new IndexerAccessException("503")).when(testee).getAndStoreResultToDatabase(uriCaptor.capture(), any(), any()); testee.getAndStoreResultToDatabase(null, IndexerApiAccessType.NFO); }
### Question: Indexer { @Transactional protected List<SearchResultItem> persistSearchResults(List<SearchResultItem> searchResultItems, IndexerSearchResult indexerSearchResult) { Stopwatch stopwatch = Stopwatch.createStarted(); synchronized (dbLock) { ArrayList<SearchResultEntity> searchResultEntities = new ArrayList<>(); Set<Long> alreadySavedIds = searchResultRepository.findAllIdsByIdIn(searchResultItems.stream().map(SearchResultIdCalculator::calculateSearchResultId).collect(Collectors.toList())); for (SearchResultItem item : searchResultItems) { long guid = SearchResultIdCalculator.calculateSearchResultId(item); if (!alreadySavedIds.contains(guid)) { SearchResultEntity searchResultEntity = new SearchResultEntity(); searchResultEntity.setIndexer(indexer); searchResultEntity.setTitle(item.getTitle()); searchResultEntity.setLink(item.getLink()); searchResultEntity.setDetails(item.getDetails()); searchResultEntity.setIndexerGuid(item.getIndexerGuid()); searchResultEntity.setFirstFound(Instant.now()); searchResultEntity.setDownloadType(item.getDownloadType()); searchResultEntity.setPubDate(item.getPubDate()); searchResultEntities.add(searchResultEntity); } item.setGuid(guid); item.setSearchResultId(guid); } debug("Found {} results which were already in the database and {} new ones", alreadySavedIds.size(), searchResultEntities.size()); try { searchResultRepository.saveAll(searchResultEntities); indexerSearchResult.setSearchResultEntities(new HashSet<>(searchResultEntities)); } catch (EntityExistsException e) { error("Unable to save the search results to the database", e); } } getLogger().debug(LoggingMarkers.PERFORMANCE, "Persisting {} search results took {}ms", searchResultItems.size(), stopwatch.elapsed(TimeUnit.MILLISECONDS)); return searchResultItems; } void initialize(IndexerConfig config, IndexerEntity indexer); @EventListener void handleNewConfig(ConfigChangedEvent configChangedEvent); IndexerSearchResult search(SearchRequest searchRequest, int offset, Integer limit); abstract NfoResult getNfo(String guid); String getName(); IndexerConfig getConfig(); IndexerEntity getIndexerEntity(); String cleanUpTitle(String title); Optional<Instant> tryParseDate(String dateString); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer: @Test public void shouldCreateNewSearchResultEntityWhenNoneIsFound() throws Exception { SearchResultItem item = new SearchResultItem(); item.setIndexer(indexerMock); item.setTitle("title"); item.setDetails("details"); item.setIndexerGuid("guid"); testee.persistSearchResults(Collections.singletonList(item), new IndexerSearchResult()); verify(searchResultRepositoryMock).saveAll(searchResultEntitiesCaptor.capture()); List<SearchResultEntity> persistedEntities = searchResultEntitiesCaptor.getValue(); assertThat(persistedEntities.size(), is(1)); assertThat(persistedEntities.get(0).getTitle(), is("title")); assertThat(persistedEntities.get(0).getDetails(), is("details")); assertThat(persistedEntities.get(0).getIndexerGuid(), is("guid")); } @Test public void shouldNotCreateNewSearchResultEntityWhenOneExists() throws Exception { SearchResultItem item = new SearchResultItem(); item.setIndexerGuid("guid"); item.setIndexer(indexerMock); when(searchResultEntityMock.getIndexerGuid()).thenReturn("guid"); when(searchResultRepositoryMock.findAllIdsByIdIn(anyList())).thenReturn(Sets.newHashSet(299225959498991027L)); testee.persistSearchResults(Collections.singletonList(item), new IndexerSearchResult()); verify(searchResultRepositoryMock).saveAll(searchResultEntitiesCaptor.capture()); List<SearchResultEntity> persistedEntities = searchResultEntitiesCaptor.getValue(); assertThat(persistedEntities.size(), is(0)); }
### Question: Indexer { protected void handleSuccess(IndexerApiAccessType accessType, Long responseTime) { if (getConfig().getDisabledLevel() > 0) { debug("Indexer was successfully called after {} failed attempts in a row", getConfig().getDisabledLevel()); } getConfig().setState(IndexerConfig.State.ENABLED); getConfig().setLastError(null); getConfig().setDisabledUntil(null); getConfig().setDisabledLevel(0); configProvider.getBaseConfig().save(false); saveApiAccess(accessType, responseTime, IndexerAccessResult.SUCCESSFUL, true); } void initialize(IndexerConfig config, IndexerEntity indexer); @EventListener void handleNewConfig(ConfigChangedEvent configChangedEvent); IndexerSearchResult search(SearchRequest searchRequest, int offset, Integer limit); abstract NfoResult getNfo(String guid); String getName(); IndexerConfig getConfig(); IndexerEntity getIndexerEntity(); String cleanUpTitle(String title); Optional<Instant> tryParseDate(String dateString); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer: @Test public void handleSuccess() throws Exception { indexerConfig.setState(IndexerConfig.State.DISABLED_SYSTEM_TEMPORARY); indexerConfig.setDisabledLevel(1); indexerConfig.setDisabledUntil(Instant.now().toEpochMilli()); testee.handleSuccess(IndexerApiAccessType.SEARCH, 0L); assertThat(indexerConfig.getState(), is(IndexerConfig.State.ENABLED)); assertThat(indexerConfig.getDisabledLevel(), is(0)); assertThat(indexerConfig.getDisabledUntil(), is(nullValue())); }
### Question: Indexer { protected void handleFailure(String reason, Boolean disablePermanently, IndexerApiAccessType accessType, Long responseTime, IndexerAccessResult accessResult) { if (disablePermanently) { getLogger().warn("Because an unrecoverable error occurred {} will be permanently disabled until reenabled by the user", indexer.getName()); getConfig().setState(IndexerConfig.State.DISABLED_SYSTEM); } else if (!configProvider.getBaseConfig().getSearching().isIgnoreTemporarilyDisabled()) { getConfig().setState(IndexerConfig.State.DISABLED_SYSTEM_TEMPORARY); getConfig().setDisabledLevel(getConfig().getDisabledLevel() + 1); long minutesToAdd = DISABLE_PERIODS.get(Math.min(DISABLE_PERIODS.size() - 1, getConfig().getDisabledLevel())); Instant disabledUntil = Instant.now().plus(minutesToAdd, ChronoUnit.MINUTES); getConfig().setDisabledUntil(disabledUntil.toEpochMilli()); getLogger().warn("Because an error occurred {} will be temporarily disabled until {}. This is error number {} in a row", indexer.getName(), disabledUntil, getConfig().getDisabledLevel()); } getConfig().setLastError(reason); configProvider.getBaseConfig().save(false); saveApiAccess(accessType, responseTime, accessResult, false); } void initialize(IndexerConfig config, IndexerEntity indexer); @EventListener void handleNewConfig(ConfigChangedEvent configChangedEvent); IndexerSearchResult search(SearchRequest searchRequest, int offset, Integer limit); abstract NfoResult getNfo(String guid); String getName(); IndexerConfig getConfig(); IndexerEntity getIndexerEntity(); String cleanUpTitle(String title); Optional<Instant> tryParseDate(String dateString); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer: @Test public void handleFailure() throws Exception { indexerConfig.setState(IndexerConfig.State.ENABLED); indexerConfig.setDisabledLevel(0); indexerConfig.setDisabledUntil(null); testee.handleFailure("reason", false, null, null, null); assertThat(indexerConfig.getState(), is(IndexerConfig.State.DISABLED_SYSTEM_TEMPORARY)); assertThat(indexerConfig.getDisabledLevel(), is(1)); long disabledPeriod = Math.abs(Instant.ofEpochMilli(indexerConfig.getDisabledUntil()).getEpochSecond() - Instant.now().getEpochSecond()); long delta = Math.abs(Indexer.DISABLE_PERIODS.get(1) * 60 - disabledPeriod); org.assertj.core.api.Assertions.assertThat(delta).isLessThan(5); indexerConfig.setState(IndexerConfig.State.ENABLED); indexerConfig.setDisabledLevel(0); indexerConfig.setDisabledUntil(null); testee.handleFailure("reason", true, null, null, null); assertThat(indexerConfig.getState(), is(IndexerConfig.State.DISABLED_SYSTEM)); }
### Question: Indexer { public String cleanUpTitle(String title) { if (Strings.isNullOrEmpty(title)) { return title; } title = title.trim(); List<String> removeTrailing = configProvider.getBaseConfig().getSearching().getRemoveTrailing().stream().map(x -> x.toLowerCase().trim()).collect(Collectors.toList()); if (removeTrailing.isEmpty()) { return title; } if (cleanupPattern == null) { String allPattern = "^(?<keep>.*)(" + removeTrailing.stream().map(x -> x.replace("*", "WILDCARDXXX").replaceAll("[-\\[\\]{}()*+?.,\\\\\\\\^$|#]", "\\\\$0").replace("WILDCARDXXX", ".*") + "$").collect(Collectors.joining("|")) + ")"; cleanupPattern = Pattern.compile(allPattern, Pattern.CASE_INSENSITIVE); } Matcher matcher = cleanupPattern.matcher(title); while (matcher.matches()) { title = matcher.replaceAll("$1").trim(); matcher = cleanupPattern.matcher(title); } return title; } void initialize(IndexerConfig config, IndexerEntity indexer); @EventListener void handleNewConfig(ConfigChangedEvent configChangedEvent); IndexerSearchResult search(SearchRequest searchRequest, int offset, Integer limit); abstract NfoResult getNfo(String guid); String getName(); IndexerConfig getConfig(); IndexerEntity getIndexerEntity(); String cleanUpTitle(String title); Optional<Instant> tryParseDate(String dateString); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer: @Test public void shouldRemoveTrailing2() { List<String> collect = IntStream.range(1, 100).mapToObj(x -> "trailing" + x + "*********").collect(Collectors.toList()); List<String> all = new ArrayList<>(); all.addAll(collect); all.add("trailing*"); baseConfig.getSearching().setRemoveTrailing(all); testee.cleanUpTitle("abc trailing1 trailing2"); testee.cleanUpTitle("abc trailing1 trailing2"); testee.cleanUpTitle("abc trailing1 trailing2"); Stopwatch stopwatch = Stopwatch.createStarted(); for (int i = 0; i < 100; i++) { testee.cleanUpTitle("abc trailing1 trailing2"); } System.out.println(stopwatch.elapsed(TimeUnit.MILLISECONDS)); }
### Question: Torznab extends Newznab { @Override protected UriComponentsBuilder buildSearchUrl(SearchRequest searchRequest, Integer offset, Integer limit) throws IndexerSearchAbortedException { return super.buildSearchUrl(searchRequest, null, null); } }### Answer: @Test public void shouldNotAddExcludedWordsToQuery() throws Exception { SearchRequest searchRequest = new SearchRequest(SearchSource.INTERNAL, SearchType.SEARCH, 0, 100); searchRequest.getInternalData().setForbiddenWords(Arrays.asList("notthis", "alsonotthis")); searchRequest.setQuery("query"); UriComponentsBuilder builder = testee.buildSearchUrl(searchRequest, 0, 100); assertThat(builder.toUriString(), not(containsString("notthis"))); }
### Question: Torznab extends Newznab { protected List<Integer> tryAndGetCategoryAsNumber(NewznabXmlItem item) { Set<Integer> foundCategories = new HashSet<>(); if (item.getCategory() != null) { try { foundCategories.add(Integer.parseInt(item.getCategory())); } catch (NumberFormatException e) { } } foundCategories.addAll(item.getNewznabAttributes().stream().filter(x -> x.getName().equals("category")).map(x -> Integer.valueOf(x.getValue())).collect(Collectors.toList())); foundCategories.addAll(item.getTorznabAttributes().stream().filter(x -> x.getName().equals("category")).map(x -> Integer.valueOf(x.getValue())).collect(Collectors.toList())); return new ArrayList<>(foundCategories); } }### Answer: @Test public void shouldGetCorrectCategoryNumber() { NewznabXmlItem item = buildBasicRssItem(); item.setTorznabAttributes(Collections.singletonList(new NewznabAttribute("category", "2000"))); List<Integer> integers = testee.tryAndGetCategoryAsNumber(item); assertThat(integers.size(), is(1)); assertThat(integers.get(0), is(2000)); item.setTorznabAttributes(Collections.singletonList(new NewznabAttribute("category", "10000"))); integers = testee.tryAndGetCategoryAsNumber(item); assertThat(integers.size(), is(1)); assertThat(integers.get(0), is(10000)); item.setTorznabAttributes(Arrays.asList(new NewznabAttribute("category", "2000"), new NewznabAttribute("category", "10000"))); integers = testee.tryAndGetCategoryAsNumber(item); integers.sort(Comparator.naturalOrder()); assertThat(integers.size(), is(2)); assertThat(integers.get(0), is(2000)); assertThat(integers.get(1), is(10000)); item.setTorznabAttributes(Arrays.asList(new NewznabAttribute("category", "2000"), new NewznabAttribute("category", "2040"))); integers = testee.tryAndGetCategoryAsNumber(item); integers.sort(Comparator.naturalOrder()); assertThat(integers.size(), is(2)); assertThat(integers.get(0), is(2000)); assertThat(integers.get(1), is(2040)); item.setTorznabAttributes(Arrays.asList(new NewznabAttribute("category", "2000"), new NewznabAttribute("category", "2040"), new NewznabAttribute("category", "10000"))); integers = testee.tryAndGetCategoryAsNumber(item); integers.sort(Comparator.naturalOrder()); assertThat(integers.size(), is(3)); assertThat(integers.get(0), is(2000)); assertThat(integers.get(1), is(2040)); }
### Question: IndexerForSearchSelector { protected boolean checkSearchSource(Indexer indexer) { boolean wrongSearchSource = !indexer.getConfig().getEnabledForSearchSource().meets(searchRequest); if (wrongSearchSource) { String message = String.format("Not using %s because the search source is %s but the indexer is only enabled for %s searches", indexer.getName(), searchRequest.getSource(), indexer.getConfig().getEnabledForSearchSource()); return handleIndexerNotSelected(indexer, message, "Not enabled for this search context"); } return true; } IndexerForSearchSelection pickIndexers(SearchRequest searchRequest); static final Pattern SCHEDULER_PATTERN; }### Answer: @Test public void shouldCheckContext() { when(searchModuleProviderMock.getIndexers()).thenReturn(Arrays.asList(indexer)); when(searchRequest.getSource()).thenReturn(SearchSource.INTERNAL); indexerConfigMock.setEnabledForSearchSource(SearchSourceRestriction.API); assertFalse(testee.checkSearchSource(indexer)); when(searchRequest.getSource()).thenReturn(SearchSource.API); assertTrue(testee.checkSearchSource(indexer)); }
### Question: Anizb extends Indexer<NewznabXmlRoot> { @Override protected UriComponentsBuilder buildSearchUrl(SearchRequest searchRequest, Integer offset, Integer limit) throws IndexerSearchAbortedException { String query = super.generateQueryIfApplicable(searchRequest, ""); query = addRequiredWordsToQuery(searchRequest, query); if (Strings.isNullOrEmpty(query)) { throw new IndexerSearchAbortedException("Anizb cannot search without a query"); } query = cleanupQuery(query); return UriComponentsBuilder.fromHttpUrl("https: } @Override NfoResult getNfo(String guid); }### Answer: @Test public void shouldBuildSimpleQuery() throws IndexerSearchAbortedException { SearchRequest searchRequest = new SearchRequest(SearchSource.INTERNAL, SearchType.SEARCH, 0, 100); searchRequest.setQuery("query"); UriComponentsBuilder builder = testee.buildSearchUrl(searchRequest, 0, 100); assertThat(builder.toUriString(), is("https: } @Test public void shouldAddRequiredWords() throws IndexerSearchAbortedException { SearchRequest searchRequest = new SearchRequest(SearchSource.INTERNAL, SearchType.SEARCH, 0, 100); searchRequest.getInternalData().setRequiredWords(Arrays.asList("a", "b")); searchRequest.setQuery("query"); UriComponentsBuilder builder = testee.buildSearchUrl(searchRequest, 0, 100); assertThat(builder.toUriString(), is("https: } @Test(expected = IndexerSearchAbortedException.class) public void shouldAbortIfSearchNotPossible() throws IndexerSearchAbortedException { SearchRequest searchRequest = new SearchRequest(SearchSource.INTERNAL, SearchType.SEARCH, 0, 100); testee.buildSearchUrl(searchRequest, 0, 100); }
### Question: NzbsOrg extends Newznab { protected String addForbiddenWords(SearchRequest searchRequest, String query) { List<String> allForbiddenWords = new ArrayList<>(searchRequest.getInternalData().getForbiddenWords()); allForbiddenWords.addAll(configProvider.getBaseConfig().getSearching().getForbiddenWords()); allForbiddenWords.addAll(searchRequest.getCategory().getForbiddenWords()); List<String> allPossibleForbiddenWords = allForbiddenWords.stream().filter(x -> !(x.contains(" ") || x.contains("-") || x.contains("."))).collect(Collectors.toList()); if (allForbiddenWords.size() > allPossibleForbiddenWords.size()) { logger.debug("Not using some forbidden words in query because characters forbidden by newznab are contained"); } if (!allPossibleForbiddenWords.isEmpty()) { StringBuilder queryBuilder = new StringBuilder(query); for (String word : allForbiddenWords) { if ((queryBuilder + " --" + word).length() < 255) { queryBuilder.append(" --").append(word); } } query = queryBuilder.toString(); } return query; } }### Answer: @Test public void shouldLimitQueryLengthWhenAddingForbiddenWords() throws Exception { SearchRequest request = new SearchRequest(SearchSource.INTERNAL, SearchType.SEARCH, 0, 100); request.getInternalData().setForbiddenWords(Arrays.asList("characters50sssssssssssssssssssssssssssssssssssss1", "characters50sssssssssssssssssssssssssssssssssssss2", "characters50sssssssssssssssssssssssssssssssssssss3", "characters50sssssssssssssssssssssssssssssssssssss4", "characters40ssssssssssssssssssssssssssss", "aaaaa", "bbbbb")); String query = testee.addForbiddenWords(request, ""); assertThat(query.length()).isLessThan(255); }
### Question: NzbsOrg extends Newznab { protected String addRequiredWords(SearchRequest searchRequest, String query) { List<String> allRequiredWords = new ArrayList<>(searchRequest.getInternalData().getRequiredWords()); allRequiredWords.addAll(configProvider.getBaseConfig().getSearching().getRequiredWords()); allRequiredWords.addAll(searchRequest.getCategory().getRequiredWords()); List<String> allPossibleRequiredWords = allRequiredWords.stream().filter(x -> !(x.contains(" ") || x.contains("-") || x.contains("."))).collect(Collectors.toList()); if (allRequiredWords.size() > allPossibleRequiredWords.size()) { logger.debug("Not using some forbidden words in query because characters forbidden by newznab are contained"); } StringBuilder queryBuilder = new StringBuilder(query); for (String word : allPossibleRequiredWords) { if ((queryBuilder + word).length() < 255) { queryBuilder.append(" ").append(queryBuilder); } } query = queryBuilder.toString(); return query; } }### Answer: @Test public void shouldLimitQueryLengthWhenAddingRequiredWords() throws Exception { SearchRequest request = new SearchRequest(SearchSource.INTERNAL, SearchType.SEARCH, 0, 100); request.getInternalData().setRequiredWords(Arrays.asList("characters50sssssssssssssssssssssssssssssssssssss1", "characters50sssssssssssssssssssssssssssssssssssss2", "characters50sssssssssssssssssssssssssssssssssssss3", "characters50sssssssssssssssssssssssssssssssssssss4", "characters40ssssssssssssssssssssssssssss", "aaaaa", "bbbbb")); String query = testee.addRequiredWords(request, ""); assertThat(query.length()).isLessThan(255); }
### Question: NzbsOrg extends Newznab { @Override protected String cleanupQuery(String query) { query = super.cleanupQuery(query); if (query.length() > 255) { logger.warn("Truncating query because its length is {} but only 255 characters are supported", query.length()); StringBuilder shorterQuery = new StringBuilder(); for (String s : query.split(" ")) { if ((shorterQuery + s).length() < 255) { shorterQuery.append(" ").append(s); } else { break; } } query = shorterQuery.toString(); } return query; } }### Answer: @Test public void shouldTruncateLongQuery() { StringBuilder longQuery = new StringBuilder(); for (int i = 0; i < 56; i++) { longQuery.append(" " + "characters15sss"); }assertThat(longQuery.length()).isGreaterThan(255); String query = testee.cleanupQuery(longQuery.toString()); assertThat(query.length()).isLessThan(255); }
### Question: Newznab extends Indexer<Xml> { @Override protected List<SearchResultItem> getSearchResultItems(Xml rssRoot, SearchRequest searchRequest) { List<SearchResultItem> searchResultItems = new ArrayList<>(); final NewznabXmlRoot newznabXmlRoot = (NewznabXmlRoot) rssRoot; checkForTooManyResults(searchRequest, newznabXmlRoot); for (NewznabXmlItem item : newznabXmlRoot.getRssChannel().getItems()) { try { SearchResultItem searchResultItem = createSearchResultItem(item); searchResultItems.add(searchResultItem); } catch (NzbHydraException e) { } } return searchResultItems; } @Override NfoResult getNfo(String guid); }### Answer: @Test public void shouldReturnCorrectSearchResults() throws Exception { NewznabXmlRoot root = RssBuilder.builder().items(Arrays.asList(RssItemBuilder.builder("title").build())).newznabResponse(0, 1).build(); when(indexerWebAccessMock.get(any(), eq(testee.config), any())).thenReturn(root); IndexerSearchResult indexerSearchResult = testee.searchInternal(new SearchRequest(SearchSource.INTERNAL, SearchType.SEARCH, 0, 100), 0, 100); assertThat(indexerSearchResult.getSearchResultItems().size(), is(1)); assertThat(indexerSearchResult.getTotalResults(), is(1)); assertThat(indexerSearchResult.isHasMoreResults(), is(false)); assertThat(indexerSearchResult.isTotalResultsKnown(), is(true)); } @Test public void shouldAccountForRejectedResults() throws Exception { List<NewznabXmlItem> items = Arrays.asList( RssItemBuilder.builder("title1").build(), RssItemBuilder.builder("title2").build(), RssItemBuilder.builder("title3").build(), RssItemBuilder.builder("title4").build(), RssItemBuilder.builder("title5").build() ); NewznabXmlRoot root = RssBuilder.builder().items(items).newznabResponse(100, 105).build(); when(indexerWebAccessMock.get(any(), eq(testee.config), any())).thenReturn(root); when(resultAcceptorMock.acceptResults(any(), any(), any())).thenAnswer(new Answer<AcceptorResult>() { @Override public AcceptorResult answer(InvocationOnMock invocation) throws Throwable { List<SearchResultItem> argument = invocation.getArgument(0); HashMultiset<String> reasonsForRejection = HashMultiset.create(); reasonsForRejection.add("some reason", 2); return new AcceptorResult(argument.subList(0, 3), reasonsForRejection); } }); IndexerSearchResult indexerSearchResult = testee.searchInternal(new SearchRequest(SearchSource.INTERNAL, SearchType.SEARCH, 0, 100), 0, 100); assertThat(indexerSearchResult.getSearchResultItems().size(), is(3)); assertThat(indexerSearchResult.getTotalResults(), is(105)); assertThat(indexerSearchResult.isHasMoreResults(), is(false)); assertThat(indexerSearchResult.isTotalResultsKnown(), is(true)); }
### Question: IndexerForSearchSelector { protected boolean checkSearchId(Indexer indexer) { boolean needToSearchById = !searchRequest.getIdentifiers().isEmpty() && !searchRequest.getQuery().isPresent(); if (needToSearchById) { boolean canUseAnyProvidedId = !Collections.disjoint(searchRequest.getIdentifiers().keySet(), indexer.getConfig().getSupportedSearchIds()); boolean cannotSearchProvidedOrConvertableId = !canUseAnyProvidedId && !infoProvider.canConvertAny(searchRequest.getIdentifiers().keySet(), Sets.newHashSet(indexer.getConfig().getSupportedSearchIds())); boolean queryGenerationEnabled = configProvider.getBaseConfig().getSearching().getGenerateQueries().meets(searchRequest); if (cannotSearchProvidedOrConvertableId && !queryGenerationEnabled) { String message = String.format("Not using %s because the search did not provide any ID that the indexer can handle and query generation is disabled", indexer.getName()); return handleIndexerNotSelected(indexer, message, "No usable ID"); } } return true; } IndexerForSearchSelection pickIndexers(SearchRequest searchRequest); static final Pattern SCHEDULER_PATTERN; }### Answer: @Test public void shouldCheckIdConversion() { Set<MediaIdType> supported = Sets.newSet(MediaIdType.TVMAZE, MediaIdType.TVDB); Set<MediaIdType> provided = Sets.newSet(MediaIdType.TVMAZE); when(searchRequest.getQuery()).thenReturn(Optional.empty()); when(infoProviderMock.canConvertAny(provided, supported)).thenReturn(true); assertTrue(testee.checkSearchId(indexer)); when(searchRequest.getQuery()).thenReturn(Optional.of("a query")); when(infoProviderMock.canConvertAny(provided, supported)).thenReturn(false); assertTrue(testee.checkSearchId(indexer)); provided = new HashSet<>(); when(searchRequest.getQuery()).thenReturn(Optional.empty()); verify(infoProviderMock, never()).canConvertAny(provided, supported); assertTrue(testee.checkSearchId(indexer)); }
### Question: Newznab extends Indexer<Xml> { protected Xml getAndStoreResultToDatabase(URI uri, IndexerApiAccessType apiAccessType) throws IndexerAccessException { Xml response = getAndStoreResultToDatabase(uri, Xml.class, apiAccessType); if (response instanceof NewznabXmlError) { handleRssError((NewznabXmlError) response, uri.toString()); } else if (!(response instanceof NewznabXmlRoot)) { throw new UnknownResponseException("Indexer returned unknown response"); } return response; } @Override NfoResult getNfo(String guid); }### Answer: @Test(expected = IndexerAuthException.class) public void shouldThrowAuthException() throws Exception { doReturn(new NewznabXmlError("101", "Wrong API key")).when(testee).getAndStoreResultToDatabase(any(), eq(Xml.class), eq(IndexerApiAccessType.SEARCH)); doNothing().when(testee).handleFailure(errorMessageCaptor.capture(), disabledPermanentlyCaptor.capture(), any(IndexerApiAccessType.class), any(), indexerApiAccessResultCaptor.capture()); testee.searchInternal(new SearchRequest(SearchSource.INTERNAL, SearchType.SEARCH, 0, 100), 0, 100); } @Test(expected = IndexerErrorCodeException.class) public void shouldThrowErrorCodeWhen100ApiHitLimits() throws Exception { doReturn(new NewznabXmlError("100", "Daily Hits Limit Reached\"")).when(testee).getAndStoreResultToDatabase(any(), eq(Xml.class), eq(IndexerApiAccessType.SEARCH)); doNothing().when(testee).handleFailure(errorMessageCaptor.capture(), disabledPermanentlyCaptor.capture(), any(IndexerApiAccessType.class), any(), indexerApiAccessResultCaptor.capture()); testee.searchInternal(new SearchRequest(SearchSource.INTERNAL, SearchType.SEARCH, 0, 100), 0, 100); } @Test(expected = IndexerProgramErrorException.class) public void shouldThrowProgramErrorCodeException() throws Exception { doReturn(new NewznabXmlError("200", "Whatever")).when(testee).getAndStoreResultToDatabase(any(), eq(Xml.class), eq(IndexerApiAccessType.SEARCH)); doNothing().when(testee).handleFailure(errorMessageCaptor.capture(), disabledPermanentlyCaptor.capture(), any(IndexerApiAccessType.class), any(), indexerApiAccessResultCaptor.capture()); testee.searchInternal(new SearchRequest(SearchSource.INTERNAL, SearchType.SEARCH, 0, 100), 0, 100); } @Test(expected = IndexerErrorCodeException.class) public void shouldThrowErrorCodeThatsNotMyFaultException() throws Exception { doReturn(new NewznabXmlError("123", "Whatever")).when(testee).getAndStoreResultToDatabase(any(), eq(Xml.class), eq(IndexerApiAccessType.SEARCH)); doNothing().when(testee).handleFailure(errorMessageCaptor.capture(), disabledPermanentlyCaptor.capture(), any(IndexerApiAccessType.class), any(), indexerApiAccessResultCaptor.capture()); testee.searchInternal(new SearchRequest(SearchSource.INTERNAL, SearchType.SEARCH, 0, 100), 0, 100); }
### Question: CurrentTenantHolder { public static String pop() { return getCurrentStack().pop(); } static void push(String tenantId); static String pop(); static String getCurrentTenant(); }### Answer: @Test(expected = EmptyStackException.class) public void testEmptyHolderPop() { CurrentTenantHolder.pop(); }
### Question: CurrentTenantHolder { public static String getCurrentTenant() { return getCurrentStack().peek(); } static void push(String tenantId); static String pop(); static String getCurrentTenant(); }### Answer: @Test(expected = EmptyStackException.class) public void testEmptyHolderPeek() { CurrentTenantHolder.getCurrentTenant(); }
### Question: DeltaJournal implements InitializingBean { public void journal(Collection<String> ids, String collection, boolean isDelete) { if ( collection.equals("applicationAuthorization") ) { return; } if (deltasEnabled && !TenantContext.isSystemCall()) { if (subdocCollectionsToCollapse.containsKey(collection)) { journalCollapsedSubDocs(ids, collection); } long now = new Date().getTime(); Update update = new Update(); update.set("t", now); update.set("c", collection); if (isDelete) { update.set("d", now); } else { update.set("u", now); } for (String id : ids) { List<byte[]> idbytes = getByteId(id); if(idbytes.size() > 1) { update.set("i", idbytes.subList(1, idbytes.size())); } template.upsert(Query.query(where("_id").is(idbytes.get(0))), update, DELTA_COLLECTION); } } } @Override void afterPropertiesSet(); void journal(Collection<String> ids, String collection, boolean isDelete); static List<byte[]> getByteId(String id); static String getEntityId(Map<String, Object> deltaRecord); void journal(String id, String collection, boolean isDelete); void journalCollapsedSubDocs(Collection<String> ids, String collection); void journalPurge(long timeOfPurge); Iterator<Map<String, Object>> findDeltaRecordBetween(final long start, final long end); void removeDeltaJournals(String tenant, long cleanUptoTime); static final String DELTA_COLLECTION; static final String PURGE; }### Answer: @Test public void testIgnoredOnSystemCall() { TenantContext.setIsSystemCall(true); deltaJournal.journal("test", "userSession", false); verify(template, never()).upsert(any(Query.class), any(Update.class), anyString()); TenantContext.setIsSystemCall(false); }
### Question: DeltaJournal implements InitializingBean { public void journalCollapsedSubDocs(Collection<String> ids, String collection) { LOG.debug("journaling {} to {}", ids, subdocCollectionsToCollapse.get(collection)); Set<String> newIds = new HashSet<String>(); for (String id : ids) { newIds.add(id.split("_id")[0] + "_id"); } journal(newIds, subdocCollectionsToCollapse.get(collection), false); } @Override void afterPropertiesSet(); void journal(Collection<String> ids, String collection, boolean isDelete); static List<byte[]> getByteId(String id); static String getEntityId(Map<String, Object> deltaRecord); void journal(String id, String collection, boolean isDelete); void journalCollapsedSubDocs(Collection<String> ids, String collection); void journalPurge(long timeOfPurge); Iterator<Map<String, Object>> findDeltaRecordBetween(final long start, final long end); void removeDeltaJournals(String tenant, long cleanUptoTime); static final String DELTA_COLLECTION; static final String PURGE; }### Answer: @Test public void testJournalCollapsedSubDocs() throws DecoderException { String assessment1id = "1234567890123456789012345678901234567890"; String assessment2id = "1234567890123456789012345678901234567892"; deltaJournal.journal( Arrays.asList(assessment1id + "_id1234567890123456789012345678901234567891_id", assessment1id + "_id1234567890123456789012345678901234567892_id", assessment2id + "_id1234567890123456789012345678901234567891_id"), "assessmentItem", false); Query q1 = Query.query(Criteria.where("_id").is(Hex.decodeHex(assessment1id.toCharArray()))); Query q2 = Query.query(Criteria.where("_id").is(Hex.decodeHex(assessment2id.toCharArray()))); BaseMatcher<Update> updateMatcher = new BaseMatcher<Update>() { @Override public boolean matches(Object arg0) { @SuppressWarnings("unchecked") Map<String, Object> o = (Map<String, Object>) ((Update) arg0).getUpdateObject().get("$set"); return o.get("c").equals("assessment"); } @Override public void describeTo(Description arg0) { arg0.appendText("Update with 'c' set to 'assessment'"); } }; verify(template).upsert(eq(q1), argThat(updateMatcher), eq("deltas")); verify(template).upsert(eq(q2), argThat(updateMatcher), eq("deltas")); }
### Question: DeltaJournal implements InitializingBean { public void journalPurge(long timeOfPurge) { String id = uuidGeneratorStrategy.generateId(); Update update = new Update(); update.set("t", timeOfPurge); update.set("c", PURGE); TenantContext.setIsSystemCall(false); template.upsert(Query.query(where("_id").is(id)), update, DELTA_COLLECTION); } @Override void afterPropertiesSet(); void journal(Collection<String> ids, String collection, boolean isDelete); static List<byte[]> getByteId(String id); static String getEntityId(Map<String, Object> deltaRecord); void journal(String id, String collection, boolean isDelete); void journalCollapsedSubDocs(Collection<String> ids, String collection); void journalPurge(long timeOfPurge); Iterator<Map<String, Object>> findDeltaRecordBetween(final long start, final long end); void removeDeltaJournals(String tenant, long cleanUptoTime); static final String DELTA_COLLECTION; static final String PURGE; }### Answer: @Test public void testJournalPurge() { final long time = new Date().getTime(); deltaJournal.journalPurge(time); BaseMatcher<Update> updateMatcher = new BaseMatcher<Update>() { @Override public boolean matches(Object arg0) { @SuppressWarnings("unchecked") Map<String, Object> o = (Map<String, Object>) ((Update) arg0).getUpdateObject().get("$set"); if (o.get("c").equals("purge") && o.get("t").equals(time)) { return true; } return false; } @Override public void describeTo(Description arg0) { arg0.appendText("Update with 'c' set to 'purge' and 't' set to time of purge"); } }; verify(template, Mockito.times(1)).upsert(Mockito.any(Query.class), argThat(updateMatcher), Mockito.eq("deltas")); }
### Question: DeltaJournal implements InitializingBean { public static List<byte[]> getByteId(String id) { try { List<byte[]> result = new ArrayList<byte[]>(); int idLength = id.length(); if(idLength < 43) { LOG.error("Short ID encountered: {}", id); return Arrays.asList(id.getBytes()); } for(String idPart: id.split("_id")){ if(!idPart.isEmpty()){ idPart = idPart.replaceAll("[^\\p{XDigit}]", ""); result.add(0, Hex.decodeHex(idPart.toCharArray())); } } return result; } catch (DecoderException e) { LOG.error("Decoder exception while decoding {}", id, e); return Arrays.asList(id.getBytes()); } } @Override void afterPropertiesSet(); void journal(Collection<String> ids, String collection, boolean isDelete); static List<byte[]> getByteId(String id); static String getEntityId(Map<String, Object> deltaRecord); void journal(String id, String collection, boolean isDelete); void journalCollapsedSubDocs(Collection<String> ids, String collection); void journalPurge(long timeOfPurge); Iterator<Map<String, Object>> findDeltaRecordBetween(final long start, final long end); void removeDeltaJournals(String tenant, long cleanUptoTime); static final String DELTA_COLLECTION; static final String PURGE; }### Answer: @Test public void testGetByteId() throws DecoderException { String id = "1234567890123456789012345678901234567890"; String superid = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; String extraid = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"; assertEquals(id, Hex.encodeHexString(DeltaJournal.getByteId(id + "_id").get(0))); assertEquals(id, Hex.encodeHexString(DeltaJournal.getByteId(superid + "_id" + id + "_id").get(0))); assertEquals(superid, Hex.encodeHexString(DeltaJournal.getByteId(superid + "_id" + id + "_id").get(1))); assertEquals(superid, Hex.encodeHexString(DeltaJournal.getByteId(extraid + "_id" + superid + "_id" + id + "_id").get(1))); assertEquals(extraid, Hex.encodeHexString(DeltaJournal.getByteId(extraid + "_id" + superid + "_id" + id + "_id").get(2))); }