Commit 687aa4c6 authored by Piotr Gawron's avatar Piotr Gawron
Browse files

api for getting list of suggested queries for mirna database

parent 32e83843
......@@ -8,6 +8,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.w3c.dom.Node;
import lcsb.mapviewer.common.XmlParser;
import lcsb.mapviewer.common.exception.InvalidArgumentException;
import lcsb.mapviewer.model.cache.CacheType;
import lcsb.mapviewer.persist.dao.cache.CacheTypeDao;
......@@ -34,7 +35,24 @@ public abstract class CachableInterface extends XmlParser {
* @throws SourceNotAvailable
* thrown when original source is unavailable
*/
public abstract Object refreshCacheQuery(Object query) throws SourceNotAvailable;
public Object refreshCacheQuery(Object query) throws SourceNotAvailable {
String result = null;
try {
if (query instanceof String) {
String name = (String) query;
if (name.startsWith("http")) {
result = getWebPageContent(name);
} else {
throw new InvalidArgumentException("Don't know what to do with string \"" + query + "\"");
}
} else {
throw new InvalidArgumentException("Don't know what to do with class: " + query.getClass());
}
} catch (IOException e) {
throw new SourceNotAvailable(e);
}
return result;
}
/**
* String containing class name of the class that extends
......
......@@ -20,113 +20,114 @@ import lcsb.mapviewer.model.map.MiriamData;
@XmlRootElement
public class MiRNA implements Serializable, TargettingStructure {
/**
*
*/
private static final long serialVersionUID = 1L;
/**
* ID coming from MiRBase.
*/
private String name;
/**
* Genes interacting with the chemical plus publications.
*/
private List<Target> targets = new ArrayList<>();
/**
* default constructor.
*/
public MiRNA() {
super();
}
/**
* Constructor that takes name of mirna as argument.
*
* @param name
* name of the mirna
*/
public MiRNA(String name) {
super();
this.name = name;
}
@Override
public String toString() {
StringBuffer result = new StringBuffer();
result.append("\nmiRBaseID: " + name);
result.append("\ntargetGenes:");
for (Target target : getTargets()) {
result.append(target.toString());
}
return result.toString();
}
/**
* @return list of genes plus publications.
*/
public List<Target> getTargets() {
return targets;
}
/**
* @param targets
* list of genes plus publications.
*/
public void setTargets(List<Target> targets) {
this.targets = targets;
}
/**
* @return id form Mirtarbase id.
*/
public String getName() {
return name;
}
/**
* @param name
* id form MirBase id.
*/
public void setName(String name) {
this.name = name;
}
/**
* Adds target to mirna.
*
* @param target target to add.
*/
public void addTarget(Target target) {
this.targets.add(target);
}
@Override
public Collection<MiriamData> getSources() {
return new ArrayList<>();
}
/**
* Comparator of the objects by their name.
*
* @author Piotr Gawron
*
*/
public static class NameComparator implements Comparator<MiRNA> {
/**
* Default string comparator.
*/
private StringComparator stringComparator = new StringComparator();
@Override
public int compare(MiRNA arg0, MiRNA arg1) {
return stringComparator.compare(arg0.getName(), arg1.getName());
}
}
/**
*
*/
private static final long serialVersionUID = 1L;
/**
* ID coming from MiRBase.
*/
private String name;
/**
* Genes interacting with the chemical plus publications.
*/
private List<Target> targets = new ArrayList<>();
/**
* default constructor.
*/
public MiRNA() {
super();
}
/**
* Constructor that takes name of mirna as argument.
*
* @param name
* name of the mirna
*/
public MiRNA(String name) {
super();
this.name = name;
}
@Override
public String toString() {
StringBuffer result = new StringBuffer();
result.append("\nmiRBaseID: " + name);
result.append("\ntargetGenes:");
for (Target target : getTargets()) {
result.append(target.toString());
}
return result.toString();
}
/**
* @return list of genes plus publications.
*/
public List<Target> getTargets() {
return targets;
}
/**
* @param targets
* list of genes plus publications.
*/
public void setTargets(List<Target> targets) {
this.targets = targets;
}
/**
* @return id form Mirtarbase id.
*/
public String getName() {
return name;
}
/**
* @param name
* id form MirBase id.
*/
public void setName(String name) {
this.name = name;
}
/**
* Adds target to mirna.
*
* @param target
* target to add.
*/
public void addTarget(Target target) {
this.targets.add(target);
}
@Override
public Collection<MiriamData> getSources() {
return new ArrayList<>();
}
/**
* Comparator of the objects by their name.
*
* @author Piotr Gawron
*
*/
public static class NameComparator implements Comparator<MiRNA> {
/**
* Default string comparator.
*/
private StringComparator stringComparator = new StringComparator();
@Override
public int compare(MiRNA arg0, MiRNA arg1) {
return stringComparator.compare(arg0.getName(), arg1.getName());
}
}
}
......@@ -322,7 +322,7 @@ public class ChemicalParser extends CachableInterface implements IExternalServic
@Override
public Object refreshCacheQuery(Object query) throws SourceNotAvailable {
try {
String result = null;
Object result = null;
if (query instanceof String) {
String identifier = (String) query;
if (identifier.startsWith(CHEMICAL_PREFIX)) {
......@@ -349,19 +349,15 @@ public class ChemicalParser extends CachableInterface implements IExternalServic
}
List<String> list = getSuggestedQueryListWithoutCache(project, diseaseId);
result = StringUtils.join(list, "\n");
} else if (identifier.startsWith("http")) {
result = getWebPageContent(identifier);
} else {
throw new InvalidArgumentException("Don't know what to do with string \"" + query + "\"");
} else {
result = super.refreshCacheQuery(query);
}
} else {
throw new InvalidArgumentException("Don't know what to do with class: " + query.getClass());
result = super.refreshCacheQuery(query);
}
return result;
} catch (ChemicalSearchException e) {
throw new SourceNotAvailable("Problem with accessing ctd database", e);
} catch (IOException e) {
throw new SourceNotAvailable("Problem with accessing webpage", e);
}
}
......
......@@ -57,241 +57,240 @@ import lcsb.mapviewer.persist.dao.cache.CacheTypeDao;
@Transactional(value = "txManager")
@Rollback(false)
@ContextConfiguration(locations = { //
"/applicationContext-annotation.xml", //
"/applicationContext-persist.xml", //
"/test-applicationContext.xml", //
"/test-applicationContext.xml", //
"/dataSource.xml", //
"/applicationContext-annotation.xml", //
"/applicationContext-persist.xml", //
"/test-applicationContext.xml", //
"/test-applicationContext.xml", //
"/dataSource.xml", //
})
@RunWith(SpringJUnit4ClassRunner.class)
public abstract class AnnotationTestFunctions extends AbstractTransactionalJUnit4SpringContextTests {
@Autowired
protected PermanentDatabaseLevelCacheInterface cache;
@Autowired
protected CacheTypeDao cacheTypeDao;
@Autowired
protected DbUtils dbUtils;
private Logger logger = Logger.getLogger(AnnotationTestFunctions.class);
private EventStorageLoggerAppender appender;
@Before
public final void _setUp() throws Exception {
Logger.getRootLogger().removeAppender(appender);
appender = new EventStorageLoggerAppender(false);
Logger.getRootLogger().addAppender(appender);
}
@After
public final void _tearDown() throws Exception {
Logger.getRootLogger().removeAppender(appender);
}
protected List<LoggingEvent> getWarnings() {
return appender.getWarnings();
}
protected List<LoggingEvent> getErrors() {
return appender.getErrors();
}
protected List<LoggingEvent> getFatals() {
return appender.getFatals();
}
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, IOException {
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, IOException {
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) {
throw new InvalidXmlSchemaException(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 = AnnotationTestFunctions.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));
AnnotationTestFunctions.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;
IOException exception = null;
for (int i = 0; i < 3; i++) {
try {
StringBuilder tmp = new StringBuilder();
URL url = new URL(accessUrl);
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
urlConn.setRequestMethod("GET");
urlConn.connect();
BufferedReader in = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
while ((inputLine = in.readLine()) != null) {
tmp.append(inputLine);
}
in.close();
return tmp.toString();
} catch (IOException e) {
exception = e;
}
}
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);
}
}
@Autowired
protected PermanentDatabaseLevelCacheInterface cache;
@Autowired
protected CacheTypeDao cacheTypeDao;
@Autowired
protected DbUtils dbUtils;
private Logger logger = Logger.getLogger(AnnotationTestFunctions.class);
private EventStorageLoggerAppender appender;
@Before
public final void _setUp() throws Exception {
Logger.getRootLogger().removeAppender(appender);
appender = new EventStorageLoggerAppender(false);
Logger.getRootLogger().addAppender(appender);
}
@After
public final void _tearDown() throws Exception {
Logger.getRootLogger().removeAppender(appender);
}
protected List<LoggingEvent> getWarnings() {
return appender.getWarnings();
}
protected List<LoggingEvent> getErrors() {
return appender.getErrors();
}
protected List<LoggingEvent> getFatals() {
return appender.getFatals();
}
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");