diff --git a/annotation/src/main/java/lcsb/mapviewer/annotation/cache/PermanentDatabaseLevelCache.java b/annotation/src/main/java/lcsb/mapviewer/annotation/cache/PermanentDatabaseLevelCache.java index 408d1981a4ee4343780cb17bf249a53a427d6bc3..0a66b94d754160543164841201c7f39888406014 100644 --- a/annotation/src/main/java/lcsb/mapviewer/annotation/cache/PermanentDatabaseLevelCache.java +++ b/annotation/src/main/java/lcsb/mapviewer/annotation/cache/PermanentDatabaseLevelCache.java @@ -2,6 +2,8 @@ package lcsb.mapviewer.annotation.cache; import java.lang.reflect.Constructor; import java.util.Calendar; +import java.util.Collection; +import java.util.LinkedList; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; @@ -143,8 +145,8 @@ public class PermanentDatabaseLevelCache extends XmlParser if (object instanceof CachableInterface) { cachableInterface = (CachableInterface) object; } else { - logger.fatal( - "Invalid class type: " + object.getClass() + ". Class cannot be cast into " + CachableInterface.class); + logger.fatal("Invalid class type: " + object.getClass() + " [" + object.toString() + + "]. Class cannot be cast into " + CachableInterface.class); } applicationContext.getAutowireCapableBeanFactory().autowireBean(object); @@ -563,16 +565,6 @@ public class PermanentDatabaseLevelCache extends XmlParser return ((ScheduledThreadPoolExecutor) cacheRefreshService).getQueue().size(); } - @Override - public boolean refreshIsBusy() { - return getRefreshPendingQueueSize() != 0 || getRefreshExecutingTasksSize() != 0; - } - - @Override - public int getRefreshExecutingTasksSize() { - return ((ScheduledThreadPoolExecutor) cacheRefreshService).getActiveCount(); - } - @Override public CacheQueryDao getCacheQueryDao() { return cacheQueryDao; @@ -584,9 +576,24 @@ public class PermanentDatabaseLevelCache extends XmlParser } @Override - public boolean databaseCacheIsBusy() { - return refreshIsBusy() || ((ScheduledThreadPoolExecutor) service).getActiveCount() > 0 - || ((ScheduledThreadPoolExecutor) service).getQueue().size() > 0; + public void waitToFinishTasks() throws InterruptedException, ExecutionException { + Collection<Future<?>> futures = new LinkedList<Future<?>>(); + futures.add(cacheRefreshService.submit(new Callable<Void>() { + @Override + public Void call() throws Exception { + return null; + } + })); + futures.add(service.submit(new Callable<Void>() { + @Override + public Void call() throws Exception { + return null; + } + })); + + for (Future<?> future:futures) { + future.get(); + } } } \ No newline at end of file diff --git a/annotation/src/main/java/lcsb/mapviewer/annotation/cache/PermanentDatabaseLevelCacheInterface.java b/annotation/src/main/java/lcsb/mapviewer/annotation/cache/PermanentDatabaseLevelCacheInterface.java index 1d6ee14bee1f13e2210f3ccb979172d58c4c74d3..59099aedabc6cd5b4f722402eebb3762e90192b8 100644 --- a/annotation/src/main/java/lcsb/mapviewer/annotation/cache/PermanentDatabaseLevelCacheInterface.java +++ b/annotation/src/main/java/lcsb/mapviewer/annotation/cache/PermanentDatabaseLevelCacheInterface.java @@ -1,5 +1,7 @@ package lcsb.mapviewer.annotation.cache; +import java.util.concurrent.ExecutionException; + import lcsb.mapviewer.persist.dao.cache.CacheQueryDao; /** @@ -20,25 +22,11 @@ public interface PermanentDatabaseLevelCacheInterface extends QueryCacheInterfac int getRefreshPendingQueueSize(); /** - * Returns true if refreshing of entries in database is in progress. - * - * @return true if refreshing of entries in database is in progress. - */ - boolean refreshIsBusy(); - - /** - * Returns approximate number of refresh tasks that are currently executed. - * - * @return approximate number of refresh tasks that are currently executed. - */ - int getRefreshExecutingTasksSize(); - - /** - * Returns true if database cache has any task in progress. - * - * @return true if database cache has any task in progress. + * Waits for all tasks in the cache to finish (refresh/get/etc). + * @throws ExecutionException + * @throws InterruptedException */ - boolean databaseCacheIsBusy(); + void waitToFinishTasks() throws InterruptedException, ExecutionException; /** * Returns {@link CacheQueryDao} used by the cache. diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/AnnotationTestFunctions.java b/annotation/src/test/java/lcsb/mapviewer/annotation/AnnotationTestFunctions.java index 73690ea7ee6c0c0fe8abaea5c850ecee265ff160..8d1e262d9a943c295c928269cd4c220d860946e4 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/AnnotationTestFunctions.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/AnnotationTestFunctions.java @@ -283,12 +283,4 @@ public abstract class AnnotationTestFunctions extends AbstractTransactionalJUnit throw exception; } - protected void waitForRefreshCacheQueueToEmpty() throws InterruptedException { - while (cache.refreshIsBusy()) { - logger.debug("Waiting for refresh queue to empty. " + cache.getRefreshPendingQueueSize() + " pending. " - + cache.getRefreshExecutingTasksSize() + " tasks are executed."); - Thread.sleep(300); - } - } - } diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/cache/PermanentDatabaseLevelCacheTest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/cache/PermanentDatabaseLevelCacheTest.java index a1672a47742f10e7a6700999852b84d0f62c0dcc..1b8b5b7fefd6f3e33fd874475d9f675862ebaee6 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/cache/PermanentDatabaseLevelCacheTest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/cache/PermanentDatabaseLevelCacheTest.java @@ -18,6 +18,7 @@ import org.junit.Test; import org.mockito.Mockito; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.annotation.Rollback; import org.w3c.dom.Node; @@ -34,6 +35,9 @@ public class PermanentDatabaseLevelCacheTest extends AnnotationTestFunctions { Logger logger = Logger.getLogger(PermanentDatabaseLevelCacheTest.class); + @Autowired + private PermanentDatabaseLevelCacheInterface permanentDatabaseLevelCache; + @Before public void setUp() throws Exception { } @@ -115,7 +119,6 @@ public class PermanentDatabaseLevelCacheTest extends AnnotationTestFunctions { @Test(timeout = 15000) public void testRefresh() throws Exception { try { - waitForRefreshCacheQueueToEmpty(); CacheType invalidType = cacheTypeDao.getByClassName(MockCacheInterface.class.getCanonicalName()); String query = "test query"; @@ -129,7 +132,7 @@ public class PermanentDatabaseLevelCacheTest extends AnnotationTestFunctions { // wasn't updated) assertEquals(val, res); // sleep a bit to wait for the second thread - waitForRefreshCacheQueueToEmpty(); + permanentDatabaseLevelCache.waitToFinishTasks(); // for the second time it should change dbUtils.createSessionForCurrentThread(); res = cache.getStringByQuery(query, invalidType); @@ -300,9 +303,8 @@ public class PermanentDatabaseLevelCacheTest extends AnnotationTestFunctions { cache.invalidateByQuery(query, invalidType); - while (cache.databaseCacheIsBusy()) { - Thread.sleep(10); - } + cache.waitToFinishTasks(); + assertEquals(1, getFatals().size()); } catch (Exception e) { @@ -337,9 +339,8 @@ public class PermanentDatabaseLevelCacheTest extends AnnotationTestFunctions { cache.invalidateByQuery(query, invalidType); - while (cache.databaseCacheIsBusy()) { - Thread.sleep(10); - } + cache.waitToFinishTasks(); + assertEquals(1, getFatals().size()); } catch (Exception e) { @@ -373,9 +374,7 @@ public class PermanentDatabaseLevelCacheTest extends AnnotationTestFunctions { cache.invalidateByQuery(query, type); - while (cache.refreshIsBusy()) { - Thread.sleep(10); - } + permanentDatabaseLevelCache.waitToFinishTasks(); assertEquals(1, getErrors().size()); } catch (Exception e) { @@ -409,9 +408,7 @@ public class PermanentDatabaseLevelCacheTest extends AnnotationTestFunctions { cache.invalidateByQuery(query, type); - while (cache.getRefreshExecutingTasksSize() + cache.getRefreshPendingQueueSize() > 0) { - Thread.sleep(10); - } + permanentDatabaseLevelCache.waitToFinishTasks(); assertEquals(0, getErrors().size()); assertEquals(0, getFatals().size()); @@ -427,8 +424,6 @@ public class PermanentDatabaseLevelCacheTest extends AnnotationTestFunctions { public void testRefreshQueryWithExceptionThrown() throws Exception { CacheQueryDao cacheQueryDao = cache.getCacheQueryDao(); try { - waitForRefreshCacheQueueToEmpty(); - CacheType type = cacheTypeDao.getByClassName(MockCacheInterface.class.getCanonicalName()); String query = ChebiAnnotator.ID_PREFIX + "1234"; @@ -450,7 +445,7 @@ public class PermanentDatabaseLevelCacheTest extends AnnotationTestFunctions { cache.invalidateByQuery(query, type); - waitForRefreshCacheQueueToEmpty(); + permanentDatabaseLevelCache.waitToFinishTasks(); assertEquals(1, getErrors().size()); @@ -488,9 +483,8 @@ public class PermanentDatabaseLevelCacheTest extends AnnotationTestFunctions { cache.invalidateByQuery(query, type); - while (cache.getRefreshExecutingTasksSize() + cache.getRefreshPendingQueueSize() > 0) { - Thread.sleep(10); - } + permanentDatabaseLevelCache.waitToFinishTasks(); + // errors are not caught assertEquals(0, getErrors().size()); assertEquals(0, getFatals().size()); diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/services/ChEMBLParserTest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/services/ChEMBLParserTest.java index 0207d4f35efa15f0839f7e71bb5cbd6615c4d74b..9c8d2e8a27cd3116ec3e2974c2d366e63655ae0c 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/services/ChEMBLParserTest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/services/ChEMBLParserTest.java @@ -6,9 +6,9 @@ import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.nullable; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.when; import java.io.IOException; @@ -24,7 +24,8 @@ import org.w3c.dom.Node; import lcsb.mapviewer.annotation.AnnotationTestFunctions; import lcsb.mapviewer.annotation.cache.GeneralCacheInterface; -import lcsb.mapviewer.annotation.cache.GeneralCacheWithExclusion; +import lcsb.mapviewer.annotation.cache.PermanentDatabaseLevelCache; +import lcsb.mapviewer.annotation.cache.PermanentDatabaseLevelCacheInterface; import lcsb.mapviewer.annotation.cache.SourceNotAvailable; import lcsb.mapviewer.annotation.cache.WebPageDownloader; import lcsb.mapviewer.annotation.cache.XmlSerializer; @@ -46,6 +47,9 @@ public class ChEMBLParserTest extends AnnotationTestFunctions { @Autowired private GeneralCacheInterface cache; + @Autowired + private PermanentDatabaseLevelCacheInterface permanentDatabaseLevelCache; + @Autowired private ChEMBLParser chemblParser; @@ -740,12 +744,10 @@ public class ChEMBLParserTest extends AnnotationTestFunctions { String query = "http://google.lu/"; String newRes = "hello"; try { - waitForRefreshCacheQueueToEmpty(); - cache.setCachedQuery(query, chemblParser.getCacheType(), newRes); cache.invalidateByQuery(query, chemblParser.getCacheType()); - waitForRefreshCacheQueueToEmpty(); + permanentDatabaseLevelCache.waitToFinishTasks(); String res = cache.getStringByQuery(query, chemblParser.getCacheType()); @@ -765,12 +767,10 @@ public class ChEMBLParserTest extends AnnotationTestFunctions { String query = ChEMBLParser.NAME_PREFIX + "TRIMETHOPRIM"; String newRes = "hello"; try { - waitForRefreshCacheQueueToEmpty(); - cache.setCachedQuery(query, chemblParser.getCacheType(), newRes); cache.invalidateByQuery(query, chemblParser.getCacheType()); - waitForRefreshCacheQueueToEmpty(); + permanentDatabaseLevelCache.waitToFinishTasks(); String res = cache.getStringByQuery(query, chemblParser.getCacheType()); diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/services/ChemicalParserTest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/services/ChemicalParserTest.java index 2cbcc496a929a3782d763ea8a377836e909674a7..0ef26253308c893606da6664106e753b9931e215 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/services/ChemicalParserTest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/services/ChemicalParserTest.java @@ -24,6 +24,8 @@ import org.springframework.beans.factory.annotation.Autowired; import lcsb.mapviewer.annotation.AnnotationTestFunctions; import lcsb.mapviewer.annotation.cache.GeneralCacheInterface; import lcsb.mapviewer.annotation.cache.GeneralCacheWithExclusion; +import lcsb.mapviewer.annotation.cache.PermanentDatabaseLevelCache; +import lcsb.mapviewer.annotation.cache.PermanentDatabaseLevelCacheInterface; import lcsb.mapviewer.annotation.cache.SourceNotAvailable; import lcsb.mapviewer.annotation.cache.WebPageDownloader; import lcsb.mapviewer.annotation.data.Chemical; @@ -55,6 +57,9 @@ public class ChemicalParserTest extends AnnotationTestFunctions { @Autowired private GeneralCacheInterface cache; + @Autowired + private PermanentDatabaseLevelCacheInterface permanentDatabaseLevelCache; + @Test public void testCreateChemicalListFromDB() throws Exception { try { @@ -229,12 +234,10 @@ public class ChemicalParserTest extends AnnotationTestFunctions { assertNotNull(chemcials); assertTrue(chemcials.size() > 0); - waitForRefreshCacheQueueToEmpty(); - cache.invalidateByQuery(chemicalParser.getIdentifier(parkinsonDiseaseId, chemcials.get(0).getChemicalId()), chemicalParser.getCacheType()); - waitForRefreshCacheQueueToEmpty(); + permanentDatabaseLevelCache.waitToFinishTasks(); idsList.clear(); diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/services/DrugbankHTMLParserTest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/services/DrugbankHTMLParserTest.java index 68cc3d43f09b287c9c0c3f4eb4cd6e8df9022c2b..5c57c7005861f678786ea3a09028f450876fe124 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/services/DrugbankHTMLParserTest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/services/DrugbankHTMLParserTest.java @@ -21,6 +21,8 @@ import org.springframework.beans.factory.annotation.Autowired; import lcsb.mapviewer.annotation.AnnotationTestFunctions; import lcsb.mapviewer.annotation.cache.GeneralCacheInterface; +import lcsb.mapviewer.annotation.cache.PermanentDatabaseLevelCache; +import lcsb.mapviewer.annotation.cache.PermanentDatabaseLevelCacheInterface; import lcsb.mapviewer.annotation.cache.SourceNotAvailable; import lcsb.mapviewer.annotation.cache.WebPageDownloader; import lcsb.mapviewer.annotation.data.Drug; @@ -38,6 +40,9 @@ public class DrugbankHTMLParserTest extends AnnotationTestFunctions { @Autowired private DrugbankHTMLParser drugBankHTMLParser; + @Autowired + private PermanentDatabaseLevelCacheInterface permanentDatabaseLevelCache; + @Test public void test1FindDrug() throws Exception { try { @@ -373,12 +378,10 @@ public class DrugbankHTMLParserTest extends AnnotationTestFunctions { String query = "http://google.lu/"; String newRes = "hello"; try { - waitForRefreshCacheQueueToEmpty(); - cache.setCachedQuery(query, drugBankHTMLParser.getCacheType(), newRes); cache.invalidateByQuery(query, drugBankHTMLParser.getCacheType()); - waitForRefreshCacheQueueToEmpty(); + permanentDatabaseLevelCache.waitToFinishTasks(); String res = cache.getStringByQuery(query, drugBankHTMLParser.getCacheType()); @@ -399,12 +402,10 @@ public class DrugbankHTMLParserTest extends AnnotationTestFunctions { String query = "drug:amantadine"; String newRes = "hello"; try { - waitForRefreshCacheQueueToEmpty(); - cache.setCachedQuery(query, drugBankHTMLParser.getCacheType(), newRes); cache.invalidateByQuery(query, drugBankHTMLParser.getCacheType()); - waitForRefreshCacheQueueToEmpty(); + permanentDatabaseLevelCache.waitToFinishTasks(); String res = cache.getStringByQuery(query, drugBankHTMLParser.getCacheType()); diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/services/MeSHParserTest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/services/MeSHParserTest.java index ddc7a6b812668a3a9889bf6408bcb78527bcc89a..aacd382a99dbf0822b7bc02b8d18922915c979d0 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/services/MeSHParserTest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/services/MeSHParserTest.java @@ -6,8 +6,8 @@ import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; +import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.nullable; -import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.when; import java.io.IOException; @@ -21,6 +21,8 @@ import org.springframework.beans.factory.annotation.Autowired; import lcsb.mapviewer.annotation.AnnotationTestFunctions; import lcsb.mapviewer.annotation.cache.GeneralCacheInterface; +import lcsb.mapviewer.annotation.cache.PermanentDatabaseLevelCache; +import lcsb.mapviewer.annotation.cache.PermanentDatabaseLevelCacheInterface; import lcsb.mapviewer.annotation.cache.SourceNotAvailable; import lcsb.mapviewer.annotation.cache.WebPageDownloader; import lcsb.mapviewer.annotation.data.MeSH; @@ -35,6 +37,9 @@ public class MeSHParserTest extends AnnotationTestFunctions { @Autowired MeSHParser meshParser; + @Autowired + private PermanentDatabaseLevelCacheInterface permanentDatabaseLevelCache; + @Autowired private GeneralCacheInterface cache; @@ -173,7 +178,8 @@ public class MeSHParserTest extends AnnotationTestFunctions { MiriamData meshID = new MiriamData(MiriamType.MESH_2012, "D004298"); MeSHParser parserUnderTest = new MeSHParser(); WebPageDownloader webPageDownloader = Mockito.mock(WebPageDownloader.class); - when(webPageDownloader.getFromNetwork(anyString(), anyString(), nullable(String.class))).thenThrow(new IOException()); + when(webPageDownloader.getFromNetwork(anyString(), anyString(), nullable(String.class))) + .thenThrow(new IOException()); parserUnderTest.setWebPageDownloader(webPageDownloader); parserUnderTest.getMeSH(meshID); @@ -203,11 +209,9 @@ public class MeSHParserTest extends AnnotationTestFunctions { MeSH mesh = meshParser.getMeSH(meshID); assertNotNull(mesh); - waitForRefreshCacheQueueToEmpty(); - cache.invalidateByQuery(meshParser.getIdentifier(meshID), meshParser.getCacheType()); - waitForRefreshCacheQueueToEmpty(); + permanentDatabaseLevelCache.waitToFinishTasks(); MeSH mesh2 = meshParser.getMeSH(meshID); assertNotNull(mesh2); @@ -281,7 +285,8 @@ public class MeSHParserTest extends AnnotationTestFunctions { try { meshParser.setCache(null); WebPageDownloader mockDownloader = Mockito.mock(WebPageDownloader.class); - when(mockDownloader.getFromNetwork(anyString(), anyString(), nullable(String.class))).thenThrow(new IOException()); + when(mockDownloader.getFromNetwork(anyString(), anyString(), nullable(String.class))) + .thenThrow(new IOException()); meshParser.setWebPageDownloader(mockDownloader); MiriamData meshID = new MiriamData(MiriamType.MESH_2012, "D010300"); @@ -304,7 +309,8 @@ public class MeSHParserTest extends AnnotationTestFunctions { WebPageDownloader downloader = meshParser.getWebPageDownloader(); try { WebPageDownloader mockDownloader = Mockito.mock(WebPageDownloader.class); - when(mockDownloader.getFromNetwork(anyString(), anyString(), nullable(String.class))).thenThrow(new IOException()); + when(mockDownloader.getFromNetwork(anyString(), anyString(), nullable(String.class))) + .thenThrow(new IOException()); meshParser.setWebPageDownloader(mockDownloader); assertEquals(ExternalServiceStatusType.DOWN, meshParser.getServiceStatus().getStatus()); } catch (Exception e) { diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/services/MiRNAParserTest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/services/MiRNAParserTest.java index 677503288dd3e1ad8af84a9ab5e63fa63b41b17a..ac1e12c007a1b3cdcc779573c752409b8ce0e228 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/services/MiRNAParserTest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/services/MiRNAParserTest.java @@ -6,7 +6,7 @@ import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; -import static org.mockito.Matchers.anyString; +import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.when; import java.util.ArrayList; @@ -23,6 +23,8 @@ import org.springframework.beans.factory.annotation.Autowired; import lcsb.mapviewer.annotation.AnnotationTestFunctions; import lcsb.mapviewer.annotation.cache.GeneralCacheInterface; +import lcsb.mapviewer.annotation.cache.PermanentDatabaseLevelCache; +import lcsb.mapviewer.annotation.cache.PermanentDatabaseLevelCacheInterface; import lcsb.mapviewer.annotation.cache.SourceNotAvailable; import lcsb.mapviewer.annotation.data.MiRNA; import lcsb.mapviewer.annotation.data.Target; @@ -38,6 +40,9 @@ public class MiRNAParserTest extends AnnotationTestFunctions { @Autowired MiRNAParser miRNAParser; + @Autowired + private PermanentDatabaseLevelCacheInterface permanentDatabaseLevelCache; + @Before public void setUp() throws Exception { } @@ -164,11 +169,9 @@ public class MiRNAParserTest extends AnnotationTestFunctions { assertTrue(!list.isEmpty()); assertEquals(1, list.get(0).getTargets().size()); - waitForRefreshCacheQueueToEmpty(); - cache.invalidateByQuery(MiRNAParser.MI_RNA_PREFIX + list.get(0).getName(), miRNAParser.getCacheType()); - waitForRefreshCacheQueueToEmpty(); + permanentDatabaseLevelCache.waitToFinishTasks(); listIds.clear(); listIds.add(list.get(0).getName()); diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/services/PubmedParserTest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/services/PubmedParserTest.java index 7b5c21f24733f0b4d21fcebda25375c8006c0b7e..72735c2f47ed788734b8ec9d382aaf22f0dfde67 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/services/PubmedParserTest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/services/PubmedParserTest.java @@ -23,6 +23,7 @@ import org.springframework.beans.factory.annotation.Autowired; import lcsb.mapviewer.annotation.AnnotationTestFunctions; import lcsb.mapviewer.annotation.cache.GeneralCacheInterface; +import lcsb.mapviewer.annotation.cache.PermanentDatabaseLevelCacheInterface; import lcsb.mapviewer.annotation.cache.SourceNotAvailable; import lcsb.mapviewer.annotation.cache.WebPageDownloader; import lcsb.mapviewer.annotation.cache.XmlSerializer; @@ -31,396 +32,404 @@ import lcsb.mapviewer.common.Configuration; import lcsb.mapviewer.common.exception.InvalidArgumentException; public class PubmedParserTest extends AnnotationTestFunctions { - Logger logger = Logger.getLogger(PubmedParserTest.class); - private boolean status; - private boolean status2; - @Autowired - PubmedParser pubmedParser; - - @Autowired - private GeneralCacheInterface cache; - - @Before - public void setUp() throws Exception { - status = Configuration.isDbCacheOn(); - status2 = Configuration.isApplicationCacheOn(); - } - - @After - public void tearDown() throws Exception { - Configuration.setDbCacheOn(status); - Configuration.setApplicationCacheOn(status2); - } - - @Test - public void test() { - try { - Configuration.setDbCacheOn(false); - Configuration.setApplicationCacheOn(false); - Article art = pubmedParser.getPubmedArticleById(9481670); - assertNotNull(art); - assertEquals( - "Adjacent asparagines in the NR2-subunit of the NMDA receptor channel control the voltage-dependent block by extracellular Mg2+.", art.getTitle()); - assertEquals((Integer) 1998, art.getYear()); - assertEquals("The Journal of physiology", art.getJournal()); - assertTrue(art.getStringAuthors().contains("Wollmuth")); - assertTrue(art.getStringAuthors().contains("Kuner")); - assertTrue(art.getStringAuthors().contains("Sakmann")); - - } catch (Exception e) { - e.printStackTrace(); - fail("Unknown exception " + e.getMessage()); - } - } - - @Test - public void testCache() { - try { - Configuration.setDbCacheOn(true); - Configuration.setApplicationCacheOn(true); - - Article art = pubmedParser.getPubmedArticleById(9481671); - assertNotNull(art); - - } catch (Exception e) { - e.printStackTrace(); - fail("Unknown exception " + e.getMessage()); - } - } - - @Test - public void testSerialization() { - try { - - Article art = new Article(); - List<String> list = new ArrayList<String>(); - list.add("aaa"); - list.add("bbb"); - art.setTitle("ttt"); - art.setAuthors(list); - art.setJournal("jjjj"); - art.setYear(123); - - String serialString = pubmedParser.getArticleSerializer().objectToString(art); - - assertTrue(serialString.contains("aaa")); - assertTrue(serialString.contains("bbb")); - assertTrue(serialString.contains("ttt")); - assertTrue(serialString.contains("jjjj")); - assertTrue(serialString.contains("123")); - - Article art2 = pubmedParser.getArticleSerializer().xmlToObject(getNodeFromXmlString(serialString)); - - assertEquals(art.getStringAuthors(), art2.getStringAuthors()); - assertEquals(art.getTitle(), art2.getTitle()); - assertEquals(art.getJournal(), art2.getJournal()); - assertEquals(art.getYear(), art2.getYear()); - - } catch (Exception e) { - e.printStackTrace(); - fail("Exception occurred"); - } - } - - /** - * This case was problematic with old API used to retrieve data from pubmed - */ - @Test - public void testProblematicCase() { - try { - - Article art = pubmedParser.getPubmedArticleById(22363258); - assertNotNull(art); - - } catch (Exception e) { - e.printStackTrace(); - fail("Unknown exception " + e.getMessage()); - } - } - - @Test - public void testCitationCount() { - try { - - Article art = pubmedParser.getPubmedArticleById(18400456); - assertNotNull(art); - assertTrue(art.getCitationCount() >= 53); - - } catch (Exception e) { - e.printStackTrace(); - fail("Unknown exception " + e.getMessage()); - } - } - - @Test - public void testGetSummary() throws Exception { - try { - String summary = pubmedParser.getSummary(18400456); - assertNotNull(summary); - assertFalse(summary.isEmpty()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testGetSummary2() throws Exception { - try { - - String summary = pubmedParser.getSummary(23644949); - assertNull(summary); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testGetSummary3() throws Exception { - try { - String summary = pubmedParser.getSummary("18400456"); - assertNotNull(summary); - assertFalse(summary.isEmpty()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - // wait max 15 second - public void testCachableInterface() throws Exception { - String query = "pubmed: 2112"; - try { - String newRes = "hello"; - waitForRefreshCacheQueueToEmpty(); - - cache.setCachedQuery(query, pubmedParser.getCacheType(), newRes); - cache.invalidateByQuery(query, pubmedParser.getCacheType()); - - waitForRefreshCacheQueueToEmpty(); - - String res = cache.getStringByQuery(query, pubmedParser.getCacheType()); - - assertNotNull(res); - - assertFalse("Value wasn't refreshed from db", newRes.equals(res)); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testRefreshInvalidCacheQuery() throws Exception { - try { - pubmedParser.refreshCacheQuery("invalid_query"); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - assertTrue(e.getMessage().contains("Don't know what to do")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testRefreshWhenExternalNotAvailable() throws Exception { - WebPageDownloader downloader = pubmedParser.getWebPageDownloader(); - try { - pubmedParser.setCache(null); - WebPageDownloader mockDownloader = Mockito.mock(WebPageDownloader.class); - when(mockDownloader.getFromNetwork(anyString(), anyString(), nullable(String.class))).thenThrow(new IOException()); - pubmedParser.setWebPageDownloader(mockDownloader); - - String query = PubmedParser.PUBMED_PREFIX + PubmedParser.SERVICE_STATUS_PUBMED_ID; - - pubmedParser.refreshCacheQuery(query); - fail("Exception expected"); - } catch (SourceNotAvailable e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } finally { - pubmedParser.setWebPageDownloader(downloader); - pubmedParser.setCache(cache); - } - - } - - @Test - public void testRefreshInvalidCacheQuery2() throws Exception { - try { - pubmedParser.refreshCacheQuery(new Object()); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - assertTrue(e.getMessage().contains("Don't know what to do")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testGetHtmlFullLinkForId() throws Exception { - try { - String htmlString = pubmedParser.getHtmlFullLinkForId(1234); - assertTrue(htmlString.contains("Change in the kinetics of sulphacetamide tissue distribution")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testStatus() throws Exception { - try { - assertEquals(ExternalServiceStatusType.OK, pubmedParser.getServiceStatus().getStatus()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testSimulateDownStatus() throws Exception { - WebPageDownloader downloader = pubmedParser.getWebPageDownloader(); - try { - WebPageDownloader mockDownloader = Mockito.mock(WebPageDownloader.class); - when(mockDownloader.getFromNetwork(anyString(), anyString(), nullable(String.class))).thenThrow(new IOException()); - pubmedParser.setWebPageDownloader(mockDownloader); - assertEquals(ExternalServiceStatusType.DOWN, pubmedParser.getServiceStatus().getStatus()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } finally { - pubmedParser.setWebPageDownloader(downloader); - } - } - - @Test - public void testSimulateDownStatus2() throws Exception { - WebPageDownloader downloader = pubmedParser.getWebPageDownloader(); - try { - WebPageDownloader mockDownloader = Mockito.mock(WebPageDownloader.class); - when(mockDownloader.getFromNetwork(anyString(), anyString(), nullable(String.class))) - .thenReturn("<responseWrapper><version>" + PubmedParser.SUPPORTED_VERSION + "</version></responseWrapper>"); - pubmedParser.setWebPageDownloader(mockDownloader); - assertEquals(ExternalServiceStatusType.DOWN, pubmedParser.getServiceStatus().getStatus()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } finally { - pubmedParser.setWebPageDownloader(downloader); - } - } - - @Test - public void testSimulateChangeStatus() throws Exception { - WebPageDownloader downloader = pubmedParser.getWebPageDownloader(); - try { - WebPageDownloader mockDownloader = Mockito.mock(WebPageDownloader.class); - when(mockDownloader.getFromNetwork(anyString(), anyString(), nullable(String.class))) - .thenReturn("<responseWrapper><version>" + PubmedParser.SUPPORTED_VERSION + "blabla</version></responseWrapper>"); - pubmedParser.setWebPageDownloader(mockDownloader); - assertEquals(ExternalServiceStatusType.CHANGED, pubmedParser.getServiceStatus().getStatus()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } finally { - pubmedParser.setWebPageDownloader(downloader); - } - } - - @Test - public void testGetApiVersion() throws Exception { - try { - assertNotNull(pubmedParser.getApiVersion()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testGetApiVersionWhenProblemWithExternalDb() throws Exception { - WebPageDownloader downloader = pubmedParser.getWebPageDownloader(); - pubmedParser.setCache(null); - try { - WebPageDownloader mockDownloader = Mockito.mock(WebPageDownloader.class); - when(mockDownloader.getFromNetwork(anyString(), anyString(), nullable(String.class))).thenReturn("unknown response"); - pubmedParser.setWebPageDownloader(mockDownloader); - pubmedParser.getApiVersion(); - fail("Exception expected"); - } catch (PubmedSearchException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } finally { - pubmedParser.setCache(cache); - pubmedParser.setWebPageDownloader(downloader); - } - } - - @Test - public void testGetApiVersionWhenProblemWithExternalDb3() throws Exception { - WebPageDownloader downloader = pubmedParser.getWebPageDownloader(); - pubmedParser.setCache(null); - try { - WebPageDownloader mockDownloader = Mockito.mock(WebPageDownloader.class); - when(mockDownloader.getFromNetwork(anyString(), anyString(), nullable(String.class))).thenReturn("<xml/>"); - pubmedParser.setWebPageDownloader(mockDownloader); - assertNull(pubmedParser.getApiVersion()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } finally { - pubmedParser.setCache(cache); - pubmedParser.setWebPageDownloader(downloader); - } - } - - @Test - public void testGetApiVersionWhenProblemWithExternalDb2() throws Exception { - WebPageDownloader downloader = pubmedParser.getWebPageDownloader(); - pubmedParser.setCache(null); - try { - WebPageDownloader mockDownloader = Mockito.mock(WebPageDownloader.class); - when(mockDownloader.getFromNetwork(anyString(), anyString(), nullable(String.class))).thenThrow(new IOException()); - pubmedParser.setWebPageDownloader(mockDownloader); - pubmedParser.getApiVersion(); - fail("Exception expected"); - } catch (PubmedSearchException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } finally { - pubmedParser.setCache(cache); - pubmedParser.setWebPageDownloader(downloader); - } - } - - @Test - public void testGetters() throws Exception { - try { - MiriamConnector mc = new MiriamConnector(); - XmlSerializer<Article> serializer = new XmlSerializer<>(Article.class); - PubmedParser parser = new PubmedParser(); - - parser.setMiriamConnector(mc); - assertEquals(mc, parser.getMiriamConnector()); - - parser.setArticleSerializer(serializer); - - assertEquals(serializer, parser.getArticleSerializer()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } + Logger logger = Logger.getLogger(PubmedParserTest.class); + private boolean status; + private boolean status2; + @Autowired + PubmedParser pubmedParser; + + @Autowired + private GeneralCacheInterface cache; + + @Autowired + protected PermanentDatabaseLevelCacheInterface permanentDatabaseLevelCacheInterface; + + @Before + public void setUp() throws Exception { + status = Configuration.isDbCacheOn(); + status2 = Configuration.isApplicationCacheOn(); + } + + @After + public void tearDown() throws Exception { + Configuration.setDbCacheOn(status); + Configuration.setApplicationCacheOn(status2); + } + + @Test + public void test() { + try { + Configuration.setDbCacheOn(false); + Configuration.setApplicationCacheOn(false); + Article art = pubmedParser.getPubmedArticleById(9481670); + assertNotNull(art); + assertEquals( + "Adjacent asparagines in the NR2-subunit of the NMDA receptor channel control the voltage-dependent block by extracellular Mg2+.", + art.getTitle()); + assertEquals((Integer) 1998, art.getYear()); + assertEquals("The Journal of physiology", art.getJournal()); + assertTrue(art.getStringAuthors().contains("Wollmuth")); + assertTrue(art.getStringAuthors().contains("Kuner")); + assertTrue(art.getStringAuthors().contains("Sakmann")); + + } catch (Exception e) { + e.printStackTrace(); + fail("Unknown exception " + e.getMessage()); + } + } + + @Test + public void testCache() { + try { + Configuration.setDbCacheOn(true); + Configuration.setApplicationCacheOn(true); + + Article art = pubmedParser.getPubmedArticleById(9481671); + assertNotNull(art); + + } catch (Exception e) { + e.printStackTrace(); + fail("Unknown exception " + e.getMessage()); + } + } + + @Test + public void testSerialization() { + try { + + Article art = new Article(); + List<String> list = new ArrayList<String>(); + list.add("aaa"); + list.add("bbb"); + art.setTitle("ttt"); + art.setAuthors(list); + art.setJournal("jjjj"); + art.setYear(123); + + String serialString = pubmedParser.getArticleSerializer().objectToString(art); + + assertTrue(serialString.contains("aaa")); + assertTrue(serialString.contains("bbb")); + assertTrue(serialString.contains("ttt")); + assertTrue(serialString.contains("jjjj")); + assertTrue(serialString.contains("123")); + + Article art2 = pubmedParser.getArticleSerializer().xmlToObject(getNodeFromXmlString(serialString)); + + assertEquals(art.getStringAuthors(), art2.getStringAuthors()); + assertEquals(art.getTitle(), art2.getTitle()); + assertEquals(art.getJournal(), art2.getJournal()); + assertEquals(art.getYear(), art2.getYear()); + + } catch (Exception e) { + e.printStackTrace(); + fail("Exception occurred"); + } + } + + /** + * This case was problematic with old API used to retrieve data from pubmed + */ + @Test + public void testProblematicCase() { + try { + + Article art = pubmedParser.getPubmedArticleById(22363258); + assertNotNull(art); + + } catch (Exception e) { + e.printStackTrace(); + fail("Unknown exception " + e.getMessage()); + } + } + + @Test + public void testCitationCount() { + try { + + Article art = pubmedParser.getPubmedArticleById(18400456); + assertNotNull(art); + assertTrue(art.getCitationCount() >= 53); + + } catch (Exception e) { + e.printStackTrace(); + fail("Unknown exception " + e.getMessage()); + } + } + + @Test + public void testGetSummary() throws Exception { + try { + String summary = pubmedParser.getSummary(18400456); + assertNotNull(summary); + assertFalse(summary.isEmpty()); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testGetSummary2() throws Exception { + try { + + String summary = pubmedParser.getSummary(23644949); + assertNull(summary); + + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testGetSummary3() throws Exception { + try { + String summary = pubmedParser.getSummary("18400456"); + assertNotNull(summary); + assertFalse(summary.isEmpty()); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + // wait max 15 second + public void testCachableInterface() throws Exception { + String query = "pubmed: 2112"; + try { + String newRes = "hello"; + permanentDatabaseLevelCacheInterface.waitToFinishTasks(); + + cache.setCachedQuery(query, pubmedParser.getCacheType(), newRes); + cache.invalidateByQuery(query, pubmedParser.getCacheType()); + + permanentDatabaseLevelCacheInterface.waitToFinishTasks(); + + String res = cache.getStringByQuery(query, pubmedParser.getCacheType()); + + assertNotNull(res); + + assertFalse("Value wasn't refreshed from db", newRes.equals(res)); + + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testRefreshInvalidCacheQuery() throws Exception { + try { + pubmedParser.refreshCacheQuery("invalid_query"); + fail("Exception expected"); + } catch (InvalidArgumentException e) { + assertTrue(e.getMessage().contains("Don't know what to do")); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testRefreshWhenExternalNotAvailable() throws Exception { + WebPageDownloader downloader = pubmedParser.getWebPageDownloader(); + try { + pubmedParser.setCache(null); + WebPageDownloader mockDownloader = Mockito.mock(WebPageDownloader.class); + when(mockDownloader.getFromNetwork(anyString(), anyString(), nullable(String.class))) + .thenThrow(new IOException()); + pubmedParser.setWebPageDownloader(mockDownloader); + + String query = PubmedParser.PUBMED_PREFIX + PubmedParser.SERVICE_STATUS_PUBMED_ID; + + pubmedParser.refreshCacheQuery(query); + fail("Exception expected"); + } catch (SourceNotAvailable e) { + } catch (Exception e) { + e.printStackTrace(); + throw e; + } finally { + pubmedParser.setWebPageDownloader(downloader); + pubmedParser.setCache(cache); + } + + } + + @Test + public void testRefreshInvalidCacheQuery2() throws Exception { + try { + pubmedParser.refreshCacheQuery(new Object()); + fail("Exception expected"); + } catch (InvalidArgumentException e) { + assertTrue(e.getMessage().contains("Don't know what to do")); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testGetHtmlFullLinkForId() throws Exception { + try { + String htmlString = pubmedParser.getHtmlFullLinkForId(1234); + assertTrue(htmlString.contains("Change in the kinetics of sulphacetamide tissue distribution")); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testStatus() throws Exception { + try { + assertEquals(ExternalServiceStatusType.OK, pubmedParser.getServiceStatus().getStatus()); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testSimulateDownStatus() throws Exception { + WebPageDownloader downloader = pubmedParser.getWebPageDownloader(); + try { + WebPageDownloader mockDownloader = Mockito.mock(WebPageDownloader.class); + when(mockDownloader.getFromNetwork(anyString(), anyString(), nullable(String.class))) + .thenThrow(new IOException()); + pubmedParser.setWebPageDownloader(mockDownloader); + assertEquals(ExternalServiceStatusType.DOWN, pubmedParser.getServiceStatus().getStatus()); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } finally { + pubmedParser.setWebPageDownloader(downloader); + } + } + + @Test + public void testSimulateDownStatus2() throws Exception { + WebPageDownloader downloader = pubmedParser.getWebPageDownloader(); + try { + WebPageDownloader mockDownloader = Mockito.mock(WebPageDownloader.class); + when(mockDownloader.getFromNetwork(anyString(), anyString(), nullable(String.class))) + .thenReturn("<responseWrapper><version>" + PubmedParser.SUPPORTED_VERSION + "</version></responseWrapper>"); + pubmedParser.setWebPageDownloader(mockDownloader); + assertEquals(ExternalServiceStatusType.DOWN, pubmedParser.getServiceStatus().getStatus()); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } finally { + pubmedParser.setWebPageDownloader(downloader); + } + } + + @Test + public void testSimulateChangeStatus() throws Exception { + WebPageDownloader downloader = pubmedParser.getWebPageDownloader(); + try { + WebPageDownloader mockDownloader = Mockito.mock(WebPageDownloader.class); + when(mockDownloader.getFromNetwork(anyString(), anyString(), nullable(String.class))).thenReturn( + "<responseWrapper><version>" + PubmedParser.SUPPORTED_VERSION + "blabla</version></responseWrapper>"); + pubmedParser.setWebPageDownloader(mockDownloader); + assertEquals(ExternalServiceStatusType.CHANGED, pubmedParser.getServiceStatus().getStatus()); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } finally { + pubmedParser.setWebPageDownloader(downloader); + } + } + + @Test + public void testGetApiVersion() throws Exception { + try { + assertNotNull(pubmedParser.getApiVersion()); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testGetApiVersionWhenProblemWithExternalDb() throws Exception { + WebPageDownloader downloader = pubmedParser.getWebPageDownloader(); + pubmedParser.setCache(null); + try { + WebPageDownloader mockDownloader = Mockito.mock(WebPageDownloader.class); + when(mockDownloader.getFromNetwork(anyString(), anyString(), nullable(String.class))) + .thenReturn("unknown response"); + pubmedParser.setWebPageDownloader(mockDownloader); + pubmedParser.getApiVersion(); + fail("Exception expected"); + } catch (PubmedSearchException e) { + } catch (Exception e) { + e.printStackTrace(); + throw e; + } finally { + pubmedParser.setCache(cache); + pubmedParser.setWebPageDownloader(downloader); + } + } + + @Test + public void testGetApiVersionWhenProblemWithExternalDb3() throws Exception { + WebPageDownloader downloader = pubmedParser.getWebPageDownloader(); + pubmedParser.setCache(null); + try { + WebPageDownloader mockDownloader = Mockito.mock(WebPageDownloader.class); + when(mockDownloader.getFromNetwork(anyString(), anyString(), nullable(String.class))).thenReturn("<xml/>"); + pubmedParser.setWebPageDownloader(mockDownloader); + assertNull(pubmedParser.getApiVersion()); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } finally { + pubmedParser.setCache(cache); + pubmedParser.setWebPageDownloader(downloader); + } + } + + @Test + public void testGetApiVersionWhenProblemWithExternalDb2() throws Exception { + WebPageDownloader downloader = pubmedParser.getWebPageDownloader(); + pubmedParser.setCache(null); + try { + WebPageDownloader mockDownloader = Mockito.mock(WebPageDownloader.class); + when(mockDownloader.getFromNetwork(anyString(), anyString(), nullable(String.class))) + .thenThrow(new IOException()); + pubmedParser.setWebPageDownloader(mockDownloader); + pubmedParser.getApiVersion(); + fail("Exception expected"); + } catch (PubmedSearchException e) { + } catch (Exception e) { + e.printStackTrace(); + throw e; + } finally { + pubmedParser.setCache(cache); + pubmedParser.setWebPageDownloader(downloader); + } + } + + @Test + public void testGetters() throws Exception { + try { + MiriamConnector mc = new MiriamConnector(); + XmlSerializer<Article> serializer = new XmlSerializer<>(Article.class); + PubmedParser parser = new PubmedParser(); + + parser.setMiriamConnector(mc); + assertEquals(mc, parser.getMiriamConnector()); + + parser.setArticleSerializer(serializer); + + assertEquals(serializer, parser.getArticleSerializer()); + + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } } diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/BiocompendiumAnnotatorTest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/BiocompendiumAnnotatorTest.java index 802ee10b476223705cb6c2261b9955cc77e10fad..99f2734a3de5cd491310b7a96cf991111f9c9530 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/BiocompendiumAnnotatorTest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/BiocompendiumAnnotatorTest.java @@ -20,6 +20,7 @@ import org.springframework.beans.factory.annotation.Autowired; import lcsb.mapviewer.annotation.AnnotationTestFunctions; import lcsb.mapviewer.annotation.cache.GeneralCacheInterface; +import lcsb.mapviewer.annotation.cache.PermanentDatabaseLevelCacheInterface; import lcsb.mapviewer.annotation.cache.SourceNotAvailable; import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.common.exception.InvalidXmlSchemaException; @@ -27,335 +28,336 @@ import lcsb.mapviewer.model.map.MiriamData; import lcsb.mapviewer.model.map.MiriamType; public class BiocompendiumAnnotatorTest extends AnnotationTestFunctions { - Logger logger = Logger.getLogger(BiocompendiumAnnotatorTest.class); - - MiriamData camk4 = new MiriamData(MiriamType.HGNC_SYMBOL, "CAMK4"); - MiriamData slc25a27 = new MiriamData(MiriamType.HGNC_SYMBOL, "SLC25A27"); - MiriamData nsmf = new MiriamData(MiriamType.HGNC_SYMBOL, "NSMF"); - MiriamData mir449a = new MiriamData(MiriamType.HGNC_SYMBOL, "MIR449A"); - - @Autowired - private GeneralCacheInterface cache; - - @Autowired - private BiocompendiumAnnotator restService; - - @Before - public void setUp() { - } - - @After - public void tearDown() throws Exception { - } - - @Test - @Ignore("Bug 32") - public void testGetAnnotationsForSpecies() throws Exception { - try { - String response = restService.getAnnotation(camk4); - assertNotNull(response); - assertTrue(response.contains("Symbol: CAMK4")); - - response = restService.getAnnotation(slc25a27); - assertNotNull(response); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testGetters() throws Exception { - try { - assertNotNull(restService.getCommonName()); - assertNotNull(restService.getUrl()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testGetAnnotationsForInvalidMiriam() throws Exception { - try { - restService.getAnnotation(new MiriamData()); - fail("Exception expected"); - - } catch (InvalidArgumentException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testParseXml() throws Exception { - BufferedReader reader; - try { - reader = new BufferedReader(new FileReader("testFiles/annotation/sampleResponse.xml")); - String line = null; - StringBuilder stringBuilder = new StringBuilder(); - String ls = System.getProperty("line.separator"); - - while ((line = reader.readLine()) != null) { - stringBuilder.append(line); - stringBuilder.append(ls); - } - reader.close(); - - Map<String, String> res = restService.getAnnotationsFromXml(stringBuilder.toString()); - - assertEquals(2, res.keySet().size()); - String response = res.get("CAMK4"); - assertNotNull(response); - assertTrue(response.contains("Symbol: CAMK4")); - - assertNotNull(res.get("SLC25A27")); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test(timeout = 10000) - @Ignore("Bug 32") - public void testGetAnnotationsForMiceSpecies() throws Exception { - ArrayList<String> names = new ArrayList<String>(); - - names.add("Fmo3"); - names.add("Nqo1"); - names.add("Abcc12"); - names.add("Mgst3"); - names.add("Txnrd1"); - names.add("Cbr3"); - names.add("Hspa1b"); - names.add("Prdx1"); - names.add("Ppard"); - names.add("Tgfb2"); - names.add("Fth1"); - names.add("Prdx6"); - names.add("Nr4a1"); - names.add("Tgfb1"); - names.add("Abcc4"); - names.add("Ager"); - names.add("Gsr"); - names.add("Sod3"); - names.add("Maff"); - names.add("Eif2ak3"); - names.add("Tgfa"); - names.add("Hbegf"); - names.add("Mafg"); - names.add("Adh7"); - names.add("Slc7a11"); - names.add("Epha3"); - names.add("Blvrb"); - // problematic one - // names.add("Me1"); - names.add("Csnk2a2"); - names.add("Gpx3"); - names.add("Mapk8"); - names.add("Gclm"); - names.add("Epha2"); - names.add("Bdnf"); - // problematic one - // names.add("ACC2"); - names.add("Ptgr1"); - names.add("Pdgfb"); - names.add("Mapk7"); - names.add("Cbr1"); - names.add("Hsp90aa1"); - names.add("Pgd"); - names.add("Sqstm1"); - names.add("Aldh9a1"); - names.add("Txn"); - names.add("Txnrd3"); - names.add("Srxn1"); - names.add("Gpx2"); - names.add("Npas4"); - names.add("Mapk1"); - names.add("Nrg1"); - names.add("Cbr"); - names.add("Hspa1a"); - names.add("Mgst2"); - names.add("Tgfbr2"); - names.add("Ephx1"); - names.add("Dnajb1"); - names.add("Abcc2"); - names.add("Gclc"); - names.add("Abcc5"); - names.add("Ggt1"); - names.add("Ftl"); - names.add("Egr1"); - names.add("Fgf13"); - // problematic one - // names.add("Hgf"); - // problematic one - // names.add("UbcH7"); - names.add("Abcc3"); - names.add("Nfe2l2"); - // problematic one - // names.add("Hsp70"); - names.add("Hsp90ab1"); - - try { - for (int i = 0; i < names.size(); i++) { - String geneName = names.get(i); - String annotation = restService.getAnnotation(new MiriamData(MiriamType.HGNC_SYMBOL, geneName)); - assertNotNull("Problem with annotation of mouse gene: " + geneName, annotation); - assertTrue("Problem with annotation of mouse gene: " + geneName, !annotation.trim().equals("")); - } - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - @Ignore("Bug 451") - public void testGetAnnotationsForNSMF() throws Exception { - try { - String response = restService.getAnnotation(nsmf); - assertNotNull(response); - assertFalse(response.trim().equals("")); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - @Ignore("Bug 451") - public void testGetAnnotationsForMIR449A() throws Exception { - try { - String response = restService.getAnnotation(mir449a); - assertNotNull(response); - assertFalse(response.trim().equals("")); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test(timeout = 15000) - public void testCachableInterfaceInvalidate() throws Exception { - String query = "GLUD1"; - try { - String newRes = "hello"; - - waitForRefreshCacheQueueToEmpty(); - - cache.setCachedQuery(query, restService.getCacheType(), newRes); - String res = cache.getStringByQuery(query, restService.getCacheType()); - assertEquals(newRes, res); - cache.invalidateByQuery(query, restService.getCacheType()); - - waitForRefreshCacheQueueToEmpty(); - - res = cache.getStringByQuery(query, restService.getCacheType()); - - assertNotNull(res); - - assertFalse("Value wasn't refreshed from db", newRes.equals(res)); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testNameWithNewLine() throws Exception { - try { - String response = restService.getAnnotation(new MiriamData(MiriamType.HGNC_SYMBOL, "some\nname")); - assertNotNull(response); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testRefreshInvalidValue() throws Exception { - try { - restService.refreshCacheQuery(new Object()); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - assertTrue(e.getMessage().contains("Don't know what to do ")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testRefreshValueWhenProblemWithSource() throws Exception { - try { - BiocompendiumAnnotator annotatorUnderTest = new BiocompendiumAnnotator() { - @Override - Map<String, String> getAnnotationsFromXml(String xml) throws InvalidXmlSchemaException { - throw new InvalidXmlSchemaException(); - } - }; - annotatorUnderTest.refreshCacheQuery(camk4.getResource()); - fail("Exception expected"); - } catch (SourceNotAvailable e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testGetInvalidAnnotations() throws Exception { - try { - restService.getAnnotation(new MiriamData(MiriamType.WIKIPEDIA, "world")); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - - } - - @Test - public void testInvalidDataToStrubg() throws Exception { - try { - restService.dataToString(new MiriamData(MiriamType.WIKIPEDIA, "world")); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testGetAnnotationsFromInvaldXml() throws Exception { - try { - Map<String, String> map = restService.getAnnotationsFromXml(""); - assertEquals(0, map.size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testGetAnnotationsFromInvaldXml2() throws Exception { - try { - Map<String, String> map = restService.getAnnotationsFromXml(null); - assertEquals(0, map.size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } + Logger logger = Logger.getLogger(BiocompendiumAnnotatorTest.class); + + MiriamData camk4 = new MiriamData(MiriamType.HGNC_SYMBOL, "CAMK4"); + MiriamData slc25a27 = new MiriamData(MiriamType.HGNC_SYMBOL, "SLC25A27"); + MiriamData nsmf = new MiriamData(MiriamType.HGNC_SYMBOL, "NSMF"); + MiriamData mir449a = new MiriamData(MiriamType.HGNC_SYMBOL, "MIR449A"); + + @Autowired + private GeneralCacheInterface cache; + + @Autowired + private PermanentDatabaseLevelCacheInterface permanentDatabaseLevelCache; + + @Autowired + private BiocompendiumAnnotator restService; + + @Before + public void setUp() { + } + + @After + public void tearDown() throws Exception { + } + + @Test + @Ignore("Bug 32") + public void testGetAnnotationsForSpecies() throws Exception { + try { + String response = restService.getAnnotation(camk4); + assertNotNull(response); + assertTrue(response.contains("Symbol: CAMK4")); + + response = restService.getAnnotation(slc25a27); + assertNotNull(response); + + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testGetters() throws Exception { + try { + assertNotNull(restService.getCommonName()); + assertNotNull(restService.getUrl()); + + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testGetAnnotationsForInvalidMiriam() throws Exception { + try { + restService.getAnnotation(new MiriamData()); + fail("Exception expected"); + + } catch (InvalidArgumentException e) { + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testParseXml() throws Exception { + BufferedReader reader; + try { + reader = new BufferedReader(new FileReader("testFiles/annotation/sampleResponse.xml")); + String line = null; + StringBuilder stringBuilder = new StringBuilder(); + String ls = System.getProperty("line.separator"); + + while ((line = reader.readLine()) != null) { + stringBuilder.append(line); + stringBuilder.append(ls); + } + reader.close(); + + Map<String, String> res = restService.getAnnotationsFromXml(stringBuilder.toString()); + + assertEquals(2, res.keySet().size()); + String response = res.get("CAMK4"); + assertNotNull(response); + assertTrue(response.contains("Symbol: CAMK4")); + + assertNotNull(res.get("SLC25A27")); + + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test(timeout = 10000) + @Ignore("Bug 32") + public void testGetAnnotationsForMiceSpecies() throws Exception { + ArrayList<String> names = new ArrayList<String>(); + + names.add("Fmo3"); + names.add("Nqo1"); + names.add("Abcc12"); + names.add("Mgst3"); + names.add("Txnrd1"); + names.add("Cbr3"); + names.add("Hspa1b"); + names.add("Prdx1"); + names.add("Ppard"); + names.add("Tgfb2"); + names.add("Fth1"); + names.add("Prdx6"); + names.add("Nr4a1"); + names.add("Tgfb1"); + names.add("Abcc4"); + names.add("Ager"); + names.add("Gsr"); + names.add("Sod3"); + names.add("Maff"); + names.add("Eif2ak3"); + names.add("Tgfa"); + names.add("Hbegf"); + names.add("Mafg"); + names.add("Adh7"); + names.add("Slc7a11"); + names.add("Epha3"); + names.add("Blvrb"); + // problematic one + // names.add("Me1"); + names.add("Csnk2a2"); + names.add("Gpx3"); + names.add("Mapk8"); + names.add("Gclm"); + names.add("Epha2"); + names.add("Bdnf"); + // problematic one + // names.add("ACC2"); + names.add("Ptgr1"); + names.add("Pdgfb"); + names.add("Mapk7"); + names.add("Cbr1"); + names.add("Hsp90aa1"); + names.add("Pgd"); + names.add("Sqstm1"); + names.add("Aldh9a1"); + names.add("Txn"); + names.add("Txnrd3"); + names.add("Srxn1"); + names.add("Gpx2"); + names.add("Npas4"); + names.add("Mapk1"); + names.add("Nrg1"); + names.add("Cbr"); + names.add("Hspa1a"); + names.add("Mgst2"); + names.add("Tgfbr2"); + names.add("Ephx1"); + names.add("Dnajb1"); + names.add("Abcc2"); + names.add("Gclc"); + names.add("Abcc5"); + names.add("Ggt1"); + names.add("Ftl"); + names.add("Egr1"); + names.add("Fgf13"); + // problematic one + // names.add("Hgf"); + // problematic one + // names.add("UbcH7"); + names.add("Abcc3"); + names.add("Nfe2l2"); + // problematic one + // names.add("Hsp70"); + names.add("Hsp90ab1"); + + try { + for (int i = 0; i < names.size(); i++) { + String geneName = names.get(i); + String annotation = restService.getAnnotation(new MiriamData(MiriamType.HGNC_SYMBOL, geneName)); + assertNotNull("Problem with annotation of mouse gene: " + geneName, annotation); + assertTrue("Problem with annotation of mouse gene: " + geneName, !annotation.trim().equals("")); + } + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + @Ignore("Bug 451") + public void testGetAnnotationsForNSMF() throws Exception { + try { + String response = restService.getAnnotation(nsmf); + assertNotNull(response); + assertFalse(response.trim().equals("")); + + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + @Ignore("Bug 451") + public void testGetAnnotationsForMIR449A() throws Exception { + try { + String response = restService.getAnnotation(mir449a); + assertNotNull(response); + assertFalse(response.trim().equals("")); + + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test(timeout = 15000) + public void testCachableInterfaceInvalidate() throws Exception { + String query = "GLUD1"; + try { + String newRes = "hello"; + + cache.setCachedQuery(query, restService.getCacheType(), newRes); + String res = cache.getStringByQuery(query, restService.getCacheType()); + assertEquals(newRes, res); + cache.invalidateByQuery(query, restService.getCacheType()); + + permanentDatabaseLevelCache.waitToFinishTasks(); + + res = cache.getStringByQuery(query, restService.getCacheType()); + + assertNotNull(res); + + assertFalse("Value wasn't refreshed from db", newRes.equals(res)); + + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testNameWithNewLine() throws Exception { + try { + String response = restService.getAnnotation(new MiriamData(MiriamType.HGNC_SYMBOL, "some\nname")); + assertNotNull(response); + + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testRefreshInvalidValue() throws Exception { + try { + restService.refreshCacheQuery(new Object()); + fail("Exception expected"); + } catch (InvalidArgumentException e) { + assertTrue(e.getMessage().contains("Don't know what to do ")); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testRefreshValueWhenProblemWithSource() throws Exception { + try { + BiocompendiumAnnotator annotatorUnderTest = new BiocompendiumAnnotator() { + @Override + Map<String, String> getAnnotationsFromXml(String xml) throws InvalidXmlSchemaException { + throw new InvalidXmlSchemaException(); + } + }; + annotatorUnderTest.refreshCacheQuery(camk4.getResource()); + fail("Exception expected"); + } catch (SourceNotAvailable e) { + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testGetInvalidAnnotations() throws Exception { + try { + restService.getAnnotation(new MiriamData(MiriamType.WIKIPEDIA, "world")); + fail("Exception expected"); + } catch (InvalidArgumentException e) { + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + + } + + @Test + public void testInvalidDataToStrubg() throws Exception { + try { + restService.dataToString(new MiriamData(MiriamType.WIKIPEDIA, "world")); + fail("Exception expected"); + } catch (InvalidArgumentException e) { + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testGetAnnotationsFromInvaldXml() throws Exception { + try { + Map<String, String> map = restService.getAnnotationsFromXml(""); + assertEquals(0, map.size()); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testGetAnnotationsFromInvaldXml2() throws Exception { + try { + Map<String, String> map = restService.getAnnotationsFromXml(null); + assertEquals(0, map.size()); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } } diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/ChebiAnnotatorTest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/ChebiAnnotatorTest.java index e6918c2a94203528ef0d40c652477c130b618e3f..1f449c43e4b5e1e34b49f0b4b66b20c78a74e5be 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/ChebiAnnotatorTest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/ChebiAnnotatorTest.java @@ -6,9 +6,9 @@ import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.nullable; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.eq; import static org.mockito.Mockito.when; import java.util.List; @@ -22,6 +22,7 @@ import org.springframework.beans.factory.annotation.Autowired; import lcsb.mapviewer.annotation.AnnotationTestFunctions; import lcsb.mapviewer.annotation.cache.GeneralCacheInterface; +import lcsb.mapviewer.annotation.cache.PermanentDatabaseLevelCacheInterface; import lcsb.mapviewer.annotation.cache.SourceNotAvailable; import lcsb.mapviewer.annotation.data.Chebi; import lcsb.mapviewer.annotation.services.ExternalServiceStatusType; @@ -48,6 +49,9 @@ public class ChebiAnnotatorTest extends AnnotationTestFunctions { @Autowired private GeneralCacheInterface cache; + @Autowired + private PermanentDatabaseLevelCacheInterface permanentDatabaseLevelCache; + @Before public void setUp() throws Exception { } @@ -184,12 +188,10 @@ public class ChebiAnnotatorTest extends AnnotationTestFunctions { String query = "id: CHEBI:28423"; String newRes = "hello"; try { - waitForRefreshCacheQueueToEmpty(); - cache.setCachedQuery(query, backend.getCacheType(), newRes); cache.invalidateByQuery(query, backend.getCacheType()); - waitForRefreshCacheQueueToEmpty(); + permanentDatabaseLevelCache.waitToFinishTasks(); String res = cache.getStringByQuery(query, backend.getCacheType()); @@ -207,12 +209,10 @@ public class ChebiAnnotatorTest extends AnnotationTestFunctions { String query = "name: water"; String newRes = "hello"; try { - waitForRefreshCacheQueueToEmpty(); - cache.setCachedQuery(query, backend.getCacheType(), newRes); cache.invalidateByQuery(query, backend.getCacheType()); - waitForRefreshCacheQueueToEmpty(); + permanentDatabaseLevelCache.waitToFinishTasks(); String res = cache.getStringByQuery(query, backend.getCacheType()); @@ -271,8 +271,8 @@ public class ChebiAnnotatorTest extends AnnotationTestFunctions { res = backend.getOntologyChebiIdsForChebiName("h2o"); assertNotNull(res); assertTrue(res.size() > 1); - assertTrue( - res.contains(new MiriamData(MiriamRelationType.BQ_BIOL_IS_DESCRIBED_BY, MiriamType.CHEBI, "CHEBI:24431", ChebiAnnotator.class))); + assertTrue(res.contains(new MiriamData(MiriamRelationType.BQ_BIOL_IS_DESCRIBED_BY, MiriamType.CHEBI, + "CHEBI:24431", ChebiAnnotator.class))); } catch (Exception e) { e.printStackTrace(); throw e; diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/EnsemblAnnotatorTest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/EnsemblAnnotatorTest.java index a8e8f29254480817122ac985c6cb7fbce68a88b4..425cc3e45c73bff9b6198ba881e5b33671896a36 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/EnsemblAnnotatorTest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/EnsemblAnnotatorTest.java @@ -6,8 +6,8 @@ import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; +import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.nullable; -import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.when; import java.io.IOException; @@ -20,6 +20,8 @@ import org.springframework.beans.factory.annotation.Autowired; import lcsb.mapviewer.annotation.AnnotationTestFunctions; import lcsb.mapviewer.annotation.cache.GeneralCacheInterface; +import lcsb.mapviewer.annotation.cache.PermanentDatabaseLevelCache; +import lcsb.mapviewer.annotation.cache.PermanentDatabaseLevelCacheInterface; import lcsb.mapviewer.annotation.cache.SourceNotAvailable; import lcsb.mapviewer.annotation.cache.WebPageDownloader; import lcsb.mapviewer.annotation.services.ExternalServiceStatusType; @@ -32,315 +34,321 @@ import lcsb.mapviewer.model.map.species.Species; public class EnsemblAnnotatorTest extends AnnotationTestFunctions { - @Autowired - EnsemblAnnotator ensemblAnnotator; - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testGetAnnotationsForEnsemblId() throws Exception { - try { - MiriamData nsmf = new MiriamData(MiriamType.ENSEMBL, "ENSG00000157764"); - GenericProtein proteinAlias = new GenericProtein("id"); - proteinAlias.addMiriamData(nsmf); - ensemblAnnotator.annotateElement(proteinAlias); - assertNotNull(proteinAlias.getSymbol()); - assertNotNull(proteinAlias.getFullName()); - assertTrue(proteinAlias.getMiriamData().size() > 1); - assertTrue(proteinAlias.getSynonyms().size() > 0); - - boolean ensemble = false; - boolean hgncId = false; - boolean hgncSymbol = false; - boolean entrez = false; - for (MiriamData md : proteinAlias.getMiriamData()) { - if (MiriamType.ENSEMBL.equals(md.getDataType())) { - ensemble = true; - } else if (MiriamType.HGNC.equals(md.getDataType())) { - hgncId = true; - } else if (MiriamType.HGNC_SYMBOL.equals(md.getDataType())) { - hgncSymbol = true; - } else if (MiriamType.ENTREZ.equals(md.getDataType())) { - entrez = true; - } - } - - assertTrue("Ensemble symbol cannot be found", ensemble); - assertTrue("Hgnc id cannot be found", hgncId); - assertTrue("Hgnc symbol cannot be found", hgncSymbol); - assertTrue("Entrez cannot be found", entrez); - - assertEquals(0, getWarnings().size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testGetAnnotationsWhenMoreThanOneId() throws Exception { - try { - MiriamData nsmf = new MiriamData(MiriamType.ENSEMBL, "ENSG00000157764"); - MiriamData nsmf1 = new MiriamData(MiriamType.ENSEMBL, "ENSG00000157765"); - GenericProtein proteinAlias = new GenericProtein("id"); - proteinAlias.addMiriamData(nsmf); - proteinAlias.addMiriamData(nsmf1); - ensemblAnnotator.annotateElement(proteinAlias); - - assertEquals(1, getWarnings().size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testGetAnnotationsWhenNoIdFound() throws Exception { - try { - GenericProtein proteinAlias = new GenericProtein("id"); - ensemblAnnotator.annotateElement(proteinAlias); - - assertEquals(1, getWarnings().size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testGetAnnotationsForInvalid() throws Exception { - try { - MiriamData nsmf = new MiriamData(MiriamType.ENSEMBL, "blabla"); - GenericProtein proteinAlias = new GenericProtein("id"); - proteinAlias.addMiriamData(nsmf); - ensemblAnnotator.annotateElement(proteinAlias); - - assertEquals("There should be warning about invalid ensembl identifier", 1, getWarnings().size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test(timeout = 15000) - public void testCachableInterfaceInvalidate() throws Exception { - String query = "http://google.pl/"; - try { - String newRes = "hello"; - - waitForRefreshCacheQueueToEmpty(); - - cache.setCachedQuery(query, ensemblAnnotator.getCacheType(), newRes); - String res = cache.getStringByQuery(query, ensemblAnnotator.getCacheType()); - assertEquals(newRes, res); - cache.invalidateByQuery(query, ensemblAnnotator.getCacheType()); - - waitForRefreshCacheQueueToEmpty(); - - res = cache.getStringByQuery(query, ensemblAnnotator.getCacheType()); - - assertNotNull(res); - - assertFalse("Value wasn't refreshed from db", newRes.equals(res)); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testStatus() throws Exception { - try { - assertEquals(ExternalServiceStatusType.OK, ensemblAnnotator.getServiceStatus().getStatus()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testStatusDown() throws Exception { - WebPageDownloader downloader = ensemblAnnotator.getWebPageDownloader(); - GeneralCacheInterface originalCache = ensemblAnnotator.getCache(); - try { - // exclude first cached value - ensemblAnnotator.setCache(null); - - WebPageDownloader mockDownloader = Mockito.mock(WebPageDownloader.class); - when(mockDownloader.getFromNetwork(anyString(), anyString(), nullable(String.class))).thenThrow(new IOException()); - ensemblAnnotator.setWebPageDownloader(mockDownloader); - assertEquals(ExternalServiceStatusType.DOWN, ensemblAnnotator.getServiceStatus().getStatus()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } finally { - ensemblAnnotator.setWebPageDownloader(downloader); - ensemblAnnotator.setCache(originalCache); - } - } - - @Test - public void testStatusChanged() throws Exception { - WebPageDownloader downloader = ensemblAnnotator.getWebPageDownloader(); - GeneralCacheInterface originalCache = ensemblAnnotator.getCache(); - try { - // exclude first cached value - ensemblAnnotator.setCache(null); - - WebPageDownloader mockDownloader = Mockito.mock(WebPageDownloader.class); - String dataXml = "<opt></opt>"; - String versionXml = "<opt><data release=\"" + EnsemblAnnotator.SUPPORTED_VERSION + "\"/></opt>"; - when(mockDownloader.getFromNetwork(anyString(), anyString(), nullable(String.class))).thenReturn(dataXml).thenReturn(versionXml); - ensemblAnnotator.setWebPageDownloader(mockDownloader); - assertEquals(ExternalServiceStatusType.CHANGED, ensemblAnnotator.getServiceStatus().getStatus()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } finally { - ensemblAnnotator.setWebPageDownloader(downloader); - ensemblAnnotator.setCache(originalCache); - } - } - - @Test - public void testStatusChanged2() throws Exception { - WebPageDownloader downloader = ensemblAnnotator.getWebPageDownloader(); - GeneralCacheInterface originalCache = ensemblAnnotator.getCache(); - try { - // exclude first cached value - ensemblAnnotator.setCache(null); - - WebPageDownloader mockDownloader = Mockito.mock(WebPageDownloader.class); - String dataXml = "<opt></opt>"; - String versionXml = "<opt><data release=\"blablabla\"/></opt>"; - when(mockDownloader.getFromNetwork(anyString(), anyString(), nullable(String.class))).thenReturn(dataXml).thenReturn(versionXml); - ensemblAnnotator.setWebPageDownloader(mockDownloader); - assertEquals(ExternalServiceStatusType.CHANGED, ensemblAnnotator.getServiceStatus().getStatus()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } finally { - ensemblAnnotator.setWebPageDownloader(downloader); - ensemblAnnotator.setCache(originalCache); - } - } - - @Test - public void testEnsemblToEntrez() throws Exception { - try { - MiriamData ensembl = new MiriamData(MiriamType.ENSEMBL, "ENSG00000154930"); - MiriamData entrez = ensemblAnnotator.ensemblIdToEntrezId(ensembl); - assertEquals(new MiriamData(MiriamType.ENTREZ, "84532", EnsemblAnnotator.class), entrez); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testInvalidEnsemblToEntrez() throws Exception { - try { - MiriamData ensembl = new MiriamData(MiriamType.WIKIPEDIA, "ENSG00000154930"); - ensemblAnnotator.ensemblIdToEntrezId(ensembl); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testEnsemblToEntrez2() throws Exception { - try { - MiriamData ensembl = new MiriamData(MiriamType.ENSEMBL, "ENSRNOG00000050619"); - MiriamData entrez = ensemblAnnotator.ensemblIdToEntrezId(ensembl); - assertNull(entrez); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testAnnotateWhenEntrezReturnWrongResponse() throws Exception { - WebPageDownloader downloader = ensemblAnnotator.getWebPageDownloader(); - try { - WebPageDownloader mockDownloader = Mockito.mock(WebPageDownloader.class); - when(mockDownloader.getFromNetwork(anyString(), anyString(), nullable(String.class))).thenThrow(new WrongResponseCodeIOException(null, 0)); - ensemblAnnotator.setWebPageDownloader(mockDownloader); - Species proteinAlias = new GenericProtein("id"); - proteinAlias.addMiriamData(new MiriamData(MiriamType.ENSEMBL, "1234")); - ensemblAnnotator.annotateElement(proteinAlias); - assertEquals(1, getWarnings().size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } finally { - ensemblAnnotator.setWebPageDownloader(downloader); - } - } - - @Test - public void testRefreshCacheQueryNotAvailable() throws Exception { - WebPageDownloader downloader = ensemblAnnotator.getWebPageDownloader(); - GeneralCacheInterface originalCache = ensemblAnnotator.getCache(); - try { - // exclude first cached value - ensemblAnnotator.setCache(null); - - WebPageDownloader mockDownloader = Mockito.mock(WebPageDownloader.class); - when(mockDownloader.getFromNetwork(anyString(), anyString(), nullable(String.class))).thenThrow(new IOException()); - ensemblAnnotator.setWebPageDownloader(mockDownloader); - ensemblAnnotator.refreshCacheQuery("http://google.pl/"); - fail("Exception expected"); - } catch (SourceNotAvailable e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } finally { - ensemblAnnotator.setWebPageDownloader(downloader); - ensemblAnnotator.setCache(originalCache); - } - } - - @Test - public void testRefreshInvalidCacheQuery() throws Exception { - try { - ensemblAnnotator.refreshCacheQuery("invalid_query"); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - assertTrue(e.getMessage().contains("Don't know what to do")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testRefreshInvalidCacheQuery2() throws Exception { - try { - ensemblAnnotator.refreshCacheQuery(new Object()); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - assertTrue(e.getMessage().contains("Don't know what to do")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } + @Autowired + EnsemblAnnotator ensemblAnnotator; + + @Autowired + private PermanentDatabaseLevelCacheInterface permanentDatabaseLevelCache; + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testGetAnnotationsForEnsemblId() throws Exception { + try { + MiriamData nsmf = new MiriamData(MiriamType.ENSEMBL, "ENSG00000157764"); + GenericProtein proteinAlias = new GenericProtein("id"); + proteinAlias.addMiriamData(nsmf); + ensemblAnnotator.annotateElement(proteinAlias); + assertNotNull(proteinAlias.getSymbol()); + assertNotNull(proteinAlias.getFullName()); + assertTrue(proteinAlias.getMiriamData().size() > 1); + assertTrue(proteinAlias.getSynonyms().size() > 0); + + boolean ensemble = false; + boolean hgncId = false; + boolean hgncSymbol = false; + boolean entrez = false; + for (MiriamData md : proteinAlias.getMiriamData()) { + if (MiriamType.ENSEMBL.equals(md.getDataType())) { + ensemble = true; + } else if (MiriamType.HGNC.equals(md.getDataType())) { + hgncId = true; + } else if (MiriamType.HGNC_SYMBOL.equals(md.getDataType())) { + hgncSymbol = true; + } else if (MiriamType.ENTREZ.equals(md.getDataType())) { + entrez = true; + } + } + + assertTrue("Ensemble symbol cannot be found", ensemble); + assertTrue("Hgnc id cannot be found", hgncId); + assertTrue("Hgnc symbol cannot be found", hgncSymbol); + assertTrue("Entrez cannot be found", entrez); + + assertEquals(0, getWarnings().size()); + + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testGetAnnotationsWhenMoreThanOneId() throws Exception { + try { + MiriamData nsmf = new MiriamData(MiriamType.ENSEMBL, "ENSG00000157764"); + MiriamData nsmf1 = new MiriamData(MiriamType.ENSEMBL, "ENSG00000157765"); + GenericProtein proteinAlias = new GenericProtein("id"); + proteinAlias.addMiriamData(nsmf); + proteinAlias.addMiriamData(nsmf1); + ensemblAnnotator.annotateElement(proteinAlias); + + assertEquals(1, getWarnings().size()); + + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testGetAnnotationsWhenNoIdFound() throws Exception { + try { + GenericProtein proteinAlias = new GenericProtein("id"); + ensemblAnnotator.annotateElement(proteinAlias); + + assertEquals(1, getWarnings().size()); + + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testGetAnnotationsForInvalid() throws Exception { + try { + MiriamData nsmf = new MiriamData(MiriamType.ENSEMBL, "blabla"); + GenericProtein proteinAlias = new GenericProtein("id"); + proteinAlias.addMiriamData(nsmf); + ensemblAnnotator.annotateElement(proteinAlias); + + assertEquals("There should be warning about invalid ensembl identifier", 1, getWarnings().size()); + + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test(timeout = 15000) + public void testCachableInterfaceInvalidate() throws Exception { + String query = "http://google.pl/"; + try { + String newRes = "hello"; + + cache.setCachedQuery(query, ensemblAnnotator.getCacheType(), newRes); + String res = cache.getStringByQuery(query, ensemblAnnotator.getCacheType()); + assertEquals(newRes, res); + cache.invalidateByQuery(query, ensemblAnnotator.getCacheType()); + + permanentDatabaseLevelCache.waitToFinishTasks(); + + res = cache.getStringByQuery(query, ensemblAnnotator.getCacheType()); + + assertNotNull(res); + + assertFalse("Value wasn't refreshed from db", newRes.equals(res)); + + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testStatus() throws Exception { + try { + assertEquals(ExternalServiceStatusType.OK, ensemblAnnotator.getServiceStatus().getStatus()); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testStatusDown() throws Exception { + WebPageDownloader downloader = ensemblAnnotator.getWebPageDownloader(); + GeneralCacheInterface originalCache = ensemblAnnotator.getCache(); + try { + // exclude first cached value + ensemblAnnotator.setCache(null); + + WebPageDownloader mockDownloader = Mockito.mock(WebPageDownloader.class); + when(mockDownloader.getFromNetwork(anyString(), anyString(), nullable(String.class))) + .thenThrow(new IOException()); + ensemblAnnotator.setWebPageDownloader(mockDownloader); + assertEquals(ExternalServiceStatusType.DOWN, ensemblAnnotator.getServiceStatus().getStatus()); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } finally { + ensemblAnnotator.setWebPageDownloader(downloader); + ensemblAnnotator.setCache(originalCache); + } + } + + @Test + public void testStatusChanged() throws Exception { + WebPageDownloader downloader = ensemblAnnotator.getWebPageDownloader(); + GeneralCacheInterface originalCache = ensemblAnnotator.getCache(); + try { + // exclude first cached value + ensemblAnnotator.setCache(null); + + WebPageDownloader mockDownloader = Mockito.mock(WebPageDownloader.class); + String dataXml = "<opt></opt>"; + String versionXml = "<opt><data release=\"" + EnsemblAnnotator.SUPPORTED_VERSION + "\"/></opt>"; + when(mockDownloader.getFromNetwork(anyString(), anyString(), nullable(String.class))).thenReturn(dataXml) + .thenReturn(versionXml); + ensemblAnnotator.setWebPageDownloader(mockDownloader); + assertEquals(ExternalServiceStatusType.CHANGED, ensemblAnnotator.getServiceStatus().getStatus()); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } finally { + ensemblAnnotator.setWebPageDownloader(downloader); + ensemblAnnotator.setCache(originalCache); + } + } + + @Test + public void testStatusChanged2() throws Exception { + WebPageDownloader downloader = ensemblAnnotator.getWebPageDownloader(); + GeneralCacheInterface originalCache = ensemblAnnotator.getCache(); + try { + // exclude first cached value + ensemblAnnotator.setCache(null); + + WebPageDownloader mockDownloader = Mockito.mock(WebPageDownloader.class); + String dataXml = "<opt></opt>"; + String versionXml = "<opt><data release=\"blablabla\"/></opt>"; + when(mockDownloader.getFromNetwork(anyString(), anyString(), nullable(String.class))).thenReturn(dataXml) + .thenReturn(versionXml); + ensemblAnnotator.setWebPageDownloader(mockDownloader); + assertEquals(ExternalServiceStatusType.CHANGED, ensemblAnnotator.getServiceStatus().getStatus()); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } finally { + ensemblAnnotator.setWebPageDownloader(downloader); + ensemblAnnotator.setCache(originalCache); + } + } + + @Test + public void testEnsemblToEntrez() throws Exception { + try { + MiriamData ensembl = new MiriamData(MiriamType.ENSEMBL, "ENSG00000154930"); + MiriamData entrez = ensemblAnnotator.ensemblIdToEntrezId(ensembl); + assertEquals(new MiriamData(MiriamType.ENTREZ, "84532", EnsemblAnnotator.class), entrez); + + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testInvalidEnsemblToEntrez() throws Exception { + try { + MiriamData ensembl = new MiriamData(MiriamType.WIKIPEDIA, "ENSG00000154930"); + ensemblAnnotator.ensemblIdToEntrezId(ensembl); + fail("Exception expected"); + } catch (InvalidArgumentException e) { + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testEnsemblToEntrez2() throws Exception { + try { + MiriamData ensembl = new MiriamData(MiriamType.ENSEMBL, "ENSRNOG00000050619"); + MiriamData entrez = ensemblAnnotator.ensemblIdToEntrezId(ensembl); + assertNull(entrez); + + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testAnnotateWhenEntrezReturnWrongResponse() throws Exception { + WebPageDownloader downloader = ensemblAnnotator.getWebPageDownloader(); + try { + WebPageDownloader mockDownloader = Mockito.mock(WebPageDownloader.class); + when(mockDownloader.getFromNetwork(anyString(), anyString(), nullable(String.class))) + .thenThrow(new WrongResponseCodeIOException(null, 0)); + ensemblAnnotator.setWebPageDownloader(mockDownloader); + Species proteinAlias = new GenericProtein("id"); + proteinAlias.addMiriamData(new MiriamData(MiriamType.ENSEMBL, "1234")); + ensemblAnnotator.annotateElement(proteinAlias); + assertEquals(1, getWarnings().size()); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } finally { + ensemblAnnotator.setWebPageDownloader(downloader); + } + } + + @Test + public void testRefreshCacheQueryNotAvailable() throws Exception { + WebPageDownloader downloader = ensemblAnnotator.getWebPageDownloader(); + GeneralCacheInterface originalCache = ensemblAnnotator.getCache(); + try { + // exclude first cached value + ensemblAnnotator.setCache(null); + + WebPageDownloader mockDownloader = Mockito.mock(WebPageDownloader.class); + when(mockDownloader.getFromNetwork(anyString(), anyString(), nullable(String.class))) + .thenThrow(new IOException()); + ensemblAnnotator.setWebPageDownloader(mockDownloader); + ensemblAnnotator.refreshCacheQuery("http://google.pl/"); + fail("Exception expected"); + } catch (SourceNotAvailable e) { + } catch (Exception e) { + e.printStackTrace(); + throw e; + } finally { + ensemblAnnotator.setWebPageDownloader(downloader); + ensemblAnnotator.setCache(originalCache); + } + } + + @Test + public void testRefreshInvalidCacheQuery() throws Exception { + try { + ensemblAnnotator.refreshCacheQuery("invalid_query"); + fail("Exception expected"); + } catch (InvalidArgumentException e) { + assertTrue(e.getMessage().contains("Don't know what to do")); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testRefreshInvalidCacheQuery2() throws Exception { + try { + ensemblAnnotator.refreshCacheQuery(new Object()); + fail("Exception expected"); + } catch (InvalidArgumentException e) { + assertTrue(e.getMessage().contains("Don't know what to do")); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } } diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/EntrezAnnotatorTest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/EntrezAnnotatorTest.java index ba9a84e9c53d96492199d08b5a542ae079319263..64856c9ed81ffbef0a4605c31d72ec8711518cc5 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/EntrezAnnotatorTest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/EntrezAnnotatorTest.java @@ -6,9 +6,9 @@ import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.nullable; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.when; import java.io.IOException; @@ -21,7 +21,7 @@ import org.springframework.beans.factory.annotation.Autowired; import lcsb.mapviewer.annotation.AnnotationTestFunctions; import lcsb.mapviewer.annotation.cache.GeneralCacheInterface; -import lcsb.mapviewer.annotation.cache.GeneralCacheWithExclusion; +import lcsb.mapviewer.annotation.cache.PermanentDatabaseLevelCacheInterface; import lcsb.mapviewer.annotation.cache.SourceNotAvailable; import lcsb.mapviewer.annotation.cache.WebPageDownloader; import lcsb.mapviewer.annotation.cache.XmlSerializer; @@ -36,386 +36,392 @@ import lcsb.mapviewer.model.map.species.Species; public class EntrezAnnotatorTest extends AnnotationTestFunctions { - @Autowired - EntrezAnnotator entrezAnnotator; - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testGetAnnotationsForEntrezId() throws Exception { - try { - MiriamData nsmf = new MiriamData(MiriamType.ENTREZ, "6647"); - GenericProtein proteinAlias = new GenericProtein("id"); - proteinAlias.addMiriamData(nsmf); - entrezAnnotator.annotateElement(proteinAlias); - assertNotNull(proteinAlias.getSymbol()); - assertNotNull(proteinAlias.getFullName()); - assertNotNull(proteinAlias.getNotes()); - assertFalse(proteinAlias.getNotes().isEmpty()); - assertTrue(proteinAlias.getMiriamData().size() > 1); - assertTrue(proteinAlias.getSynonyms().size() > 0); - - boolean ensemble = false; - boolean hgncId = false; - boolean entrez = false; - for (MiriamData md : proteinAlias.getMiriamData()) { - if (MiriamType.ENSEMBL.equals(md.getDataType())) { - ensemble = true; - } else if (MiriamType.HGNC.equals(md.getDataType())) { - hgncId = true; - } else if (MiriamType.ENTREZ.equals(md.getDataType())) { - entrez = true; - } - } - - assertTrue("Ensemble symbol cannot be found", ensemble); - assertTrue("Hgnc id cannot be found", hgncId); - assertTrue("Entrez cannot be found", entrez); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test(timeout = 15000) - public void testGetAnnotationsForInvalid() throws Exception { - try { - MiriamData nsmf = new MiriamData(MiriamType.ENTREZ, "blabla"); - GenericProtein proteinAlias = new GenericProtein("id"); - proteinAlias.addMiriamData(nsmf); - entrezAnnotator.annotateElement(proteinAlias); - - assertEquals(1, getWarnings().size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test(timeout = 15000) - public void testCachableInterfaceInvalidate() throws Exception { - String query = "http://google.pl/"; - try { - String newRes = "hello"; - - waitForRefreshCacheQueueToEmpty(); - - cache.setCachedQuery(query, entrezAnnotator.getCacheType(), newRes); - String res = cache.getStringByQuery(query, entrezAnnotator.getCacheType()); - assertEquals(newRes, res); - cache.invalidateByQuery(query, entrezAnnotator.getCacheType()); - - waitForRefreshCacheQueueToEmpty(); - - res = cache.getStringByQuery(query, entrezAnnotator.getCacheType()); - - assertNotNull(res); - - assertFalse("Value wasn't refreshed from db", newRes.equals(res)); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testStatus() throws Exception { - try { - assertEquals(ExternalServiceStatusType.OK, entrezAnnotator.getServiceStatus().getStatus()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testSimulateDownStatus() throws Exception { - WebPageDownloader downloader = entrezAnnotator.getWebPageDownloader(); - try { - WebPageDownloader mockDownloader = Mockito.mock(WebPageDownloader.class); - when(mockDownloader.getFromNetwork(anyString(), anyString(), nullable(String.class))).thenThrow(new IOException()); - entrezAnnotator.setWebPageDownloader(mockDownloader); - assertEquals(ExternalServiceStatusType.DOWN, entrezAnnotator.getServiceStatus().getStatus()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } finally { - entrezAnnotator.setWebPageDownloader(downloader); - } - } - - @Test - public void testSimulateChangedStatus() throws Exception { - XmlSerializer<EntrezData> entrezSerializer = entrezAnnotator.getEntrezSerializer(); - try { - @SuppressWarnings("unchecked") - XmlSerializer<EntrezData> mockSerializer = Mockito.mock(XmlSerializer.class); - when(mockSerializer.xmlToObject(any())).thenReturn(new EntrezData()); - entrezAnnotator.setEntrezSerializer(mockSerializer); - assertEquals(ExternalServiceStatusType.CHANGED, entrezAnnotator.getServiceStatus().getStatus()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } finally { - entrezAnnotator.setEntrezSerializer(entrezSerializer); - } - } - - @Test - public void testGetHgncFromEntrez() throws Exception { - try { - assertEquals(new MiriamData(MiriamType.HGNC, "11179", EntrezAnnotator.class), entrezAnnotator.getHgncIdFromEntrez(new MiriamData(MiriamType.ENTREZ, "6647", EntrezAnnotator.class))); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testGetHgncFromEntrezForInvalidId() throws Exception { - try { - assertNull(entrezAnnotator.getHgncIdFromEntrez(new MiriamData(MiriamType.ENTREZ, "664711111"))); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testGetHgncFromEntrezForInvalidId1() throws Exception { - try { - entrezAnnotator.getHgncIdFromEntrez(new MiriamData(MiriamType.WIKIPEDIA, "664711111")); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test(timeout = 15000) - public void testRefreshToHgncConversion() throws Exception { - GeneralCacheInterface cache = entrezAnnotator.getCache(); - try { - entrezAnnotator.setCache(null); - assertNull(entrezAnnotator.refreshCacheQuery(EntrezAnnotator.CACHE_HGNC_ID_PREFIX + "blablabla")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } finally { - entrezAnnotator.setCache(cache); - } - } - - @Test(timeout = 60000) - public void testRefreshToHgncConversion2() throws Exception { - try { - assertNotNull(entrezAnnotator.refreshCacheQuery(EntrezAnnotator.CACHE_HGNC_ID_PREFIX + "6647")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testRefreshInvalidCacheQuery() throws Exception { - try { - entrezAnnotator.refreshCacheQuery("invalid_query"); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - assertTrue(e.getMessage().contains("Don't know what to do")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testRefreshInvalidCacheQuery2() throws Exception { - try { - entrezAnnotator.refreshCacheQuery(new Object()); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - assertTrue(e.getMessage().contains("Don't know what to do")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test(timeout = 15000) - public void testRefreshEntrezData() throws Exception { - try { - assertNotNull(entrezAnnotator.refreshCacheQuery(EntrezAnnotator.ENTREZ_DATA_PREFIX + "6647")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testRefreshCacheQueryNotAvailable() throws Exception { - WebPageDownloader downloader = entrezAnnotator.getWebPageDownloader(); - GeneralCacheInterface originalCache = entrezAnnotator.getCache(); - try { - // exclude first cached value - entrezAnnotator.setCache(null); - - WebPageDownloader mockDownloader = Mockito.mock(WebPageDownloader.class); - when(mockDownloader.getFromNetwork(anyString(), anyString(), nullable(String.class))).thenThrow(new IOException()); - entrezAnnotator.setWebPageDownloader(mockDownloader); - entrezAnnotator.refreshCacheQuery("http://google.pl/"); - fail("Exception expected"); - } catch (SourceNotAvailable e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } finally { - entrezAnnotator.setWebPageDownloader(downloader); - entrezAnnotator.setCache(originalCache); - } - } - - @Test - public void testRefreshCacheQueryWithInvalidEntrezServerResponse() throws Exception { - WebPageDownloader downloader = entrezAnnotator.getWebPageDownloader(); - GeneralCacheInterface originalCache = entrezAnnotator.getCache(); - try { - // exclude first cached value - entrezAnnotator.setCache(null); - - WebPageDownloader mockDownloader = Mockito.mock(WebPageDownloader.class); - when(mockDownloader.getFromNetwork(anyString(), anyString(), nullable(String.class))).thenThrow(new IOException()); - entrezAnnotator.setWebPageDownloader(mockDownloader); - entrezAnnotator.refreshCacheQuery(EntrezAnnotator.ENTREZ_DATA_PREFIX + "6647"); - fail("Exception expected"); - } catch (SourceNotAvailable e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } finally { - entrezAnnotator.setWebPageDownloader(downloader); - entrezAnnotator.setCache(originalCache); - } - } - - @Test - public void testAnnotateElementWithoutId() throws Exception { - try { - GenericProtein proteinAlias = new GenericProtein("id"); - entrezAnnotator.annotateElement(proteinAlias); - - assertEquals(1, getWarnings().size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testAnnotateElementWithTwoEntrez() throws Exception { - try { - Species proteinAlias = new GenericProtein("id"); - proteinAlias.addMiriamData(new MiriamData(MiriamType.ENTREZ, "6647")); - proteinAlias.addMiriamData(new MiriamData(MiriamType.ENTREZ, "6648")); - entrezAnnotator.annotateElement(proteinAlias); - - assertEquals(1, getWarnings().size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testParseEntrezResponse() throws Exception { - WebPageDownloader downloader = entrezAnnotator.getWebPageDownloader(); - GeneralCacheInterface cache = entrezAnnotator.getCache(); - try { - entrezAnnotator.setCache(null); - String response = super.readFile("testFiles/annotation/entrezResponse.xml"); - WebPageDownloader mockDownloader = Mockito.mock(WebPageDownloader.class); - when(mockDownloader.getFromNetwork(anyString(), anyString(), nullable(String.class))).thenReturn(response); - entrezAnnotator.setWebPageDownloader(mockDownloader); - EntrezData data = entrezAnnotator.getEntrezForMiriamData(new MiriamData(), ""); - boolean ensembl = false; - boolean hgnc = false; - for (MiriamData md : data.getMiriamData()) { - if (md.getDataType().equals(MiriamType.HGNC)) { - hgnc = true; - } - if (md.getDataType().equals(MiriamType.ENSEMBL)) { - ensembl = true; - } - } - assertTrue(ensembl); - assertTrue(hgnc); - assertNotNull(data.getDescription()); - assertFalse(data.getDescription().isEmpty()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } finally { - entrezAnnotator.setWebPageDownloader(downloader); - entrezAnnotator.setCache(cache); - } - } - - @Test - public void testParseInvalidEntrezResponse() throws Exception { - WebPageDownloader downloader = entrezAnnotator.getWebPageDownloader(); - GeneralCacheInterface cache = entrezAnnotator.getCache(); - try { - entrezAnnotator.setCache(null); - String response = ""; - WebPageDownloader mockDownloader = Mockito.mock(WebPageDownloader.class); - when(mockDownloader.getFromNetwork(anyString(), anyString(), nullable(String.class))).thenReturn(response); - entrezAnnotator.setWebPageDownloader(mockDownloader); - entrezAnnotator.getEntrezForMiriamData(new MiriamData(), ""); - fail("Exception expected"); - } catch (AnnotatorException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } finally { - entrezAnnotator.setWebPageDownloader(downloader); - entrezAnnotator.setCache(cache); - } - - } - - @Test - public void testParseInvalidEntrezResponse2() throws Exception { - WebPageDownloader downloader = entrezAnnotator.getWebPageDownloader(); - GeneralCacheInterface cache = entrezAnnotator.getCache(); - try { - entrezAnnotator.setCache(null); - WebPageDownloader mockDownloader = Mockito.mock(WebPageDownloader.class); - when(mockDownloader.getFromNetwork(anyString(), anyString(), nullable(String.class))).thenThrow(new WrongResponseCodeIOException(null, 404)); - entrezAnnotator.setWebPageDownloader(mockDownloader); - entrezAnnotator.getEntrezForMiriamData(new MiriamData(), ""); - fail("Exception expected"); - } catch (AnnotatorException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } finally { - entrezAnnotator.setWebPageDownloader(downloader); - entrezAnnotator.setCache(cache); - } - - } + @Autowired + EntrezAnnotator entrezAnnotator; + + @Autowired + private PermanentDatabaseLevelCacheInterface permanentDatabaseLevelCache; + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testGetAnnotationsForEntrezId() throws Exception { + try { + MiriamData nsmf = new MiriamData(MiriamType.ENTREZ, "6647"); + GenericProtein proteinAlias = new GenericProtein("id"); + proteinAlias.addMiriamData(nsmf); + entrezAnnotator.annotateElement(proteinAlias); + assertNotNull(proteinAlias.getSymbol()); + assertNotNull(proteinAlias.getFullName()); + assertNotNull(proteinAlias.getNotes()); + assertFalse(proteinAlias.getNotes().isEmpty()); + assertTrue(proteinAlias.getMiriamData().size() > 1); + assertTrue(proteinAlias.getSynonyms().size() > 0); + + boolean ensemble = false; + boolean hgncId = false; + boolean entrez = false; + for (MiriamData md : proteinAlias.getMiriamData()) { + if (MiriamType.ENSEMBL.equals(md.getDataType())) { + ensemble = true; + } else if (MiriamType.HGNC.equals(md.getDataType())) { + hgncId = true; + } else if (MiriamType.ENTREZ.equals(md.getDataType())) { + entrez = true; + } + } + + assertTrue("Ensemble symbol cannot be found", ensemble); + assertTrue("Hgnc id cannot be found", hgncId); + assertTrue("Entrez cannot be found", entrez); + + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test(timeout = 15000) + public void testGetAnnotationsForInvalid() throws Exception { + try { + MiriamData nsmf = new MiriamData(MiriamType.ENTREZ, "blabla"); + GenericProtein proteinAlias = new GenericProtein("id"); + proteinAlias.addMiriamData(nsmf); + entrezAnnotator.annotateElement(proteinAlias); + + assertEquals(1, getWarnings().size()); + + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test(timeout = 15000) + public void testCachableInterfaceInvalidate() throws Exception { + String query = "http://google.pl/"; + try { + String newRes = "hello"; + + cache.setCachedQuery(query, entrezAnnotator.getCacheType(), newRes); + String res = cache.getStringByQuery(query, entrezAnnotator.getCacheType()); + assertEquals(newRes, res); + cache.invalidateByQuery(query, entrezAnnotator.getCacheType()); + + permanentDatabaseLevelCache.waitToFinishTasks(); + + res = cache.getStringByQuery(query, entrezAnnotator.getCacheType()); + + assertNotNull(res); + + assertFalse("Value wasn't refreshed from db", newRes.equals(res)); + + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testStatus() throws Exception { + try { + assertEquals(ExternalServiceStatusType.OK, entrezAnnotator.getServiceStatus().getStatus()); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testSimulateDownStatus() throws Exception { + WebPageDownloader downloader = entrezAnnotator.getWebPageDownloader(); + try { + WebPageDownloader mockDownloader = Mockito.mock(WebPageDownloader.class); + when(mockDownloader.getFromNetwork(anyString(), anyString(), nullable(String.class))) + .thenThrow(new IOException()); + entrezAnnotator.setWebPageDownloader(mockDownloader); + assertEquals(ExternalServiceStatusType.DOWN, entrezAnnotator.getServiceStatus().getStatus()); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } finally { + entrezAnnotator.setWebPageDownloader(downloader); + } + } + + @Test + public void testSimulateChangedStatus() throws Exception { + XmlSerializer<EntrezData> entrezSerializer = entrezAnnotator.getEntrezSerializer(); + try { + @SuppressWarnings("unchecked") + XmlSerializer<EntrezData> mockSerializer = Mockito.mock(XmlSerializer.class); + when(mockSerializer.xmlToObject(any())).thenReturn(new EntrezData()); + entrezAnnotator.setEntrezSerializer(mockSerializer); + assertEquals(ExternalServiceStatusType.CHANGED, entrezAnnotator.getServiceStatus().getStatus()); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } finally { + entrezAnnotator.setEntrezSerializer(entrezSerializer); + } + } + + @Test + public void testGetHgncFromEntrez() throws Exception { + try { + assertEquals(new MiriamData(MiriamType.HGNC, "11179", EntrezAnnotator.class), + entrezAnnotator.getHgncIdFromEntrez(new MiriamData(MiriamType.ENTREZ, "6647", EntrezAnnotator.class))); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testGetHgncFromEntrezForInvalidId() throws Exception { + try { + assertNull(entrezAnnotator.getHgncIdFromEntrez(new MiriamData(MiriamType.ENTREZ, "664711111"))); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testGetHgncFromEntrezForInvalidId1() throws Exception { + try { + entrezAnnotator.getHgncIdFromEntrez(new MiriamData(MiriamType.WIKIPEDIA, "664711111")); + fail("Exception expected"); + } catch (InvalidArgumentException e) { + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test(timeout = 15000) + public void testRefreshToHgncConversion() throws Exception { + GeneralCacheInterface cache = entrezAnnotator.getCache(); + try { + entrezAnnotator.setCache(null); + assertNull(entrezAnnotator.refreshCacheQuery(EntrezAnnotator.CACHE_HGNC_ID_PREFIX + "blablabla")); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } finally { + entrezAnnotator.setCache(cache); + } + } + + @Test(timeout = 60000) + public void testRefreshToHgncConversion2() throws Exception { + try { + assertNotNull(entrezAnnotator.refreshCacheQuery(EntrezAnnotator.CACHE_HGNC_ID_PREFIX + "6647")); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testRefreshInvalidCacheQuery() throws Exception { + try { + entrezAnnotator.refreshCacheQuery("invalid_query"); + fail("Exception expected"); + } catch (InvalidArgumentException e) { + assertTrue(e.getMessage().contains("Don't know what to do")); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testRefreshInvalidCacheQuery2() throws Exception { + try { + entrezAnnotator.refreshCacheQuery(new Object()); + fail("Exception expected"); + } catch (InvalidArgumentException e) { + assertTrue(e.getMessage().contains("Don't know what to do")); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test(timeout = 15000) + public void testRefreshEntrezData() throws Exception { + try { + assertNotNull(entrezAnnotator.refreshCacheQuery(EntrezAnnotator.ENTREZ_DATA_PREFIX + "6647")); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testRefreshCacheQueryNotAvailable() throws Exception { + WebPageDownloader downloader = entrezAnnotator.getWebPageDownloader(); + GeneralCacheInterface originalCache = entrezAnnotator.getCache(); + try { + // exclude first cached value + entrezAnnotator.setCache(null); + + WebPageDownloader mockDownloader = Mockito.mock(WebPageDownloader.class); + when(mockDownloader.getFromNetwork(anyString(), anyString(), nullable(String.class))) + .thenThrow(new IOException()); + entrezAnnotator.setWebPageDownloader(mockDownloader); + entrezAnnotator.refreshCacheQuery("http://google.pl/"); + fail("Exception expected"); + } catch (SourceNotAvailable e) { + } catch (Exception e) { + e.printStackTrace(); + throw e; + } finally { + entrezAnnotator.setWebPageDownloader(downloader); + entrezAnnotator.setCache(originalCache); + } + } + + @Test + public void testRefreshCacheQueryWithInvalidEntrezServerResponse() throws Exception { + WebPageDownloader downloader = entrezAnnotator.getWebPageDownloader(); + GeneralCacheInterface originalCache = entrezAnnotator.getCache(); + try { + // exclude first cached value + entrezAnnotator.setCache(null); + + WebPageDownloader mockDownloader = Mockito.mock(WebPageDownloader.class); + when(mockDownloader.getFromNetwork(anyString(), anyString(), nullable(String.class))) + .thenThrow(new IOException()); + entrezAnnotator.setWebPageDownloader(mockDownloader); + entrezAnnotator.refreshCacheQuery(EntrezAnnotator.ENTREZ_DATA_PREFIX + "6647"); + fail("Exception expected"); + } catch (SourceNotAvailable e) { + } catch (Exception e) { + e.printStackTrace(); + throw e; + } finally { + entrezAnnotator.setWebPageDownloader(downloader); + entrezAnnotator.setCache(originalCache); + } + } + + @Test + public void testAnnotateElementWithoutId() throws Exception { + try { + GenericProtein proteinAlias = new GenericProtein("id"); + entrezAnnotator.annotateElement(proteinAlias); + + assertEquals(1, getWarnings().size()); + + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testAnnotateElementWithTwoEntrez() throws Exception { + try { + Species proteinAlias = new GenericProtein("id"); + proteinAlias.addMiriamData(new MiriamData(MiriamType.ENTREZ, "6647")); + proteinAlias.addMiriamData(new MiriamData(MiriamType.ENTREZ, "6648")); + entrezAnnotator.annotateElement(proteinAlias); + + assertEquals(1, getWarnings().size()); + + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testParseEntrezResponse() throws Exception { + WebPageDownloader downloader = entrezAnnotator.getWebPageDownloader(); + GeneralCacheInterface cache = entrezAnnotator.getCache(); + try { + entrezAnnotator.setCache(null); + String response = super.readFile("testFiles/annotation/entrezResponse.xml"); + WebPageDownloader mockDownloader = Mockito.mock(WebPageDownloader.class); + when(mockDownloader.getFromNetwork(anyString(), anyString(), nullable(String.class))).thenReturn(response); + entrezAnnotator.setWebPageDownloader(mockDownloader); + EntrezData data = entrezAnnotator.getEntrezForMiriamData(new MiriamData(), ""); + boolean ensembl = false; + boolean hgnc = false; + for (MiriamData md : data.getMiriamData()) { + if (md.getDataType().equals(MiriamType.HGNC)) { + hgnc = true; + } + if (md.getDataType().equals(MiriamType.ENSEMBL)) { + ensembl = true; + } + } + assertTrue(ensembl); + assertTrue(hgnc); + assertNotNull(data.getDescription()); + assertFalse(data.getDescription().isEmpty()); + + } catch (Exception e) { + e.printStackTrace(); + throw e; + } finally { + entrezAnnotator.setWebPageDownloader(downloader); + entrezAnnotator.setCache(cache); + } + } + + @Test + public void testParseInvalidEntrezResponse() throws Exception { + WebPageDownloader downloader = entrezAnnotator.getWebPageDownloader(); + GeneralCacheInterface cache = entrezAnnotator.getCache(); + try { + entrezAnnotator.setCache(null); + String response = ""; + WebPageDownloader mockDownloader = Mockito.mock(WebPageDownloader.class); + when(mockDownloader.getFromNetwork(anyString(), anyString(), nullable(String.class))).thenReturn(response); + entrezAnnotator.setWebPageDownloader(mockDownloader); + entrezAnnotator.getEntrezForMiriamData(new MiriamData(), ""); + fail("Exception expected"); + } catch (AnnotatorException e) { + } catch (Exception e) { + e.printStackTrace(); + throw e; + } finally { + entrezAnnotator.setWebPageDownloader(downloader); + entrezAnnotator.setCache(cache); + } + + } + + @Test + public void testParseInvalidEntrezResponse2() throws Exception { + WebPageDownloader downloader = entrezAnnotator.getWebPageDownloader(); + GeneralCacheInterface cache = entrezAnnotator.getCache(); + try { + entrezAnnotator.setCache(null); + WebPageDownloader mockDownloader = Mockito.mock(WebPageDownloader.class); + when(mockDownloader.getFromNetwork(anyString(), anyString(), nullable(String.class))) + .thenThrow(new WrongResponseCodeIOException(null, 404)); + entrezAnnotator.setWebPageDownloader(mockDownloader); + entrezAnnotator.getEntrezForMiriamData(new MiriamData(), ""); + fail("Exception expected"); + } catch (AnnotatorException e) { + } catch (Exception e) { + e.printStackTrace(); + throw e; + } finally { + entrezAnnotator.setWebPageDownloader(downloader); + entrezAnnotator.setCache(cache); + } + + } } diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/GoAnnotatorTest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/GoAnnotatorTest.java index cda5bb5ca3fce92738a2e03566c4c3a080222c8c..bc77268d3851b5454f58e74c1e9a2fc4fdba2cf8 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/GoAnnotatorTest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/GoAnnotatorTest.java @@ -5,8 +5,8 @@ import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; +import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.nullable; -import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.when; import java.io.IOException; @@ -20,6 +20,7 @@ import org.springframework.beans.factory.annotation.Autowired; import lcsb.mapviewer.annotation.AnnotationTestFunctions; import lcsb.mapviewer.annotation.cache.GeneralCacheInterface; +import lcsb.mapviewer.annotation.cache.PermanentDatabaseLevelCache; import lcsb.mapviewer.annotation.cache.PermanentDatabaseLevelCacheInterface; import lcsb.mapviewer.annotation.cache.SourceNotAvailable; import lcsb.mapviewer.annotation.cache.WebPageDownloader; @@ -38,7 +39,7 @@ public class GoAnnotatorTest extends AnnotationTestFunctions { GoAnnotator goAnnotator; @Autowired - private PermanentDatabaseLevelCacheInterface cache; + private PermanentDatabaseLevelCacheInterface permanentDatabaseLevelCache; @Before public void setUp() throws Exception { @@ -102,12 +103,10 @@ public class GoAnnotatorTest extends AnnotationTestFunctions { String query = GoAnnotator.GO_TERM_CACHE_PREFIX + "GO:0046902"; String newRes = "hello"; try { - waitForRefreshCacheQueueToEmpty(); - cache.setCachedQuery(query, goAnnotator.getCacheType(), newRes); cache.invalidateByQuery(query, goAnnotator.getCacheType()); - waitForRefreshCacheQueueToEmpty(); + permanentDatabaseLevelCache.waitToFinishTasks(); String res = cache.getStringByQuery(query, goAnnotator.getCacheType()); @@ -129,7 +128,8 @@ public class GoAnnotatorTest extends AnnotationTestFunctions { goAnnotator.setCache(null); WebPageDownloader mockDownloader = Mockito.mock(WebPageDownloader.class); - when(mockDownloader.getFromNetwork(anyString(), anyString(), nullable(String.class))).thenThrow(new IOException()); + when(mockDownloader.getFromNetwork(anyString(), anyString(), nullable(String.class))) + .thenThrow(new IOException()); goAnnotator.setWebPageDownloader(mockDownloader); goAnnotator.refreshCacheQuery("http://google.pl/"); fail("Exception expected"); @@ -195,7 +195,8 @@ public class GoAnnotatorTest extends AnnotationTestFunctions { WebPageDownloader downloader = goAnnotator.getWebPageDownloader(); try { WebPageDownloader mockDownloader = Mockito.mock(WebPageDownloader.class); - when(mockDownloader.getFromNetwork(anyString(), anyString(), nullable(String.class))).thenThrow(new IOException()); + when(mockDownloader.getFromNetwork(anyString(), anyString(), nullable(String.class))) + .thenThrow(new IOException()); goAnnotator.setWebPageDownloader(mockDownloader); assertEquals(ExternalServiceStatusType.DOWN, goAnnotator.getServiceStatus().getStatus()); } catch (Exception e) { diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/HgncAnnotatorTest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/HgncAnnotatorTest.java index 6d3f84cd6d05aa240437aba9cf2bfcaffb243101..d491779e34060ec1160a8be393c9fbb2d761e40c 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/HgncAnnotatorTest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/HgncAnnotatorTest.java @@ -6,8 +6,8 @@ import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; +import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.nullable; -import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.when; import java.io.IOException; @@ -22,6 +22,8 @@ import org.springframework.beans.factory.annotation.Autowired; import lcsb.mapviewer.annotation.AnnotationTestFunctions; import lcsb.mapviewer.annotation.cache.GeneralCacheInterface; +import lcsb.mapviewer.annotation.cache.PermanentDatabaseLevelCache; +import lcsb.mapviewer.annotation.cache.PermanentDatabaseLevelCacheInterface; import lcsb.mapviewer.annotation.cache.SourceNotAvailable; import lcsb.mapviewer.annotation.cache.WebPageDownloader; import lcsb.mapviewer.annotation.services.ExternalServiceStatusType; @@ -38,6 +40,9 @@ public class HgncAnnotatorTest extends AnnotationTestFunctions { @Autowired private HgncAnnotator hgncAnnotator; + @Autowired + private PermanentDatabaseLevelCacheInterface permanentDatabaseLevelCache; + @Before public void setUp() { } @@ -207,16 +212,16 @@ public class HgncAnnotatorTest extends AnnotationTestFunctions { GenericProtein bidProtein = new GenericProtein("id"); bidProtein.setName("BID"); hgncAnnotator.annotateElement(bidProtein); - + GenericProtein bidMutationProtein = new GenericProtein("id2"); bidMutationProtein.setName("BID (p15)"); hgncAnnotator.annotateElement(bidMutationProtein); - - assertEquals(bidProtein.getSymbol(),bidMutationProtein.getSymbol()); - assertEquals(bidProtein.getFormerSymbols(),bidMutationProtein.getFormerSymbols()); - assertEquals(bidProtein.getFullName(),bidMutationProtein.getFullName()); - assertEquals(bidProtein.getMiriamData(),bidMutationProtein.getMiriamData()); - assertEquals(bidProtein.getSynonyms(),bidMutationProtein.getSynonyms()); + + assertEquals(bidProtein.getSymbol(), bidMutationProtein.getSymbol()); + assertEquals(bidProtein.getFormerSymbols(), bidMutationProtein.getFormerSymbols()); + assertEquals(bidProtein.getFullName(), bidMutationProtein.getFullName()); + assertEquals(bidProtein.getMiriamData(), bidMutationProtein.getMiriamData()); + assertEquals(bidProtein.getSynonyms(), bidMutationProtein.getSynonyms()); } catch (Exception e) { e.printStackTrace(); @@ -260,14 +265,12 @@ public class HgncAnnotatorTest extends AnnotationTestFunctions { try { String newRes = "hello"; - waitForRefreshCacheQueueToEmpty(); - cache.setCachedQuery(query, hgncAnnotator.getCacheType(), newRes); String res = cache.getStringByQuery(query, hgncAnnotator.getCacheType()); assertEquals(newRes, res); cache.invalidateByQuery(query, hgncAnnotator.getCacheType()); - waitForRefreshCacheQueueToEmpty(); + permanentDatabaseLevelCache.waitToFinishTasks(); res = cache.getStringByQuery(query, hgncAnnotator.getCacheType()); @@ -520,7 +523,8 @@ public class HgncAnnotatorTest extends AnnotationTestFunctions { hgncAnnotator.setCache(null); WebPageDownloader mockDownloader = Mockito.mock(WebPageDownloader.class); - when(mockDownloader.getFromNetwork(anyString(), anyString(), nullable(String.class))).thenThrow(new IOException()); + when(mockDownloader.getFromNetwork(anyString(), anyString(), nullable(String.class))) + .thenThrow(new IOException()); hgncAnnotator.setWebPageDownloader(mockDownloader); hgncAnnotator.refreshCacheQuery("http://google.pl/"); fail("Exception expected"); @@ -539,7 +543,8 @@ public class HgncAnnotatorTest extends AnnotationTestFunctions { WebPageDownloader downloader = hgncAnnotator.getWebPageDownloader(); try { WebPageDownloader mockDownloader = Mockito.mock(WebPageDownloader.class); - when(mockDownloader.getFromNetwork(anyString(), anyString(), nullable(String.class))).thenThrow(new IOException()); + when(mockDownloader.getFromNetwork(anyString(), anyString(), nullable(String.class))) + .thenThrow(new IOException()); hgncAnnotator.setWebPageDownloader(mockDownloader); assertEquals(ExternalServiceStatusType.DOWN, hgncAnnotator.getServiceStatus().getStatus()); } catch (Exception e) { diff --git a/reactome/src/test/java/lcsb/mapviewer/reactome/ReactomeTestFunctions.java b/reactome/src/test/java/lcsb/mapviewer/reactome/ReactomeTestFunctions.java index 7696b1a875297b9c71529b3a12fb0eac400edf9c..80019a0fd68c3ad7aadcabeee1842ba42338426c 100644 --- a/reactome/src/test/java/lcsb/mapviewer/reactome/ReactomeTestFunctions.java +++ b/reactome/src/test/java/lcsb/mapviewer/reactome/ReactomeTestFunctions.java @@ -27,15 +27,6 @@ import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; -import lcsb.mapviewer.annotation.cache.PermanentDatabaseLevelCacheInterface; -import lcsb.mapviewer.common.exception.InvalidXmlSchemaException; -import lcsb.mapviewer.converter.ConverterParams; -import lcsb.mapviewer.converter.model.celldesigner.CellDesignerXmlParser; -import lcsb.mapviewer.model.map.model.Model; -import lcsb.mapviewer.persist.DbUtils; -import lcsb.mapviewer.reactome.utils.DataSourceUpdater; -import lcsb.mapviewer.reactome.utils.ReactomeQueryUtil; - import org.apache.log4j.Logger; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; @@ -49,209 +40,211 @@ import org.w3c.dom.NodeList; import org.xml.sax.InputSource; import org.xml.sax.SAXException; +import lcsb.mapviewer.annotation.cache.PermanentDatabaseLevelCacheInterface; +import lcsb.mapviewer.common.exception.InvalidXmlSchemaException; +import lcsb.mapviewer.converter.ConverterParams; +import lcsb.mapviewer.converter.model.celldesigner.CellDesignerXmlParser; +import lcsb.mapviewer.model.map.model.Model; +import lcsb.mapviewer.persist.DbUtils; +import lcsb.mapviewer.reactome.utils.DataSourceUpdater; +import lcsb.mapviewer.reactome.utils.ReactomeQueryUtil; + @Transactional(value = "txManager") @Rollback(false) @ContextConfiguration(locations = { "/applicationContext-annotation.xml", // - "/applicationContext-reactome.xml", // - "/applicationContext-persist.xml", // - "/test-applicationContext.xml", // - "/test-dataSource.xml", // + "/applicationContext-reactome.xml", // + "/applicationContext-persist.xml", // + "/test-applicationContext.xml", // + "/test-dataSource.xml", // }) @RunWith(SpringJUnit4ClassRunner.class) public abstract class ReactomeTestFunctions { - private Logger logger = Logger.getLogger(ReactomeTestFunctions.class); - - @Autowired - protected PermanentDatabaseLevelCacheInterface cache; - - @Autowired - protected DataSourceUpdater rc; - - @Autowired - protected DbUtils dbUtils; - - @Autowired - protected ReactomeQueryUtil rcu; - - protected String readFile(String file) throws IOException { - StringBuilder stringBuilder = new StringBuilder(); - BufferedReader reader = new BufferedReader(new FileReader(file)); - try { - String line = null; - String ls = System.getProperty("line.separator"); - - while ((line = reader.readLine()) != null) { - stringBuilder.append(line); - stringBuilder.append(ls); - } - } finally { - reader.close(); - } - - return stringBuilder.toString(); - } - - protected Node getNodeFromXmlString(String text) throws InvalidXmlSchemaException { - InputSource is = new InputSource(); - is.setCharacterStream(new StringReader(text)); - return getXmlDocumentFromInputSource(is).getChildNodes().item(0); - } - - protected Document getXmlDocumentFromFile(String fileName) throws InvalidXmlSchemaException, IOException { - File file = new File(fileName); - InputStream inputStream = new FileInputStream(file); - Reader reader = null; - try { - reader = new InputStreamReader(inputStream, "UTF-8"); - InputSource is = new InputSource(reader); - - Document result = getXmlDocumentFromInputSource(is); - inputStream.close(); - return result; - } catch (UnsupportedEncodingException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - return null; - } - - protected Document getXmlDocumentFromInputSource(InputSource stream) throws InvalidXmlSchemaException { - DocumentBuilder db; - try { - db = DocumentBuilderFactory.newInstance().newDocumentBuilder(); - } catch (ParserConfigurationException e) { - throw new InvalidXmlSchemaException("Problem with xml parser"); - } - Document doc = null; - try { - doc = db.parse(stream); - } catch (SAXException e) { - logger.error(e); - } catch (IOException e) { - logger.error(e); - } - return doc; - } - - private static Map<String, Model> models = new HashMap<String, Model>(); - - protected Model getModelForFile(String fileName, boolean fromCache) throws Exception { - if (!fromCache) { - logger.debug("File without cache: " + fileName); - return new CellDesignerXmlParser().createModel(new ConverterParams().filename(fileName)); - } - Model result = ReactomeTestFunctions.models.get(fileName); - if (result == null) { - logger.debug("File to cache: " + fileName); - - CellDesignerXmlParser parser = new CellDesignerXmlParser(); - result = parser.createModel(new ConverterParams().filename(fileName).sizeAutoAdjust(false)); - ReactomeTestFunctions.models.put(fileName, result); - } - return result; - } - - protected String createTmpFileName() { - try { - File f = File.createTempFile("prefix", ".txt"); - String filename = f.getName(); - f.delete(); - return filename; - } catch (IOException e) { - e.printStackTrace(); - return null; - } - } - - protected String nodeToString(Node node) { - return nodeToString(node, false); - } - - protected String nodeToString(Node node, boolean includeHeadNode) { - if (node == null) - return null; - StringWriter sw = new StringWriter(); - try { - Transformer t = TransformerFactory.newInstance().newTransformer(); - t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); - t.setOutputProperty(OutputKeys.INDENT, "yes"); - t.setOutputProperty(OutputKeys.METHOD, "xml"); - - NodeList list = node.getChildNodes(); - for (int i = 0; i < list.getLength(); i++) { - Node element = list.item(i); - t.transform(new DOMSource(element), new StreamResult(sw)); - } - } catch (TransformerException te) { - logger.debug("nodeToString Transformer Exception"); - } - if (includeHeadNode) { - return "<" + node.getNodeName() + ">" + sw.toString() + "</" + node.getNodeName() + ">"; - } - return sw.toString(); - } - - protected boolean equalFiles(String fileA, String fileB) throws IOException { - int BLOCK_SIZE = 65536; - FileInputStream inputStreamA = new FileInputStream(fileA); - FileInputStream inputStreamB = new FileInputStream(fileB); - // vary BLOCK_SIZE to suit yourself. - // it should probably a factor or multiple of the size of a disk - // sector/cluster. - // Note that your max heap size may need to be adjused - // if you have a very big block size or lots of these comparators. - - // assume inputStreamA and inputStreamB are streams from your two files. - byte[] streamABlock = new byte[BLOCK_SIZE]; - byte[] streamBBlock = new byte[BLOCK_SIZE]; - boolean match = true; - int bytesReadA = 0; - int bytesReadB = 0; - do { - bytesReadA = inputStreamA.read(streamABlock); - bytesReadB = inputStreamB.read(streamBBlock); - match = ((bytesReadA == bytesReadB) && Arrays.equals(streamABlock, streamBBlock)); - } while (match && (bytesReadA > -1)); - inputStreamA.close(); - inputStreamB.close(); - return match; - } - - public File createTempDirectory() throws IOException { - final File temp; - - temp = File.createTempFile("temp", Long.toString(System.nanoTime())); - - if (!(temp.delete())) { - throw new IOException("Could not delete temp file: " + temp.getAbsolutePath()); - } - - if (!(temp.mkdir())) { - throw new IOException("Could not create temp directory: " + temp.getAbsolutePath()); - } - - return (temp); - } - - protected String getWebpage(String accessUrl) throws IOException { - String inputLine; - StringBuilder tmp = new StringBuilder(); - URL url = new URL(accessUrl); - URLConnection urlConn = url.openConnection(); - BufferedReader in = new BufferedReader(new InputStreamReader(urlConn.getInputStream())); - - while ((inputLine = in.readLine()) != null) { - tmp.append(inputLine); - } - in.close(); - return tmp.toString(); - } - - protected void waitForRefreshCacheQueueToEmpty() throws InterruptedException { - while (cache.refreshIsBusy()) { - logger.debug("Waiting for refresh queue to empty. " + cache.getRefreshPendingQueueSize() + " pending. " + cache.getRefreshExecutingTasksSize() - + " tasks are executed."); - Thread.sleep(100); - } - } + private Logger logger = Logger.getLogger(ReactomeTestFunctions.class); + + @Autowired + protected PermanentDatabaseLevelCacheInterface cache; + + @Autowired + protected DataSourceUpdater rc; + + @Autowired + protected DbUtils dbUtils; + + @Autowired + protected ReactomeQueryUtil rcu; + + protected String readFile(String file) throws IOException { + StringBuilder stringBuilder = new StringBuilder(); + BufferedReader reader = new BufferedReader(new FileReader(file)); + try { + String line = null; + String ls = System.getProperty("line.separator"); + + while ((line = reader.readLine()) != null) { + stringBuilder.append(line); + stringBuilder.append(ls); + } + } finally { + reader.close(); + } + + return stringBuilder.toString(); + } + + protected Node getNodeFromXmlString(String text) throws InvalidXmlSchemaException { + InputSource is = new InputSource(); + is.setCharacterStream(new StringReader(text)); + return getXmlDocumentFromInputSource(is).getChildNodes().item(0); + } + + protected Document getXmlDocumentFromFile(String fileName) throws InvalidXmlSchemaException, IOException { + File file = new File(fileName); + InputStream inputStream = new FileInputStream(file); + Reader reader = null; + try { + reader = new InputStreamReader(inputStream, "UTF-8"); + InputSource is = new InputSource(reader); + + Document result = getXmlDocumentFromInputSource(is); + inputStream.close(); + return result; + } catch (UnsupportedEncodingException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + return null; + } + + protected Document getXmlDocumentFromInputSource(InputSource stream) throws InvalidXmlSchemaException { + DocumentBuilder db; + try { + db = DocumentBuilderFactory.newInstance().newDocumentBuilder(); + } catch (ParserConfigurationException e) { + throw new InvalidXmlSchemaException("Problem with xml parser"); + } + Document doc = null; + try { + doc = db.parse(stream); + } catch (SAXException e) { + logger.error(e); + } catch (IOException e) { + logger.error(e); + } + return doc; + } + + private static Map<String, Model> models = new HashMap<String, Model>(); + + protected Model getModelForFile(String fileName, boolean fromCache) throws Exception { + if (!fromCache) { + logger.debug("File without cache: " + fileName); + return new CellDesignerXmlParser().createModel(new ConverterParams().filename(fileName)); + } + Model result = ReactomeTestFunctions.models.get(fileName); + if (result == null) { + logger.debug("File to cache: " + fileName); + + CellDesignerXmlParser parser = new CellDesignerXmlParser(); + result = parser.createModel(new ConverterParams().filename(fileName).sizeAutoAdjust(false)); + ReactomeTestFunctions.models.put(fileName, result); + } + return result; + } + + protected String createTmpFileName() { + try { + File f = File.createTempFile("prefix", ".txt"); + String filename = f.getName(); + f.delete(); + return filename; + } catch (IOException e) { + e.printStackTrace(); + return null; + } + } + + protected String nodeToString(Node node) { + return nodeToString(node, false); + } + + protected String nodeToString(Node node, boolean includeHeadNode) { + if (node == null) + return null; + StringWriter sw = new StringWriter(); + try { + Transformer t = TransformerFactory.newInstance().newTransformer(); + t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); + t.setOutputProperty(OutputKeys.INDENT, "yes"); + t.setOutputProperty(OutputKeys.METHOD, "xml"); + + NodeList list = node.getChildNodes(); + for (int i = 0; i < list.getLength(); i++) { + Node element = list.item(i); + t.transform(new DOMSource(element), new StreamResult(sw)); + } + } catch (TransformerException te) { + logger.debug("nodeToString Transformer Exception"); + } + if (includeHeadNode) { + return "<" + node.getNodeName() + ">" + sw.toString() + "</" + node.getNodeName() + ">"; + } + return sw.toString(); + } + + protected boolean equalFiles(String fileA, String fileB) throws IOException { + int BLOCK_SIZE = 65536; + FileInputStream inputStreamA = new FileInputStream(fileA); + FileInputStream inputStreamB = new FileInputStream(fileB); + // vary BLOCK_SIZE to suit yourself. + // it should probably a factor or multiple of the size of a disk + // sector/cluster. + // Note that your max heap size may need to be adjused + // if you have a very big block size or lots of these comparators. + + // assume inputStreamA and inputStreamB are streams from your two files. + byte[] streamABlock = new byte[BLOCK_SIZE]; + byte[] streamBBlock = new byte[BLOCK_SIZE]; + boolean match = true; + int bytesReadA = 0; + int bytesReadB = 0; + do { + bytesReadA = inputStreamA.read(streamABlock); + bytesReadB = inputStreamB.read(streamBBlock); + match = ((bytesReadA == bytesReadB) && Arrays.equals(streamABlock, streamBBlock)); + } while (match && (bytesReadA > -1)); + inputStreamA.close(); + inputStreamB.close(); + return match; + } + + public File createTempDirectory() throws IOException { + final File temp; + + temp = File.createTempFile("temp", Long.toString(System.nanoTime())); + + if (!(temp.delete())) { + throw new IOException("Could not delete temp file: " + temp.getAbsolutePath()); + } + + if (!(temp.mkdir())) { + throw new IOException("Could not create temp directory: " + temp.getAbsolutePath()); + } + + return (temp); + } + + protected String getWebpage(String accessUrl) throws IOException { + String inputLine; + StringBuilder tmp = new StringBuilder(); + URL url = new URL(accessUrl); + URLConnection urlConn = url.openConnection(); + BufferedReader in = new BufferedReader(new InputStreamReader(urlConn.getInputStream())); + + while ((inputLine = in.readLine()) != null) { + tmp.append(inputLine); + } + in.close(); + return tmp.toString(); + } + } diff --git a/reactome/src/test/java/lcsb/mapviewer/reactome/utils/ReactomeConnectorTest.java b/reactome/src/test/java/lcsb/mapviewer/reactome/utils/ReactomeConnectorTest.java index 65aed9ba0998833b2d56e8b96f926dc0ccf244f6..cfc792e5f612d0caad2fad0009e871be3fb2ccb6 100644 --- a/reactome/src/test/java/lcsb/mapviewer/reactome/utils/ReactomeConnectorTest.java +++ b/reactome/src/test/java/lcsb/mapviewer/reactome/utils/ReactomeConnectorTest.java @@ -12,7 +12,15 @@ import java.util.List; import java.util.Map; import java.util.Set; +import org.apache.log4j.Logger; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.w3c.dom.Node; + import lcsb.mapviewer.annotation.cache.GeneralCacheInterface; +import lcsb.mapviewer.annotation.cache.PermanentDatabaseLevelCacheInterface; import lcsb.mapviewer.model.cache.CacheType; import lcsb.mapviewer.model.map.MiriamData; import lcsb.mapviewer.model.map.MiriamType; @@ -24,171 +32,165 @@ import lcsb.mapviewer.reactome.model.ReactomeReaction; import lcsb.mapviewer.reactome.model.ReactomeReactionlikeEvent; import lcsb.mapviewer.reactome.model.ReactomeSimpleEntity; -import org.apache.log4j.Logger; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.springframework.beans.factory.annotation.Autowired; -import org.w3c.dom.Node; - public class ReactomeConnectorTest extends ReactomeTestFunctions { - Logger logger = Logger.getLogger(ReactomeConnectorTest.class); - - CacheType reactomeCacheType; - - @Autowired - private GeneralCacheInterface cache; - - @Before - public void setUp() throws Exception { - reactomeCacheType = rc.getCacheType(); - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testGetEntities() throws Exception { - try { - List<ReactomePhysicalEntity> list = rc.getEntitiesForName("GAK", true); - assertNotNull(list); - assertTrue("Too few elements on the list: " + list.size(), list.size() > 1); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testGetReactions() throws Exception { - try { - List<ReactomeReactionlikeEvent> list = rc.getReactionsForEntityId(162704); - assertNotNull(list); - assertTrue("Too few elements on the list: " + list.size(), list.size() > 0); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testGetNodeForId() { - try { - Node node = rc.getFullNodeForDbId(1385634); - assertNotNull(node); - assertEquals("referenceDatabase", node.getNodeName()); - } catch (Exception e) { - e.printStackTrace(); - fail("Unknown exception"); - } - } - - @Test - public void testGetTypeForId() { - try { - Class<?> clazz = rc.getTypeForDbId(109624); - assertNotNull(clazz); - assertEquals(clazz.getName(), ReactomeReaction.class.getName()); - - clazz = rc.getTypeForDbId(70154); - assertNotNull(clazz); - assertEquals(clazz.getName(), ReactomeInstanceEdit.class.getName()); - - } catch (Exception e) { - e.printStackTrace(); - fail("Unknown exception"); - } - } - - @Test - public void testGetObjectsForIds() { - try { - List<Integer> ids = new ArrayList<Integer>(); - ids.add(3896801); - ids.add(549119); - - Map<Integer, ReactomeDatabaseObject> objects = rc.getFullObjectsForDbIds(ids); - assertEquals(2, objects.keySet().size()); - ReactomeDatabaseObject object = objects.get(3896801); - assertNotNull(object); - } catch (Exception e) { - e.printStackTrace(); - fail("Unknown exception"); - } - } - - @Test - public void testGetObjectsForIds2() { - try { - List<Integer> ids = new ArrayList<Integer>(); - ids.add(2671814); - ids.add(2562550); - ids.add(2562550); - ids.add(2562550); - - Map<Integer, ReactomeDatabaseObject> objects = rc.getFullObjectsForDbIds(ids); - assertEquals(2, objects.keySet().size()); - } catch (Exception e) { - e.printStackTrace(); - fail("Unknown exception"); - } - } - - @Test - public void testGetEntitiesForChebiId() throws Exception { - try { - Set<MiriamData> ids = new HashSet<MiriamData>(); - ids.add(new MiriamData(MiriamType.CHEBI, "CHEBI:15378")); - List<ReactomePhysicalEntity> list = rc.getEntitiesForChebiId(ids, false); - assertNotNull(list); - assertTrue(list.size() > 0); - assertTrue(list.get(0) instanceof ReactomeSimpleEntity); - ReactomeSimpleEntity entity = (ReactomeSimpleEntity) list.get(0); - assertNotNull(entity); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testGetSimpleObjectListByQuery() throws Exception { - try { - String query = "name=GAK"; - List<ReactomeDatabaseObject> list = rc.getSimpleObjectListByQuery(query, ReactomePhysicalEntity.class); - assertNotNull(list); - assertTrue(list.size() > 0); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - - } - - @Test(timeout = 15000) - public void testCachableInterfaceByParams() throws Exception { - String url = "http://reactome.org/ReactomeRESTfulAPI/RESTfulWS/listByQuery/DatabaseObjects"; - String query = "identifier=2562550\n" + url; - String newRes = "hello"; - try { - waitForRefreshCacheQueueToEmpty(); - - cache.setCachedQuery(query, reactomeCacheType, newRes); - cache.invalidateByQuery(query, reactomeCacheType); - - waitForRefreshCacheQueueToEmpty(); - - String res = cache.getStringByQuery(query, reactomeCacheType); - - assertNotNull(res); - - assertFalse("Value wasn't refreshed from db", newRes.equals(res)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } + Logger logger = Logger.getLogger(ReactomeConnectorTest.class); + + CacheType reactomeCacheType; + + @Autowired + private PermanentDatabaseLevelCacheInterface permanentDatabaseLevelCache; + + @Autowired + private GeneralCacheInterface cache; + + @Before + public void setUp() throws Exception { + reactomeCacheType = rc.getCacheType(); + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testGetEntities() throws Exception { + try { + List<ReactomePhysicalEntity> list = rc.getEntitiesForName("GAK", true); + assertNotNull(list); + assertTrue("Too few elements on the list: " + list.size(), list.size() > 1); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testGetReactions() throws Exception { + try { + List<ReactomeReactionlikeEvent> list = rc.getReactionsForEntityId(162704); + assertNotNull(list); + assertTrue("Too few elements on the list: " + list.size(), list.size() > 0); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testGetNodeForId() { + try { + Node node = rc.getFullNodeForDbId(1385634); + assertNotNull(node); + assertEquals("referenceDatabase", node.getNodeName()); + } catch (Exception e) { + e.printStackTrace(); + fail("Unknown exception"); + } + } + + @Test + public void testGetTypeForId() { + try { + Class<?> clazz = rc.getTypeForDbId(109624); + assertNotNull(clazz); + assertEquals(clazz.getName(), ReactomeReaction.class.getName()); + + clazz = rc.getTypeForDbId(70154); + assertNotNull(clazz); + assertEquals(clazz.getName(), ReactomeInstanceEdit.class.getName()); + + } catch (Exception e) { + e.printStackTrace(); + fail("Unknown exception"); + } + } + + @Test + public void testGetObjectsForIds() { + try { + List<Integer> ids = new ArrayList<Integer>(); + ids.add(3896801); + ids.add(549119); + + Map<Integer, ReactomeDatabaseObject> objects = rc.getFullObjectsForDbIds(ids); + assertEquals(2, objects.keySet().size()); + ReactomeDatabaseObject object = objects.get(3896801); + assertNotNull(object); + } catch (Exception e) { + e.printStackTrace(); + fail("Unknown exception"); + } + } + + @Test + public void testGetObjectsForIds2() { + try { + List<Integer> ids = new ArrayList<Integer>(); + ids.add(2671814); + ids.add(2562550); + ids.add(2562550); + ids.add(2562550); + + Map<Integer, ReactomeDatabaseObject> objects = rc.getFullObjectsForDbIds(ids); + assertEquals(2, objects.keySet().size()); + } catch (Exception e) { + e.printStackTrace(); + fail("Unknown exception"); + } + } + + @Test + public void testGetEntitiesForChebiId() throws Exception { + try { + Set<MiriamData> ids = new HashSet<MiriamData>(); + ids.add(new MiriamData(MiriamType.CHEBI, "CHEBI:15378")); + List<ReactomePhysicalEntity> list = rc.getEntitiesForChebiId(ids, false); + assertNotNull(list); + assertTrue(list.size() > 0); + assertTrue(list.get(0) instanceof ReactomeSimpleEntity); + ReactomeSimpleEntity entity = (ReactomeSimpleEntity) list.get(0); + assertNotNull(entity); + + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testGetSimpleObjectListByQuery() throws Exception { + try { + String query = "name=GAK"; + List<ReactomeDatabaseObject> list = rc.getSimpleObjectListByQuery(query, ReactomePhysicalEntity.class); + assertNotNull(list); + assertTrue(list.size() > 0); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + + } + + @Test(timeout = 15000) + public void testCachableInterfaceByParams() throws Exception { + String url = "http://reactome.org/ReactomeRESTfulAPI/RESTfulWS/listByQuery/DatabaseObjects"; + String query = "identifier=2562550\n" + url; + String newRes = "hello"; + try { + cache.setCachedQuery(query, reactomeCacheType, newRes); + cache.invalidateByQuery(query, reactomeCacheType); + + permanentDatabaseLevelCache.waitToFinishTasks(); + + String res = cache.getStringByQuery(query, reactomeCacheType); + + assertNotNull(res); + + assertFalse("Value wasn't refreshed from db", newRes.equals(res)); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } }