Commit 11339bed authored by Piotr Gawron's avatar Piotr Gawron
Browse files

rest api provides more information for elements

parent cb35cfa2
......@@ -13,6 +13,7 @@
</attributes>
</classpathentry>
<classpathentry kind="src" path="src/main/resources"/>
<classpathentry kind="src" path="src/test/resources"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8">
<attributes>
<attribute name="maven.pomderived" value="true"/>
......
......@@ -48,6 +48,13 @@
<artifactId>spring-faces</artifactId>
<version>${springframework.webflow.version}</version>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>${mockito.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
......@@ -8,6 +8,7 @@ import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestParam;
......@@ -22,9 +23,11 @@ import lcsb.mapviewer.services.interfaces.IModelService;
import lcsb.mapviewer.services.interfaces.IProjectService;
import lcsb.mapviewer.services.interfaces.IUserService;
import lcsb.mapviewer.services.search.data.LightReactionView;
import lcsb.mapviewer.services.view.AnnotationViewFactory;
@Transactional(value = "txManager")
public class ProjectRestImpl {
Logger logger = Logger.getLogger(ProjectRestImpl.class);
@Autowired
private IUserService userService;
......@@ -35,6 +38,9 @@ public class ProjectRestImpl {
@Autowired
private IModelService modelService;
@Autowired
AnnotationViewFactory annotationViewFactory;
public ProjectMetaData getMetaData(@RequestParam(value = "projectId") String projectId, @RequestParam(value = "token") String token)
throws SecurityException {
......@@ -150,6 +156,22 @@ public class ProjectRestImpl {
value = element.getName();
} else if (column.equals("type")) {
value = element.getStringType();
} else if (column.equals("symbol")) {
value = element.getSymbol();
} else if (column.equals("fullname")) {
value = element.getFullName();
} else if (column.equals("abbreviation")) {
value = element.getAbbreviation();
} else if (column.equals("references")) {
value = annotationViewFactory.createList(element.getMiriamData());
} else if (column.equals("synonyms")) {
value = element.getSynonyms();
} else if (column.equals("formula")) {
value = element.getFormula();
} else if (column.equals("description")) {
value = element.getNotes();
} else if (column.equals("formersymbols")) {
value = element.getFormerSymbols();
} else if (column.equals("bounds")) {
value = new Rectangle2D.Double(element.getX(), element.getY(), element.getWidth(), element.getHeight());
} else {
......@@ -167,6 +189,17 @@ public class ProjectRestImpl {
columnsSet.add("modelId");
columnsSet.add("name");
columnsSet.add("type");
columnsSet.add("description");
columnsSet.add("type");
columnsSet.add("symbol");
columnsSet.add("fullName");
columnsSet.add("abbreviation");
columnsSet.add("formula");
columnsSet.add("name");
columnsSet.add("synonyms");
columnsSet.add("formerSymbols");
columnsSet.add("references");
columnsSet.add("bounds");
} else {
for (String str : columns.split(",")) {
columnsSet.add(str);
......@@ -182,7 +215,7 @@ public class ProjectRestImpl {
columnsSet.add("modelId");
columnsSet.add("type");
columnsSet.add("lines");
columnsSet.add("centerPoint");
columnsSet.add("centerPoint");
} else {
for (String str : columns.split(",")) {
columnsSet.add(str);
......
package lcsb.mapviewer.api.project;
import static org.junit.Assert.assertFalse;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
import java.util.Map;
import org.apache.log4j.Logger;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import lcsb.mapviewer.model.map.model.Model;
import lcsb.mapviewer.services.interfaces.IModelService;
public class ProjectRestImplTest extends RestTestFunctions {
Logger logger = Logger.getLogger(ProjectRestImplTest.class);
@Autowired
ProjectRestImpl projectRestImpl;
@Autowired
IModelService modelService;
@AfterClass
public static void tearDownAfterClass() throws Exception {
}
@Before
public void setUp() throws Exception {
}
@After
public void tearDown() throws Exception {
}
@Test
public void testGetElementsProcessAllColumns() throws Exception {
try {
Model model = super.getModelForFile("testFiles/model/sample.xml", true);
IModelService mockModelService = Mockito.mock(IModelService.class);
Mockito.when(mockModelService.getLastModelByProjectId(anyString(), any())).thenReturn(model);
projectRestImpl.setModelService(mockModelService);
for (Map<String, Object> element : projectRestImpl.getElements("sample", "", "", token.getId())) {
for (String paramName : element.keySet()) {
Object val = element.get(paramName);
String paramValue = "";
if (val != null) {
paramValue = val.toString();
}
assertFalse("Improper handler for column name: " + paramName, paramValue.contains("Unknown column"));
}
}
} catch (Exception e) {
e.printStackTrace();
throw e;
} finally {
projectRestImpl.setModelService(modelService);
}
}
}
package lcsb.mapviewer.api.project;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.junit.After;
import org.junit.Before;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import lcsb.mapviewer.common.Configuration;
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.services.interfaces.IUserService;
import lcsb.mapviewer.services.view.AuthenticationToken;
@Transactional(value = "txManager")
@Rollback(true)
@ContextConfiguration(locations = { "/applicationContext-persist.xml", "/applicationContext-annotation.xml", "/applicationContext-service.xml","/applicationContext-rest.xml" })
@RunWith(SpringJUnit4ClassRunner.class)
public abstract class RestTestFunctions {
private Logger logger = Logger.getLogger(RestTestFunctions.class);
public double EPSILON = 1e-6;
@Autowired
protected PasswordEncoder passwordEncoder;
@Autowired
protected IUserService userService;
@Autowired
protected DbUtils dbUtils;
AuthenticationToken token;
AuthenticationToken adminToken;
@Before
public void generalSetUp() {
dbUtils.setAutoFlush(false);
token = userService.login(Configuration.ANONYMOUS_LOGIN, null);
// assume that we have admin account with all the privileges
adminToken = userService.login("admin", "admin");
}
@After
public void generatTearDown() throws IOException {
File f = new File("map_images");
if (f.exists()) {
logger.info("Removing output test directory: " + f.getAbsolutePath());
FileUtils.deleteDirectory(f);
}
}
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 = RestTestFunctions.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));
RestTestFunctions.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();
}
}
#Set root logger 's level and its appender to an appender called CONSOLE which is defined below.
log4j.rootLogger=info, CONSOLE, R
#Set the behavior of the CONSOLE appender
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%d %5p [%t] (%F:%L) - %m%n
#log4j.appender.CONSOLE.layout.ConversionPattern=%m%n
#Set the behavior of the FILE appender
log4j.appender.R=org.apache.log4j.FileAppender
log4j.appender.R.File=${catalina.home}/logs/MapViewer.log
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%d %5p [%t] (%F:%L) - %m%n
log4j.logger.org.springframework=warn
log4j.logger.org.hibernate=warn
log4j.logger.lcsb=debug
log4j.logger.lcsb.mapviewer.annotation.cache=info
log4j.logger.lcsb.mapviewer.persist=info
\ No newline at end of file
This diff is collapsed.
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment