├── .coveralls.yml ├── .gitignore ├── .travis.yml ├── LICENSE.txt ├── README.md ├── docs └── images │ ├── logo.ai │ ├── logo.png │ └── logo300.png ├── examples ├── R │ └── README.md ├── javascript │ └── README.md └── python │ ├── README.md │ └── basic │ ├── .ipynb_checkpoints │ ├── CytoscapeREST_Basic1-checkpoint.ipynb │ └── CytoscapeREST_Basic2-checkpoint.ipynb │ ├── CytoscapeREST_Basic1.ipynb │ ├── CytoscapeREST_Basic2.ipynb │ ├── cytoscape │ ├── __init__.py │ ├── __init__.pyc │ ├── arbor.js │ ├── cyjs.pyc │ ├── loader.js │ ├── main.pyc │ ├── template.html │ ├── viewer.py │ └── viewer.pyc │ └── sample_data │ └── yeast_network.json ├── pom.xml └── src ├── main └── java │ └── org │ └── cytoscape │ └── rest │ └── internal │ ├── CyActivator.java │ ├── EdgeBundler.java │ ├── EncodingUtil.java │ ├── GraphicsWriterManager.java │ ├── MappingFactoryManager.java │ ├── TaskFactoryManager.java │ ├── TaskFactoryManagerImpl.java │ ├── commands │ ├── handlers │ │ ├── MessageHandler.java │ │ ├── TextHTMLHandler.java │ │ └── TextPlainHandler.java │ └── resources │ │ └── CommandResource.java │ ├── datamapper │ ├── GroupMapper.java │ ├── MapperUtil.java │ ├── TableMapper.java │ ├── VisualStyleMapper.java │ └── package-info.java │ ├── model │ ├── CyJsNetwork.java │ ├── CytoscapeVersion.java │ ├── Edge.java │ ├── EdgeData.java │ ├── Elements.java │ ├── MemoryStatus.java │ ├── NetworkData.java │ ├── Node.java │ ├── NodeData.java │ └── ServerStatus.java │ ├── reader │ ├── EdgeListReader.java │ ├── EdgeListReaderFactory.java │ ├── EdgeTableReader.java │ └── package-info.java │ ├── resource │ ├── AbstractResource.java │ ├── AlgorithmicResource.java │ ├── CyExceptionMapper.java │ ├── GlobalTableResource.java │ ├── GroupResource.java │ ├── JsonTags.java │ ├── MiscResource.java │ ├── NetworkFullResource.java │ ├── NetworkNameResource.java │ ├── NetworkResource.java │ ├── NetworkViewResource.java │ ├── RootResource.java │ ├── SessionResource.java │ ├── StyleResource.java │ ├── TableResource.java │ ├── UIResource.java │ └── package-info.java │ ├── serializer │ ├── ContinuousMappingSerializer.java │ ├── CyTableSerializer.java │ ├── DiscreteMappingSerializer.java │ ├── GraphObjectSerializer.java │ ├── GroupModule.java │ ├── GroupSerializer.java │ ├── PassthroughMappingSerializer.java │ ├── RowSerializer.java │ ├── TableModule.java │ ├── TableSerializer.java │ ├── VisualMappingsSerializer.java │ ├── VisualStyleModule.java │ ├── VisualStyleSerializer.java │ └── package-info.java │ └── task │ ├── CyBinder.java │ ├── GrizzlyServerManager.java │ └── HeadlessTaskMonitor.java └── test ├── java └── org │ └── cytoscape │ └── rest │ ├── JSONTranslatorTest.java │ ├── NetworkMapperTest.java │ ├── TableMapperTest.java │ ├── TableModuleTest.java │ ├── inetrnal │ └── reader │ │ └── EdgeListReaderTest.java │ └── service │ ├── AlgorithmicResourceTest.java │ ├── BasicResourceTest.java │ ├── GlobalResourceTest.java │ ├── GroupTest.java │ ├── NetworkDataServiceTest.java │ ├── NetworkNameResourceTest.java │ ├── NetworkResourceDeletionTest.java │ ├── NetworkResourceTest.java │ ├── NetworkViewResourceTest.java │ ├── RootTest.java │ ├── SessionResourceTest.java │ ├── StyleResourceTest.java │ ├── TableResourceTest.java │ └── UiResourceTest.java └── resources ├── galFiltered.cyjs ├── json └── galFiltered.json ├── net10k.txt ├── node_test.js ├── small.el └── table_test.js /.coveralls.yml: -------------------------------------------------------------------------------- 1 | service_name: travis-ci 2 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | target 2 | .project 3 | .DS_Store 4 | .classpath 5 | .settings -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: java 2 | 3 | sudo: false 4 | 5 | jdk: 6 | - oraclejdk8 7 | 8 | branches: 9 | only: 10 | - develop 11 | - master 12 | 13 | after_success: 14 | - mvn clean cobertura:cobertura coveralls:report 15 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2014-2015 The Cytoscape Consortium 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in 13 | all copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | THE SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # This repoditory is obsolete. 2 | # Please visit [new repository](https://github.com/cytoscape/cyREST) 3 | 4 | ![](http://cl.ly/XohP/logo300.png) 5 | 6 | # cyREST: a language-agnostic RESTful API for Cytoscape 7 | 8 | [![Build Status](https://travis-ci.org/idekerlab/cyREST.svg?branch=develop)](https://travis-ci.org/idekerlab/cyREST) 9 | 10 | [![Coverage Status](https://coveralls.io/repos/idekerlab/cyREST/badge.svg)](https://coveralls.io/r/idekerlab/cyREST) 11 | 12 | ![](http://cl.ly/Xemf/networkx_cytoscape.png) 13 | 14 | ## Introduction 15 | 16 | ### In One Sentence 17 | __An application to control [Cytoscape](http://www.cytoscape.org) from [RStudio](http://www.rstudio.com/), [IPython Notebook](http://ipython.org/notebook.html), [Node.js](http://nodejs.org/) or other programming languages.__ 18 | 19 | ### More Details 20 | This is a Cytoscape App to provide low-level API access to Cytoscape data objects, including networks, data tables, and Visual Styles, for programming languages such as R, Python, JavaScript, and MATLAB via RESTful API. You can write your own Cytoscape workflows with programming languages of your choice. 21 | 22 | __This app is still in beta status and we need your feedback!__ 23 | 24 | ## System Requirements 25 | To use cyREST 0.9.16 and newer, you need the following: 26 | 27 | * [Java 8](http://www.oracle.com/technetwork/java/javase/downloads/index.html) 28 | * Oracle JDK is recommended, but should be compatible with OpenJDK. 29 | * __Does not work with Java 7 and older!!__ 30 | * [Cytoscape 3.2.1+](http://www.cytoscape.org/) 31 | 32 | ## Documentation 33 | __All documents, including tutorials and full API list, are available from our [Wiki](https://github.com/idekerlab/cyREST/wiki)__. 34 | 35 | ## Problems or Feature Requests? 36 | The API Version 1 is not finalized yet. Please send your feature requests to our [mailing list](https://groups.google.com/forum/#!forum/cytoscape-discuss). 37 | 38 | Please report the problems to our issue tracker: 39 | 40 | * [cyREST Issue Tracker](https://github.com/idekerlab/cyREST/issues) 41 | 42 | And of course, pull requests are always welcome! 43 | 44 | ## License 45 | * Source Code: [The MIT license](http://opensource.org/licenses/MIT) 46 | * Documentation: [CC BY-SA 4.0](http://creativecommons.org/licenses/by-sa/4.0/) 47 | 48 | ## Cite cyREST 49 | (TBD) 50 | 51 | ---- 52 | © 2014-2015 [Cytoscape Consortium](http://www.cytoscape.org/). Developed and maintained by [Keiichiro Ono](http://keiono.github.io/), [UCSD Trey Ideker Lab](http://idekerlab.ucsd.edu/Pages/default.aspx). 53 | -------------------------------------------------------------------------------- /docs/images/logo.ai: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/idekerlab/cyREST/0c30dbfda73b8695a23df0c5df294ccb0d847556/docs/images/logo.ai -------------------------------------------------------------------------------- /docs/images/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/idekerlab/cyREST/0c30dbfda73b8695a23df0c5df294ccb0d847556/docs/images/logo.png -------------------------------------------------------------------------------- /docs/images/logo300.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/idekerlab/cyREST/0c30dbfda73b8695a23df0c5df294ccb0d847556/docs/images/logo300.png -------------------------------------------------------------------------------- /examples/R/README.md: -------------------------------------------------------------------------------- 1 | # R Examples 2 | 3 | # Introduction 4 | 5 | -------------------------------------------------------------------------------- /examples/javascript/README.md: -------------------------------------------------------------------------------- 1 | # JavaScript Workflows 2 | 3 | ## Introduction 4 | 5 | -------------------------------------------------------------------------------- /examples/python/README.md: -------------------------------------------------------------------------------- 1 | # Python Examples 2 | 3 | -------------------------------------------------------------------------------- /examples/python/basic/.ipynb_checkpoints/CytoscapeREST_Basic2-checkpoint.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "metadata": { 3 | "name": "", 4 | "signature": "sha256:d6a3efd7903943b5456e9a2eaee13132dae0cec1b7b0edb74c51396fa893f386" 5 | }, 6 | "nbformat": 3, 7 | "nbformat_minor": 0, 8 | "worksheets": [ 9 | { 10 | "cells": [ 11 | { 12 | "cell_type": "markdown", 13 | "metadata": {}, 14 | "source": [ 15 | "# Basic Workflow 2: NetworkX and Cytoscape\n", 16 | "\n", 17 | "\n", 18 | "by [Keiichiro Ono](http://keiono.github.io/)\n", 19 | "\n", 20 | "\n", 21 | "----\n", 22 | "\n", 23 | "![](http://cytoscape.org/images/logo/cy3logoOrange.svg)\n", 24 | "\n", 25 | "\n", 26 | "![](http://ipython.org/_static/IPy_header.png)\n", 27 | "\n", 28 | "\n", 29 | "## Introduction\n", 30 | "Welcome to the part 2 of basic tutorial. In this example, you will learn how to use Cytoscape with NetworkX, a very poweful network analysis toolkit.\n", 31 | "\n", 32 | "### Prerequisites\n", 33 | "* Basic knowledge of RESTful API\n", 34 | " * [This is a good introduction to REST](http://www.restapitutorial.com/)\n", 35 | "* Basic Python skill\n", 36 | "* Basic knowledge of Cytoscape \n", 37 | "\n", 38 | "### System Requirments\n", 39 | "* [Java 7+](http://www.oracle.com/technetwork/java/javase/downloads/jdk7-downloads-1880260.html)\n", 40 | "* [Cytoscape 3.1.1 or later](http://cytoscape.org/download.html)\n", 41 | "* Latest version of [cy-rest app](https://github.com/keiono/cy-rest/releases/latest)\n", 42 | "\n", 43 | "----\n", 44 | "## Questions or Feature Requests?\n", 45 | "Please send them to our [mailing list](https://groups.google.com/forum/#!forum/cytoscape-discuss)" 46 | ] 47 | }, 48 | { 49 | "cell_type": "code", 50 | "collapsed": false, 51 | "input": [ 52 | "import requests\n", 53 | "import json\n", 54 | "import networkx as nx\n", 55 | "\n", 56 | "# Basic Setup\n", 57 | "PORT_NUMBER = 1234\n", 58 | "BASE = 'http://localhost:' + str(PORT_NUMBER) + '/v1/'\n", 59 | "\n", 60 | "# Header for posting data to the server as JSON\n", 61 | "HEADERS = {'Content-Type': 'application/json'}" 62 | ], 63 | "language": "python", 64 | "metadata": {}, 65 | "outputs": [], 66 | "prompt_number": 1 67 | }, 68 | { 69 | "cell_type": "markdown", 70 | "metadata": {}, 71 | "source": [ 72 | "## Generate Networks with NetworkX\n", 73 | "\n", 74 | "### Generate scale-free networks" 75 | ] 76 | }, 77 | { 78 | "cell_type": "code", 79 | "collapsed": false, 80 | "input": [ 81 | "graphs = []\n", 82 | "\n", 83 | "# Create 10 small randome networks\n", 84 | "for i in range(10):\n", 85 | " # Generate scale-free graph\n", 86 | " g = nx.scale_free_graph(50);\n", 87 | " \n", 88 | " # Perform simple graph analysis\n", 89 | " \n", 90 | " # Node statistics\n", 91 | " bc = nx.betweenness_centrality(g)\n", 92 | " degree = nx.degree(g)\n", 93 | " cc = nx.closeness_centrality(g)\n", 94 | " nx.set_node_attributes(g, 'betweenness', bc)\n", 95 | " nx.set_node_attributes(g, 'closeness', cc)\n", 96 | " nx.set_node_attributes(g, 'degree', degree)\n", 97 | " \n", 98 | " # Network statistics\n", 99 | " g.graph[\"avg_shortest_path_len\"] = nx.average_shortest_path_length(g)\n", 100 | " g.graph[\"density\"] = nx.density(g)\n", 101 | " graphs.append(g)" 102 | ], 103 | "language": "python", 104 | "metadata": {}, 105 | "outputs": [], 106 | "prompt_number": 6 107 | }, 108 | { 109 | "cell_type": "markdown", 110 | "metadata": {}, 111 | "source": [ 112 | "### Send all network models to Cytoscape" 113 | ] 114 | }, 115 | { 116 | "cell_type": "code", 117 | "collapsed": false, 118 | "input": [ 119 | "# Remove all networks\n", 120 | "requests.delete(BASE + 'networks')\n", 121 | "\n", 122 | "import cytoscape.viewer as cy\n", 123 | "\n", 124 | "for graph in graphs:\n", 125 | " cyjs_network = cy.from_networkx(graph)\n", 126 | " res1 = requests.post(BASE + 'networks', data=json.dumps(cyjs_network), headers=HEADERS)" 127 | ], 128 | "language": "python", 129 | "metadata": {}, 130 | "outputs": [], 131 | "prompt_number": 7 132 | }, 133 | { 134 | "cell_type": "markdown", 135 | "metadata": {}, 136 | "source": [ 137 | "## (Now graphs are in Cytoscape. Do analysis, visualization, etc...)" 138 | ] 139 | }, 140 | { 141 | "cell_type": "markdown", 142 | "metadata": {}, 143 | "source": [ 144 | "## Get the visualization back to this notebook." 145 | ] 146 | }, 147 | { 148 | "cell_type": "code", 149 | "collapsed": false, 150 | "input": [ 151 | "response = requests.get(BASE + 'networks?format=SUID')\n", 152 | "network_list = json.loads(response.content)\n", 153 | "print(network_list)\n", 154 | "\n", 155 | "network_views = []\n", 156 | "for suid in network_list:\n", 157 | " response2 = requests.get(BASE + 'networks/' + str(suid) + \"/views/first\")\n", 158 | " network_views.append(json.loads(response2.content))" 159 | ], 160 | "language": "python", 161 | "metadata": {}, 162 | "outputs": [ 163 | { 164 | "output_type": "stream", 165 | "stream": "stdout", 166 | "text": [ 167 | "[64700, 66370, 66720, 64008, 66054, 64362, 65726, 65028, 67068, 65340]\n" 168 | ] 169 | } 170 | ], 171 | "prompt_number": 9 172 | }, 173 | { 174 | "cell_type": "code", 175 | "collapsed": false, 176 | "input": [ 177 | "# Visual Style can be a simple Python object!\n", 178 | "\n", 179 | "my_style = {\n", 180 | " \"title\" : \"My Style 10\",\n", 181 | " \"defaults\" : [ {\n", 182 | " \"visualProperty\" : \"EDGE_WIDTH\",\n", 183 | " \"value\" : 11.0\n", 184 | " }, {\n", 185 | " \"visualProperty\" : \"EDGE_STROKE_UNSELECTED_PAINT\",\n", 186 | " \"value\" : \"#00ddff\"\n", 187 | " }, {\n", 188 | " \"visualProperty\" : \"NODE_WIDTH\",\n", 189 | " \"value\" : 20\n", 190 | " }, {\n", 191 | " \"visualProperty\" : \"NODE_HEIGHT\",\n", 192 | " \"value\" : 20\n", 193 | " }],\n", 194 | " \"mappings\" : [ {\n", 195 | " \"mappingType\" : \"discrete\",\n", 196 | " \"mappingColumn\" : \"degree\",\n", 197 | " \"mappingColumnType\" : \"Integer\",\n", 198 | " \"visualProperty\" : \"NODE_FILL_COLOR\",\n", 199 | " \"map\" : [ {\n", 200 | " \"key\" : \"1\",\n", 201 | " \"value\" : \"#440055\"\n", 202 | " }, {\n", 203 | " \"key\" : \"4\",\n", 204 | " \"value\" : \"#00FF11\"\n", 205 | " } ]\n", 206 | " }, {\n", 207 | " \"mappingType\" : \"passthrough\",\n", 208 | " \"mappingColumn\" : \"name\",\n", 209 | " \"mappingColumnType\" : \"String\",\n", 210 | " \"visualProperty\" : \"NODE_LABEL\"\n", 211 | " } ]\n", 212 | "}\n", 213 | "\n", 214 | "requests.post(BASE + \"styles\", data=json.dumps(my_style), headers=HEADERS)" 215 | ], 216 | "language": "python", 217 | "metadata": {}, 218 | "outputs": [ 219 | { 220 | "metadata": {}, 221 | "output_type": "pyout", 222 | "prompt_number": 11, 223 | "text": [ 224 | "" 225 | ] 226 | } 227 | ], 228 | "prompt_number": 11 229 | } 230 | ], 231 | "metadata": {} 232 | } 233 | ] 234 | } -------------------------------------------------------------------------------- /examples/python/basic/CytoscapeREST_Basic2.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "metadata": { 3 | "name": "", 4 | "signature": "sha256:d6a3efd7903943b5456e9a2eaee13132dae0cec1b7b0edb74c51396fa893f386" 5 | }, 6 | "nbformat": 3, 7 | "nbformat_minor": 0, 8 | "worksheets": [ 9 | { 10 | "cells": [ 11 | { 12 | "cell_type": "markdown", 13 | "metadata": {}, 14 | "source": [ 15 | "# Basic Workflow 2: NetworkX and Cytoscape\n", 16 | "\n", 17 | "\n", 18 | "by [Keiichiro Ono](http://keiono.github.io/)\n", 19 | "\n", 20 | "\n", 21 | "----\n", 22 | "\n", 23 | "![](http://cytoscape.org/images/logo/cy3logoOrange.svg)\n", 24 | "\n", 25 | "\n", 26 | "![](http://ipython.org/_static/IPy_header.png)\n", 27 | "\n", 28 | "\n", 29 | "## Introduction\n", 30 | "Welcome to the part 2 of basic tutorial. In this example, you will learn how to use Cytoscape with NetworkX, a very poweful network analysis toolkit.\n", 31 | "\n", 32 | "### Prerequisites\n", 33 | "* Basic knowledge of RESTful API\n", 34 | " * [This is a good introduction to REST](http://www.restapitutorial.com/)\n", 35 | "* Basic Python skill\n", 36 | "* Basic knowledge of Cytoscape \n", 37 | "\n", 38 | "### System Requirments\n", 39 | "* [Java 7+](http://www.oracle.com/technetwork/java/javase/downloads/jdk7-downloads-1880260.html)\n", 40 | "* [Cytoscape 3.1.1 or later](http://cytoscape.org/download.html)\n", 41 | "* Latest version of [cy-rest app](https://github.com/keiono/cy-rest/releases/latest)\n", 42 | "\n", 43 | "----\n", 44 | "## Questions or Feature Requests?\n", 45 | "Please send them to our [mailing list](https://groups.google.com/forum/#!forum/cytoscape-discuss)" 46 | ] 47 | }, 48 | { 49 | "cell_type": "code", 50 | "collapsed": false, 51 | "input": [ 52 | "import requests\n", 53 | "import json\n", 54 | "import networkx as nx\n", 55 | "\n", 56 | "# Basic Setup\n", 57 | "PORT_NUMBER = 1234\n", 58 | "BASE = 'http://localhost:' + str(PORT_NUMBER) + '/v1/'\n", 59 | "\n", 60 | "# Header for posting data to the server as JSON\n", 61 | "HEADERS = {'Content-Type': 'application/json'}" 62 | ], 63 | "language": "python", 64 | "metadata": {}, 65 | "outputs": [], 66 | "prompt_number": 1 67 | }, 68 | { 69 | "cell_type": "markdown", 70 | "metadata": {}, 71 | "source": [ 72 | "## Generate Networks with NetworkX\n", 73 | "\n", 74 | "### Generate scale-free networks" 75 | ] 76 | }, 77 | { 78 | "cell_type": "code", 79 | "collapsed": false, 80 | "input": [ 81 | "graphs = []\n", 82 | "\n", 83 | "# Create 10 small randome networks\n", 84 | "for i in range(10):\n", 85 | " # Generate scale-free graph\n", 86 | " g = nx.scale_free_graph(50);\n", 87 | " \n", 88 | " # Perform simple graph analysis\n", 89 | " \n", 90 | " # Node statistics\n", 91 | " bc = nx.betweenness_centrality(g)\n", 92 | " degree = nx.degree(g)\n", 93 | " cc = nx.closeness_centrality(g)\n", 94 | " nx.set_node_attributes(g, 'betweenness', bc)\n", 95 | " nx.set_node_attributes(g, 'closeness', cc)\n", 96 | " nx.set_node_attributes(g, 'degree', degree)\n", 97 | " \n", 98 | " # Network statistics\n", 99 | " g.graph[\"avg_shortest_path_len\"] = nx.average_shortest_path_length(g)\n", 100 | " g.graph[\"density\"] = nx.density(g)\n", 101 | " graphs.append(g)" 102 | ], 103 | "language": "python", 104 | "metadata": {}, 105 | "outputs": [], 106 | "prompt_number": 6 107 | }, 108 | { 109 | "cell_type": "markdown", 110 | "metadata": {}, 111 | "source": [ 112 | "### Send all network models to Cytoscape" 113 | ] 114 | }, 115 | { 116 | "cell_type": "code", 117 | "collapsed": false, 118 | "input": [ 119 | "# Remove all networks\n", 120 | "requests.delete(BASE + 'networks')\n", 121 | "\n", 122 | "import cytoscape.viewer as cy\n", 123 | "\n", 124 | "for graph in graphs:\n", 125 | " cyjs_network = cy.from_networkx(graph)\n", 126 | " res1 = requests.post(BASE + 'networks', data=json.dumps(cyjs_network), headers=HEADERS)" 127 | ], 128 | "language": "python", 129 | "metadata": {}, 130 | "outputs": [], 131 | "prompt_number": 7 132 | }, 133 | { 134 | "cell_type": "markdown", 135 | "metadata": {}, 136 | "source": [ 137 | "## (Now graphs are in Cytoscape. Do analysis, visualization, etc...)" 138 | ] 139 | }, 140 | { 141 | "cell_type": "markdown", 142 | "metadata": {}, 143 | "source": [ 144 | "## Get the visualization back to this notebook." 145 | ] 146 | }, 147 | { 148 | "cell_type": "code", 149 | "collapsed": false, 150 | "input": [ 151 | "response = requests.get(BASE + 'networks?format=SUID')\n", 152 | "network_list = json.loads(response.content)\n", 153 | "print(network_list)\n", 154 | "\n", 155 | "network_views = []\n", 156 | "for suid in network_list:\n", 157 | " response2 = requests.get(BASE + 'networks/' + str(suid) + \"/views/first\")\n", 158 | " network_views.append(json.loads(response2.content))" 159 | ], 160 | "language": "python", 161 | "metadata": {}, 162 | "outputs": [ 163 | { 164 | "output_type": "stream", 165 | "stream": "stdout", 166 | "text": [ 167 | "[64700, 66370, 66720, 64008, 66054, 64362, 65726, 65028, 67068, 65340]\n" 168 | ] 169 | } 170 | ], 171 | "prompt_number": 9 172 | }, 173 | { 174 | "cell_type": "code", 175 | "collapsed": false, 176 | "input": [ 177 | "# Visual Style can be a simple Python object!\n", 178 | "\n", 179 | "my_style = {\n", 180 | " \"title\" : \"My Style 10\",\n", 181 | " \"defaults\" : [ {\n", 182 | " \"visualProperty\" : \"EDGE_WIDTH\",\n", 183 | " \"value\" : 11.0\n", 184 | " }, {\n", 185 | " \"visualProperty\" : \"EDGE_STROKE_UNSELECTED_PAINT\",\n", 186 | " \"value\" : \"#00ddff\"\n", 187 | " }, {\n", 188 | " \"visualProperty\" : \"NODE_WIDTH\",\n", 189 | " \"value\" : 20\n", 190 | " }, {\n", 191 | " \"visualProperty\" : \"NODE_HEIGHT\",\n", 192 | " \"value\" : 20\n", 193 | " }],\n", 194 | " \"mappings\" : [ {\n", 195 | " \"mappingType\" : \"discrete\",\n", 196 | " \"mappingColumn\" : \"degree\",\n", 197 | " \"mappingColumnType\" : \"Integer\",\n", 198 | " \"visualProperty\" : \"NODE_FILL_COLOR\",\n", 199 | " \"map\" : [ {\n", 200 | " \"key\" : \"1\",\n", 201 | " \"value\" : \"#440055\"\n", 202 | " }, {\n", 203 | " \"key\" : \"4\",\n", 204 | " \"value\" : \"#00FF11\"\n", 205 | " } ]\n", 206 | " }, {\n", 207 | " \"mappingType\" : \"passthrough\",\n", 208 | " \"mappingColumn\" : \"name\",\n", 209 | " \"mappingColumnType\" : \"String\",\n", 210 | " \"visualProperty\" : \"NODE_LABEL\"\n", 211 | " } ]\n", 212 | "}\n", 213 | "\n", 214 | "requests.post(BASE + \"styles\", data=json.dumps(my_style), headers=HEADERS)" 215 | ], 216 | "language": "python", 217 | "metadata": {}, 218 | "outputs": [ 219 | { 220 | "metadata": {}, 221 | "output_type": "pyout", 222 | "prompt_number": 11, 223 | "text": [ 224 | "" 225 | ] 226 | } 227 | ], 228 | "prompt_number": 11 229 | } 230 | ], 231 | "metadata": {} 232 | } 233 | ] 234 | } -------------------------------------------------------------------------------- /examples/python/basic/cytoscape/__init__.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | JS_LOADER_FILE ="loader.js" 4 | 5 | # Initialize 6 | def init(): 7 | from IPython.core.display import display, Javascript 8 | 9 | path = os.path.abspath(os.path.dirname(__file__)) + "/" + JS_LOADER_FILE 10 | js_loader = open(path).read() 11 | return display(Javascript(js_loader)) 12 | 13 | 14 | # Load Cytoscape.js and dependent libraries 15 | init() -------------------------------------------------------------------------------- /examples/python/basic/cytoscape/__init__.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/idekerlab/cyREST/0c30dbfda73b8695a23df0c5df294ccb0d847556/examples/python/basic/cytoscape/__init__.pyc -------------------------------------------------------------------------------- /examples/python/basic/cytoscape/cyjs.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/idekerlab/cyREST/0c30dbfda73b8695a23df0c5df294ccb0d847556/examples/python/basic/cytoscape/cyjs.pyc -------------------------------------------------------------------------------- /examples/python/basic/cytoscape/loader.js: -------------------------------------------------------------------------------- 1 | if (window['cytoscape'] === undefined) { 2 | var paths = { 3 | cytoscape: 'http://cytoscape.github.io/cytoscape.js/api/cytoscape.js-latest/cytoscape.min' 4 | }; 5 | 6 | require.config({ 7 | paths: paths 8 | }); 9 | 10 | require(['cytoscape'], function(cytoscape) { 11 | window['cytoscape'] = cytoscape; 12 | 13 | var event = document.createEvent("HTMLEvents"); 14 | event.initEvent("load_cytoscape", true, false); 15 | window.dispatchEvent(event); 16 | }); 17 | } -------------------------------------------------------------------------------- /examples/python/basic/cytoscape/main.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/idekerlab/cyREST/0c30dbfda73b8695a23df0c5df294ccb0d847556/examples/python/basic/cytoscape/main.pyc -------------------------------------------------------------------------------- /examples/python/basic/cytoscape/template.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 20 | 21 | 56 | 57 | 58 | 59 |
60 | 61 |
62 | 63 | 64 | 65 | -------------------------------------------------------------------------------- /examples/python/basic/cytoscape/viewer.py: -------------------------------------------------------------------------------- 1 | import uuid 2 | import json 3 | import os 4 | 5 | ######### Default Values ########### 6 | 7 | # Define default widget size 8 | DEF_HEIGHT = 700 9 | DEF_WIDTH = 1160 10 | 11 | # Default network 12 | DEF_NODES = [ 13 | { 'data': { 'id': 'Network Data' } }, 14 | { 'data': { 'id': 'Empty' } } 15 | ] 16 | 17 | DEF_EDGES = [ 18 | { 'data': { 'id': 'is', 'source': 'Network Data', 'target': 'Empty' } } 19 | ] 20 | 21 | DEF_LAYOUT = 'preset' 22 | DEF_STYLE = 'default' 23 | 24 | PRESET_LAYOUTS = { 25 | 'Preset': 'preset', 26 | 'Circle':'circle', 27 | 'Concentric':'concentric', 28 | 'Breadthfirst':'breadthfirst', 29 | 'Spring':'cose', 30 | 'Grid':'grid' 31 | } 32 | 33 | DEF_SCALING = 1.0 34 | 35 | HTML_TEMPLATE_FILE = 'template.html' 36 | 37 | 38 | def render(network, style=DEF_STYLE, layout_algorithm=DEF_LAYOUT, height=DEF_HEIGHT, width=DEF_WIDTH): 39 | from jinja2 import Template 40 | from IPython.core.display import display, HTML 41 | 42 | if network==None: 43 | nodes = DEF_NODES 44 | edges = DEF_EDGES 45 | else: 46 | nodes = network['elements']['nodes'] 47 | edges = network['elements']['edges'] 48 | 49 | path = os.path.abspath(os.path.dirname(__file__)) + '/' + HTML_TEMPLATE_FILE 50 | template = Template(open(path).read()) 51 | cyjs_widget = template.render(nodes = json.dumps(nodes), edges = json.dumps(edges), 52 | uuid="cy" + str(uuid.uuid4()), widget_width = str(width), widget_height = str(height), 53 | layout=layout_algorithm, style_json=json.dumps(style)) 54 | 55 | return display(HTML(cyjs_widget)) 56 | 57 | # List of available layout algorithms 58 | def get_layouts(): 59 | return PRESET_LAYOUTS 60 | 61 | 62 | # Convert to Cytoscape.js format from NetworkX object 63 | def from_networkx(networkx_graph): 64 | new_graph = {} 65 | elements = {} 66 | nodes = [] 67 | edges = [] 68 | 69 | nodes_x = networkx_graph.nodes(); 70 | edges_x = networkx_graph.edges(); 71 | 72 | # Network Attributes 73 | net_attr_keys = networkx_graph.graph.keys(); 74 | network_data = {} 75 | for net_key in net_attr_keys: 76 | network_data[net_key] = networkx_graph.graph[net_key] 77 | 78 | new_graph['data'] = network_data 79 | 80 | for node in nodes_x: 81 | new_node = {} 82 | data = {} 83 | data['id'] = str(node) 84 | data['name'] = str(node) 85 | for key in networkx_graph.node[node].keys(): 86 | data[key] = networkx_graph.node[node][key] 87 | new_node['data'] = data 88 | nodes.append(new_node) 89 | 90 | for edge in edges_x: 91 | new_edge = {} 92 | data = {} 93 | data['source'] = str(edge[0]) 94 | data['target'] = str(edge[1]) 95 | 96 | new_edge['data'] = data 97 | edges.append(new_edge) 98 | 99 | elements['nodes'] = nodes 100 | elements['edges'] = edges 101 | new_graph['elements'] = elements 102 | 103 | return new_graph 104 | 105 | 106 | def from_igraph(igraph_network, layout, scale=DEF_SCALING): 107 | new_graph = {} 108 | elements = {} 109 | nodes = [] 110 | edges = [] 111 | 112 | el = igraph_network.get_edgelist() 113 | nodes_original = igraph_network.vs; 114 | 115 | node_attr = igraph_network.vs.attributes() 116 | 117 | idx = 0 118 | for node in nodes_original: 119 | new_node = {} 120 | data = {} 121 | data['id'] = str(node.index) 122 | data['name'] = str(node.index) 123 | for key in node_attr: 124 | data[key] = node[key] 125 | new_node['data'] = data 126 | if layout is not None: 127 | position = {} 128 | position['x'] = layout[idx][0] * scale 129 | position['y'] = layout[idx][1] * scale 130 | new_node['position'] = position 131 | 132 | nodes.append(new_node) 133 | idx = idx + 1 134 | 135 | for edge in el: 136 | new_edge = {} 137 | data = {} 138 | data['source'] = str(edge[0]) 139 | data['target'] = str(edge[1]) 140 | new_edge['data'] = data 141 | edges.append(new_edge) 142 | 143 | elements['nodes'] = nodes 144 | elements['edges'] = edges 145 | new_graph['elements'] = elements 146 | 147 | return new_graph 148 | 149 | def from_sgraph(sgraph): 150 | new_graph = {} 151 | elements = {} 152 | nodes = [] 153 | edges = [] 154 | 155 | nodes_original = sgraph.vertices 156 | el = sgraph.edges; 157 | 158 | node_attr = nodes_original[0].keys() 159 | 160 | for node in nodes_original: 161 | new_node = {} 162 | data = {} 163 | data['id'] = node['__id'] 164 | data['name'] = node['__id'] 165 | for key in node_attr: 166 | data[key] = node[key] 167 | new_node['data'] = data 168 | nodes.append(new_node) 169 | 170 | 171 | for edge in el: 172 | new_edge = {} 173 | data = {} 174 | data['source'] = str(edge['__src_id']) 175 | data['target'] = str(edge['__dst_id']) 176 | new_edge['data'] = data 177 | edges.append(new_edge) 178 | 179 | elements['nodes'] = nodes 180 | elements['edges'] = edges 181 | new_graph['elements'] = elements 182 | 183 | return new_graph 184 | 185 | 186 | def embedShare(url, width=DEF_WIDTH, height=DEF_HEIGHT): 187 | from IPython.core.display import display 188 | from IPython.lib.display import IFrame 189 | return display(IFrame(url, width, height)) -------------------------------------------------------------------------------- /examples/python/basic/cytoscape/viewer.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/idekerlab/cyREST/0c30dbfda73b8695a23df0c5df294ccb0d847556/examples/python/basic/cytoscape/viewer.pyc -------------------------------------------------------------------------------- /src/main/java/org/cytoscape/rest/internal/EdgeBundler.java: -------------------------------------------------------------------------------- 1 | package org.cytoscape.rest.internal; 2 | 3 | import org.cytoscape.task.NetworkTaskFactory; 4 | 5 | public interface EdgeBundler { 6 | 7 | NetworkTaskFactory getBundlerTF(); 8 | 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/org/cytoscape/rest/internal/EncodingUtil.java: -------------------------------------------------------------------------------- 1 | package org.cytoscape.rest.internal; 2 | 3 | import java.nio.charset.Charset; 4 | import java.nio.charset.CharsetEncoder; 5 | 6 | final class EncodingUtil { 7 | 8 | private static final String ENCODING = "UTF-8"; 9 | 10 | public static CharsetEncoder getEncoder() { 11 | final CharsetEncoder encoder; 12 | 13 | if (Charset.isSupported(ENCODING)) { 14 | // UTF-8 is supported by system 15 | encoder = Charset.forName(ENCODING).newEncoder(); 16 | } else { 17 | // Use default. 18 | encoder = Charset.defaultCharset().newEncoder(); 19 | } 20 | 21 | return encoder; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/org/cytoscape/rest/internal/GraphicsWriterManager.java: -------------------------------------------------------------------------------- 1 | package org.cytoscape.rest.internal; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | import java.util.Set; 6 | 7 | import org.cytoscape.io.CyFileFilter; 8 | import org.cytoscape.io.write.PresentationWriterFactory; 9 | 10 | public class GraphicsWriterManager { 11 | 12 | private final Map factories; 13 | 14 | public GraphicsWriterManager() { 15 | factories = new HashMap<>(); 16 | } 17 | 18 | public PresentationWriterFactory getFactory(final String fileType) { 19 | return factories.get(fileType); 20 | } 21 | 22 | @SuppressWarnings("rawtypes") 23 | public void addFactory(PresentationWriterFactory factory, Map properties) { 24 | final CyFileFilter ff = factory.getFileFilter(); 25 | final Set ext = ff.getExtensions(); 26 | 27 | final String firstExt = ext.iterator().next(); 28 | System.out.println("Got writer: " + firstExt); 29 | 30 | factories.put(firstExt, factory); 31 | } 32 | 33 | @SuppressWarnings("rawtypes") 34 | public void removeFactory(PresentationWriterFactory factory, Map properties) { 35 | final CyFileFilter ff = factory.getFileFilter(); 36 | final Set ext = ff.getExtensions(); 37 | factories.remove(ext.iterator().next()); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/org/cytoscape/rest/internal/MappingFactoryManager.java: -------------------------------------------------------------------------------- 1 | package org.cytoscape.rest.internal; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | 6 | import org.cytoscape.view.vizmap.VisualMappingFunctionFactory; 7 | 8 | import com.qmino.miredot.annotations.MireDotIgnore; 9 | 10 | @MireDotIgnore 11 | public class MappingFactoryManager { 12 | 13 | private final Map, VisualMappingFunctionFactory> factories; 14 | 15 | public MappingFactoryManager() { 16 | factories = new HashMap, VisualMappingFunctionFactory>(); 17 | } 18 | 19 | public VisualMappingFunctionFactory getFactory(Class mappingType) { 20 | return factories.get(mappingType); 21 | } 22 | 23 | @SuppressWarnings("rawtypes") 24 | public void addFactory(VisualMappingFunctionFactory factory, Map properties) { 25 | factories.put(factory.getMappingFunctionType(), factory); 26 | } 27 | 28 | @SuppressWarnings("rawtypes") 29 | public void removeFactory(VisualMappingFunctionFactory factory, Map properties) { 30 | factories.remove(factory.getMappingFunctionType()); 31 | } 32 | } -------------------------------------------------------------------------------- /src/main/java/org/cytoscape/rest/internal/TaskFactoryManager.java: -------------------------------------------------------------------------------- 1 | package org.cytoscape.rest.internal; 2 | 3 | import org.cytoscape.task.NetworkCollectionTaskFactory; 4 | import org.cytoscape.task.NetworkTaskFactory; 5 | import org.cytoscape.work.TaskFactory; 6 | 7 | public interface TaskFactoryManager { 8 | 9 | /** 10 | * Get task factory by ID meta data. 11 | * 12 | * @param id 13 | * @return Matching TaskFactory 14 | */ 15 | TaskFactory getTaskFactory(final String id); 16 | 17 | NetworkTaskFactory getNetworkTaskFactory(final String id); 18 | 19 | NetworkCollectionTaskFactory getNetworkCollectionTaskFactory(final String id); 20 | 21 | 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/org/cytoscape/rest/internal/TaskFactoryManagerImpl.java: -------------------------------------------------------------------------------- 1 | package org.cytoscape.rest.internal; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | 6 | import org.cytoscape.task.NetworkCollectionTaskFactory; 7 | import org.cytoscape.task.NetworkTaskFactory; 8 | import org.cytoscape.work.ServiceProperties; 9 | import org.cytoscape.work.TaskFactory; 10 | 11 | 12 | @SuppressWarnings("rawtypes") 13 | public class TaskFactoryManagerImpl implements TaskFactoryManager { 14 | 15 | private Map tfMap = new HashMap(); 16 | 17 | public void addTaskFactory(TaskFactory tf, Map props) { 18 | if (tf == null) 19 | return; 20 | 21 | Object tfID = props.get(ServiceProperties.ID); 22 | if (tfID != null) { 23 | tfMap.put(tfID.toString(), tf); 24 | // System.out.println("## got TF: " + tfID); 25 | } else { 26 | // generate ID from class Name 27 | String tfName = tf.toString(); 28 | // System.out.println("tfName = " + tfName); 29 | tfMap.put(tfName, tf); 30 | } 31 | } 32 | 33 | public void addNetworkTaskFactory(NetworkTaskFactory tf, Map props) { 34 | if (tf == null) 35 | return; 36 | 37 | Object tfID = props.get(ServiceProperties.ID); 38 | if (tfID != null) { 39 | tfMap.put(tfID.toString(), tf); 40 | // System.out.println("## got TF: " + tfID); 41 | } else { 42 | // generate ID from class Name 43 | String tfName = tf.toString(); 44 | // System.out.println("tfName = " + tfName); 45 | tfMap.put(tfName, tf); 46 | } 47 | } 48 | 49 | public void addNetworkCollectionTaskFactory(NetworkCollectionTaskFactory tf, Map props) { 50 | if (tf == null) 51 | return; 52 | 53 | Object tfID = props.get(ServiceProperties.ID); 54 | if (tfID != null) { 55 | tfMap.put(tfID.toString(), tf); 56 | // System.out.println("## got NC TF: " + tfID); 57 | } else { 58 | // generate ID from class Name 59 | String tfName = tf.getClass().getSimpleName(); 60 | // System.out.println("NC = " + tfName); 61 | tfMap.put(tfName, tf); 62 | } 63 | } 64 | 65 | public void removeTaskFactory(TaskFactory command, Map props) { 66 | } 67 | 68 | public void removeNetworkTaskFactory(NetworkTaskFactory command, Map props) { 69 | } 70 | 71 | public void removeNetworkCollectionTaskFactory(NetworkCollectionTaskFactory command, Map props) { 72 | } 73 | 74 | public TaskFactory getTaskFactory(final String id) { 75 | Object tf = tfMap.get(id); 76 | if (tf instanceof TaskFactory) 77 | return (TaskFactory) tf; 78 | else 79 | return null; 80 | } 81 | 82 | public NetworkTaskFactory getNetworkTaskFactory(final String id) { 83 | Object tf = tfMap.get(id); 84 | if (tf instanceof NetworkTaskFactory) 85 | return (NetworkTaskFactory) tf; 86 | else 87 | return null; 88 | } 89 | 90 | public NetworkCollectionTaskFactory getNetworkCollectionTaskFactory(final String id) { 91 | Object tf = tfMap.get(id); 92 | if (tf instanceof NetworkCollectionTaskFactory) 93 | return (NetworkCollectionTaskFactory) tf; 94 | else 95 | return null; 96 | } 97 | 98 | } 99 | -------------------------------------------------------------------------------- /src/main/java/org/cytoscape/rest/internal/commands/handlers/MessageHandler.java: -------------------------------------------------------------------------------- 1 | /* vim: set ts=2: */ 2 | /** 3 | * Copyright (c) 2010 The Regents of the University of California. 4 | * All rights reserved. 5 | * 6 | * Redistribution and use in source and binary forms, with or without 7 | * modification, are permitted provided that the following conditions 8 | * are met: 9 | * 1. Redistributions of source code must retain the above copyright 10 | * notice, this list of conditions, and the following disclaimer. 11 | * 2. Redistributions in binary form must reproduce the above 12 | * copyright notice, this list of conditions, and the following 13 | * disclaimer in the documentation and/or other materials provided 14 | * with the distribution. 15 | * 3. Redistributions must acknowledge that this software was 16 | * originally developed by the UCSF Computer Graphics Laboratory 17 | * under support by the NIH National Center for Research Resources, 18 | * grant P41-RR01081. 19 | * 20 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER "AS IS" AND ANY 21 | * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 22 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 23 | * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS BE LIABLE 24 | * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 25 | * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT 26 | * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR 27 | * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 28 | * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE 29 | * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, 30 | * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 31 | * 32 | */ 33 | package org.cytoscape.rest.internal.commands.handlers; 34 | 35 | public interface MessageHandler { 36 | 37 | public void appendCommand(final String s); 38 | 39 | public void appendError(final String s); 40 | 41 | public void appendWarning(final String s); 42 | 43 | public void appendResult(final Object s); 44 | 45 | public void appendMessage(final String s); 46 | 47 | public String getMessages(); 48 | } 49 | -------------------------------------------------------------------------------- /src/main/java/org/cytoscape/rest/internal/commands/handlers/TextHTMLHandler.java: -------------------------------------------------------------------------------- 1 | /* vim: set ts=2: */ 2 | /** 3 | * Copyright (c) 2010 The Regents of the University of California. 4 | * All rights reserved. 5 | * 6 | * Redistribution and use in source and binary forms, with or without 7 | * modification, are permitted provided that the following conditions 8 | * are met: 9 | * 1. Redistributions of source code must retain the above copyright 10 | * notice, this list of conditions, and the following disclaimer. 11 | * 2. Redistributions in binary form must reproduce the above 12 | * copyright notice, this list of conditions, and the following 13 | * disclaimer in the documentation and/or other materials provided 14 | * with the distribution. 15 | * 3. Redistributions must acknowledge that this software was 16 | * originally developed by the UCSF Computer Graphics Laboratory 17 | * under support by the NIH National Center for Research Resources, 18 | * grant P41-RR01081. 19 | * 20 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER "AS IS" AND ANY 21 | * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 22 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 23 | * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS BE LIABLE 24 | * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 25 | * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT 26 | * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR 27 | * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 28 | * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE 29 | * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, 30 | * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 31 | * 32 | */ 33 | package org.cytoscape.rest.internal.commands.handlers; 34 | 35 | import java.util.ArrayList; 36 | import java.util.List; 37 | 38 | /** 39 | * This is just a lame HTML handler to set things up. There is a lot more we 40 | * could do to style the messages and make them clear, but I don't really 41 | * anticipate anyone will use this from a web browser except for debugging. 42 | */ 43 | public class TextHTMLHandler implements MessageHandler { 44 | List messages; 45 | 46 | public TextHTMLHandler() { 47 | messages = new ArrayList(); 48 | } 49 | 50 | public void appendCommand(String s) { 51 | messages.add("

" 52 | + s + "

"); 53 | } 54 | 55 | public void appendError(String s) { 56 | messages.add("

" 57 | + s + "

"); 58 | } 59 | 60 | public void appendWarning(String s) { 61 | messages.add("

" 62 | + s + "

"); 63 | } 64 | 65 | public void appendResult(Object s) { 66 | messages.add("

" 67 | + s + "

"); 68 | } 69 | 70 | public void appendMessage(String s) { 71 | messages.add("

" 72 | + s + "

"); 73 | } 74 | 75 | public String getMessages() { 76 | String str = ""; 77 | for (String s : messages) { 78 | str += s + "\n"; 79 | } 80 | return str; 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /src/main/java/org/cytoscape/rest/internal/commands/handlers/TextPlainHandler.java: -------------------------------------------------------------------------------- 1 | /* vim: set ts=2: */ 2 | /** 3 | * Copyright (c) 2010 The Regents of the University of California. 4 | * All rights reserved. 5 | * 6 | * Redistribution and use in source and binary forms, with or without 7 | * modification, are permitted provided that the following conditions 8 | * are met: 9 | * 1. Redistributions of source code must retain the above copyright 10 | * notice, this list of conditions, and the following disclaimer. 11 | * 2. Redistributions in binary form must reproduce the above 12 | * copyright notice, this list of conditions, and the following 13 | * disclaimer in the documentation and/or other materials provided 14 | * with the distribution. 15 | * 3. Redistributions must acknowledge that this software was 16 | * originally developed by the UCSF Computer Graphics Laboratory 17 | * under support by the NIH National Center for Research Resources, 18 | * grant P41-RR01081. 19 | * 20 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER "AS IS" AND ANY 21 | * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 22 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 23 | * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS BE LIABLE 24 | * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 25 | * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT 26 | * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR 27 | * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 28 | * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE 29 | * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, 30 | * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 31 | * 32 | */ 33 | package org.cytoscape.rest.internal.commands.handlers; 34 | 35 | import java.util.ArrayList; 36 | import java.util.List; 37 | 38 | public class TextPlainHandler implements MessageHandler { 39 | List messages; 40 | 41 | public TextPlainHandler() { 42 | messages = new ArrayList(); 43 | } 44 | 45 | public void appendCommand(String s) { 46 | messages.add(s); 47 | } 48 | 49 | public void appendError(String s) { 50 | messages.add(s); 51 | } 52 | 53 | public void appendWarning(String s) { 54 | messages.add(s); 55 | } 56 | 57 | public void appendResult(Object s) { 58 | messages.add(s.toString()); 59 | } 60 | 61 | public void appendMessage(String s) { 62 | messages.add(s); 63 | } 64 | 65 | public String getMessages() { 66 | String str = ""; 67 | for (String s : messages) { 68 | str += s + "\n"; 69 | } 70 | return str; 71 | } 72 | } -------------------------------------------------------------------------------- /src/main/java/org/cytoscape/rest/internal/datamapper/GroupMapper.java: -------------------------------------------------------------------------------- 1 | package org.cytoscape.rest.internal.datamapper; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | import org.cytoscape.group.CyGroup; 7 | import org.cytoscape.group.CyGroupFactory; 8 | import org.cytoscape.model.CyEdge; 9 | import org.cytoscape.model.CyNetwork; 10 | import org.cytoscape.model.CyNode; 11 | import org.cytoscape.model.CyRow; 12 | import org.cytoscape.model.subnetwork.CyRootNetwork; 13 | import org.cytoscape.model.subnetwork.CySubNetwork; 14 | 15 | import com.fasterxml.jackson.databind.JsonNode; 16 | 17 | public class GroupMapper { 18 | 19 | 20 | /** 21 | * Create a new group from a list of nodes. 22 | * 23 | * @param rootNode 24 | * @param factory 25 | * @param network 26 | * @return 27 | */ 28 | public CyGroup createGroup(final JsonNode rootNode, final CyGroupFactory factory, final CyNetwork network) { 29 | 30 | // Extract required fields: member nodes and name of new node. 31 | final String groupName = rootNode.get(CyNetwork.NAME).textValue(); 32 | final JsonNode memberNodes = rootNode.get("nodes"); 33 | 34 | // This is optional. 35 | final JsonNode memberEdges = rootNode.get("edges"); 36 | 37 | if(groupName == null || groupName.isEmpty()) { 38 | throw new IllegalArgumentException("Group name is missing."); 39 | } 40 | 41 | if(memberNodes.isArray() == false) { 42 | throw new IllegalArgumentException("Invalid parameter."); 43 | } 44 | 45 | if(memberNodes.size() == 0) { 46 | throw new IllegalArgumentException("Group member list is empty."); 47 | } 48 | 49 | // Phase 1: Create list of member nodes. 50 | final List nodes = new ArrayList(); 51 | for (final JsonNode node : memberNodes) { 52 | final CyNode n = network.getNode(node.asLong()); 53 | if (n != null) { 54 | nodes.add(n); 55 | } 56 | } 57 | 58 | // Phase 2: Create group from the list of nodes. 59 | final CyGroup group = factory.createGroup(network, nodes, null, true); 60 | final CyRow groupRow = ((CySubNetwork)network).getRootNetwork().getRow(group.getGroupNode(), CyRootNetwork.SHARED_ATTRS); 61 | groupRow.set(CyRootNetwork.SHARED_NAME, groupName); 62 | 63 | // Add edges if necessary... 64 | if (memberEdges != null && memberEdges.isArray()) { 65 | final List edges = new ArrayList(); 66 | for (final JsonNode edge : memberEdges) { 67 | final CyEdge e = network.getEdge(edge.asLong()); 68 | if (e != null) { 69 | edges.add(e); 70 | } 71 | } 72 | group.addEdges(edges); 73 | } 74 | 75 | return group; 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /src/main/java/org/cytoscape/rest/internal/datamapper/MapperUtil.java: -------------------------------------------------------------------------------- 1 | package org.cytoscape.rest.internal.datamapper; 2 | 3 | import com.fasterxml.jackson.databind.JsonNode; 4 | 5 | public class MapperUtil { 6 | 7 | public static final Class getColumnClass(final String type) { 8 | if (type.equals(Double.class.getSimpleName())) { 9 | return Double.class; 10 | } else if (type.equals(Long.class.getSimpleName())) { 11 | return Long.class; 12 | } else if (type.equals(Integer.class.getSimpleName())) { 13 | return Integer.class; 14 | } else if (type.equals(Float.class.getSimpleName())) { 15 | return Float.class; 16 | } else if (type.equals(Boolean.class.getSimpleName())) { 17 | return Boolean.class; 18 | } else if (type.equals(String.class.getSimpleName())) { 19 | return String.class; 20 | } else if (type.equals(Number.class.getSimpleName())) { 21 | return Double.class; 22 | } else { 23 | return null; 24 | } 25 | } 26 | 27 | public static final Object getRawValue(final String queryString, Class type) { 28 | Object raw = queryString; 29 | 30 | if (type == Boolean.class) { 31 | raw = Boolean.parseBoolean(queryString); 32 | } else if (type == Double.class) { 33 | raw = Double.parseDouble(queryString); 34 | } else if (type == Integer.class) { 35 | raw = Integer.parseInt(queryString); 36 | } else if (type == Long.class) { 37 | raw = Long.parseLong(queryString); 38 | } else if (type == Float.class) { 39 | raw = Float.parseFloat(queryString); 40 | } 41 | return raw; 42 | } 43 | 44 | public static final Object getValue(final JsonNode value, final Class type) { 45 | if (type == String.class) { 46 | return value.asText(); 47 | } else if (type == Boolean.class || type.getSimpleName() == "boolean") { 48 | return value.asBoolean(); 49 | } else if (type == Double.class || type.getSimpleName() == "double") { 50 | return value.asDouble(); 51 | } else if (type == Integer.class || type.getSimpleName() == "int") { 52 | return value.asInt(); 53 | } else if (type == Long.class || type.getSimpleName() == "long") { 54 | return value.asLong(); 55 | } else if (type == Float.class || type.getSimpleName() == "float") { 56 | return value.asDouble(); 57 | } else { 58 | return null; 59 | } 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /src/main/java/org/cytoscape/rest/internal/datamapper/TableMapper.java: -------------------------------------------------------------------------------- 1 | package org.cytoscape.rest.internal.datamapper; 2 | 3 | import java.util.Collection; 4 | import java.util.Iterator; 5 | import java.util.List; 6 | 7 | import javax.ws.rs.NotFoundException; 8 | 9 | import org.cytoscape.model.CyColumn; 10 | import org.cytoscape.model.CyIdentifiable; 11 | import org.cytoscape.model.CyRow; 12 | import org.cytoscape.model.CyTable; 13 | import org.cytoscape.rest.internal.resource.JsonTags; 14 | 15 | import com.fasterxml.jackson.databind.JsonNode; 16 | 17 | /** 18 | * Create & Update table objects. 19 | * 20 | * 21 | */ 22 | public class TableMapper { 23 | 24 | public void updateColumnName(final JsonNode rootNode, final CyTable table) { 25 | final JsonNode currentNameTag = rootNode.get(JsonTags.COLUMN_NAME_OLD); 26 | if(currentNameTag == null) { 27 | throw new IllegalArgumentException("Original column name is missing."); 28 | } 29 | 30 | final JsonNode newNameTag = rootNode.get(JsonTags.COLUMN_NAME_NEW); 31 | if(newNameTag == null) { 32 | throw new IllegalArgumentException("New column name is missing."); 33 | } 34 | 35 | final String currentName = currentNameTag.asText(); 36 | if(currentName == null || currentName.isEmpty()) { 37 | throw new IllegalArgumentException("Original column name is missing."); 38 | } 39 | final String newName = newNameTag.asText(); 40 | if(newName == null || newName.isEmpty()) { 41 | throw new IllegalArgumentException("New column name is missing."); 42 | } 43 | 44 | final CyColumn column = table.getColumn(currentName); 45 | if (column == null) { 46 | throw new NotFoundException("Column does not exist."); 47 | } 48 | column.setName(newName); 49 | } 50 | 51 | public void createNewColumn(final JsonNode rootNode, 52 | final CyTable table, final CyTable localTable) { 53 | // Extract required fields 54 | final String columnName = rootNode.get(JsonTags.COLUMN_NAME).textValue(); 55 | final Class type = MapperUtil.getColumnClass(rootNode.get(JsonTags.COLUMN_TYPE).textValue()); 56 | 57 | if(table.getColumn(columnName) !=null) { 58 | throw new IllegalArgumentException("Column already exists: " + columnName); 59 | } 60 | 61 | // Optional: fields 62 | boolean isImmutable = false; 63 | boolean isList = false; 64 | boolean isLocal = false; 65 | final JsonNode immutable = rootNode.get(JsonTags.COLUMN_IMMUTABLE); 66 | final JsonNode list = rootNode.get(JsonTags.COLUMN_IS_LIST); 67 | final JsonNode local = rootNode.get(JsonTags.COLUMN_IS_LOCAL); 68 | if(list != null) { 69 | isList = list.asBoolean(); 70 | } 71 | if(immutable != null) { 72 | isImmutable = immutable.asBoolean(); 73 | } 74 | if(local != null) { 75 | isLocal = local.asBoolean(); 76 | } 77 | 78 | if(isList) { 79 | if(isLocal) { 80 | localTable.createListColumn(columnName, type, isImmutable); 81 | } else { 82 | table.createListColumn(columnName, type, isImmutable); 83 | } 84 | } else { 85 | if(isLocal) { 86 | localTable.createColumn(columnName, type, isImmutable); 87 | } else { 88 | table.createColumn(columnName, type, isImmutable); 89 | } 90 | } 91 | } 92 | 93 | public void updateColumnValues(final JsonNode rootNode, final CyTable table, final String columnName) { 94 | // This should be an array of objects 95 | for(final JsonNode entry:rootNode) { 96 | final Long primaryKey = entry.get(CyIdentifiable.SUID).asLong(); 97 | final CyRow row = table.getRow(primaryKey); 98 | if(row == null) { 99 | continue; 100 | } 101 | 102 | JsonNode value = entry.get("value"); 103 | setValue(table.getColumn(columnName).getType(), value, row, columnName); 104 | } 105 | } 106 | 107 | 108 | public void updateAllColumnValues(final String defaultValue, final CyTable table, final String columnName) { 109 | // This should be an array of objects 110 | final Class dataType = table.getColumn(columnName).getType(); 111 | for(final CyRow row : table.getAllRows()) { 112 | assignValue(defaultValue, dataType, row, columnName); 113 | } 114 | } 115 | 116 | 117 | /** 118 | * This is for PUT method for default tables. 119 | * 120 | * @param rootNode a JSON array. 121 | * @param table CyTable to be updated. 122 | * 123 | */ 124 | 125 | private static final String KEY = "key"; 126 | private static final String DATA_KEY = "dataKey"; 127 | private static final String DATA = "data"; 128 | 129 | public void updateTableValues(final JsonNode rootNode, final CyTable table) { 130 | // Validate body 131 | final JsonNode data = rootNode.get(DATA); 132 | if(data == null) { 133 | throw new NotFoundException("Data array is missing."); 134 | } 135 | if(!data.isArray()) { 136 | throw new IllegalArgumentException("Data should be an array."); 137 | } 138 | 139 | final JsonNode keyCol = rootNode.get(KEY); 140 | final String keyColName; 141 | if(keyCol == null) { 142 | // If not specified, simply use SUID. 143 | keyColName = CyIdentifiable.SUID; 144 | } else { 145 | keyColName = keyCol.asText(); 146 | } 147 | 148 | // Check such column exists or not. 149 | final CyColumn col = table.getColumn(keyColName); 150 | if(col == null) { 151 | throw new NotFoundException("No such column in the table: " + keyColName); 152 | } 153 | 154 | final JsonNode dataKeyCol = rootNode.get(DATA_KEY); 155 | final String dataKeyColName; 156 | if(dataKeyCol == null) { 157 | dataKeyColName = CyIdentifiable.SUID; 158 | } else { 159 | dataKeyColName = dataKeyCol.asText(); 160 | } 161 | 162 | // This should be an array of objects 163 | for(final JsonNode entry:data) { 164 | final JsonNode keyValue = entry.get(dataKeyColName); 165 | if(keyValue == null) { 166 | // Skip the entry if there is no mapping key value. 167 | continue; 168 | } 169 | 170 | final Object key = MapperUtil.getValue(keyValue, col.getType()); 171 | if(key == null) { 172 | // Key is invalid. 173 | continue; 174 | } 175 | final Collection machingRows = table.getMatchingRows(keyColName, key); 176 | 177 | if(machingRows.isEmpty()) { 178 | continue; 179 | } 180 | 181 | for (final CyRow row : machingRows) { 182 | final Iterator fields = entry.fieldNames(); 183 | while (fields.hasNext()) { 184 | final String field = fields.next(); 185 | final JsonNode value = entry.get(field); 186 | if(value == null) { 187 | continue; 188 | } 189 | 190 | CyColumn column = table.getColumn(field); 191 | if (column == null) { 192 | // Need to create new column. 193 | final Class type = getValueType(value); 194 | if(type == List.class) { 195 | // List is not supported. 196 | continue; 197 | } 198 | table.createColumn(field, type, false); 199 | column = table.getColumn(field); 200 | } 201 | 202 | try { 203 | setValue(column.getType(), value, row, field); 204 | } catch (Exception e) { 205 | // Simply ignore invalid value 206 | e.printStackTrace(); 207 | continue; 208 | } 209 | } 210 | } 211 | } 212 | } 213 | 214 | 215 | 216 | 217 | private final void setValue(final Class type, final JsonNode value, final CyRow row, final String columnName) { 218 | if (type == String.class) { 219 | row.set(columnName, value.asText()); 220 | } else if (type == Boolean.class) { 221 | row.set(columnName, value.asBoolean()); 222 | } else if (type == Double.class) { 223 | row.set(columnName, value.asDouble()); 224 | } else if (type == Integer.class) { 225 | row.set(columnName, value.asInt()); 226 | } else if (type == Long.class) { 227 | row.set(columnName, value.asLong()); 228 | } else if (type == Float.class) { 229 | row.set(columnName, value.asDouble()); 230 | } 231 | } 232 | 233 | private final void assignValue(final String value, final Class type, final CyRow row, final String columnName) { 234 | if (type == String.class) { 235 | row.set(columnName, value.toString()); 236 | } else if (type == Boolean.class) { 237 | row.set(columnName, Boolean.parseBoolean(value)); 238 | } else if (type == Double.class) { 239 | row.set(columnName, Double.parseDouble(value)); 240 | } else if (type == Integer.class) { 241 | row.set(columnName, Integer.parseInt(value)); 242 | } else if (type == Long.class) { 243 | row.set(columnName, Long.parseLong(value)); 244 | } else if (type == Float.class) { 245 | row.set(columnName, Double.parseDouble(value)); 246 | } 247 | } 248 | 249 | /** 250 | * Check data type. All numbers will be set to Double. 251 | * 252 | * @param value 253 | * @return 254 | * 255 | */ 256 | private final Class getValueType(final JsonNode value) { 257 | if (value.isArray()) { 258 | return List.class; 259 | } else if (value.isBoolean()) { 260 | return Boolean.class; 261 | } else if (value.isNumber()) { 262 | return Double.class; 263 | } else { 264 | return String.class; 265 | } 266 | } 267 | } 268 | -------------------------------------------------------------------------------- /src/main/java/org/cytoscape/rest/internal/datamapper/VisualStyleMapper.java: -------------------------------------------------------------------------------- 1 | package org.cytoscape.rest.internal.datamapper; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | import java.util.Set; 6 | 7 | import javax.ws.rs.core.Response; 8 | 9 | import org.cytoscape.model.CyEdge; 10 | import org.cytoscape.model.CyIdentifiable; 11 | import org.cytoscape.model.CyNetwork; 12 | import org.cytoscape.model.CyNode; 13 | import org.cytoscape.rest.internal.MappingFactoryManager; 14 | import org.cytoscape.view.model.View; 15 | import org.cytoscape.view.model.VisualLexicon; 16 | import org.cytoscape.view.model.VisualProperty; 17 | import org.cytoscape.view.vizmap.VisualMappingFunction; 18 | import org.cytoscape.view.vizmap.VisualMappingFunctionFactory; 19 | import org.cytoscape.view.vizmap.VisualPropertyDependency; 20 | import org.cytoscape.view.vizmap.VisualStyle; 21 | import org.cytoscape.view.vizmap.VisualStyleFactory; 22 | import org.cytoscape.view.vizmap.mappings.BoundaryRangeValues; 23 | import org.cytoscape.view.vizmap.mappings.ContinuousMapping; 24 | import org.cytoscape.view.vizmap.mappings.DiscreteMapping; 25 | import org.cytoscape.view.vizmap.mappings.PassthroughMapping; 26 | 27 | import com.fasterxml.jackson.databind.JsonNode; 28 | import com.qmino.miredot.annotations.MireDotIgnore; 29 | 30 | @MireDotIgnore 31 | public class VisualStyleMapper { 32 | 33 | private static final String TITLE = "title"; 34 | private static final String MAPPINGS = "mappings"; 35 | private static final String DEFAULTS = "defaults"; 36 | 37 | public static final String MAPPING_TYPE = "mappingType"; 38 | private static final String MAPPING_DISCRETE = "discrete"; 39 | private static final String MAPPING_PASSTHROUGH = "passthrough"; 40 | private static final String MAPPING_CONTINUOUS = "continuous"; 41 | 42 | public static final String MAPPING_COLUMN = "mappingColumn"; 43 | public static final String MAPPING_COLUMN_TYPE = "mappingColumnType"; 44 | public static final String MAPPING_VP = "visualProperty"; 45 | 46 | private static final String MAPPING_DISCRETE_MAP = "map"; 47 | private static final String MAPPING_DISCRETE_KEY = "key"; 48 | private static final String MAPPING_DISCRETE_VALUE = "value"; 49 | 50 | public static final String VP_DEPENDENCY = "visualPropertyDependency"; 51 | public static final String VP_DEPENDENCY_ENABLED = "enabled"; 52 | 53 | 54 | public VisualStyle buildVisualStyle(final MappingFactoryManager factoryManager, final VisualStyleFactory factory, 55 | final VisualLexicon lexicon, final JsonNode rootNode) { 56 | 57 | final JsonNode title = rootNode.get(TITLE); 58 | final VisualStyle style = factory.createVisualStyle(title.textValue()); 59 | 60 | final JsonNode defaults = rootNode.get(DEFAULTS); 61 | final JsonNode mappings = rootNode.get(MAPPINGS); 62 | 63 | if(defaults != null) { 64 | parseDefaults(defaults, style, lexicon); 65 | } 66 | 67 | if(mappings != null) { 68 | parseMappings(mappings, style, lexicon, factoryManager); 69 | } 70 | return style; 71 | } 72 | 73 | public void buildMappings(final VisualStyle style, final MappingFactoryManager factoryManager, 74 | final VisualLexicon lexicon, final JsonNode mappings) { 75 | parseMappings(mappings, style, lexicon, factoryManager); 76 | } 77 | 78 | public void updateStyleName(final VisualStyle style, 79 | final VisualLexicon lexicon, final JsonNode rootNode) { 80 | final String newTitle = rootNode.get(TITLE).textValue(); 81 | style.setTitle(newTitle); 82 | } 83 | 84 | @SuppressWarnings({ "rawtypes", "unchecked" }) 85 | private final void parseDefaults(final JsonNode defaults, final VisualStyle style, final VisualLexicon lexicon) { 86 | for (final JsonNode vpNode : defaults) { 87 | String vpName = vpNode.get(MAPPING_VP).textValue(); 88 | final VisualProperty vp = getVisualProperty(vpName, lexicon); 89 | final JsonNode value = vpNode.get("value"); 90 | if (vp == null || value == null ) { 91 | continue; 92 | } 93 | 94 | Object parsedValue = null; 95 | if(value.isTextual()) { 96 | parsedValue = vp.parseSerializableString(value.asText()); 97 | } else { 98 | parsedValue = vp.parseSerializableString(value.toString()); 99 | } 100 | 101 | style.setDefaultValue(vp, parsedValue); 102 | } 103 | } 104 | 105 | 106 | @SuppressWarnings({ "rawtypes", "unchecked" }) 107 | private final void parseMappings(JsonNode mappings, VisualStyle style, VisualLexicon lexicon, 108 | MappingFactoryManager factoryManager) { 109 | 110 | for (final JsonNode mapping : mappings) { 111 | final String type = mapping.get(MAPPING_TYPE).textValue(); 112 | final String column = mapping.get(MAPPING_COLUMN).textValue(); 113 | final String colType = mapping.get(MAPPING_COLUMN_TYPE).textValue(); 114 | final String vpName = mapping.get(MAPPING_VP).textValue(); 115 | 116 | final VisualProperty vp = getVisualProperty(vpName, lexicon); 117 | final Class columnType = MapperUtil.getColumnClass(colType); 118 | if (vp == null || columnType == null) { 119 | continue; 120 | } 121 | 122 | VisualMappingFunction newMapping = null; 123 | if (type.equals(MAPPING_DISCRETE)) { 124 | final VisualMappingFunctionFactory factory = factoryManager.getFactory(DiscreteMapping.class); 125 | newMapping = parseDiscrete(column, columnType, vp, factory, mapping.get(MAPPING_DISCRETE_MAP)); 126 | } else if (type.equals(MAPPING_CONTINUOUS)) { 127 | final VisualMappingFunctionFactory factory = factoryManager.getFactory(ContinuousMapping.class); 128 | newMapping = parseContinuous(column, columnType, vp, factory, mapping); 129 | } else if (type.equals(MAPPING_PASSTHROUGH)) { 130 | final VisualMappingFunctionFactory factory = factoryManager.getFactory(PassthroughMapping.class); 131 | newMapping = parsePassthrough(column, columnType, vp, factory); 132 | } 133 | 134 | if (newMapping != null) { 135 | if(style.getVisualMappingFunction(vp) != null) { 136 | style.removeVisualMappingFunction(vp); 137 | } 138 | style.addVisualMappingFunction(newMapping); 139 | } 140 | } 141 | } 142 | 143 | @SuppressWarnings("rawtypes") 144 | private final VisualProperty getVisualProperty(String vpName, VisualLexicon lexicon) { 145 | VisualProperty vp = null; 146 | 147 | if (vpName.startsWith("NODE")) { 148 | vp = lexicon.lookup(CyNode.class, vpName); 149 | } else if (vpName.startsWith("EDGE")) { 150 | vp = lexicon.lookup(CyEdge.class, vpName); 151 | } else if (vpName.startsWith("NETWORK")) { 152 | vp = lexicon.lookup(CyNetwork.class, vpName); 153 | } 154 | return vp; 155 | } 156 | 157 | 158 | private final Object parseKeyValue(final Class type, final String value) { 159 | if (type == Double.class) { 160 | return Double.parseDouble(value); 161 | } else if (type == Long.class) { 162 | return Long.parseLong(value); 163 | } else if (type == Integer.class) { 164 | return Integer.parseInt(value); 165 | } else if (type == Float.class) { 166 | return Float.parseFloat(value); 167 | } else if (type == Boolean.class) { 168 | return Boolean.parseBoolean(value); 169 | } else if (type == String.class) { 170 | return value; 171 | } else { 172 | return null; 173 | } 174 | } 175 | 176 | @SuppressWarnings({ "rawtypes", "unchecked" }) 177 | private final DiscreteMapping parseDiscrete(String columnName, Class type, VisualProperty vp, 178 | VisualMappingFunctionFactory factory, JsonNode discreteMapping) { 179 | DiscreteMapping mapping = (DiscreteMapping) factory.createVisualMappingFunction(columnName, type, vp); 180 | 181 | final Map map = new HashMap(); 182 | for (JsonNode pair : discreteMapping) { 183 | final Object key = parseKeyValue(type, pair.get(MAPPING_DISCRETE_KEY).textValue()); 184 | if (key != null) { 185 | map.put(key, vp.parseSerializableString(pair.get(MAPPING_DISCRETE_VALUE).textValue())); 186 | } 187 | } 188 | mapping.putAll(map); 189 | return mapping; 190 | } 191 | 192 | @SuppressWarnings({ "rawtypes", "unchecked" }) 193 | private final ContinuousMapping parseContinuous(String columnName, Class type, VisualProperty vp, 194 | VisualMappingFunctionFactory factory, JsonNode mappingNode) { 195 | 196 | final ContinuousMapping mapping = (ContinuousMapping) factory.createVisualMappingFunction(columnName, type, vp); 197 | for(JsonNode point:mappingNode.get("points")) { 198 | JsonNode val = point.get("value"); 199 | JsonNode lesser = point.get("lesser"); 200 | JsonNode equal = point.get("equal"); 201 | JsonNode greater = point.get("greater"); 202 | 203 | final BoundaryRangeValues newPoint = 204 | new BoundaryRangeValues(vp.parseSerializableString(lesser.asText()), 205 | vp.parseSerializableString(equal.asText()), 206 | vp.parseSerializableString(greater.asText())); 207 | mapping.addPoint(val.asDouble(), newPoint); 208 | } 209 | 210 | return mapping; 211 | } 212 | 213 | @SuppressWarnings("rawtypes") 214 | private final PassthroughMapping parsePassthrough(String columnName, Class type, VisualProperty vp, 215 | VisualMappingFunctionFactory factory) { 216 | 217 | return (PassthroughMapping) factory.createVisualMappingFunction(columnName, type, vp); 218 | } 219 | 220 | 221 | /** 222 | * 223 | * Directly update view object. 224 | * 225 | * @param view 226 | * @param rootNode 227 | * @param lexicon 228 | */ 229 | public Response updateView(final View view, final JsonNode rootNode, final VisualLexicon lexicon) { 230 | for (final JsonNode vpNode : rootNode) { 231 | String vpName = vpNode.get(MAPPING_VP).textValue(); 232 | final VisualProperty vp = getVisualProperty(vpName, lexicon); 233 | final JsonNode value = vpNode.get(MAPPING_DISCRETE_VALUE); 234 | if (vp == null || value == null ) { 235 | continue; 236 | } 237 | 238 | Object parsedValue = null; 239 | if(value.isTextual()) { 240 | parsedValue = vp.parseSerializableString(value.asText()); 241 | } else { 242 | parsedValue = vp.parseSerializableString(value.toString()); 243 | } 244 | 245 | view.setVisualProperty(vp, parsedValue); 246 | } 247 | return Response.ok().build(); 248 | } 249 | 250 | 251 | public void updateDependencies(final VisualStyle style, final JsonNode rootNode) { 252 | final Set> deps = style.getAllVisualPropertyDependencies(); 253 | 254 | final Map> names = new HashMap<>(); 255 | for(final VisualPropertyDependency dep:deps) { 256 | names.put(dep.getIdString(), dep); 257 | } 258 | 259 | for (final JsonNode depNode : rootNode) { 260 | String depId = depNode.get(VisualStyleMapper.VP_DEPENDENCY).textValue(); 261 | final VisualPropertyDependency dep = names.get(depId); 262 | if(dep == null) { 263 | continue; 264 | } 265 | 266 | final JsonNode enabled = depNode.get("enabled"); 267 | if (enabled == null) { 268 | continue; 269 | } 270 | 271 | boolean value = enabled.asBoolean(); 272 | dep.setDependency(value); 273 | } 274 | } 275 | } 276 | -------------------------------------------------------------------------------- /src/main/java/org/cytoscape/rest/internal/datamapper/package-info.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | * Data mapper objects from serialized text to Cytoscape data objects. 4 | * 5 | */ 6 | package org.cytoscape.rest.internal.datamapper; -------------------------------------------------------------------------------- /src/main/java/org/cytoscape/rest/internal/model/CyJsNetwork.java: -------------------------------------------------------------------------------- 1 | package org.cytoscape.rest.internal.model; 2 | 3 | /** 4 | * Dummy class for generating API document. 5 | */ 6 | public class CyJsNetwork { 7 | 8 | private NetworkData data; 9 | private Elements elements; 10 | 11 | /** 12 | * @return the data 13 | */ 14 | public NetworkData getData() { 15 | return data; 16 | } 17 | 18 | /** 19 | * @param data 20 | * the data to set 21 | */ 22 | public void setData(NetworkData data) { 23 | this.data = data; 24 | } 25 | 26 | /** 27 | * @return the elements 28 | */ 29 | public Elements getElements() { 30 | return elements; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/org/cytoscape/rest/internal/model/CytoscapeVersion.java: -------------------------------------------------------------------------------- 1 | package org.cytoscape.rest.internal.model; 2 | 3 | import javax.xml.bind.annotation.XmlRootElement; 4 | 5 | @XmlRootElement 6 | public class CytoscapeVersion { 7 | private final String apiVersion; 8 | private final String cytoscapeVersion; 9 | 10 | public CytoscapeVersion(final String apiVersion, final String cytoscapeVersion) { 11 | this.apiVersion = apiVersion; 12 | this.cytoscapeVersion = cytoscapeVersion; 13 | } 14 | 15 | /** 16 | * @return the apiVersion 17 | */ 18 | public String getApiVersion() { 19 | return apiVersion; 20 | } 21 | 22 | /** 23 | * @return the cytoscapeVersion 24 | */ 25 | public String getCytoscapeVersion() { 26 | return cytoscapeVersion; 27 | } 28 | 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/org/cytoscape/rest/internal/model/Edge.java: -------------------------------------------------------------------------------- 1 | package org.cytoscape.rest.internal.model; 2 | 3 | public class Edge { 4 | private EdgeData data; 5 | 6 | /** 7 | * @return the data 8 | */ 9 | public EdgeData getData() { 10 | return data; 11 | } 12 | 13 | /** 14 | * @param data 15 | * the data to set 16 | */ 17 | public void setData(EdgeData data) { 18 | this.data = data; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/org/cytoscape/rest/internal/model/EdgeData.java: -------------------------------------------------------------------------------- 1 | package org.cytoscape.rest.internal.model; 2 | 3 | public class EdgeData { 4 | 5 | private String source; 6 | private String target; 7 | 8 | /** 9 | * @return the source 10 | */ 11 | public String getSource() { 12 | return source; 13 | } 14 | 15 | /** 16 | * @param source 17 | * the source to set 18 | */ 19 | public void setSource(String source) { 20 | this.source = source; 21 | } 22 | 23 | /** 24 | * @return the target 25 | */ 26 | public String getTarget() { 27 | return target; 28 | } 29 | 30 | /** 31 | * @param target 32 | * the target to set 33 | */ 34 | public void setTarget(String target) { 35 | this.target = target; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/org/cytoscape/rest/internal/model/Elements.java: -------------------------------------------------------------------------------- 1 | package org.cytoscape.rest.internal.model; 2 | 3 | import java.util.Collection; 4 | 5 | public class Elements { 6 | private Collection nodes; 7 | private Collection edges; 8 | /** 9 | * @return the nodes 10 | */ 11 | public Collection getNodes() { 12 | return nodes; 13 | } 14 | /** 15 | * @param nodes the nodes to set 16 | */ 17 | public void setNodes(Collection nodes) { 18 | this.nodes = nodes; 19 | } 20 | /** 21 | * @return the edges 22 | */ 23 | public Collection getEdges() { 24 | return edges; 25 | } 26 | /** 27 | * @param edges the edges to set 28 | */ 29 | public void setEdges(Collection edges) { 30 | this.edges = edges; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/org/cytoscape/rest/internal/model/MemoryStatus.java: -------------------------------------------------------------------------------- 1 | package org.cytoscape.rest.internal.model; 2 | 3 | import javax.xml.bind.annotation.XmlRootElement; 4 | 5 | @XmlRootElement 6 | public class MemoryStatus { 7 | 8 | private static final Integer MB = 1024 * 1024; 9 | private final Runtime runtime = Runtime.getRuntime(); 10 | private final Long usedMemory = (runtime.totalMemory() - runtime.freeMemory()) / MB; 11 | private final Long freeMemory = runtime.freeMemory() / MB; 12 | private final Long totalMemory = runtime.totalMemory() / MB; 13 | private final Long maxMemory = runtime.maxMemory() / MB; 14 | 15 | /** 16 | * @return the usedMemory 17 | */ 18 | public Long getUsedMemory() { 19 | return usedMemory; 20 | } 21 | 22 | /** 23 | * @return the freeMemory 24 | */ 25 | public Long getFreeMemory() { 26 | return freeMemory; 27 | } 28 | 29 | /** 30 | * @return the totalMemory 31 | */ 32 | public Long getTotalMemory() { 33 | return totalMemory; 34 | } 35 | 36 | /** 37 | * @return the maxMemory 38 | */ 39 | public Long getMaxMemory() { 40 | return maxMemory; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/org/cytoscape/rest/internal/model/NetworkData.java: -------------------------------------------------------------------------------- 1 | package org.cytoscape.rest.internal.model; 2 | 3 | public class NetworkData { 4 | 5 | } 6 | -------------------------------------------------------------------------------- /src/main/java/org/cytoscape/rest/internal/model/Node.java: -------------------------------------------------------------------------------- 1 | package org.cytoscape.rest.internal.model; 2 | 3 | 4 | public class Node { 5 | private NodeData data; 6 | 7 | /** 8 | * @return the data 9 | */ 10 | public NodeData getData() { 11 | return data; 12 | } 13 | 14 | /** 15 | * @param data the data to set 16 | */ 17 | public void setData(NodeData data) { 18 | this.data = data; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/org/cytoscape/rest/internal/model/NodeData.java: -------------------------------------------------------------------------------- 1 | package org.cytoscape.rest.internal.model; 2 | 3 | public class NodeData { 4 | 5 | private String id; 6 | 7 | /** 8 | * @return the id 9 | */ 10 | public String getId() { 11 | return id; 12 | } 13 | 14 | /** 15 | * @param id the id to set 16 | */ 17 | public void setId(String id) { 18 | this.id = id; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/org/cytoscape/rest/internal/model/ServerStatus.java: -------------------------------------------------------------------------------- 1 | package org.cytoscape.rest.internal.model; 2 | 3 | import javax.xml.bind.annotation.XmlRootElement; 4 | 5 | @XmlRootElement 6 | public class ServerStatus { 7 | 8 | private String apiVersion; 9 | private Integer numberOfCores; 10 | 11 | private MemoryStatus memoryStatus; 12 | 13 | 14 | public ServerStatus() { 15 | this.setApiVersion("v1"); 16 | this.setNumberOfCores(Runtime.getRuntime().availableProcessors()); 17 | this.setMemoryStatus(new MemoryStatus()); 18 | } 19 | 20 | /** 21 | * @return the apiVersion 22 | */ 23 | public String getApiVersion() { 24 | return apiVersion; 25 | } 26 | 27 | /** 28 | * @param apiVersion 29 | * the apiVersion to set 30 | */ 31 | public void setApiVersion(String apiVersion) { 32 | this.apiVersion = apiVersion; 33 | } 34 | 35 | /** 36 | * @return the numberOfCores 37 | */ 38 | public Integer getNumberOfCores() { 39 | return numberOfCores; 40 | } 41 | 42 | /** 43 | * @param numberOfCores 44 | * the numberOfCores to set 45 | */ 46 | public void setNumberOfCores(Integer numberOfCores) { 47 | this.numberOfCores = numberOfCores; 48 | } 49 | 50 | /** 51 | * @return the memoryStatus 52 | */ 53 | public MemoryStatus getMemoryStatus() { 54 | return memoryStatus; 55 | } 56 | 57 | /** 58 | * @param memoryStatus the memoryStatus to set 59 | */ 60 | public void setMemoryStatus(MemoryStatus memoryStatus) { 61 | this.memoryStatus = memoryStatus; 62 | } 63 | 64 | } 65 | -------------------------------------------------------------------------------- /src/main/java/org/cytoscape/rest/internal/reader/EdgeListReader.java: -------------------------------------------------------------------------------- 1 | package org.cytoscape.rest.internal.reader; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.IOException; 5 | import java.io.InputStream; 6 | import java.io.InputStreamReader; 7 | import java.nio.charset.Charset; 8 | import java.util.HashMap; 9 | import java.util.Map; 10 | import java.util.regex.Pattern; 11 | 12 | import org.cytoscape.io.read.AbstractCyNetworkReader; 13 | import org.cytoscape.model.CyEdge; 14 | import org.cytoscape.model.CyNetwork; 15 | import org.cytoscape.model.CyNetworkFactory; 16 | import org.cytoscape.model.CyNetworkManager; 17 | import org.cytoscape.model.CyNode; 18 | import org.cytoscape.model.subnetwork.CyRootNetwork; 19 | import org.cytoscape.model.subnetwork.CyRootNetworkManager; 20 | import org.cytoscape.model.subnetwork.CySubNetwork; 21 | import org.cytoscape.view.model.CyNetworkView; 22 | import org.cytoscape.view.model.CyNetworkViewFactory; 23 | import org.cytoscape.work.TaskMonitor; 24 | 25 | /** 26 | * Network Reader for Edge Lists 27 | */ 28 | public class EdgeListReader extends AbstractCyNetworkReader { 29 | 30 | private final static Pattern SPLIT_PATTERN = Pattern.compile("[\\s\\t]+"); 31 | private final static String SOURCE = "source"; 32 | private final static String TARGET= "target"; 33 | 34 | private final CyNetworkManager cyNetworkManager; 35 | private final CyRootNetworkManager cyRootNetworkManager; 36 | 37 | private final String collectionName; 38 | 39 | public EdgeListReader(final InputStream inputStream, final CyNetworkViewFactory cyNetworkViewFactory, 40 | final CyNetworkFactory cyNetworkFactory, final CyNetworkManager cyNetworkManager, 41 | final CyRootNetworkManager cyRootNetworkManager, final String collecitonName) { 42 | super(inputStream, cyNetworkViewFactory, cyNetworkFactory, cyNetworkManager, cyRootNetworkManager); 43 | this.collectionName = collecitonName; 44 | this.cyRootNetworkManager = cyRootNetworkManager; 45 | this.cyNetworkManager = cyNetworkManager; 46 | } 47 | 48 | private CyRootNetwork getRootNetworkByName(final String collectionName) { 49 | 50 | for (CyNetwork net : cyNetworkManager.getNetworkSet()) { 51 | final CyRootNetwork rootNet = cyRootNetworkManager.getRootNetwork(net); 52 | if(rootNet.getRow(rootNet).get(CyRootNetwork.NAME, String.class).equals(collectionName)) { 53 | return rootNet; 54 | } 55 | } 56 | 57 | return null; 58 | } 59 | 60 | @Override 61 | public CyNetworkView buildCyNetworkView(final CyNetwork network) { 62 | // No layout will be applied for performance. 63 | return this.cyNetworkViewFactory.createNetworkView(network); 64 | } 65 | 66 | 67 | @Override 68 | public void run(TaskMonitor taskMonitor) throws Exception { 69 | try { 70 | read(taskMonitor); 71 | } finally { 72 | if (inputStream != null) { 73 | inputStream.close(); 74 | inputStream = null; 75 | } 76 | } 77 | } 78 | 79 | 80 | private final void read(TaskMonitor tm) throws IOException { 81 | String line; 82 | final BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, Charset.forName("UTF-8") 83 | .newDecoder()), 128 * 1024); 84 | 85 | CySubNetwork subNetwork = null; 86 | CyRootNetwork rootNetwork = getRootNetwork(); 87 | 88 | if (rootNetwork != null) { 89 | // Root network exists 90 | subNetwork = rootNetwork.addSubNetwork(); 91 | } else { 92 | // Search networks 93 | rootNetwork = getRootNetworkByName(collectionName); 94 | if(rootNetwork == null) { 95 | // Need to create new network with new root. 96 | subNetwork = (CySubNetwork) cyNetworkFactory.createNetwork(); 97 | } else { 98 | subNetwork = rootNetwork.addSubNetwork(); 99 | } 100 | } 101 | 102 | // Create default columns 103 | if(subNetwork.getDefaultEdgeTable().getColumn(SOURCE) == null) 104 | subNetwork.getDefaultEdgeTable().createColumn(SOURCE, String.class, true); 105 | if(subNetwork.getDefaultEdgeTable().getColumn(TARGET) == null) 106 | subNetwork.getDefaultEdgeTable().createColumn(TARGET, String.class, true); 107 | 108 | Map nMap = new HashMap<>(); 109 | 110 | while ((line = br.readLine()) != null) { 111 | 112 | // Cancel called. Clean up the garbage. 113 | if (cancelled) { 114 | nMap.clear(); 115 | nMap = null; 116 | subNetwork = null; 117 | br.close(); 118 | return; 119 | } 120 | 121 | // Ignore invalid line 122 | if (line.trim().length() <= 0) 123 | continue; 124 | 125 | final String[] parts = SPLIT_PATTERN.split(line); 126 | if (parts.length == 2) { 127 | CyNode sourceNode = nMap.get(parts[0]); 128 | if (sourceNode == null) { 129 | sourceNode = subNetwork.addNode(); 130 | subNetwork.getRow(sourceNode).set(CyNetwork.NAME, parts[0]); 131 | nMap.put(parts[0], sourceNode); 132 | } 133 | CyNode targetNode = nMap.get(parts[1]); 134 | if (targetNode == null) { 135 | targetNode = subNetwork.addNode(); 136 | subNetwork.getRow(targetNode).set(CyNetwork.NAME, parts[1]); 137 | nMap.put(parts[1], targetNode); 138 | } 139 | 140 | final CyEdge edge = subNetwork.addEdge(sourceNode, targetNode, true); 141 | subNetwork.getRow(edge).set(CyEdge.INTERACTION, "-"); 142 | subNetwork.getRow(edge).set(SOURCE, parts[0]); 143 | subNetwork.getRow(edge).set(TARGET, parts[1]); 144 | 145 | } else if(parts.length == 1){ 146 | // No edge will be added. Node only. 147 | } 148 | } 149 | 150 | br.close(); 151 | nMap.clear(); 152 | nMap = null; 153 | 154 | this.networks = new CyNetwork[] { subNetwork }; 155 | } 156 | } -------------------------------------------------------------------------------- /src/main/java/org/cytoscape/rest/internal/reader/EdgeListReaderFactory.java: -------------------------------------------------------------------------------- 1 | package org.cytoscape.rest.internal.reader; 2 | 3 | import java.io.InputStream; 4 | 5 | import org.cytoscape.io.CyFileFilter; 6 | import org.cytoscape.io.read.AbstractInputStreamTaskFactory; 7 | import org.cytoscape.model.CyNetworkFactory; 8 | import org.cytoscape.model.CyNetworkManager; 9 | import org.cytoscape.model.subnetwork.CyRootNetworkManager; 10 | import org.cytoscape.view.model.CyNetworkViewFactory; 11 | import org.cytoscape.work.TaskIterator; 12 | 13 | /** 14 | * Factory for Edge List reader objects. 15 | * 16 | */ 17 | public class EdgeListReaderFactory extends AbstractInputStreamTaskFactory { 18 | 19 | private final CyNetworkViewFactory cyNetworkViewFactory; 20 | private final CyNetworkFactory cyNetworkFactory; 21 | private final CyNetworkManager cyNetworkManager;; 22 | private final CyRootNetworkManager cyRootNetworkManager; 23 | 24 | 25 | public EdgeListReaderFactory(CyFileFilter filter, CyNetworkViewFactory cyNetworkViewFactory, 26 | CyNetworkFactory cyNetworkFactory, final CyNetworkManager cyNetworkManager, 27 | CyRootNetworkManager cyRootNetworkManager) { 28 | super(filter); 29 | this.cyNetworkManager = cyNetworkManager; 30 | this.cyRootNetworkManager = cyRootNetworkManager; 31 | this.cyNetworkFactory = cyNetworkFactory; 32 | this.cyNetworkViewFactory = cyNetworkViewFactory; 33 | } 34 | 35 | @Override 36 | public TaskIterator createTaskIterator(InputStream inputStream, String collectionName) { 37 | return new TaskIterator(new EdgeListReader(inputStream, cyNetworkViewFactory, cyNetworkFactory, 38 | this.cyNetworkManager, this.cyRootNetworkManager, collectionName)); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/org/cytoscape/rest/internal/reader/EdgeTableReader.java: -------------------------------------------------------------------------------- 1 | package org.cytoscape.rest.internal.reader; 2 | 3 | import org.cytoscape.io.read.CyTableReader; 4 | import org.cytoscape.model.CyTable; 5 | import org.cytoscape.work.TaskMonitor; 6 | 7 | /** 8 | * Reader for reading edge table based on source & target. 9 | * 10 | */ 11 | public class EdgeTableReader implements CyTableReader { 12 | 13 | @Override 14 | public void run(TaskMonitor taskMonitor) throws Exception { 15 | // TODO Auto-generated method stub 16 | 17 | } 18 | 19 | @Override 20 | public void cancel() { 21 | // TODO Auto-generated method stub 22 | 23 | } 24 | 25 | @Override 26 | public CyTable[] getTables() { 27 | // TODO Auto-generated method stub 28 | return null; 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/org/cytoscape/rest/internal/reader/package-info.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | * Extra readers for widely used data formats. 4 | * 5 | */ 6 | package org.cytoscape.rest.internal.reader; -------------------------------------------------------------------------------- /src/main/java/org/cytoscape/rest/internal/resource/AbstractResource.java: -------------------------------------------------------------------------------- 1 | package org.cytoscape.rest.internal.resource; 2 | 3 | import java.io.ByteArrayOutputStream; 4 | import java.io.IOException; 5 | import java.util.Collection; 6 | import java.util.HashSet; 7 | import java.util.Set; 8 | 9 | import javax.validation.constraints.NotNull; 10 | import javax.ws.rs.InternalServerErrorException; 11 | import javax.ws.rs.NotFoundException; 12 | import javax.ws.rs.WebApplicationException; 13 | import javax.ws.rs.core.Context; 14 | import javax.ws.rs.core.MediaType; 15 | import javax.ws.rs.core.Response; 16 | import javax.ws.rs.core.Response.Status; 17 | 18 | import org.cytoscape.application.CyApplicationManager; 19 | import org.cytoscape.io.read.InputStreamTaskFactory; 20 | import org.cytoscape.io.write.CyNetworkViewWriterFactory; 21 | import org.cytoscape.io.write.CyWriter; 22 | import org.cytoscape.model.CyIdentifiable; 23 | import org.cytoscape.model.CyNetwork; 24 | import org.cytoscape.model.CyNetworkFactory; 25 | import org.cytoscape.model.CyNetworkManager; 26 | import org.cytoscape.model.CyNode; 27 | import org.cytoscape.model.CyRow; 28 | import org.cytoscape.model.CyTable; 29 | import org.cytoscape.model.CyTableManager; 30 | import org.cytoscape.model.subnetwork.CyRootNetworkManager; 31 | import org.cytoscape.property.CyProperty; 32 | import org.cytoscape.rest.internal.TaskFactoryManager; 33 | import org.cytoscape.rest.internal.CyActivator.WriterListener; 34 | import org.cytoscape.rest.internal.datamapper.MapperUtil; 35 | import org.cytoscape.rest.internal.reader.EdgeListReaderFactory; 36 | import org.cytoscape.rest.internal.serializer.GraphObjectSerializer; 37 | import org.cytoscape.rest.internal.task.HeadlessTaskMonitor; 38 | import org.cytoscape.task.create.NewNetworkSelectedNodesAndEdgesTaskFactory; 39 | import org.cytoscape.task.read.LoadNetworkURLTaskFactory; 40 | import org.cytoscape.view.model.CyNetworkView; 41 | import org.cytoscape.view.model.CyNetworkViewFactory; 42 | import org.cytoscape.view.model.CyNetworkViewManager; 43 | import org.cytoscape.view.model.VisualLexicon; 44 | import org.cytoscape.view.vizmap.VisualMappingManager; 45 | 46 | import com.fasterxml.jackson.core.JsonFactory; 47 | import com.fasterxml.jackson.core.JsonGenerator; 48 | 49 | /** 50 | * Prepare services to be injected. 51 | * 52 | */ 53 | public abstract class AbstractResource { 54 | 55 | // TODO: do we need this level of version granularity? 56 | protected static final String API_VERSION = "v1"; 57 | protected static final String ERROR_TAG = "\"error\":"; 58 | 59 | 60 | /** 61 | * Create a informative error message instead of plain 500. 62 | * 63 | * @param errorMessage 64 | * @param ex 65 | * @param status 66 | * @return 67 | */ 68 | protected final WebApplicationException getError(final String errorMessage, final Exception ex, final Status status) { 69 | // This is necessary to avoid threading issues. 70 | final Exception cause = new Exception(ex.getMessage()); 71 | cause.setStackTrace(ex.getStackTrace()); 72 | final Exception wrapped = new IllegalStateException(errorMessage, cause); 73 | 74 | if (status == Response.Status.INTERNAL_SERVER_ERROR) { 75 | // Otherwise, 500. 76 | return new InternalServerErrorException(Response.status(status).type(MediaType.APPLICATION_JSON) 77 | .entity(wrapped).build()); 78 | } else { 79 | // All other types 80 | return new WebApplicationException(Response.status(status).type(MediaType.APPLICATION_JSON) 81 | .entity(wrapped).build()); 82 | } 83 | } 84 | 85 | @Context 86 | @NotNull 87 | protected CyApplicationManager applicationManager; 88 | 89 | @Context 90 | protected CyNetworkManager networkManager; 91 | 92 | @Context 93 | protected CyRootNetworkManager cyRootNetworkManager; 94 | 95 | @Context 96 | protected CyTableManager tableManager; 97 | 98 | @Context 99 | protected CyNetworkViewManager networkViewManager; 100 | 101 | @Context 102 | protected CyNetworkFactory networkFactory; 103 | 104 | @Context 105 | protected CyNetworkViewFactory networkViewFactory; 106 | 107 | @Context 108 | protected TaskFactoryManager tfManager; 109 | 110 | @Context 111 | protected InputStreamTaskFactory cytoscapeJsReaderFactory; 112 | 113 | @Context 114 | @NotNull 115 | protected VisualMappingManager vmm; 116 | 117 | @Context 118 | protected CyNetworkViewWriterFactory cytoscapeJsWriterFactory; 119 | 120 | @Context 121 | protected WriterListener vizmapWriterFactoryListener; 122 | 123 | @Context 124 | protected LoadNetworkURLTaskFactory loadNetworkURLTaskFactory; 125 | 126 | @Context 127 | protected CyProperty props; 128 | 129 | @Context 130 | protected NewNetworkSelectedNodesAndEdgesTaskFactory newNetworkSelectedNodesAndEdgesTaskFactory; 131 | 132 | @Context 133 | protected EdgeListReaderFactory edgeListReaderFactory; 134 | 135 | 136 | protected final GraphObjectSerializer serializer; 137 | 138 | public AbstractResource() { 139 | this.serializer = new GraphObjectSerializer(); 140 | } 141 | 142 | protected final CyNetwork getCyNetwork(final Long id) { 143 | if (id == null) { 144 | throw new NotFoundException("SUID is null."); 145 | } 146 | 147 | final CyNetwork network = networkManager.getNetwork(id); 148 | if (network == null) { 149 | throw new NotFoundException("Could not find network with SUID: " + id); 150 | } 151 | return network; 152 | } 153 | 154 | protected final Collection getCyNetworkViews(final Long id) { 155 | final Collection views = networkViewManager.getNetworkViews(getCyNetwork(id)); 156 | if (views.isEmpty()) { 157 | throw new NotFoundException("No view is available for network with SUID: " + id); 158 | } 159 | return views; 160 | } 161 | 162 | protected final CyNode getNode(final CyNetwork network, final Long nodeId) { 163 | final CyNode node = network.getNode(nodeId); 164 | if (node == null) { 165 | throw new NotFoundException("Could not find node with SUID: " + nodeId); 166 | } 167 | return node; 168 | } 169 | 170 | protected final String getGraphObject(final CyNetwork network, final CyIdentifiable obj) { 171 | final CyRow row = network.getRow(obj); 172 | 173 | try { 174 | return this.serializer.serializeGraphObject(obj, row); 175 | } catch (IOException e) { 176 | throw getError("Could not serialize graph object with SUID: " + obj.getSUID(), e, 177 | Response.Status.INTERNAL_SERVER_ERROR); 178 | } 179 | } 180 | 181 | protected final String getNames(final Collection names) throws IOException { 182 | final JsonFactory factory = new JsonFactory(); 183 | 184 | String result = null; 185 | ByteArrayOutputStream stream = new ByteArrayOutputStream(); 186 | JsonGenerator generator = null; 187 | generator = factory.createGenerator(stream); 188 | generator.writeStartArray(); 189 | 190 | for (final String name : names) { 191 | generator.writeString(name); 192 | } 193 | 194 | generator.writeEndArray(); 195 | generator.close(); 196 | result = stream.toString("UTF-8"); 197 | stream.close(); 198 | return result; 199 | } 200 | 201 | protected final String getNumberObjectString(final String fieldName, final Number value) { 202 | final JsonFactory factory = new JsonFactory(); 203 | 204 | String result = null; 205 | ByteArrayOutputStream stream = new ByteArrayOutputStream(); 206 | JsonGenerator generator = null; 207 | try { 208 | generator = factory.createGenerator(stream); 209 | generator.writeStartObject(); 210 | generator.writeFieldName(fieldName); 211 | generator.writeNumber(value.longValue()); 212 | generator.writeEndObject(); 213 | generator.close(); 214 | result = stream.toString("UTF-8"); 215 | stream.close(); 216 | } catch (IOException e) { 217 | throw getError("Could not serialize number: " + value, e, Response.Status.INTERNAL_SERVER_ERROR); 218 | } 219 | 220 | return result; 221 | } 222 | 223 | protected final Set getNetworksByQuery(final String query, final String column) { 224 | final Set networks = networkManager.getNetworkSet(); 225 | final Set matchedNetworks = new HashSet<>(); 226 | 227 | for (final CyNetwork network : networks) { 228 | // First, check shared table 229 | CyTable table = network.getDefaultNetworkTable(); 230 | if(table.getColumn(column) == null) { 231 | table = network.getTable(CyNetwork.class, CyNetwork.LOCAL_ATTRS); 232 | } 233 | // If column does not exists in the default table, check local one: 234 | if(table.getColumn(column) == null) { 235 | // Still not found? Give up and continue. 236 | // TODO: should we check hidden tables, too? 237 | continue; 238 | } 239 | final Object rawQuery = MapperUtil.getRawValue(query, table.getColumn(column).getType()); 240 | final Collection rows = table.getMatchingRows(column, rawQuery); 241 | if (rows.isEmpty() == false) { 242 | matchedNetworks.add(network); 243 | } 244 | } 245 | return matchedNetworks; 246 | } 247 | 248 | 249 | protected final String getNetworkString(final CyNetwork network) { 250 | final ByteArrayOutputStream stream = new ByteArrayOutputStream(); 251 | CyWriter writer = cytoscapeJsWriterFactory.createWriter(stream, network); 252 | String jsonString = null; 253 | try { 254 | writer.run(new HeadlessTaskMonitor()); 255 | jsonString = stream.toString("UTF-8"); 256 | stream.close(); 257 | } catch (Exception e) { 258 | throw getError("Could not serialize network into JSON.", e, Response.Status.PRECONDITION_FAILED); 259 | } 260 | 261 | return jsonString; 262 | } 263 | 264 | protected final VisualLexicon getLexicon() { 265 | final Set lexicon = vmm.getAllVisualLexicon(); 266 | if (lexicon.isEmpty()) { 267 | throw getError("Could not find visual lexicon.", new IllegalStateException(), Response.Status.INTERNAL_SERVER_ERROR); 268 | } 269 | 270 | // TODO: What happens if we have multiple renderer? 271 | return lexicon.iterator().next(); 272 | } 273 | 274 | } -------------------------------------------------------------------------------- /src/main/java/org/cytoscape/rest/internal/resource/CyExceptionMapper.java: -------------------------------------------------------------------------------- 1 | package org.cytoscape.rest.internal.resource; 2 | 3 | import javax.ws.rs.InternalServerErrorException; 4 | import javax.ws.rs.core.MediaType; 5 | import javax.ws.rs.core.Response; 6 | import javax.ws.rs.ext.ExceptionMapper; 7 | import javax.ws.rs.ext.Provider; 8 | 9 | import org.glassfish.grizzly.utils.Exceptions; 10 | 11 | @Provider 12 | public class CyExceptionMapper implements ExceptionMapper { 13 | 14 | @Override 15 | public Response toResponse(InternalServerErrorException ex) { 16 | return Response.status(500).entity(Exceptions.getStackTraceAsString(ex)).type(MediaType.APPLICATION_JSON) 17 | .build(); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/org/cytoscape/rest/internal/resource/GlobalTableResource.java: -------------------------------------------------------------------------------- 1 | package org.cytoscape.rest.internal.resource; 2 | 3 | import java.util.Set; 4 | 5 | import javax.inject.Singleton; 6 | import javax.validation.constraints.NotNull; 7 | import javax.ws.rs.GET; 8 | import javax.ws.rs.Path; 9 | import javax.ws.rs.Produces; 10 | import javax.ws.rs.core.Context; 11 | import javax.ws.rs.core.MediaType; 12 | 13 | import org.cytoscape.model.CyTable; 14 | import org.cytoscape.model.CyTableFactory; 15 | import org.cytoscape.rest.internal.serializer.TableModule; 16 | 17 | import com.fasterxml.jackson.databind.ObjectMapper; 18 | 19 | @Singleton 20 | @Path("/v1/tables") 21 | public class GlobalTableResource extends AbstractResource { 22 | 23 | @Context 24 | @NotNull 25 | private CyTableFactory tableFactory; 26 | 27 | private final ObjectMapper tableObjectMapper; 28 | 29 | public GlobalTableResource() { 30 | super(); 31 | this.tableObjectMapper = new ObjectMapper(); 32 | this.tableObjectMapper.registerModule(new TableModule()); 33 | } 34 | 35 | /** 36 | * 37 | * @summary Get number of global tables 38 | * 39 | * @return Number of global tables. 40 | */ 41 | @GET 42 | @Path("/count") 43 | @Produces(MediaType.APPLICATION_JSON) 44 | public String getTableCount() { 45 | final Set globals = tableManager.getGlobalTables(); 46 | return getNumberObjectString(JsonTags.COUNT, globals.size()); 47 | } 48 | } -------------------------------------------------------------------------------- /src/main/java/org/cytoscape/rest/internal/resource/GroupResource.java: -------------------------------------------------------------------------------- 1 | package org.cytoscape.rest.internal.resource; 2 | 3 | import java.io.IOException; 4 | import java.io.InputStream; 5 | import java.util.Set; 6 | 7 | import javax.inject.Singleton; 8 | import javax.ws.rs.Consumes; 9 | import javax.ws.rs.DELETE; 10 | import javax.ws.rs.GET; 11 | import javax.ws.rs.NotFoundException; 12 | import javax.ws.rs.POST; 13 | import javax.ws.rs.Path; 14 | import javax.ws.rs.PathParam; 15 | import javax.ws.rs.Produces; 16 | import javax.ws.rs.core.Context; 17 | import javax.ws.rs.core.MediaType; 18 | import javax.ws.rs.core.Response; 19 | 20 | import org.cytoscape.group.CyGroup; 21 | import org.cytoscape.group.CyGroupFactory; 22 | import org.cytoscape.group.CyGroupManager; 23 | import org.cytoscape.model.CyNetwork; 24 | import org.cytoscape.model.CyNode; 25 | import org.cytoscape.model.subnetwork.CySubNetwork; 26 | import org.cytoscape.rest.internal.datamapper.GroupMapper; 27 | import org.cytoscape.rest.internal.serializer.GroupModule; 28 | 29 | import com.fasterxml.jackson.core.JsonProcessingException; 30 | import com.fasterxml.jackson.databind.JsonNode; 31 | import com.fasterxml.jackson.databind.ObjectMapper; 32 | 33 | @Singleton 34 | @Path("/v1/networks/{networkId}/groups") 35 | public class GroupResource extends AbstractResource { 36 | 37 | private final ObjectMapper groupMapper; 38 | private final GroupMapper mapper; 39 | 40 | @Context 41 | private CyGroupFactory groupFactory; 42 | 43 | @Context 44 | private CyGroupManager groupManager; 45 | 46 | public GroupResource() { 47 | super(); 48 | this.groupMapper = new ObjectMapper(); 49 | this.groupMapper.registerModule(new GroupModule()); 50 | this.mapper = new GroupMapper(); 51 | } 52 | 53 | /** 54 | * @summary Get all groups in the network 55 | * 56 | * @param networkId 57 | * Network SUID 58 | * 59 | * @return List of all groups in the network 60 | * 61 | */ 62 | @GET 63 | @Path("/") 64 | @Produces(MediaType.APPLICATION_JSON) 65 | public String getAllGroups(@PathParam("networkId") Long networkId) { 66 | final CyNetwork network = getCyNetwork(networkId); 67 | final Set groups = groupManager.getGroupSet(network); 68 | try { 69 | return this.groupMapper.writeValueAsString(groups); 70 | } catch (JsonProcessingException e) { 71 | throw getError("Could not serialize groups.", e, Response.Status.INTERNAL_SERVER_ERROR); 72 | } 73 | } 74 | 75 | 76 | /** 77 | * 78 | * @summary Get number of groups in the network 79 | * 80 | * @param networkId 81 | * Network SUID 82 | * 83 | * @return Number of groups in the network 84 | */ 85 | @GET 86 | @Path("/count") 87 | @Produces(MediaType.APPLICATION_JSON) 88 | public String getGroupCount(@PathParam("networkId") Long networkId) { 89 | final CyNetwork network = getCyNetwork(networkId); 90 | return getNumberObjectString(JsonTags.COUNT, groupManager.getGroupSet(network).size()); 91 | } 92 | 93 | /** 94 | * @summary Get group for a node 95 | * 96 | * @param networkId 97 | * Networks SUID 98 | * @param groupNodeId 99 | * Group Node SUID 100 | * 101 | * @return A group where the node belongs to 102 | */ 103 | @GET 104 | @Path("/{groupNodeId}") 105 | @Produces(MediaType.APPLICATION_JSON) 106 | public String getGroup(@PathParam("networkId") Long networkId, @PathParam("groupNodeId") Long nodeId) { 107 | final CyNetwork network = getCyNetwork(networkId); 108 | final CyNode node = network.getNode(nodeId); 109 | if (node == null) { 110 | throw new NotFoundException("Could not find the node with SUID: " + nodeId); 111 | } 112 | 113 | final CyGroup group = groupManager.getGroup(node, network); 114 | if (group == null) { 115 | throw new NotFoundException("Could not find group."); 116 | } 117 | try { 118 | return groupMapper.writeValueAsString(group); 119 | } catch (JsonProcessingException e) { 120 | throw getError("Could not serialize Group.", e, Response.Status.INTERNAL_SERVER_ERROR); 121 | } 122 | } 123 | 124 | /** 125 | * @summary Delete all groups in the network 126 | * 127 | * @param networkId 128 | * Network SUID 129 | * 130 | */ 131 | @DELETE 132 | @Path("/") 133 | public void deleteAllGroups(@PathParam("networkId") Long networkId) { 134 | final CyNetwork network = getCyNetwork(networkId); 135 | final Set groups = groupManager.getGroupSet(network); 136 | try { 137 | for (final CyGroup group : groups) { 138 | groupManager.destroyGroup(group); 139 | } 140 | } catch (Exception e) { 141 | throw getError("Could not delete group.", e, Response.Status.INTERNAL_SERVER_ERROR); 142 | } 143 | } 144 | 145 | /** 146 | * 147 | * @summary Delete a group 148 | * 149 | * @param networkId 150 | * Network SUID 151 | * @param groupNodeId 152 | * Group node SUID 153 | */ 154 | @DELETE 155 | @Path("/{groupNodeId}") 156 | public void deleteGroup(@PathParam("networkId") Long networkId, @PathParam("groupNodeId") Long groupNodeId) { 157 | final CyGroup group = getGroupById(networkId, groupNodeId); 158 | try { 159 | groupManager.destroyGroup(group); 160 | } catch (Exception e) { 161 | throw getError("Could not delete group.", e, Response.Status.INTERNAL_SERVER_ERROR); 162 | } 163 | } 164 | 165 | /** 166 | * @summary Expand group nodes 167 | * 168 | * @param networkId 169 | * Network SUID 170 | * @param groupNodeId 171 | * Group node SUID 172 | * 173 | */ 174 | @GET 175 | @Path("/{groupNodeId}/expand") 176 | public void expandGroup(@PathParam("networkId") Long networkId, @PathParam("groupNodeId") Long groupNodeId) { 177 | toggle(networkId, groupNodeId, false); 178 | } 179 | 180 | /** 181 | * @summary Collapse group nodes 182 | * 183 | * @param networkId 184 | * Network SUID 185 | * @param groupNodeId 186 | * Group node SUID 187 | * 188 | */ 189 | @GET 190 | @Path("/{groupNodeId}/collapse") 191 | public void collapseGroup(@PathParam("networkId") Long networkId, @PathParam("groupNodeId") Long groupNodeId) { 192 | toggle(networkId, groupNodeId, true); 193 | } 194 | 195 | private final void toggle(final Long networkId, final Long suid, boolean collapse) { 196 | final CyGroup group = getGroupById(networkId, suid); 197 | final CyNetwork network = getCyNetwork(networkId); 198 | try { 199 | if (collapse) { 200 | group.collapse(network); 201 | } else { 202 | group.expand(network); 203 | } 204 | } catch (Exception e) { 205 | throw getError("Could not toggle group state. Collapse: " + collapse, e, Response.Status.INTERNAL_SERVER_ERROR); 206 | } 207 | } 208 | 209 | private final CyGroup getGroupById(final Long networkId, final Long suid) { 210 | final CyNetwork network = getCyNetwork(networkId); 211 | CyNode node = network.getNode(suid); 212 | if (node == null) { 213 | node = ((CySubNetwork) network).getRootNetwork().getNode(suid); 214 | if (node == null) 215 | throw new NotFoundException("Could not find the node with SUID: " + suid); 216 | } 217 | 218 | final CyGroup group = groupManager.getGroup(node, network); 219 | if (group == null) { 220 | throw new NotFoundException("Could not find group."); 221 | } 222 | return group; 223 | } 224 | 225 | /** 226 | * Create a new group from a list of nodes. The Body should be in the following format: 227 | * 228 | *
229 | 	 * 	{
230 | 	 * 		"name": (New group node name),
231 | 	 * 		"nodes": [
232 | 	 * 			nodeSUID1, nodeSUID2, ...
233 | 	 * 		]
234 | 	 * 	}
235 | 	 * 
236 | * 237 | * 238 | * @summary Create a new group 239 | * 240 | * @param networkId 241 | * Network SUID 242 | * 243 | * @return New group node's SUID 244 | * 245 | */ 246 | @POST 247 | @Path("/") 248 | @Consumes(MediaType.APPLICATION_JSON) 249 | @Produces(MediaType.APPLICATION_JSON) 250 | public String createGroup(@PathParam("networkId") Long networkId, final InputStream is) { 251 | final CyNetwork network = getCyNetwork(networkId); 252 | final ObjectMapper objMapper = new ObjectMapper(); 253 | 254 | JsonNode rootNode = null; 255 | try { 256 | rootNode = objMapper.readValue(is, JsonNode.class); 257 | } catch (IOException ex) { 258 | throw getError("Could not create JSON root node.", ex, Response.Status.INTERNAL_SERVER_ERROR); 259 | } 260 | try { 261 | final CyGroup newGroup = mapper.createGroup(rootNode, groupFactory, network); 262 | return getNumberObjectString("groupSUID", newGroup.getGroupNode().getSUID()); 263 | } catch (Exception e) { 264 | throw getError("Could not create group.", e, Response.Status.INTERNAL_SERVER_ERROR); 265 | } 266 | } 267 | } -------------------------------------------------------------------------------- /src/main/java/org/cytoscape/rest/internal/resource/JsonTags.java: -------------------------------------------------------------------------------- 1 | package org.cytoscape.rest.internal.resource; 2 | 3 | public class JsonTags { 4 | 5 | 6 | // For JSON 7 | 8 | public static final String TITLE = "title"; 9 | public static final String PUBLIC = "public"; 10 | public static final String MUTABLE = "mutable"; 11 | public static final String PRIMARY_KEY = "primaryKey"; 12 | public static final String ROWS = "rows"; 13 | 14 | public static final String COUNT = "count"; 15 | 16 | public static final String COLUMN_NAME = "name"; 17 | public static final String COLUMN_NAME_OLD = "oldName"; 18 | public static final String COLUMN_NAME_NEW = "newName"; 19 | public static final String COLUMN_TYPE = "type"; 20 | public static final String COLUMN_VALUES = "values"; 21 | public static final String COLUMN_IMMUTABLE = "immutable"; 22 | public static final String COLUMN_IS_LIST = "list"; 23 | public static final String COLUMN_IS_LOCAL = "local"; 24 | 25 | public static final String TABLE_FORMAT = "format"; 26 | 27 | public static final String SOURCE = "source"; 28 | public static final String TARGET= "target"; 29 | public static final String DIRECTED = "directed"; 30 | 31 | public static final String NETWORK_SUID = "networkSUID"; 32 | 33 | public static final String URL = "url"; 34 | public static final String FORMAT_EDGELIST = "edgelist"; 35 | 36 | 37 | 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/org/cytoscape/rest/internal/resource/MiscResource.java: -------------------------------------------------------------------------------- 1 | package org.cytoscape.rest.internal.resource; 2 | 3 | import java.util.Properties; 4 | 5 | import javax.inject.Singleton; 6 | import javax.ws.rs.GET; 7 | import javax.ws.rs.InternalServerErrorException; 8 | import javax.ws.rs.NotFoundException; 9 | import javax.ws.rs.PUT; 10 | import javax.ws.rs.Path; 11 | import javax.ws.rs.Produces; 12 | import javax.ws.rs.core.MediaType; 13 | 14 | import org.cytoscape.rest.internal.model.CytoscapeVersion; 15 | import org.cytoscape.rest.internal.model.ServerStatus; 16 | 17 | /** 18 | * Resource to provide general status of the Cytoscape REST server. 19 | * 20 | * 21 | * @servicetag Server status 22 | * 23 | */ 24 | @Singleton 25 | @Path("/v1") 26 | public class MiscResource extends AbstractResource { 27 | 28 | /** 29 | * @summary Cytoscape RESTful API server status 30 | * 31 | * @return Summary of server status 32 | * 33 | * @statuscode 500 If REST API Module is not working. 34 | */ 35 | @GET 36 | @Path("/") 37 | @Produces(MediaType.APPLICATION_JSON + ";charset=utf-8") 38 | public ServerStatus getStatus() { 39 | return new ServerStatus(); 40 | } 41 | 42 | 43 | /** 44 | * Run System.gc(). In general, this is not necessary. 45 | * 46 | * @summary Force to run garbage collection to free up memory 47 | */ 48 | @GET 49 | @Path("/gc") 50 | @Produces(MediaType.APPLICATION_JSON) 51 | public void runGarbageCollection() { 52 | Runtime.getRuntime().gc(); 53 | } 54 | 55 | 56 | /** 57 | * 58 | * @summary Get Cytoscape and REST API version 59 | * 60 | * @return Cytoscape version and REST API version 61 | * 62 | */ 63 | @GET 64 | @Path("/version") 65 | @Produces(MediaType.APPLICATION_JSON) 66 | public CytoscapeVersion getCytoscapeVersion() { 67 | 68 | if (props == null) { 69 | throw new InternalServerErrorException("Could not find CyProperty object."); 70 | } 71 | 72 | final Properties property = (Properties) this.props.getProperties(); 73 | final Object versionNumber = property.get("cytoscape.version.number"); 74 | if (versionNumber != null) { 75 | return new CytoscapeVersion(API_VERSION, versionNumber.toString()); 76 | } else { 77 | throw new NotFoundException("Could not find Cytoscape version number property."); 78 | } 79 | } 80 | 81 | 82 | @PUT 83 | @Path("/ui/show-details") 84 | @Produces(MediaType.APPLICATION_JSON) 85 | public CytoscapeVersion updateShowGraphicsDetailsOption() { 86 | 87 | if (props == null) { 88 | throw new InternalServerErrorException("Could not find CyProperty object."); 89 | } 90 | 91 | final Properties property = (Properties) this.props.getProperties(); 92 | final Object versionNumber = property.get("cytoscape.version.number"); 93 | if (versionNumber != null) { 94 | return new CytoscapeVersion(API_VERSION, versionNumber.toString()); 95 | } else { 96 | throw new NotFoundException("Could not find Cytoscape version number property."); 97 | } 98 | } 99 | } 100 | -------------------------------------------------------------------------------- /src/main/java/org/cytoscape/rest/internal/resource/NetworkFullResource.java: -------------------------------------------------------------------------------- 1 | package org.cytoscape.rest.internal.resource; 2 | 3 | import java.util.Set; 4 | 5 | import javax.inject.Singleton; 6 | import javax.ws.rs.GET; 7 | import javax.ws.rs.Path; 8 | import javax.ws.rs.Produces; 9 | import javax.ws.rs.QueryParam; 10 | import javax.ws.rs.core.MediaType; 11 | import javax.ws.rs.core.Response; 12 | 13 | import org.cytoscape.model.CyNetwork; 14 | 15 | import com.qmino.miredot.annotations.ReturnType; 16 | 17 | @Singleton 18 | @Path("/v1/networks.json") 19 | public class NetworkFullResource extends AbstractResource { 20 | 21 | public NetworkFullResource() { 22 | super(); 23 | } 24 | 25 | /** 26 | * 27 | * Returns full list of network data as a JSON array. 28 | * JSON is in Cytoscape.js 29 | * format. If no query parameter is given, returns all networks in current session. 30 | * 31 | * @summary Get networks in Cytoscape.js JSON format 32 | * 33 | * @param column Optional. Network table column name to be used for search. 34 | * @param query Optional. Search query. 35 | * 36 | * @return Matched networks in Cytoscape.js JSON. If no query is given, all networks. 37 | * 38 | */ 39 | @GET 40 | @Path("/") 41 | @Produces(MediaType.APPLICATION_JSON + "; charset=UTF-8") 42 | @ReturnType("java.util.List") 43 | public String getNetworks(@QueryParam("column") String column, @QueryParam("query") String query) { 44 | Set networks; 45 | 46 | if (column == null && query == null) { 47 | networks = networkManager.getNetworkSet(); 48 | } else { 49 | if(column == null || column.length() == 0) { 50 | throw getError("Column name parameter is missing.", new IllegalArgumentException(), Response.Status.INTERNAL_SERVER_ERROR); 51 | } 52 | if(query == null || query.length() == 0) { 53 | throw getError("Query parameter is missing.", new IllegalArgumentException(), Response.Status.INTERNAL_SERVER_ERROR); 54 | } 55 | networks = getNetworksByQuery(query, column); 56 | } 57 | 58 | return getNetworksAsString(networks); 59 | } 60 | 61 | 62 | private final String getNetworksAsString(final Set networks) { 63 | if (networks.isEmpty()) { 64 | return "[]"; 65 | } 66 | 67 | final StringBuilder result = new StringBuilder(); 68 | result.append("["); 69 | 70 | for (final CyNetwork network : networks) { 71 | result.append(getNetworkString(network)); 72 | result.append(","); 73 | } 74 | String jsonString = result.toString(); 75 | jsonString = jsonString.substring(0, jsonString.length() - 1); 76 | 77 | return jsonString + "]"; 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /src/main/java/org/cytoscape/rest/internal/resource/NetworkNameResource.java: -------------------------------------------------------------------------------- 1 | package org.cytoscape.rest.internal.resource; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Collections; 5 | import java.util.HashMap; 6 | import java.util.List; 7 | import java.util.Map; 8 | import java.util.Set; 9 | 10 | import javax.inject.Singleton; 11 | import javax.ws.rs.GET; 12 | import javax.ws.rs.Path; 13 | import javax.ws.rs.Produces; 14 | import javax.ws.rs.QueryParam; 15 | import javax.ws.rs.core.MediaType; 16 | import javax.ws.rs.core.Response; 17 | 18 | import org.cytoscape.model.CyNetwork; 19 | 20 | import com.qmino.miredot.annotations.ReturnType; 21 | 22 | @Singleton 23 | @Path("/v1/networks.names") 24 | public class NetworkNameResource extends AbstractResource { 25 | 26 | public NetworkNameResource() { 27 | super(); 28 | } 29 | 30 | /** 31 | * 32 | * Returns full list of network data as a JSON array. JSON is in Cytoscape.js format. 34 | * If no query parameter is given, returns all networks in current session. 35 | * 36 | * @summary Get networks in Cytoscape.js JSON format 37 | * 38 | * @param column 39 | * Optional. Network table column name to be used for search. 40 | * @param query 41 | * Optional. Search query. 42 | * 43 | * @return Matched networks in Cytoscape.js JSON. If no query is given, all 44 | * networks. 45 | * 46 | */ 47 | @GET 48 | @Path("/") 49 | @Produces(MediaType.APPLICATION_JSON + "; charset=UTF-8") 50 | @ReturnType("java.util.List") 51 | public List> getNetworks(@QueryParam("column") String column, 52 | @QueryParam("query") String query) { 53 | Set networks; 54 | 55 | if (column == null && query == null) { 56 | networks = networkManager.getNetworkSet(); 57 | } else { 58 | if (column == null || column.length() == 0) { 59 | throw getError("Column name parameter is missing.", 60 | new IllegalArgumentException(), 61 | Response.Status.INTERNAL_SERVER_ERROR); 62 | } 63 | if (query == null || query.length() == 0) { 64 | throw getError("Query parameter is missing.", 65 | new IllegalArgumentException(), 66 | Response.Status.INTERNAL_SERVER_ERROR); 67 | } 68 | networks = getNetworksByQuery(query, column); 69 | } 70 | 71 | return getNetworksAsSimpleList(networks); 72 | } 73 | 74 | @SuppressWarnings("unchecked") 75 | private final List> getNetworksAsSimpleList(final Set networks) { 76 | if (networks.isEmpty()) { 77 | return Collections.EMPTY_LIST; 78 | } 79 | 80 | final List> networksList = new ArrayList<>(); 81 | for(final CyNetwork network: networks) { 82 | final Map values = new HashMap<>(); 83 | values.put("SUID", network.getSUID()); 84 | values.put("name", network.getRow(network).get(CyNetwork.NAME, String.class)); 85 | networksList.add(values); 86 | } 87 | 88 | return networksList; 89 | } 90 | } -------------------------------------------------------------------------------- /src/main/java/org/cytoscape/rest/internal/resource/RootResource.java: -------------------------------------------------------------------------------- 1 | package org.cytoscape.rest.internal.resource; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | 6 | import javax.inject.Singleton; 7 | import javax.ws.rs.GET; 8 | import javax.ws.rs.Path; 9 | import javax.ws.rs.Produces; 10 | import javax.ws.rs.core.MediaType; 11 | 12 | /** 13 | * Root of the REST API server. 14 | * 15 | */ 16 | @Singleton 17 | @Path("/") 18 | public class RootResource extends AbstractResource { 19 | 20 | private static final String[] VERSION_LIST = { API_VERSION }; 21 | private static final Map VERSION_MAP = new HashMap(); 22 | static { 23 | VERSION_MAP.put("availableApiVersions", VERSION_LIST); 24 | } 25 | 26 | /** 27 | * @summary Get available REST API versions 28 | * 29 | * @return List of available REST API versions. Currently, v1 is the only 30 | * available version. 31 | * 32 | */ 33 | @GET 34 | @Path("/") 35 | @Produces(MediaType.APPLICATION_JSON) 36 | public Map getVersions() { 37 | return VERSION_MAP; 38 | } 39 | 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/org/cytoscape/rest/internal/resource/SessionResource.java: -------------------------------------------------------------------------------- 1 | package org.cytoscape.rest.internal.resource; 2 | 3 | import java.io.File; 4 | 5 | import javax.inject.Singleton; 6 | import javax.validation.constraints.NotNull; 7 | import javax.ws.rs.DELETE; 8 | import javax.ws.rs.GET; 9 | import javax.ws.rs.POST; 10 | import javax.ws.rs.Path; 11 | import javax.ws.rs.Produces; 12 | import javax.ws.rs.QueryParam; 13 | import javax.ws.rs.core.Context; 14 | import javax.ws.rs.core.MediaType; 15 | import javax.ws.rs.core.Response; 16 | 17 | import org.cytoscape.rest.internal.task.HeadlessTaskMonitor; 18 | import org.cytoscape.session.CySessionManager; 19 | import org.cytoscape.task.create.NewSessionTaskFactory; 20 | import org.cytoscape.task.read.OpenSessionTaskFactory; 21 | import org.cytoscape.task.write.SaveSessionAsTaskFactory; 22 | import org.cytoscape.work.Task; 23 | import org.cytoscape.work.TaskIterator; 24 | 25 | 26 | 27 | @Singleton 28 | @Path("/v1/session") 29 | public class SessionResource extends AbstractResource { 30 | 31 | @Context 32 | @NotNull 33 | private CySessionManager sessionManager; 34 | 35 | @Context 36 | @NotNull 37 | private SaveSessionAsTaskFactory saveSessionAsTaskFactory; 38 | 39 | @Context 40 | @NotNull 41 | private OpenSessionTaskFactory openSessionTaskFactory; 42 | 43 | @Context 44 | @NotNull 45 | private NewSessionTaskFactory newSessionTaskFactory; 46 | 47 | 48 | public SessionResource() { 49 | super(); 50 | } 51 | 52 | 53 | /** 54 | * 55 | * @summary Get current session name 56 | * 57 | * @return Current session name 58 | */ 59 | @GET 60 | @Path("/name") 61 | @Produces(MediaType.APPLICATION_JSON) 62 | public String getSessionName() { 63 | String sessionName = sessionManager.getCurrentSessionFileName(); 64 | if(sessionName == null || sessionName.isEmpty()) { 65 | sessionName = ""; 66 | } 67 | 68 | return "{\"name\": \"" + sessionName +"\"}"; 69 | } 70 | 71 | 72 | /** 73 | * 74 | * @summary Delete current session and start new one 75 | * 76 | * @return Success message 77 | * 78 | */ 79 | @DELETE 80 | @Path("/") 81 | @Produces(MediaType.APPLICATION_JSON) 82 | public String deleteSession() { 83 | 84 | try { 85 | TaskIterator itr = newSessionTaskFactory.createTaskIterator(true); 86 | while(itr.hasNext()) { 87 | final Task task = itr.next(); 88 | task.run(new HeadlessTaskMonitor()); 89 | } 90 | } catch (Exception e) { 91 | e.printStackTrace(); 92 | throw getError("Could not delete current session.", e, Response.Status.INTERNAL_SERVER_ERROR); 93 | } 94 | return "{\"message\": \"New session created.\"}"; 95 | } 96 | 97 | 98 | /** 99 | * This get method load a new session from a file 100 | * 101 | * @summary Load new session from a local file 102 | * 103 | * @param file File name (should be absolute path) 104 | * 105 | * @return Session file name as string 106 | * 107 | */ 108 | @GET 109 | @Path("/") 110 | @Produces(MediaType.APPLICATION_JSON) 111 | public String getSessionFromFile(@QueryParam("file") String file) { 112 | File sessionFile = null; 113 | try { 114 | sessionFile = new File(file); 115 | TaskIterator itr = openSessionTaskFactory.createTaskIterator(sessionFile); 116 | while(itr.hasNext()) { 117 | final Task task = itr.next(); 118 | task.run(new HeadlessTaskMonitor()); 119 | } 120 | } catch (Exception e) { 121 | e.printStackTrace(); 122 | throw getError("Could not save session.", e, Response.Status.INTERNAL_SERVER_ERROR); 123 | } 124 | 125 | return "{\"file\": \"" + sessionFile.getAbsolutePath() +"\"}"; 126 | } 127 | 128 | 129 | /** 130 | * 131 | * @summary Create a session file 132 | * 133 | * @param file Session file location (should be absolute path) 134 | * 135 | * @return Session file name 136 | */ 137 | @POST 138 | @Path("/") 139 | @Produces(MediaType.APPLICATION_JSON) 140 | public String createSessionFile(@QueryParam("file") String file) { 141 | File sessionFile = null; 142 | try { 143 | sessionFile = new File(file); 144 | TaskIterator itr = saveSessionAsTaskFactory.createTaskIterator(sessionFile); 145 | while(itr.hasNext()) { 146 | final Task task = itr.next(); 147 | task.run(new HeadlessTaskMonitor()); 148 | } 149 | } catch (Exception e) { 150 | e.printStackTrace(); 151 | throw getError("Could not save session.", e, Response.Status.INTERNAL_SERVER_ERROR); 152 | } 153 | 154 | return "{\"file\": \"" + sessionFile.getAbsolutePath() +"\"}"; 155 | } 156 | } 157 | -------------------------------------------------------------------------------- /src/main/java/org/cytoscape/rest/internal/resource/UIResource.java: -------------------------------------------------------------------------------- 1 | package org.cytoscape.rest.internal.resource; 2 | 3 | import java.io.IOException; 4 | import java.io.InputStream; 5 | import java.util.Arrays; 6 | import java.util.HashMap; 7 | import java.util.List; 8 | import java.util.Map; 9 | import java.util.stream.Collectors; 10 | 11 | import javax.inject.Singleton; 12 | import javax.validation.constraints.NotNull; 13 | import javax.ws.rs.Consumes; 14 | import javax.ws.rs.GET; 15 | import javax.ws.rs.InternalServerErrorException; 16 | import javax.ws.rs.NotFoundException; 17 | import javax.ws.rs.PUT; 18 | import javax.ws.rs.Path; 19 | import javax.ws.rs.PathParam; 20 | import javax.ws.rs.Produces; 21 | import javax.ws.rs.core.Context; 22 | import javax.ws.rs.core.MediaType; 23 | import javax.ws.rs.core.Response; 24 | import javax.ws.rs.core.Response.Status; 25 | 26 | import org.cytoscape.application.swing.CySwingApplication; 27 | import org.cytoscape.application.swing.CytoPanel; 28 | import org.cytoscape.application.swing.CytoPanelName; 29 | import org.cytoscape.application.swing.CytoPanelState; 30 | import org.cytoscape.rest.internal.CyActivator.LevelOfDetails; 31 | import org.cytoscape.work.TaskIterator; 32 | import org.cytoscape.work.TaskMonitor; 33 | 34 | import com.fasterxml.jackson.core.JsonParseException; 35 | import com.fasterxml.jackson.core.sym.Name; 36 | import com.fasterxml.jackson.databind.JsonMappingException; 37 | import com.fasterxml.jackson.databind.JsonNode; 38 | import com.fasterxml.jackson.databind.ObjectMapper; 39 | 40 | 41 | @Singleton 42 | @Path("/v1/ui") 43 | public class UIResource extends AbstractResource { 44 | 45 | @Context 46 | @NotNull 47 | protected CySwingApplication desktop; 48 | 49 | @Context 50 | @NotNull 51 | protected LevelOfDetails detailsTF; 52 | 53 | @Context 54 | @NotNull 55 | private TaskMonitor headlessTaskMonitor; 56 | 57 | 58 | /** 59 | * 60 | * @summary Get status of Desktop 61 | * 62 | * @return An object with isDesktopAvailable field. 63 | * This value is true if Cytoscape Desktop is available. 64 | * And it is false if Cytoscape is running in headless mode (not available yet). 65 | * 66 | */ 67 | @GET 68 | @Path("/") 69 | @Produces(MediaType.APPLICATION_JSON + ";charset=utf-8") 70 | public Map getDesktop() { 71 | final Map status = new HashMap<>(); 72 | boolean desktopAvailable = false; 73 | if(desktop != null) { 74 | desktopAvailable = true; 75 | } 76 | status.put("isDesktopAvailable", desktopAvailable); 77 | return status; 78 | } 79 | 80 | 81 | /** 82 | * 83 | * Switch between full graphics details <---> fast rendering mode. 84 | * 85 | * @summary Toggle level of graphics details (LoD). 86 | * 87 | * @return Success message. 88 | */ 89 | @PUT 90 | @Path("/lod") 91 | @Produces(MediaType.APPLICATION_JSON + ";charset=utf-8") 92 | public Response updateLodState() { 93 | final TaskIterator lod = detailsTF.getLodTF().createTaskIterator(null); 94 | 95 | try { 96 | lod.next().run(headlessTaskMonitor); 97 | } catch (Exception e) { 98 | throw getError("Could not toggle LOD.", e, 99 | Response.Status.INTERNAL_SERVER_ERROR); 100 | } 101 | 102 | return Response.status(Response.Status.OK) 103 | .type(MediaType.APPLICATION_JSON) 104 | .entity("{\"message\":\"Toggled Graphics level of details.\"}").build(); 105 | } 106 | 107 | /** 108 | * The return value will includes status of all CytoPanels. 109 | * Each entry includes: 110 | * 111 | *
    112 | *
  • 113 | * name: Official name of the CytoPanel: 114 | *
      115 | *
    • SOUTH
    • 116 | *
    • EAST
    • 117 | *
    • WEST
    • 118 | *
    • SOUTH_WEST
    • 119 | *
    120 | *
  • 121 | *
  • 122 | * state: State of the CytoPanel: 123 | *
      124 | *
    • FLOAT
    • 125 | *
    • DOCK
    • 126 | *
    • HIDE
    • 127 | *
    128 | *
  • 129 | *
130 | * 131 | * @summary Get status of all CytoPanels 132 | * 133 | * @return Panel status as an array 134 | */ 135 | @GET 136 | @Path("/panels") 137 | @Produces(MediaType.APPLICATION_JSON + ";charset=utf-8") 138 | public List> getAllPanelStatus() { 139 | try { 140 | return Arrays.asList(CytoPanelName.values()).stream() 141 | .map(panelName->desktop.getCytoPanel(panelName)) 142 | .map(panel->getMap(panel)) 143 | .collect(Collectors.toList()); 144 | } catch(Exception ex) { 145 | throw getError("Could not getpanel status", ex, Status.INTERNAL_SERVER_ERROR); 146 | } 147 | } 148 | 149 | 150 | private final Map getMap(final CytoPanel panel) { 151 | final Map values = new HashMap<>(); 152 | values.put("name", panel.getCytoPanelName().name()); 153 | values.put("state", panel.getState().name()); 154 | return values; 155 | } 156 | 157 | 158 | /** 159 | * 160 | * @summary Get status of a CytoPanel 161 | * 162 | * @param panelName official name of the CytroPanel 163 | * 164 | * @return Status of the CytoPanel (name-state pair) 165 | */ 166 | @GET 167 | @Path("/panels/{panelName}") 168 | @Produces(MediaType.APPLICATION_JSON + ";charset=utf-8") 169 | public Response getPanelStatus(@PathParam("panelName") String panelName) { 170 | final CytoPanelName panel = CytoPanelName.valueOf(panelName); 171 | System.out.println(panel); 172 | if(panel == null) { 173 | return Response.status(Response.Status.NOT_FOUND).build(); 174 | } 175 | final CytoPanel panelObject = desktop.getCytoPanel(panel); 176 | return Response.ok(getMap(panelObject)).build(); 177 | } 178 | 179 | 180 | /** 181 | * 182 | * You can update multiple panel states at once. 183 | * Body of your request should have same format as the return value of GET method. 184 | * 185 | * @summary Update CytoPanel states 186 | * 187 | * @return Response 200 if success 188 | */ 189 | @PUT 190 | @Path("/panels") 191 | @Consumes(MediaType.APPLICATION_JSON) 192 | public Response updatePanelStatus(final InputStream is) { 193 | 194 | final ObjectMapper objMapper = new ObjectMapper(); 195 | 196 | JsonNode rootNode = null; 197 | try { 198 | rootNode = objMapper.readValue(is, JsonNode.class); 199 | } catch (IOException e) { 200 | throw new InternalServerErrorException("Could not parse input JSON.", e); 201 | } 202 | 203 | for (final JsonNode entry : rootNode) { 204 | final JsonNode panelName = entry.get("name"); 205 | final JsonNode panelStatus = entry.get("state"); 206 | 207 | if(panelName == null || panelStatus == null) { 208 | throw new IllegalArgumentException("Imput parameters are missing."); 209 | } 210 | 211 | final CytoPanelName panel = CytoPanelName.valueOf(panelName.asText()); 212 | if(panel == null) { 213 | throw new IllegalArgumentException("Could not find panel: " + panelName.asText()); 214 | } 215 | 216 | final CytoPanelState state = CytoPanelState.valueOf(panelStatus.asText()); 217 | if(state == null) { 218 | throw new IllegalArgumentException("Invalid Panel State: " + panelStatus.asText()); 219 | } 220 | 221 | final CytoPanel panelObject = desktop.getCytoPanel(panel); 222 | panelObject.setState(state); 223 | } 224 | 225 | return Response.ok().build(); 226 | } 227 | } -------------------------------------------------------------------------------- /src/main/java/org/cytoscape/rest/internal/resource/package-info.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | * Actual RESTful API implementations using JAX-RS (Jersey). 4 | * 5 | * 6 | */ 7 | package org.cytoscape.rest.internal.resource; -------------------------------------------------------------------------------- /src/main/java/org/cytoscape/rest/internal/serializer/ContinuousMappingSerializer.java: -------------------------------------------------------------------------------- 1 | package org.cytoscape.rest.internal.serializer; 2 | 3 | import java.io.IOException; 4 | import java.util.List; 5 | 6 | import org.cytoscape.rest.internal.datamapper.VisualStyleMapper; 7 | import org.cytoscape.view.model.VisualProperty; 8 | import org.cytoscape.view.vizmap.mappings.BoundaryRangeValues; 9 | import org.cytoscape.view.vizmap.mappings.ContinuousMapping; 10 | import org.cytoscape.view.vizmap.mappings.ContinuousMappingPoint; 11 | 12 | import com.fasterxml.jackson.core.JsonGenerator; 13 | import com.fasterxml.jackson.core.JsonProcessingException; 14 | import com.fasterxml.jackson.databind.JsonSerializer; 15 | import com.fasterxml.jackson.databind.SerializerProvider; 16 | import com.qmino.miredot.annotations.MireDotIgnore; 17 | 18 | @SuppressWarnings("rawtypes") 19 | @MireDotIgnore 20 | public class ContinuousMappingSerializer extends JsonSerializer { 21 | 22 | @Override 23 | public Class handledType() { 24 | return ContinuousMapping.class; 25 | } 26 | 27 | @Override 28 | public void serialize(ContinuousMapping mapping, JsonGenerator jgen, SerializerProvider provider) throws IOException, 29 | JsonProcessingException { 30 | jgen.useDefaultPrettyPrinter(); 31 | 32 | jgen.writeStartObject(); 33 | jgen.writeStringField(VisualStyleMapper.MAPPING_TYPE, "continuous"); 34 | jgen.writeStringField(VisualStyleMapper.MAPPING_COLUMN, mapping.getMappingColumnName()); 35 | jgen.writeStringField(VisualStyleMapper.MAPPING_COLUMN_TYPE, mapping.getMappingColumnType().getSimpleName()); 36 | jgen.writeStringField(VisualStyleMapper.MAPPING_VP, mapping.getVisualProperty().getIdString()); 37 | 38 | serializePoints(mapping, jgen); 39 | 40 | jgen.writeEndObject(); 41 | } 42 | 43 | @SuppressWarnings("unchecked") 44 | private final void serializePoints(final ContinuousMapping mapping, final JsonGenerator jgen) throws IOException { 45 | 46 | final VisualProperty vp = mapping.getVisualProperty(); 47 | jgen.writeArrayFieldStart("points"); 48 | final List points = mapping.getAllPoints(); 49 | for(final ContinuousMappingPoint point : points) { 50 | jgen.writeStartObject(); 51 | final Number val = (Number) point.getValue(); 52 | jgen.writeNumberField("value", val.doubleValue()); 53 | final BoundaryRangeValues range = point.getRange(); 54 | jgen.writeStringField("lesser", vp.toSerializableString(range.lesserValue)); 55 | jgen.writeStringField("equal", vp.toSerializableString(range.equalValue)); 56 | jgen.writeStringField("greater", vp.toSerializableString(range.greaterValue)); 57 | jgen.writeEndObject(); 58 | } 59 | jgen.writeEndArray(); 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /src/main/java/org/cytoscape/rest/internal/serializer/CyTableSerializer.java: -------------------------------------------------------------------------------- 1 | package org.cytoscape.rest.internal.serializer; 2 | 3 | import java.util.Collection; 4 | import java.util.List; 5 | 6 | import org.cytoscape.model.CyColumn; 7 | import org.cytoscape.model.CyRow; 8 | import org.cytoscape.model.CyTable; 9 | 10 | public class CyTableSerializer { 11 | 12 | private String SEP = ","; 13 | 14 | public String toCSV(final CyTable table, final String sep) throws Exception { 15 | 16 | String separator = sep; 17 | System.out.println(separator); 18 | if(separator == null) { 19 | separator = SEP; 20 | } 21 | 22 | final StringBuilder builder = new StringBuilder(); 23 | 24 | final Collection columns = table.getColumns(); 25 | final int colLength = columns.size(); 26 | 27 | // Rows to be serialized 28 | final List rows = table.getAllRows(); 29 | int idx = 1; 30 | 31 | // Add header 32 | for (final CyColumn column : columns) { 33 | builder.append(column.getName()); 34 | if (idx == colLength) { 35 | builder.append("\n"); 36 | } else { 37 | builder.append(separator); 38 | } 39 | idx++; 40 | } 41 | 42 | for (final CyRow row : rows) { 43 | idx = 1; 44 | for (final CyColumn column : columns) { 45 | final Class type = column.getType(); 46 | if (type != List.class) { 47 | final Object value = row.get(column.getName(), type); 48 | if (value != null) { 49 | builder.append(value.toString()); 50 | } 51 | } else { 52 | final List listValue = row.getList(column.getName(), column.getListElementType()); 53 | builder.append(listToString(listValue)); 54 | } 55 | if (idx == colLength) { 56 | builder.append("\n"); 57 | } else { 58 | builder.append(separator); 59 | } 60 | idx++; 61 | } 62 | } 63 | return builder.toString(); 64 | } 65 | 66 | private final String listToString(final List listCell) { 67 | if (listCell == null) { 68 | return ""; 69 | } 70 | 71 | final StringBuilder listBuilder = new StringBuilder(); 72 | 73 | for (final Object item : listCell) { 74 | if (item != null) { 75 | listBuilder.append(item.toString()); 76 | listBuilder.append("|"); 77 | } 78 | } 79 | final String cellString = listBuilder.toString(); 80 | if (cellString != null && cellString.isEmpty() == false) { 81 | return cellString.substring(0, cellString.length() - 1); 82 | } else { 83 | return ""; 84 | } 85 | } 86 | } -------------------------------------------------------------------------------- /src/main/java/org/cytoscape/rest/internal/serializer/DiscreteMappingSerializer.java: -------------------------------------------------------------------------------- 1 | package org.cytoscape.rest.internal.serializer; 2 | 3 | import java.io.IOException; 4 | import java.util.Map; 5 | 6 | import org.cytoscape.rest.internal.datamapper.VisualStyleMapper; 7 | import org.cytoscape.view.model.VisualProperty; 8 | import org.cytoscape.view.vizmap.mappings.DiscreteMapping; 9 | 10 | import com.fasterxml.jackson.core.JsonGenerator; 11 | import com.fasterxml.jackson.core.JsonProcessingException; 12 | import com.fasterxml.jackson.databind.JsonSerializer; 13 | import com.fasterxml.jackson.databind.SerializerProvider; 14 | import com.qmino.miredot.annotations.MireDotIgnore; 15 | 16 | @SuppressWarnings("rawtypes") 17 | @MireDotIgnore 18 | public class DiscreteMappingSerializer extends JsonSerializer { 19 | 20 | @Override 21 | public Class handledType() { 22 | return DiscreteMapping.class; 23 | } 24 | 25 | @Override 26 | public void serialize(DiscreteMapping mapping, JsonGenerator jgen, SerializerProvider provider) throws IOException, 27 | JsonProcessingException { 28 | jgen.useDefaultPrettyPrinter(); 29 | 30 | jgen.writeStartObject(); 31 | 32 | jgen.writeStringField(VisualStyleMapper.MAPPING_TYPE, "discrete"); 33 | jgen.writeStringField(VisualStyleMapper.MAPPING_COLUMN, mapping.getMappingColumnName()); 34 | jgen.writeStringField(VisualStyleMapper.MAPPING_COLUMN_TYPE, mapping.getMappingColumnType().getSimpleName()); 35 | jgen.writeStringField(VisualStyleMapper.MAPPING_VP, mapping.getVisualProperty().getIdString()); 36 | 37 | serializeMapping(mapping, jgen); 38 | 39 | jgen.writeEndObject(); 40 | } 41 | 42 | 43 | @SuppressWarnings("unchecked") 44 | private final void serializeMapping(final DiscreteMapping mapping, JsonGenerator jgen) throws IOException { 45 | final Map valueMap = mapping.getAll(); 46 | 47 | final VisualProperty vp = mapping.getVisualProperty(); 48 | 49 | jgen.writeArrayFieldStart("map"); 50 | 51 | for(final Object key:valueMap.keySet()) { 52 | final Object value = valueMap.get(key); 53 | jgen.writeStartObject(); 54 | jgen.writeStringField("key", key.toString()); 55 | jgen.writeStringField("value", vp.toSerializableString(value)); 56 | jgen.writeEndObject(); 57 | } 58 | jgen.writeEndArray(); 59 | } 60 | } -------------------------------------------------------------------------------- /src/main/java/org/cytoscape/rest/internal/serializer/GraphObjectSerializer.java: -------------------------------------------------------------------------------- 1 | package org.cytoscape.rest.internal.serializer; 2 | 3 | import java.io.ByteArrayOutputStream; 4 | import java.io.IOException; 5 | import java.util.Collection; 6 | import java.util.List; 7 | import java.util.Map; 8 | import java.util.regex.Matcher; 9 | import java.util.regex.Pattern; 10 | 11 | import org.cytoscape.model.CyColumn; 12 | import org.cytoscape.model.CyEdge; 13 | import org.cytoscape.model.CyIdentifiable; 14 | import org.cytoscape.model.CyRow; 15 | import org.cytoscape.rest.internal.resource.JsonTags; 16 | 17 | import com.fasterxml.jackson.core.JsonFactory; 18 | import com.fasterxml.jackson.core.JsonGenerationException; 19 | import com.fasterxml.jackson.core.JsonGenerator; 20 | 21 | public class GraphObjectSerializer { 22 | 23 | private static final Pattern REPLACE_INVALID_JS_CHAR_PATTERN = Pattern.compile("^[^a-zA-Z_]+|[^a-zA-Z_0-9]+"); 24 | 25 | public final String serializeGraphObject(final CyIdentifiable obj, final CyRow row) throws IOException { 26 | 27 | final JsonFactory factory = new JsonFactory(); 28 | 29 | String result = null; 30 | ByteArrayOutputStream stream = new ByteArrayOutputStream(); 31 | JsonGenerator generator = null; 32 | generator = factory.createGenerator(stream); 33 | generator.writeStartObject(); 34 | generator.writeObjectFieldStart("data"); 35 | serializeRow(generator, obj, row); 36 | generator.writeEndObject(); 37 | generator.writeEndObject(); 38 | generator.close(); 39 | result = stream.toString("UTF-8"); 40 | stream.close(); 41 | return result; 42 | } 43 | 44 | public final String serializeRow(final CyRow row) throws IOException { 45 | 46 | final JsonFactory factory = new JsonFactory(); 47 | 48 | String result = null; 49 | ByteArrayOutputStream stream = new ByteArrayOutputStream(); 50 | JsonGenerator generator = null; 51 | generator = factory.createGenerator(stream); 52 | generator.writeStartObject(); 53 | serializeSingleRow(generator, row); 54 | generator.writeEndObject(); 55 | generator.close(); 56 | result = stream.toString("UTF-8"); 57 | stream.close(); 58 | return result; 59 | } 60 | 61 | public final String serializeCell(final CyRow row, final String columnName) throws IOException { 62 | 63 | final CyColumn column = row.getTable().getColumn(columnName); 64 | if (column == null) { 65 | throw new IOException("No such column: " + columnName); 66 | } 67 | 68 | final Object value = row.get(columnName, column.getType()); 69 | final JsonFactory factory = new JsonFactory(); 70 | 71 | String result = null; 72 | ByteArrayOutputStream stream = new ByteArrayOutputStream(); 73 | JsonGenerator generator = null; 74 | generator = factory.createGenerator(stream); 75 | generator.writeStartObject(); 76 | serializeCell(generator, column, value); 77 | generator.writeEndObject(); 78 | generator.close(); 79 | result = stream.toString("UTF-8"); 80 | stream.close(); 81 | return result; 82 | } 83 | 84 | public final String serializeAllRows(final Collection rows) throws IOException { 85 | 86 | final JsonFactory factory = new JsonFactory(); 87 | 88 | String result = null; 89 | ByteArrayOutputStream stream = new ByteArrayOutputStream(); 90 | JsonGenerator generator = null; 91 | generator = factory.createGenerator(stream); 92 | 93 | generator.writeStartArray(); 94 | for (final CyRow row : rows) { 95 | generator.writeStartObject(); 96 | serializeSingleRow(generator, row); 97 | generator.writeEndObject(); 98 | } 99 | generator.writeEndArray(); 100 | 101 | generator.close(); 102 | result = stream.toString("UTF-8"); 103 | stream.close(); 104 | return result; 105 | } 106 | 107 | 108 | public final String serializeColumns(final Collection columns) throws IOException { 109 | 110 | final JsonFactory factory = new JsonFactory(); 111 | 112 | String result = null; 113 | ByteArrayOutputStream stream = new ByteArrayOutputStream(); 114 | JsonGenerator generator = null; 115 | generator = factory.createGenerator(stream); 116 | 117 | generator.writeStartArray(); 118 | for (final CyColumn column : columns) { 119 | generator.writeStartObject(); 120 | generator.writeStringField(JsonTags.COLUMN_NAME, column.getName()); 121 | generator.writeStringField(JsonTags.COLUMN_TYPE, column.getType().getSimpleName()); 122 | generator.writeBooleanField(JsonTags.COLUMN_IMMUTABLE, column.isImmutable()); 123 | generator.writeBooleanField(JsonTags.PRIMARY_KEY, column.isPrimaryKey()); 124 | generator.writeEndObject(); 125 | } 126 | generator.writeEndArray(); 127 | 128 | generator.close(); 129 | result = stream.toString("UTF-8"); 130 | stream.close(); 131 | return result; 132 | } 133 | 134 | public final String serializeColumnValues(final CyColumn column, final Collection values) throws IOException { 135 | 136 | final JsonFactory factory = new JsonFactory(); 137 | 138 | String result = null; 139 | ByteArrayOutputStream stream = new ByteArrayOutputStream(); 140 | JsonGenerator generator = null; 141 | generator = factory.createGenerator(stream); 142 | 143 | try { 144 | generator.writeStartObject(); 145 | generator.writeStringField(JsonTags.COLUMN_NAME, column.getName()); 146 | generator.writeFieldName(JsonTags.COLUMN_VALUES); 147 | generator.writeStartArray(); 148 | for (final Object value : values) { 149 | if (column.getType() == List.class) { 150 | writeList(column.getListElementType(), (List) value, generator); 151 | } else { 152 | writeValue(column.getType(), value, generator); 153 | } 154 | } 155 | generator.writeEndArray(); 156 | generator.writeEndObject(); 157 | 158 | generator.close(); 159 | result = stream.toString("UTF-8"); 160 | stream.close(); 161 | } catch(Exception e) { 162 | e.printStackTrace(); 163 | } 164 | return result; 165 | } 166 | 167 | 168 | private final void serializeSingleRow(final JsonGenerator generator, final CyRow row) throws IOException { 169 | final Collection columns = row.getTable().getColumns(); 170 | final Map values = row.getAllValues(); 171 | for (final CyColumn col : columns) { 172 | final Object value = values.get(col.getName()); 173 | if (value == null) 174 | continue; 175 | Class type = col.getType(); 176 | final String columnName = col.getName(); 177 | generator.writeFieldName(replaceColumnName(columnName)); 178 | if (type == List.class) { 179 | writeList(col.getListElementType(), (List) value, generator); 180 | } else { 181 | writeValue(type, value, generator); 182 | } 183 | } 184 | } 185 | 186 | private final void serializeRow(JsonGenerator generator, final CyIdentifiable obj, final CyRow row) 187 | throws IOException { 188 | final Collection columns = row.getTable().getColumns(); 189 | final Map values = row.getAllValues(); 190 | if (obj instanceof CyEdge) { 191 | final Long sourceId = ((CyEdge) obj).getSource().getSUID(); 192 | final Long targetId = ((CyEdge) obj).getTarget().getSUID(); 193 | generator.writeNumberField("source", sourceId); 194 | generator.writeNumberField("target", targetId); 195 | } else { 196 | generator.writeNumberField("id", obj.getSUID()); 197 | } 198 | for (final CyColumn col : columns) { 199 | final Object value = values.get(col.getName()); 200 | if (value == null) 201 | continue; 202 | 203 | Class type = col.getType(); 204 | final String columnName = col.getName(); 205 | generator.writeFieldName(replaceColumnName(columnName)); 206 | if (type == List.class) { 207 | writeList(col.getListElementType(), (List) value, generator); 208 | } else { 209 | writeValue(type, value, generator); 210 | } 211 | } 212 | } 213 | 214 | private final void serializeCell(final JsonGenerator generator, final CyColumn col, Object value) 215 | throws IOException { 216 | Class type = col.getType(); 217 | final String columnName = col.getName(); 218 | generator.writeFieldName(replaceColumnName(columnName)); 219 | if (type == List.class) { 220 | writeList(col.getListElementType(), (List) value, generator); 221 | } else { 222 | writeValue(type, value, generator); 223 | } 224 | } 225 | 226 | private final void writeList(final Class type, final List values, final JsonGenerator jgen) 227 | throws JsonGenerationException, IOException { 228 | 229 | if(values == null) { 230 | return; 231 | } 232 | 233 | jgen.writeStartArray(); 234 | for (final Object value : values) 235 | writeValue(type, value, jgen); 236 | jgen.writeEndArray(); 237 | } 238 | 239 | private final String replaceColumnName(final String columnName) { 240 | final Matcher matcher = REPLACE_INVALID_JS_CHAR_PATTERN.matcher(columnName); 241 | return matcher.replaceAll("_"); 242 | } 243 | 244 | private final void writeValue(final Class type, final Object value, final JsonGenerator generator) 245 | throws IOException { 246 | if(value == null) { 247 | return; 248 | } 249 | 250 | if (type == String.class) { 251 | generator.writeString(value.toString()); 252 | } else if (type == Boolean.class) { 253 | generator.writeBoolean((Boolean) value); 254 | } else if (type == Double.class) { 255 | generator.writeNumber((Double) value); 256 | } else if (type == Integer.class) { 257 | generator.writeNumber((Integer) value); 258 | } else if (type == Long.class) { 259 | generator.writeNumber((Long) value); 260 | } else if (type == Float.class) { 261 | generator.writeNumber((Double) value); 262 | } 263 | } 264 | } -------------------------------------------------------------------------------- /src/main/java/org/cytoscape/rest/internal/serializer/GroupModule.java: -------------------------------------------------------------------------------- 1 | package org.cytoscape.rest.internal.serializer; 2 | 3 | import com.fasterxml.jackson.core.Version; 4 | import com.fasterxml.jackson.databind.module.SimpleModule; 5 | 6 | public class GroupModule extends SimpleModule { 7 | 8 | private static final long serialVersionUID = -1590853632349015561L; 9 | 10 | public GroupModule() { 11 | super("GroupModule", new Version(1, 0, 0, null, null, null)); 12 | addSerializer(new GroupSerializer()); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/org/cytoscape/rest/internal/serializer/GroupSerializer.java: -------------------------------------------------------------------------------- 1 | package org.cytoscape.rest.internal.serializer; 2 | 3 | import java.io.IOException; 4 | import java.util.List; 5 | import java.util.Set; 6 | 7 | import org.cytoscape.group.CyGroup; 8 | import org.cytoscape.model.CyEdge; 9 | import org.cytoscape.model.CyIdentifiable; 10 | import org.cytoscape.model.CyNode; 11 | 12 | import com.fasterxml.jackson.core.JsonGenerator; 13 | import com.fasterxml.jackson.core.JsonProcessingException; 14 | import com.fasterxml.jackson.databind.JsonSerializer; 15 | import com.fasterxml.jackson.databind.SerializerProvider; 16 | 17 | public class GroupSerializer extends JsonSerializer { 18 | 19 | @Override 20 | public Class handledType() { 21 | return CyGroup.class; 22 | } 23 | 24 | @Override 25 | public void serialize(final CyGroup group, JsonGenerator jgen, SerializerProvider provider) throws IOException, 26 | JsonProcessingException { 27 | 28 | jgen.useDefaultPrettyPrinter(); 29 | 30 | jgen.writeStartObject(); 31 | 32 | final CyNode groupNode = group.getGroupNode(); 33 | final List memberNodes = group.getNodeList(); 34 | final List internalEdges = group.getInternalEdgeList(); 35 | final Set externalEdges = group.getExternalEdgeList(); 36 | jgen.writeNumberField(CyIdentifiable.SUID, groupNode.getSUID()); 37 | 38 | // TODO: Bug? Always false 39 | // jgen.writeBooleanField("collapsed", group.isCollapsed(group.getRootNetwork())); 40 | 41 | jgen.writeArrayFieldStart("nodes"); 42 | for (final CyNode node : memberNodes) { 43 | jgen.writeNumber(node.getSUID()); 44 | } 45 | jgen.writeEndArray(); 46 | 47 | jgen.writeArrayFieldStart("internal_edges"); 48 | for (final CyEdge edge : internalEdges) { 49 | jgen.writeNumber(edge.getSUID()); 50 | } 51 | jgen.writeEndArray(); 52 | 53 | jgen.writeArrayFieldStart("external_edges"); 54 | for (final CyEdge edge : externalEdges) { 55 | jgen.writeNumber(edge.getSUID()); 56 | } 57 | jgen.writeEndArray(); 58 | 59 | jgen.writeEndObject(); 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /src/main/java/org/cytoscape/rest/internal/serializer/PassthroughMappingSerializer.java: -------------------------------------------------------------------------------- 1 | package org.cytoscape.rest.internal.serializer; 2 | 3 | import java.io.IOException; 4 | 5 | import org.cytoscape.rest.internal.datamapper.VisualStyleMapper; 6 | import org.cytoscape.view.vizmap.mappings.PassthroughMapping; 7 | 8 | import com.fasterxml.jackson.core.JsonGenerator; 9 | import com.fasterxml.jackson.core.JsonProcessingException; 10 | import com.fasterxml.jackson.databind.JsonSerializer; 11 | import com.fasterxml.jackson.databind.SerializerProvider; 12 | import com.qmino.miredot.annotations.MireDotIgnore; 13 | 14 | @SuppressWarnings("rawtypes") 15 | @MireDotIgnore 16 | public class PassthroughMappingSerializer extends JsonSerializer { 17 | 18 | @Override 19 | public Class handledType() { 20 | return PassthroughMapping.class; 21 | } 22 | 23 | @Override 24 | public void serialize(PassthroughMapping mapping, JsonGenerator jgen, SerializerProvider provider) throws IOException, 25 | JsonProcessingException { 26 | jgen.useDefaultPrettyPrinter(); 27 | jgen.writeStartObject(); 28 | jgen.writeStringField(VisualStyleMapper.MAPPING_TYPE, "passthrough"); 29 | jgen.writeStringField(VisualStyleMapper.MAPPING_COLUMN, mapping.getMappingColumnName()); 30 | jgen.writeStringField(VisualStyleMapper.MAPPING_COLUMN_TYPE, mapping.getMappingColumnType().getSimpleName()); 31 | jgen.writeStringField(VisualStyleMapper.MAPPING_VP, mapping.getVisualProperty().getIdString()); 32 | jgen.writeEndObject(); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/org/cytoscape/rest/internal/serializer/RowSerializer.java: -------------------------------------------------------------------------------- 1 | package org.cytoscape.rest.internal.serializer; 2 | 3 | import java.io.IOException; 4 | import java.util.List; 5 | import java.util.Map; 6 | import java.util.Set; 7 | import java.util.regex.Matcher; 8 | import java.util.regex.Pattern; 9 | 10 | import org.cytoscape.model.CyRow; 11 | import org.cytoscape.model.CyTable; 12 | 13 | import com.fasterxml.jackson.core.JsonGenerationException; 14 | import com.fasterxml.jackson.core.JsonGenerator; 15 | import com.fasterxml.jackson.core.JsonProcessingException; 16 | import com.fasterxml.jackson.databind.JsonSerializer; 17 | import com.fasterxml.jackson.databind.SerializerProvider; 18 | 19 | public class RowSerializer extends JsonSerializer { 20 | 21 | private static final Pattern REPLACE_INVALID_JS_CHAR_PATTERN = Pattern.compile("^[^a-zA-Z_]+|[^a-zA-Z_0-9]+"); 22 | 23 | 24 | @Override 25 | public void serialize(final CyRow row, JsonGenerator jgen, SerializerProvider provider) throws IOException, 26 | JsonProcessingException { 27 | 28 | final CyTable table = row.getTable(); 29 | final Map cells = row.getAllValues(); 30 | final Set columnNames = cells.keySet(); 31 | 32 | jgen.writeStartObject(); 33 | 34 | for(final String columnName : columnNames) { 35 | final Object value = cells.get(columnName); 36 | // Skip if there is no value. 37 | if (value == null) 38 | continue; 39 | 40 | Class type = table.getColumn(columnName).getType(); 41 | if (type == List.class) { 42 | type = table.getColumn(columnName).getListElementType(); 43 | writeList(type, columnName, (List) value, jgen); 44 | } else { 45 | jgen.writeFieldName(replaceColumnName(columnName)); 46 | writeValue(type, value, jgen); 47 | } 48 | } 49 | 50 | jgen.writeEndObject(); 51 | } 52 | 53 | 54 | private final void writeList(final Class type, String columnName, List values, JsonGenerator jgen) 55 | throws JsonGenerationException, IOException { 56 | 57 | jgen.writeArrayFieldStart(replaceColumnName(columnName)); 58 | for (final Object value : values) { 59 | writeValue(type, value, jgen); 60 | } 61 | jgen.writeEndArray(); 62 | } 63 | 64 | private final String replaceColumnName(final String columnName) { 65 | final Matcher matcher = REPLACE_INVALID_JS_CHAR_PATTERN.matcher(columnName); 66 | return matcher.replaceAll("_"); 67 | } 68 | 69 | private final void writeValue(final Class type, Object value, JsonGenerator jgen) 70 | throws JsonGenerationException, IOException { 71 | if (type == String.class) { 72 | jgen.writeString(value.toString()); 73 | } else if (type == Boolean.class) { 74 | jgen.writeBoolean((Boolean) value); 75 | } else if (type == Double.class) { 76 | jgen.writeNumber((Double) value); 77 | } else if (type == Integer.class) { 78 | jgen.writeNumber((Integer) value); 79 | } else if (type == Long.class) { 80 | jgen.writeNumber((Long) value); 81 | } else if (type == Float.class) { 82 | jgen.writeNumber((Double) value); 83 | } 84 | } 85 | 86 | @Override 87 | public Class handledType() { 88 | return CyRow.class; 89 | } 90 | } -------------------------------------------------------------------------------- /src/main/java/org/cytoscape/rest/internal/serializer/TableModule.java: -------------------------------------------------------------------------------- 1 | package org.cytoscape.rest.internal.serializer; 2 | 3 | import com.fasterxml.jackson.core.Version; 4 | import com.fasterxml.jackson.databind.module.SimpleModule; 5 | 6 | public class TableModule extends SimpleModule { 7 | 8 | private static final long serialVersionUID = -4690460168404145341L; 9 | 10 | static final String FORMAT_VERSION_TAG = "format_version"; 11 | static final String FORMAT_VERSION = "1.0"; 12 | 13 | public TableModule() { 14 | super("TableModule", new Version(1, 0, 0, null, null, null)); 15 | addSerializer(new TableSerializer()); 16 | addSerializer(new RowSerializer()); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/org/cytoscape/rest/internal/serializer/TableSerializer.java: -------------------------------------------------------------------------------- 1 | package org.cytoscape.rest.internal.serializer; 2 | 3 | import java.io.IOException; 4 | import java.util.List; 5 | 6 | import org.cytoscape.model.CyIdentifiable; 7 | import org.cytoscape.model.CyRow; 8 | import org.cytoscape.model.CyTable; 9 | import org.cytoscape.rest.internal.resource.JsonTags; 10 | 11 | import com.fasterxml.jackson.core.JsonGenerator; 12 | import com.fasterxml.jackson.core.JsonProcessingException; 13 | import com.fasterxml.jackson.databind.JsonSerializer; 14 | import com.fasterxml.jackson.databind.SerializerProvider; 15 | 16 | public class TableSerializer extends JsonSerializer { 17 | 18 | @Override 19 | public Class handledType() { 20 | return CyTable.class; 21 | } 22 | 23 | @Override 24 | public void serialize(CyTable table, JsonGenerator generator, SerializerProvider provider) throws IOException, 25 | JsonProcessingException { 26 | generator.useDefaultPrettyPrinter(); 27 | 28 | generator.writeStartObject(); 29 | 30 | generator.writeNumberField(CyIdentifiable.SUID, table.getSUID()); 31 | generator.writeStringField(JsonTags.TITLE, table.getTitle()); 32 | generator.writeBooleanField(JsonTags.PUBLIC, table.isPublic()); 33 | generator.writeStringField(JsonTags.MUTABLE, table.getMutability().name()); 34 | generator.writeStringField(JsonTags.PRIMARY_KEY, table.getPrimaryKey().getName()); 35 | 36 | final List rows = table.getAllRows(); 37 | generator.writeObjectField(JsonTags.ROWS, rows); 38 | 39 | generator.writeEndObject(); 40 | } 41 | } -------------------------------------------------------------------------------- /src/main/java/org/cytoscape/rest/internal/serializer/VisualMappingsSerializer.java: -------------------------------------------------------------------------------- 1 | package org.cytoscape.rest.internal.serializer; 2 | 3 | import java.io.IOException; 4 | import java.util.Collection; 5 | 6 | import org.cytoscape.view.vizmap.VisualMappingFunction; 7 | 8 | import com.fasterxml.jackson.core.JsonGenerator; 9 | import com.fasterxml.jackson.core.JsonProcessingException; 10 | import com.fasterxml.jackson.databind.JsonSerializer; 11 | import com.fasterxml.jackson.databind.SerializerProvider; 12 | 13 | public class VisualMappingsSerializer extends JsonSerializer>> { 14 | 15 | @Override 16 | public void serialize(Collection> mappings, JsonGenerator jgen, SerializerProvider provider) 17 | throws IOException, JsonProcessingException { 18 | 19 | jgen.writeStartArray(); 20 | for(final VisualMappingFunction mapping:mappings) { 21 | jgen.writeObject(mapping); 22 | } 23 | jgen.writeEndArray(); 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/org/cytoscape/rest/internal/serializer/VisualStyleModule.java: -------------------------------------------------------------------------------- 1 | package org.cytoscape.rest.internal.serializer; 2 | 3 | import com.fasterxml.jackson.core.Version; 4 | import com.fasterxml.jackson.databind.module.SimpleModule; 5 | 6 | public class VisualStyleModule extends SimpleModule { 7 | 8 | private static final long serialVersionUID = -4690460168404145341L; 9 | 10 | static final String FORMAT_VERSION_TAG = "format_version"; 11 | static final String FORMAT_VERSION = "1.0"; 12 | 13 | public VisualStyleModule() { 14 | super("VisualStyleSerializer", new Version(1, 0, 0, null, null, null)); 15 | addSerializer(new DiscreteMappingSerializer()); 16 | addSerializer(new ContinuousMappingSerializer()); 17 | addSerializer(new PassthroughMappingSerializer()); 18 | } 19 | } -------------------------------------------------------------------------------- /src/main/java/org/cytoscape/rest/internal/serializer/package-info.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | * Classes to serialize Cytoscape data objects into JSON. 4 | * 5 | */ 6 | package org.cytoscape.rest.internal.serializer; -------------------------------------------------------------------------------- /src/main/java/org/cytoscape/rest/internal/task/CyBinder.java: -------------------------------------------------------------------------------- 1 | package org.cytoscape.rest.internal.task; 2 | 3 | import java.util.Properties; 4 | 5 | import org.cytoscape.application.CyApplicationManager; 6 | import org.cytoscape.application.swing.CySwingApplication; 7 | import org.cytoscape.command.AvailableCommands; 8 | import org.cytoscape.command.CommandExecutorTaskFactory; 9 | import org.cytoscape.group.CyGroupFactory; 10 | import org.cytoscape.group.CyGroupManager; 11 | import org.cytoscape.io.read.InputStreamTaskFactory; 12 | import org.cytoscape.io.write.CyNetworkViewWriterFactory; 13 | import org.cytoscape.model.CyNetworkFactory; 14 | import org.cytoscape.model.CyNetworkManager; 15 | import org.cytoscape.model.CyTableFactory; 16 | import org.cytoscape.model.CyTableManager; 17 | import org.cytoscape.model.subnetwork.CyRootNetworkManager; 18 | import org.cytoscape.property.CyProperty; 19 | import org.cytoscape.rest.internal.CyActivator.LevelOfDetails; 20 | import org.cytoscape.rest.internal.CyActivator.WriterListener; 21 | import org.cytoscape.rest.internal.EdgeBundler; 22 | import org.cytoscape.rest.internal.GraphicsWriterManager; 23 | import org.cytoscape.rest.internal.MappingFactoryManager; 24 | import org.cytoscape.rest.internal.TaskFactoryManager; 25 | import org.cytoscape.rest.internal.reader.EdgeListReaderFactory; 26 | import org.cytoscape.session.CySessionManager; 27 | import org.cytoscape.task.NetworkTaskFactory; 28 | import org.cytoscape.task.create.NewNetworkSelectedNodesAndEdgesTaskFactory; 29 | import org.cytoscape.task.create.NewSessionTaskFactory; 30 | import org.cytoscape.task.read.LoadNetworkURLTaskFactory; 31 | import org.cytoscape.task.read.OpenSessionTaskFactory; 32 | import org.cytoscape.task.select.SelectFirstNeighborsTaskFactory; 33 | import org.cytoscape.task.write.ExportNetworkViewTaskFactory; 34 | import org.cytoscape.task.write.SaveSessionAsTaskFactory; 35 | import org.cytoscape.view.layout.CyLayoutAlgorithmManager; 36 | import org.cytoscape.view.model.CyNetworkViewFactory; 37 | import org.cytoscape.view.model.CyNetworkViewManager; 38 | import org.cytoscape.view.presentation.RenderingEngineManager; 39 | import org.cytoscape.view.vizmap.VisualMappingManager; 40 | import org.cytoscape.view.vizmap.VisualStyleFactory; 41 | import org.cytoscape.work.SynchronousTaskManager; 42 | import org.cytoscape.work.TaskMonitor; 43 | import org.glassfish.hk2.utilities.binding.AbstractBinder; 44 | 45 | public class CyBinder extends AbstractBinder { 46 | 47 | private final TaskMonitor headlessMonitor; 48 | 49 | private final CyNetworkManager networkManager; 50 | private final CyNetworkViewManager networkViewManager; 51 | private final CySessionManager sessionManager; 52 | private final CyNetworkFactory networkFactory; 53 | private final CyNetworkViewFactory networkViewFactory; 54 | private final TaskFactoryManager tfManager; 55 | private final CyApplicationManager applicationManager; 56 | private final VisualMappingManager vmm; 57 | private final CyLayoutAlgorithmManager layoutManager; 58 | private final CyTableManager tableMamanger; 59 | private final CyTableFactory tableFactory; 60 | 61 | private final WriterListener vizmapWriterFactoryListener; 62 | private final VisualStyleFactory vsFactory; 63 | 64 | private final MappingFactoryManager mappingFactoryManager; 65 | private final CyGroupFactory groupFactory; 66 | private final CyGroupManager groupManager; 67 | private final CyRootNetworkManager cyRootNetworkManager; 68 | 69 | private final LoadNetworkURLTaskFactory loadNetworkURLTaskFactory; 70 | 71 | private final CyProperty props; 72 | 73 | // TFs 74 | private final NewNetworkSelectedNodesAndEdgesTaskFactory newNetworkSelectedNodesAndEdgesTaskFactory; 75 | private final EdgeListReaderFactory edgelistReaderFactory; 76 | private final CyNetworkViewWriterFactory cytoscapeJsWriterFactory; 77 | private final InputStreamTaskFactory cytoscapeJsReaderFactory; 78 | private final NetworkTaskFactory fitContent; 79 | private final LevelOfDetails toggleLod; 80 | private final EdgeBundler edgeBundler; 81 | private final RenderingEngineManager renderingEngineManager; 82 | private final SaveSessionAsTaskFactory saveSessionAsTaskFactory; 83 | private final OpenSessionTaskFactory openSessionTaskFactory; 84 | private final NewSessionTaskFactory newSessionTaskFactory; 85 | private final CySwingApplication desktop; 86 | private final SelectFirstNeighborsTaskFactory selectFirstNeighborsTaskFactory; 87 | private final ExportNetworkViewTaskFactory exportNetworkViewTaskFactory; 88 | 89 | private final GraphicsWriterManager graphicsWriterManager; 90 | 91 | // For Command API 92 | private final AvailableCommands available; 93 | private final CommandExecutorTaskFactory ceTaskFactory; 94 | private final SynchronousTaskManager synchronousTaskManager; 95 | 96 | 97 | public CyBinder(final CyNetworkManager networkManager, final CyNetworkViewManager networkViewManager, 98 | final CyNetworkFactory networkFactory, final TaskFactoryManager tfManager, 99 | final CyApplicationManager applicationManager, final VisualMappingManager vmm, 100 | final CyNetworkViewWriterFactory cytoscapeJsWriterFactory, 101 | final InputStreamTaskFactory cytoscapeJsReaderFactory, final CyLayoutAlgorithmManager layoutManager, 102 | final WriterListener vizmapWriterFactoryListener, final TaskMonitor headlessMonitor, 103 | final CyTableManager tableManager, final VisualStyleFactory vsFactory, 104 | final MappingFactoryManager mappingFactoryManager, final CyGroupFactory groupFactory, 105 | final CyGroupManager groupManager, final CyRootNetworkManager cyRootNetworkManager, 106 | final LoadNetworkURLTaskFactory loadNetworkURLTaskFactory, final CyProperty props, 107 | final NewNetworkSelectedNodesAndEdgesTaskFactory newNetworkSelectedNodesAndEdgesTaskFactory, 108 | final EdgeListReaderFactory edgelistReaderFactory, final CyNetworkViewFactory networkViewFactory, 109 | final CyTableFactory tableFactory, final NetworkTaskFactory fitContent, final EdgeBundler edgeBundler, 110 | final RenderingEngineManager renderingEngineManager, final CySessionManager sessionManager, 111 | final SaveSessionAsTaskFactory saveSessionAsTaskFactory, final OpenSessionTaskFactory openSessionTaskFactory, 112 | final NewSessionTaskFactory newSessionTaskFactory, final CySwingApplication desktop, 113 | final LevelOfDetails toggleLod, final SelectFirstNeighborsTaskFactory selectFirstNeighborsTaskFactory, 114 | final GraphicsWriterManager graphicsWriterManager, final ExportNetworkViewTaskFactory exportNetworkViewTaskFactory, 115 | final AvailableCommands available, final CommandExecutorTaskFactory ceTaskFactory, 116 | final SynchronousTaskManager synchronousTaskManager) { 117 | this.networkManager = networkManager; 118 | this.networkViewManager = networkViewManager; 119 | this.networkFactory = networkFactory; 120 | this.tfManager = tfManager; 121 | this.applicationManager = applicationManager; 122 | this.vmm = vmm; 123 | this.cytoscapeJsReaderFactory = cytoscapeJsReaderFactory; 124 | this.cytoscapeJsWriterFactory = cytoscapeJsWriterFactory; 125 | this.layoutManager = layoutManager; 126 | this.vizmapWriterFactoryListener = vizmapWriterFactoryListener; 127 | this.headlessMonitor = headlessMonitor; 128 | this.tableMamanger = tableManager; 129 | this.vsFactory = vsFactory; 130 | this.mappingFactoryManager = mappingFactoryManager; 131 | this.groupFactory = groupFactory; 132 | this.groupManager = groupManager; 133 | this.cyRootNetworkManager = cyRootNetworkManager; 134 | this.loadNetworkURLTaskFactory = loadNetworkURLTaskFactory; 135 | this.props = props; 136 | this.newNetworkSelectedNodesAndEdgesTaskFactory = newNetworkSelectedNodesAndEdgesTaskFactory; 137 | this.edgelistReaderFactory = edgelistReaderFactory; 138 | this.networkViewFactory = networkViewFactory; 139 | this.tableFactory = tableFactory; 140 | this.fitContent = fitContent; 141 | this.edgeBundler = edgeBundler; 142 | this.renderingEngineManager = renderingEngineManager; 143 | this.sessionManager = sessionManager; 144 | this.saveSessionAsTaskFactory = saveSessionAsTaskFactory; 145 | this.openSessionTaskFactory = openSessionTaskFactory; 146 | this.newSessionTaskFactory = newSessionTaskFactory; 147 | this.desktop = desktop; 148 | this.toggleLod = toggleLod; 149 | this.selectFirstNeighborsTaskFactory = selectFirstNeighborsTaskFactory; 150 | this.graphicsWriterManager = graphicsWriterManager; 151 | this.exportNetworkViewTaskFactory = exportNetworkViewTaskFactory; 152 | this.available = available; 153 | this.ceTaskFactory = ceTaskFactory; 154 | this.synchronousTaskManager = synchronousTaskManager; 155 | } 156 | 157 | 158 | @Override 159 | protected void configure() { 160 | bind(networkManager).to(CyNetworkManager.class); 161 | bind(networkViewManager).to(CyNetworkViewManager.class); 162 | bind(networkFactory).to(CyNetworkFactory.class); 163 | bind(tfManager).to(TaskFactoryManager.class); 164 | bind(vmm).to(VisualMappingManager.class); 165 | bind(applicationManager).to(CyApplicationManager.class); 166 | bind(cytoscapeJsReaderFactory).to(InputStreamTaskFactory.class); 167 | bind(cytoscapeJsWriterFactory).to(CyNetworkViewWriterFactory.class); 168 | bind(layoutManager).to(CyLayoutAlgorithmManager.class); 169 | bind(vizmapWriterFactoryListener).to(WriterListener.class); 170 | bind(headlessMonitor).to(TaskMonitor.class); 171 | bind(tableMamanger).to(CyTableManager.class); 172 | bind(vsFactory).to(VisualStyleFactory.class); 173 | bind(mappingFactoryManager).to(MappingFactoryManager.class); 174 | bind(groupFactory).to(CyGroupFactory.class); 175 | bind(groupManager).to(CyGroupManager.class); 176 | bind(cyRootNetworkManager).to(CyRootNetworkManager.class); 177 | bind(loadNetworkURLTaskFactory).to(LoadNetworkURLTaskFactory.class); 178 | bind(props).to(CyProperty.class); 179 | bind(newNetworkSelectedNodesAndEdgesTaskFactory).to(NewNetworkSelectedNodesAndEdgesTaskFactory.class); 180 | bind(edgelistReaderFactory).to(EdgeListReaderFactory.class); 181 | bind(networkViewFactory).to(CyNetworkViewFactory.class); 182 | bind(tableFactory).to(CyTableFactory.class); 183 | bind(fitContent).to(NetworkTaskFactory.class); 184 | bind(edgeBundler).to(EdgeBundler.class); 185 | bind(renderingEngineManager).to(RenderingEngineManager.class); 186 | bind(sessionManager).to(CySessionManager.class); 187 | bind(saveSessionAsTaskFactory).to(SaveSessionAsTaskFactory.class); 188 | bind(openSessionTaskFactory).to(OpenSessionTaskFactory.class); 189 | bind(newSessionTaskFactory).to(NewSessionTaskFactory.class); 190 | bind(desktop).to(CySwingApplication.class); 191 | bind(toggleLod).to(LevelOfDetails.class); 192 | bind(selectFirstNeighborsTaskFactory).to(SelectFirstNeighborsTaskFactory.class); 193 | bind(graphicsWriterManager).to(GraphicsWriterManager.class); 194 | bind(exportNetworkViewTaskFactory).to(ExportNetworkViewTaskFactory.class); 195 | 196 | // For Command API 197 | bind(available).to(AvailableCommands.class); 198 | bind(ceTaskFactory).to(CommandExecutorTaskFactory.class); 199 | bind(synchronousTaskManager).to(SynchronousTaskManager.class); 200 | } 201 | } -------------------------------------------------------------------------------- /src/main/java/org/cytoscape/rest/internal/task/GrizzlyServerManager.java: -------------------------------------------------------------------------------- 1 | package org.cytoscape.rest.internal.task; 2 | 3 | import java.net.URI; 4 | import java.util.Properties; 5 | 6 | import javax.ws.rs.core.UriBuilder; 7 | 8 | import org.cytoscape.property.CyProperty; 9 | import org.cytoscape.rest.internal.commands.resources.CommandResource; 10 | import org.cytoscape.rest.internal.resource.AlgorithmicResource; 11 | import org.cytoscape.rest.internal.resource.GlobalTableResource; 12 | import org.cytoscape.rest.internal.resource.GroupResource; 13 | import org.cytoscape.rest.internal.resource.MiscResource; 14 | import org.cytoscape.rest.internal.resource.NetworkFullResource; 15 | import org.cytoscape.rest.internal.resource.NetworkResource; 16 | import org.cytoscape.rest.internal.resource.NetworkNameResource; 17 | import org.cytoscape.rest.internal.resource.NetworkViewResource; 18 | import org.cytoscape.rest.internal.resource.RootResource; 19 | import org.cytoscape.rest.internal.resource.SessionResource; 20 | import org.cytoscape.rest.internal.resource.StyleResource; 21 | import org.cytoscape.rest.internal.resource.TableResource; 22 | import org.cytoscape.rest.internal.resource.UIResource; 23 | import org.glassfish.grizzly.http.server.HttpServer; 24 | import org.glassfish.hk2.utilities.Binder; 25 | import org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpServerFactory; 26 | import org.glassfish.jersey.jackson.JacksonFeature; 27 | import org.glassfish.jersey.server.ResourceConfig; 28 | import org.slf4j.Logger; 29 | import org.slf4j.LoggerFactory; 30 | 31 | /** 32 | * Task to start Grizzly server. 33 | * 34 | */ 35 | public final class GrizzlyServerManager { 36 | 37 | private final static Logger logger = LoggerFactory.getLogger(GrizzlyServerManager.class); 38 | 39 | public static final String PORT_NUMBER_PROP = "rest.port"; 40 | public static final Integer DEF_PORT_NUMBER = 1234; 41 | 42 | private String baseURL = "http://0.0.0.0"; 43 | private Integer portNumber = DEF_PORT_NUMBER; 44 | 45 | private final Binder binder; 46 | 47 | private HttpServer server = null; 48 | 49 | public GrizzlyServerManager(final Binder binder, CyProperty props) { 50 | this.binder = binder; 51 | 52 | // Get property from property 53 | Object portNumberProp = props.getProperties().get(PORT_NUMBER_PROP); 54 | if(portNumberProp != null) { 55 | try { 56 | portNumber = Integer.parseInt(portNumberProp.toString()); 57 | } catch(Exception ex) { 58 | portNumber = DEF_PORT_NUMBER; 59 | } 60 | } 61 | } 62 | 63 | 64 | public void startServer() throws Exception { 65 | if (server == null) { 66 | final URI baseURI = UriBuilder.fromUri(baseURL).port(portNumber).build(); 67 | final ResourceConfig rc = new ResourceConfig( 68 | RootResource.class, 69 | NetworkResource.class, 70 | NetworkFullResource.class, 71 | NetworkViewResource.class, 72 | TableResource.class, 73 | MiscResource.class, 74 | AlgorithmicResource.class, 75 | StyleResource.class, 76 | GroupResource.class, 77 | GlobalTableResource.class, 78 | SessionResource.class, 79 | NetworkNameResource.class, 80 | UIResource.class, 81 | // For Commands 82 | CommandResource.class); 83 | rc.registerInstances(binder).packages("org.glassfish.jersey.examples.jackson") 84 | .register(JacksonFeature.class); 85 | 86 | this.server = GrizzlyHttpServerFactory.createHttpServer(baseURI, rc); 87 | logger.info("========== Cytoscape RESTful API service started. Listening at port: " + portNumber + " =============="); 88 | } 89 | } 90 | 91 | public void stopServer() { 92 | if(this.server != null) { 93 | this.server.shutdown(); 94 | } 95 | } 96 | } -------------------------------------------------------------------------------- /src/main/java/org/cytoscape/rest/internal/task/HeadlessTaskMonitor.java: -------------------------------------------------------------------------------- 1 | package org.cytoscape.rest.internal.task; 2 | 3 | import org.cytoscape.work.Task; 4 | import org.cytoscape.work.TaskMonitor; 5 | import org.slf4j.Logger; 6 | import org.slf4j.LoggerFactory; 7 | 8 | /** 9 | * Task monitor for non-interactive task execution. 10 | * 11 | * TODO: print out more meaningful message. 12 | */ 13 | public class HeadlessTaskMonitor implements TaskMonitor { 14 | 15 | private static final Logger logger = LoggerFactory.getLogger(HeadlessTaskMonitor.class); 16 | 17 | private String taskName = ""; 18 | 19 | public void setTask(final Task task) { 20 | this.taskName = "Task (" + task.toString() + ")"; 21 | } 22 | 23 | 24 | @Override 25 | public void setTitle(final String title) { 26 | logger.info(taskName + " title: " + title); 27 | } 28 | 29 | 30 | @Override 31 | public void setStatusMessage(final String statusMessage) { 32 | logger.info(taskName + " status: " + statusMessage); 33 | } 34 | 35 | 36 | @Override 37 | public void setProgress(final double progress) { 38 | } 39 | 40 | 41 | @Override 42 | public void showMessage(Level level, String message) { 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/test/java/org/cytoscape/rest/JSONTranslatorTest.java: -------------------------------------------------------------------------------- 1 | package org.cytoscape.rest; 2 | 3 | import static org.junit.Assert.assertNotNull; 4 | 5 | import javax.script.Bindings; 6 | import javax.script.ScriptEngine; 7 | import javax.script.ScriptEngineManager; 8 | 9 | import org.junit.After; 10 | import org.junit.Before; 11 | 12 | public abstract class JSONTranslatorTest { 13 | 14 | protected ScriptEngine jsEngine; 15 | protected Bindings bindings; 16 | 17 | @Before 18 | public void setUp() throws Exception { 19 | final ScriptEngineManager manager = new ScriptEngineManager(); 20 | jsEngine = manager.getEngineByExtension("js"); 21 | 22 | assertNotNull(jsEngine); 23 | 24 | bindings = jsEngine.createBindings(); 25 | } 26 | 27 | @After 28 | public void tearDown() throws Exception { 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /src/test/java/org/cytoscape/rest/NetworkMapperTest.java: -------------------------------------------------------------------------------- 1 | package org.cytoscape.rest; 2 | 3 | import static org.junit.Assert.assertNotNull; 4 | 5 | import java.io.BufferedReader; 6 | import java.io.FileReader; 7 | import java.io.IOException; 8 | 9 | import org.junit.After; 10 | import org.junit.Before; 11 | import org.junit.Test; 12 | 13 | public class NetworkMapperTest { 14 | 15 | private String jsonAsString = ""; 16 | 17 | // private NetworkTestSupport support = new NetworkTestSupport(); 18 | 19 | @Before 20 | public void setUp() throws Exception { 21 | readSamples(); 22 | } 23 | 24 | private final void readSamples() throws IOException { 25 | FileReader in = new FileReader("./src/test/resources/json/galFiltered.json"); 26 | BufferedReader br = new BufferedReader(in); 27 | String line; 28 | StringBuilder builder = new StringBuilder(); 29 | while ((line = br.readLine()) != null) 30 | builder.append(line); 31 | 32 | br.close(); 33 | in.close(); 34 | 35 | jsonAsString = builder.toString(); 36 | } 37 | 38 | @After 39 | public void tearDown() throws Exception { 40 | } 41 | 42 | @Test 43 | public void testTranslate() throws Exception { 44 | 45 | // Make sure sample data is available. 46 | assertNotNull(jsonAsString); 47 | 48 | // final JSON2CyNetworkTranslator translator = new 49 | // JSON2CyNetworkTranslator(support.getNetworkFactory()); 50 | // 51 | // CyNetwork network = translator.translate(jsonAsString); 52 | // 53 | // assertNotNull(network); 54 | // assertEquals(331, network.getNodeCount()); 55 | // assertEquals(362, network.getEdgeCount()); 56 | // 57 | // Collection rows = 58 | // network.getDefaultNodeTable().getMatchingRows(CyNetwork.NAME, 59 | // "YGL134W"); 60 | // assertNotNull(rows); 61 | // assertEquals(1, rows.size()); 62 | // final CyRow row1 = rows.iterator().next(); 63 | // final Long suid = row1.get(CyIdentifiable.SUID, Long.class); 64 | // CyNode node = network.getNode(suid); 65 | // assertNotNull(node); 66 | // assertEquals("YGL134W", network.getRow(node).get(CyNetwork.NAME, 67 | // String.class)); 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /src/test/java/org/cytoscape/rest/TableMapperTest.java: -------------------------------------------------------------------------------- 1 | package org.cytoscape.rest; 2 | 3 | import org.junit.After; 4 | import org.junit.Before; 5 | import org.junit.Test; 6 | 7 | public class TableMapperTest { 8 | 9 | // private final NetworkTestSupport testSupport = new NetworkTestSupport(); 10 | 11 | 12 | @Before 13 | public void setUp() throws Exception { 14 | } 15 | 16 | @After 17 | public void tearDown() throws Exception { 18 | } 19 | 20 | @Test 21 | public void testSanity() { 22 | 23 | } 24 | 25 | @Test 26 | public void testTranslation() { 27 | // final CyNetwork network = testSupport.getNetwork(); 28 | // final CyNode node1 = network.addNode(); 29 | // final CyNode node2 = network.addNode(); 30 | // final CyNode node3 = network.addNode(); 31 | // final CyEdge edge = network.addEdge(node1, node2, true); 32 | 33 | // final String result = 34 | // translator.translate(network.getDefaultNetworkTable()); 35 | // assertEquals("{\"SUID\":"+network.getSUID()+"}", result); 36 | } 37 | 38 | } -------------------------------------------------------------------------------- /src/test/java/org/cytoscape/rest/TableModuleTest.java: -------------------------------------------------------------------------------- 1 | package org.cytoscape.rest; 2 | 3 | import static org.junit.Assert.assertNotNull; 4 | import static org.junit.Assert.assertTrue; 5 | 6 | import java.io.FileReader; 7 | import java.io.Reader; 8 | import java.util.ArrayList; 9 | import java.util.Collection; 10 | 11 | import javax.script.Bindings; 12 | import javax.script.ScriptEngine; 13 | import javax.script.ScriptEngineManager; 14 | 15 | import org.cytoscape.model.CyNetwork; 16 | import org.cytoscape.model.CyTable; 17 | import org.cytoscape.model.NetworkTestSupport; 18 | import org.cytoscape.rest.internal.serializer.TableModule; 19 | import org.junit.After; 20 | import org.junit.Before; 21 | import org.junit.Test; 22 | 23 | import com.fasterxml.jackson.databind.ObjectMapper; 24 | 25 | public class TableModuleTest { 26 | 27 | private ObjectMapper tableObjectMapper; 28 | private final NetworkTestSupport testSupport = new NetworkTestSupport(); 29 | 30 | protected ScriptEngine jsEngine; 31 | protected Bindings bindings; 32 | 33 | @Before 34 | public void setUp() throws Exception { 35 | final ScriptEngineManager manager = new ScriptEngineManager(); 36 | jsEngine = manager.getEngineByExtension("js"); 37 | 38 | assertNotNull(jsEngine); 39 | 40 | bindings = jsEngine.createBindings(); 41 | } 42 | 43 | @After 44 | public void tearDown() throws Exception { 45 | } 46 | 47 | @Test 48 | public void testTableSerializer() throws Exception { 49 | this.tableObjectMapper = new ObjectMapper(); 50 | this.tableObjectMapper.registerModule(new TableModule()); 51 | 52 | final CyNetwork network = buildNetwork(); 53 | final Collection tables = new ArrayList(); 54 | tables.add(network.getDefaultNetworkTable()); 55 | 56 | final String serializedTable = tableObjectMapper.writeValueAsString(tables); 57 | assertNotNull(serializedTable); 58 | 59 | System.out.println(serializedTable); 60 | 61 | assertTrue(serializedTable.contains("\"description\"")); 62 | 63 | // parse JSON with JS Engine 64 | parseJsonInJavaScript(serializedTable); 65 | 66 | } 67 | 68 | private final CyNetwork buildNetwork() { 69 | 70 | final CyNetwork network = testSupport.getNetwork(); 71 | network.getRow(network).set(CyNetwork.NAME, "network1"); 72 | network.getDefaultNetworkTable().createColumn("description", String.class, false); 73 | network.getRow(network).set("description", "this is a test"); 74 | 75 | // final CyNode node1 = network.addNode(); 76 | // final CyNode node2 = network.addNode(); 77 | // final CyNode node3 = network.addNode(); 78 | // final CyEdge edge = network.addEdge(node1, node2, true); 79 | 80 | return network; 81 | } 82 | 83 | 84 | private final void parseJsonInJavaScript(final String result) throws Exception { 85 | bindings.put("result", result); 86 | 87 | // This is the actual test cases written in JavaScript. 88 | final Reader scriptReader = new FileReader("./src/test/resources/table_test.js"); 89 | 90 | final Object jsResult = jsEngine.eval(scriptReader, bindings); 91 | scriptReader.close(); 92 | 93 | assertNotNull(jsResult); 94 | assertTrue(jsResult instanceof Boolean); 95 | assertTrue((Boolean)jsResult); 96 | } 97 | } -------------------------------------------------------------------------------- /src/test/java/org/cytoscape/rest/inetrnal/reader/EdgeListReaderTest.java: -------------------------------------------------------------------------------- 1 | package org.cytoscape.rest.inetrnal.reader; 2 | 3 | import static org.junit.Assert.assertEquals; 4 | import static org.junit.Assert.assertNotNull; 5 | import static org.mockito.Mockito.mock; 6 | import static org.mockito.Mockito.when; 7 | 8 | import java.io.File; 9 | import java.io.FileInputStream; 10 | 11 | import org.cytoscape.application.CyApplicationManager; 12 | import org.cytoscape.ding.NetworkViewTestSupport; 13 | import org.cytoscape.model.CyNetwork; 14 | import org.cytoscape.model.CyNetworkFactory; 15 | import org.cytoscape.model.CyNetworkManager; 16 | import org.cytoscape.model.NetworkTestSupport; 17 | import org.cytoscape.model.subnetwork.CyRootNetworkManager; 18 | import org.cytoscape.rest.internal.reader.EdgeListReader; 19 | import org.cytoscape.view.layout.CyLayoutAlgorithm; 20 | import org.cytoscape.view.layout.CyLayoutAlgorithmManager; 21 | import org.cytoscape.view.model.CyNetworkView; 22 | import org.cytoscape.view.model.CyNetworkViewFactory; 23 | import org.cytoscape.work.AbstractTask; 24 | import org.cytoscape.work.TaskIterator; 25 | import org.cytoscape.work.TaskMonitor; 26 | import org.junit.After; 27 | import org.junit.Before; 28 | import org.junit.Test; 29 | import org.mockito.Mockito; 30 | 31 | public class EdgeListReaderTest { 32 | 33 | protected TaskMonitor taskMonitor; 34 | protected CyNetworkFactory netFactory; 35 | protected CyNetworkViewFactory viewFactory; 36 | protected CyLayoutAlgorithmManager layouts; 37 | protected CyNetworkManager networkManager; 38 | protected CyRootNetworkManager rootNetworkManager; 39 | protected CyApplicationManager cyApplicationManager; 40 | 41 | static final class EmptyTask extends AbstractTask { 42 | public void run(final TaskMonitor tm) { 43 | } 44 | } 45 | 46 | @SuppressWarnings("unchecked") 47 | @Before 48 | public void setUp() throws Exception { 49 | taskMonitor = mock(TaskMonitor.class); 50 | 51 | CyLayoutAlgorithm def = mock(CyLayoutAlgorithm.class); 52 | Object context = new Object(); 53 | when(def.createLayoutContext()).thenReturn(context); 54 | when(def.getDefaultLayoutContext()).thenReturn(context); 55 | when( 56 | def.createTaskIterator(Mockito.any(CyNetworkView.class), Mockito.any(Object.class), Mockito.anySet(), 57 | Mockito.any(String.class))).thenReturn(new TaskIterator(new EmptyTask())); 58 | 59 | layouts = mock(CyLayoutAlgorithmManager.class); 60 | when(layouts.getDefaultLayout()).thenReturn(def); 61 | 62 | NetworkTestSupport nts = new NetworkTestSupport(); 63 | netFactory = nts.getNetworkFactory(); 64 | networkManager = nts.getNetworkManager(); 65 | rootNetworkManager = nts.getRootNetworkFactory(); 66 | 67 | cyApplicationManager = mock(CyApplicationManager.class); 68 | NetworkViewTestSupport nvts = new NetworkViewTestSupport(); 69 | viewFactory = nvts.getNetworkViewFactory(); 70 | } 71 | 72 | @After 73 | public void tearDown() throws Exception { 74 | } 75 | 76 | @Test 77 | public void testSmallEdgeList() throws Exception { 78 | final EdgeListReader reader = readFile("small.el"); 79 | final CyNetwork[] networks = reader.getNetworks(); 80 | assertNotNull(networks); 81 | assertEquals(1, networks.length); 82 | final CyNetwork network = networks[0]; 83 | 84 | int nodeCount = network.getNodeCount(); 85 | assertEquals(331, nodeCount); 86 | int edgeCount = network.getEdgeCount(); 87 | assertEquals(362, edgeCount); 88 | 89 | } 90 | 91 | @Test 92 | public void testIgraphEdgeList() throws Exception { 93 | final EdgeListReader reader = readFile("net10k.txt"); 94 | final CyNetwork[] networks = reader.getNetworks(); 95 | assertNotNull(networks); 96 | assertEquals(1, networks.length); 97 | final CyNetwork network = networks[0]; 98 | 99 | int nodeCount = network.getNodeCount(); 100 | assertEquals(1000, nodeCount); 101 | int edgeCount = network.getEdgeCount(); 102 | assertEquals(999, edgeCount); 103 | } 104 | 105 | private EdgeListReader readFile(final String fileName) throws Exception { 106 | File f = new File("./src/test/resources/" + fileName); 107 | EdgeListReader snvp = new EdgeListReader(new FileInputStream(f), viewFactory, netFactory, this.networkManager, 108 | this.rootNetworkManager, "collection1"); 109 | new TaskIterator(snvp); 110 | snvp.run(taskMonitor); 111 | 112 | return snvp; 113 | } 114 | 115 | } 116 | -------------------------------------------------------------------------------- /src/test/java/org/cytoscape/rest/service/AlgorithmicResourceTest.java: -------------------------------------------------------------------------------- 1 | package org.cytoscape.rest.service; 2 | 3 | import static org.junit.Assert.*; 4 | 5 | import java.util.HashSet; 6 | import java.util.Set; 7 | 8 | import javax.ws.rs.core.Application; 9 | import javax.ws.rs.core.Response; 10 | 11 | import org.cytoscape.rest.internal.resource.AlgorithmicResource; 12 | import org.glassfish.jersey.server.ResourceConfig; 13 | import org.junit.Test; 14 | 15 | import com.fasterxml.jackson.databind.JsonNode; 16 | import com.fasterxml.jackson.databind.ObjectMapper; 17 | 18 | public class AlgorithmicResourceTest extends BasicResourceTest { 19 | 20 | private ObjectMapper mapper = new ObjectMapper(); 21 | 22 | @Override 23 | protected Application configure() { 24 | return new ResourceConfig(AlgorithmicResource.class); 25 | } 26 | 27 | @Test 28 | public void testGetLayouts() throws Exception { 29 | final Response result = target("/v1/apply/layouts").request().get(); 30 | assertNotNull(result); 31 | assertFalse(result.getStatus() == 500); 32 | assertEquals(200, result.getStatus()); 33 | System.out.println("res: " + result.toString()); 34 | final String body = result.readEntity(String.class); 35 | System.out.println(body); 36 | final JsonNode root = mapper.readTree(body); 37 | assertTrue(root.isArray()); 38 | assertEquals(root.size(), 1); 39 | assertEquals("grid", root.get(0).asText()); 40 | } 41 | 42 | 43 | @Test 44 | public void testGetLayout() throws Exception { 45 | final Response result = target("/v1/apply/layouts/grid").request().get(); 46 | assertNotNull(result); 47 | assertFalse(result.getStatus() == 500); 48 | assertEquals(200, result.getStatus()); 49 | 50 | System.out.println("res: " + result.toString()); 51 | 52 | final String body = result.readEntity(String.class); 53 | System.out.println(body); 54 | final JsonNode root = mapper.readTree(body); 55 | assertEquals("grid", root.get("name").asText()); 56 | assertTrue(root.get("parameters").isArray()); 57 | } 58 | 59 | 60 | @Test 61 | public void testGetLayoutParameters() throws Exception { 62 | final Response result = target("/v1/apply/layouts/grid/parameters").request().get(); 63 | assertNotNull(result); 64 | assertFalse(result.getStatus() == 500); 65 | assertEquals(200, result.getStatus()); 66 | 67 | System.out.println("res: " + result.toString()); 68 | 69 | final String body = result.readEntity(String.class); 70 | System.out.println(body); 71 | final JsonNode root = mapper.readTree(body); 72 | assertTrue(root.isArray()); 73 | } 74 | 75 | 76 | @Test 77 | public void testGetLayoutColumnType() throws Exception { 78 | final Response result = target("/v1/apply/layouts/grid/columntypes").request().get(); 79 | assertNotNull(result); 80 | assertFalse(result.getStatus() == 500); 81 | assertEquals(200, result.getStatus()); 82 | 83 | System.out.println("res: " + result.toString()); 84 | 85 | final String body = result.readEntity(String.class); 86 | System.out.println(body); 87 | final JsonNode root = mapper.readTree(body); 88 | assertTrue(root.isObject()); 89 | } 90 | 91 | 92 | @Test 93 | public void testGetStyles() throws Exception { 94 | final Response result = target("/v1/apply/styles").request().get(); 95 | assertNotNull(result); 96 | assertFalse(result.getStatus() == 500); 97 | assertEquals(200, result.getStatus()); 98 | System.out.println("res: " + result.toString()); 99 | final String body = result.readEntity(String.class); 100 | System.out.println(body); 101 | final JsonNode root = mapper.readTree(body); 102 | assertTrue(root.isArray()); 103 | assertEquals(2, root.size()); 104 | Set vsNames = new HashSet<>(); 105 | for(JsonNode n: root) { 106 | vsNames.add(n.asText()); 107 | } 108 | 109 | assertTrue(vsNames.contains("vs1")); 110 | assertTrue(vsNames.contains("mock1")); 111 | } 112 | 113 | @Test 114 | public void testApplyLayout() { 115 | Long suid = view.getModel().getSUID(); 116 | Response result = target("/v1/apply/layouts/grid/" + suid) 117 | .queryParam("column", "test").request().get(); 118 | System.out.println("res: " + result.toString()); 119 | 120 | // TODO: Add more realistic test 121 | assertTrue(result.getStatus() == 500); 122 | } 123 | 124 | 125 | @Test 126 | public void testApplyStyle() throws Exception { 127 | Long suid = view.getModel().getSUID(); 128 | Response result = target("/v1/apply/styles/vs1/" + suid).request().get(); 129 | System.out.println("res: " + result.toString()); 130 | assertFalse(result.getStatus() == 500); 131 | assertEquals(200, result.getStatus()); 132 | final String body = result.readEntity(String.class); 133 | System.out.println(body); 134 | final JsonNode root = mapper.readTree(body); 135 | assertTrue(root.isObject()); 136 | assertNotNull(root.get("message").asText()); 137 | } 138 | } -------------------------------------------------------------------------------- /src/test/java/org/cytoscape/rest/service/GlobalResourceTest.java: -------------------------------------------------------------------------------- 1 | package org.cytoscape.rest.service; 2 | 3 | import static org.junit.Assert.assertEquals; 4 | import static org.junit.Assert.assertNotNull; 5 | 6 | import javax.ws.rs.core.Application; 7 | 8 | import org.cytoscape.rest.internal.resource.GlobalTableResource; 9 | import org.glassfish.jersey.server.ResourceConfig; 10 | import org.junit.Test; 11 | 12 | import com.fasterxml.jackson.databind.JsonNode; 13 | import com.fasterxml.jackson.databind.ObjectMapper; 14 | 15 | public class GlobalResourceTest extends BasicResourceTest { 16 | 17 | 18 | private ObjectMapper mapper = new ObjectMapper(); 19 | 20 | 21 | @Override 22 | protected Application configure() { 23 | return new ResourceConfig(GlobalTableResource.class); 24 | } 25 | 26 | @Test 27 | public void testGetTableCount() throws Exception { 28 | 29 | String result = target("/v1/tables/count").request().get( 30 | String.class); 31 | assertNotNull(result); 32 | final JsonNode root = mapper.readTree(result); 33 | JsonNode count = root.get("count"); 34 | assertNotNull(count); 35 | assertEquals(0, count.asInt()); 36 | } 37 | } -------------------------------------------------------------------------------- /src/test/java/org/cytoscape/rest/service/GroupTest.java: -------------------------------------------------------------------------------- 1 | package org.cytoscape.rest.service; 2 | 3 | import static org.junit.Assert.assertEquals; 4 | import static org.junit.Assert.assertNotNull; 5 | import static org.junit.Assert.assertTrue; 6 | 7 | import javax.ws.rs.core.Application; 8 | import javax.ws.rs.core.Response; 9 | 10 | import org.cytoscape.rest.internal.resource.GroupResource; 11 | import org.glassfish.jersey.server.ResourceConfig; 12 | import org.junit.Test; 13 | 14 | import com.fasterxml.jackson.databind.JsonNode; 15 | import com.fasterxml.jackson.databind.ObjectMapper; 16 | 17 | public class GroupTest extends BasicResourceTest { 18 | 19 | private ObjectMapper mapper = new ObjectMapper(); 20 | 21 | @Override 22 | protected Application configure() { 23 | return new ResourceConfig(GroupResource.class); 24 | } 25 | 26 | private void createGroup() { 27 | 28 | } 29 | 30 | @Test 31 | public void testGetGroups() throws Exception { 32 | final Long suid = network.getSUID(); 33 | final Response result = target("/v1/networks/" + suid + "/groups").request().get(); 34 | assertNotNull(result); 35 | assertEquals(200, result.getStatus()); 36 | System.out.println("res: " + result.toString()); 37 | final String body = result.readEntity(String.class); 38 | System.out.println(body); 39 | final JsonNode root = mapper.readTree(body); 40 | assertTrue(root.isArray()); 41 | assertEquals(0, root.size()); 42 | } 43 | 44 | 45 | @Test 46 | public void testGetGroup() throws Exception { 47 | final Long suid = network.getSUID(); 48 | 49 | // This is invalid Group ID 50 | final Response result = target("/v1/networks/" + suid + "/groups/11111111").request().get(); 51 | assertNotNull(result); 52 | assertEquals(404, result.getStatus()); 53 | // TODO: Create mock 54 | } 55 | 56 | 57 | @Test 58 | public void testGetGroupCount() throws Exception { 59 | final Long suid = network.getSUID(); 60 | final Response result = target("/v1/networks/" + suid + "/groups/count").request().get(); 61 | assertNotNull(result); 62 | assertEquals(200, result.getStatus()); 63 | System.out.println("res: " + result.toString()); 64 | final String body = result.readEntity(String.class); 65 | System.out.println(body); 66 | final JsonNode root = mapper.readTree(body); 67 | assertTrue(root.isObject()); 68 | assertEquals(0, root.get("count").asInt()); 69 | } 70 | } -------------------------------------------------------------------------------- /src/test/java/org/cytoscape/rest/service/NetworkDataServiceTest.java: -------------------------------------------------------------------------------- 1 | package org.cytoscape.rest.service; 2 | 3 | import static org.junit.Assert.assertEquals; 4 | import static org.junit.Assert.assertNotNull; 5 | import static org.mockito.Mockito.mock; 6 | 7 | import org.cytoscape.application.CyApplicationManager; 8 | import org.cytoscape.ding.NetworkViewTestSupport; 9 | import org.cytoscape.io.write.CyNetworkViewWriterFactory; 10 | import org.cytoscape.model.CyEdge; 11 | import org.cytoscape.model.CyNetwork; 12 | import org.cytoscape.model.CyNetworkFactory; 13 | import org.cytoscape.model.CyNetworkManager; 14 | import org.cytoscape.model.CyNode; 15 | import org.cytoscape.rest.internal.TaskFactoryManager; 16 | import org.cytoscape.rest.internal.resource.NetworkResource; 17 | import org.cytoscape.view.model.CyNetworkViewFactory; 18 | import org.cytoscape.view.model.CyNetworkViewManager; 19 | import org.cytoscape.view.vizmap.VisualMappingManager; 20 | import org.junit.After; 21 | import org.junit.Before; 22 | import org.junit.Test; 23 | 24 | 25 | public class NetworkDataServiceTest { 26 | 27 | private final NetworkViewTestSupport testSupport = new NetworkViewTestSupport(); 28 | private CyNetwork network; 29 | 30 | private NetworkResource nds = new NetworkResource(); 31 | 32 | @Before 33 | public void setUp() throws Exception { 34 | network = buildNetwork(); 35 | nds = new NetworkResource(); 36 | assertNotNull(nds); 37 | 38 | } 39 | 40 | @After 41 | public void tearDown() throws Exception { 42 | } 43 | 44 | private final void createServer() { 45 | 46 | 47 | CyNetworkFactory networkFactory = testSupport.getNetworkFactory(); 48 | CyNetworkManager networkManager = testSupport.getNetworkManager(); 49 | CyNetworkViewFactory networkViewFactory = testSupport.getNetworkViewFactory(); 50 | CyNetworkViewManager networkViewManager = mock(CyNetworkViewManager.class); 51 | VisualMappingManager vmm = mock(VisualMappingManager.class); 52 | CyApplicationManager applicationManager = mock(CyApplicationManager.class); 53 | 54 | TaskFactoryManager tfManager = mock(TaskFactoryManager.class); 55 | CyNetworkViewWriterFactory cytoscapeJsWriterFactory; 56 | //CyBinder binder = new CyBinder(networkManager, networkViewManager, networkFactory, tfManager , applicationManager, vmm, cytoscapeJsWriterFactory, cytoscapeJsReaderFactory) 57 | } 58 | 59 | private final CyNetwork buildNetwork() { 60 | final CyNetwork network = testSupport.getNetwork(); 61 | final CyNode node1 = network.addNode(); 62 | final CyNode node2 = network.addNode(); 63 | final CyEdge edge = network.addEdge(node1, node2, true); 64 | testSupport.getNetworkManager().addNetwork(network); 65 | 66 | assertEquals(testSupport.getNetworkManager().getNetworkSet().size(), 1); 67 | return network; 68 | } 69 | 70 | 71 | @Test 72 | public void testGetNetworkCount() { 73 | } 74 | 75 | @Test 76 | public void testGetNodeCount() { 77 | } 78 | 79 | @Test 80 | public void testGetEdgeCount() { 81 | } 82 | 83 | @Test 84 | public void testGetNetworks() { 85 | } 86 | 87 | @Test 88 | public void testGetNetworkJSON() { 89 | } 90 | 91 | @Test 92 | public void testGetNodes() { 93 | } 94 | 95 | @Test 96 | public void testGetEdges() { 97 | } 98 | 99 | @Test 100 | public void testGetGraphObjectStringStringString() { 101 | } 102 | 103 | @Test 104 | public void testGetAdjEdges() { 105 | } 106 | 107 | @Test 108 | public void testGetNetworkPointer() { 109 | } 110 | 111 | @Test 112 | public void testGetNeighbours() { 113 | } 114 | 115 | @Test 116 | public void testCreateNode() { 117 | } 118 | 119 | @Test 120 | public void testUpdateNetwork() { 121 | } 122 | 123 | @Test 124 | public void testDeleteAllNetworks() { 125 | } 126 | 127 | @Test 128 | public void testDeleteNetwork() { 129 | } 130 | 131 | @Test 132 | public void testDeleteAllNodes() { 133 | } 134 | 135 | @Test 136 | public void testDeleteAllEdges() { 137 | } 138 | 139 | @Test 140 | public void testDeleteNode() { 141 | } 142 | 143 | @Test 144 | public void testDeleteEdge() { 145 | } 146 | 147 | @Test 148 | public void testCreateNetwork() { 149 | } 150 | 151 | @Test 152 | public void testRunNetworkTask() { 153 | } 154 | 155 | @Test 156 | public void testRunNetworkCollectionTask() { 157 | } 158 | 159 | @Test 160 | public void testRunStatelessTask() { 161 | } 162 | } 163 | -------------------------------------------------------------------------------- /src/test/java/org/cytoscape/rest/service/NetworkNameResourceTest.java: -------------------------------------------------------------------------------- 1 | package org.cytoscape.rest.service; 2 | 3 | import static org.junit.Assert.assertEquals; 4 | import static org.junit.Assert.assertNotNull; 5 | import static org.junit.Assert.assertTrue; 6 | 7 | import javax.ws.rs.core.Application; 8 | 9 | import org.cytoscape.model.CyNetwork; 10 | import org.cytoscape.rest.internal.resource.NetworkResource; 11 | import org.glassfish.jersey.server.ResourceConfig; 12 | import org.junit.Test; 13 | 14 | import com.fasterxml.jackson.databind.JsonNode; 15 | import com.fasterxml.jackson.databind.ObjectMapper; 16 | 17 | public class NetworkNameResourceTest extends BasicResourceTest { 18 | 19 | private ObjectMapper mapper = new ObjectMapper(); 20 | 21 | @Override 22 | protected Application configure() { 23 | return new ResourceConfig(NetworkResource.class); 24 | } 25 | 26 | @Test 27 | public void testGetNetworks() throws Exception { 28 | String result = target("/v1/networks.names").request().get(String.class); 29 | assertNotNull(result); 30 | final JsonNode root = mapper.readTree(result); 31 | assertTrue(root.isArray()); 32 | assertEquals(2, root.size()); 33 | 34 | 35 | final JsonNode firstEntry = root.get(0); 36 | assertTrue(firstEntry.isObject()); 37 | 38 | assertNotNull(firstEntry.get("name").asText()); 39 | assertNotNull(firstEntry.get("SUID").asLong()); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/test/java/org/cytoscape/rest/service/NetworkResourceDeletionTest.java: -------------------------------------------------------------------------------- 1 | package org.cytoscape.rest.service; 2 | 3 | import static org.junit.Assert.assertEquals; 4 | import static org.junit.Assert.assertNotNull; 5 | 6 | import java.util.List; 7 | 8 | import javax.ws.rs.core.Application; 9 | import javax.ws.rs.core.Response; 10 | 11 | import org.cytoscape.model.CyEdge; 12 | import org.cytoscape.model.CyNetwork; 13 | import org.cytoscape.model.CyNode; 14 | import org.cytoscape.rest.internal.resource.NetworkResource; 15 | import org.glassfish.jersey.server.ResourceConfig; 16 | import org.junit.Test; 17 | 18 | public class NetworkResourceDeletionTest extends BasicResourceTest { 19 | 20 | 21 | @Override 22 | protected Application configure() { 23 | return new ResourceConfig(NetworkResource.class); 24 | } 25 | 26 | @Test 27 | public void testGetNodes() throws Exception { 28 | final Long suid = network.getSUID(); 29 | 30 | final List nodes = network.getNodeList(); 31 | 32 | // Pick specific node: 33 | CyNode node1 = null; 34 | for(CyNode node: nodes) { 35 | if(network.getRow(node).get(CyNetwork.NAME, String.class).equals("n4")) { 36 | node1 = node; 37 | break; 38 | } 39 | } 40 | assertNotNull(node1); 41 | 42 | final Response result = target("/v1/networks/" + suid.toString() + "/nodes/" + node1.getSUID()) 43 | .request().delete(); 44 | assertEquals(200, result.getStatus()); 45 | 46 | assertEquals(3, network.getNodeList().size()); 47 | 48 | } 49 | 50 | 51 | @Test 52 | public void testDeleteEdges() throws Exception { 53 | final Long suid = network.getSUID(); 54 | final List edges = network.getEdgeList(); 55 | final CyEdge edge1 = edges.get(0); 56 | assertNotNull(edge1); 57 | 58 | final Response result = target("/v1/networks/" + suid.toString() + "/edges/" + edge1.getSUID()) 59 | .request().delete(); 60 | assertEquals(200, result.getStatus()); 61 | 62 | assertEquals(2, network.getEdgeList().size()); 63 | 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /src/test/java/org/cytoscape/rest/service/RootTest.java: -------------------------------------------------------------------------------- 1 | package org.cytoscape.rest.service; 2 | 3 | import static org.junit.Assert.*; 4 | 5 | import java.util.List; 6 | import java.util.Map; 7 | 8 | import javax.ws.rs.core.Application; 9 | 10 | import org.cytoscape.rest.internal.resource.RootResource; 11 | import org.glassfish.jersey.server.ResourceConfig; 12 | import org.glassfish.jersey.test.JerseyTest; 13 | import org.junit.Test; 14 | 15 | public class RootTest extends JerseyTest { 16 | 17 | @Override 18 | protected Application configure() { 19 | return new ResourceConfig(RootResource.class); 20 | } 21 | 22 | @Test 23 | public void test() { 24 | final Map status = target("/").request().get(Map.class); 25 | assertEquals(status.size(), 1); 26 | assertNotNull(status.get("availableApiVersions")); 27 | List vers = (List) status.get("availableApiVersions"); 28 | assertEquals(vers.size(), 1); 29 | assertEquals(vers.get(0), "v1"); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/test/java/org/cytoscape/rest/service/SessionResourceTest.java: -------------------------------------------------------------------------------- 1 | package org.cytoscape.rest.service; 2 | 3 | import static org.junit.Assert.*; 4 | 5 | import java.io.File; 6 | 7 | import javax.ws.rs.client.Entity; 8 | import javax.ws.rs.core.Application; 9 | import javax.ws.rs.core.MediaType; 10 | import javax.ws.rs.core.Response; 11 | 12 | import org.cytoscape.rest.internal.resource.SessionResource; 13 | import org.glassfish.jersey.server.ResourceConfig; 14 | import org.junit.Test; 15 | 16 | import com.fasterxml.jackson.databind.JsonNode; 17 | import com.fasterxml.jackson.databind.ObjectMapper; 18 | 19 | public class SessionResourceTest extends BasicResourceTest { 20 | 21 | private ObjectMapper mapper = new ObjectMapper(); 22 | 23 | @Override 24 | protected Application configure() { 25 | return new ResourceConfig(SessionResource.class); 26 | } 27 | 28 | @Test 29 | public void testGetSessionName() throws Exception { 30 | String result = target("/v1/session/name").request().get(String.class); 31 | assertNotNull(result); 32 | final JsonNode root = mapper.readTree(result); 33 | assertTrue(root.isObject()); 34 | assertNotNull(root.get("name")); 35 | assertEquals("testSession", root.get("name").asText()); 36 | } 37 | 38 | 39 | @Test 40 | public void testLoadSession() throws Exception { 41 | File dummySession = new File("test1.cys"); 42 | String result = target("/v1/session").queryParam("file", dummySession.getName()).request().get(String.class); 43 | assertNotNull(result); 44 | final JsonNode root = mapper.readTree(result); 45 | assertTrue(root.isObject()); 46 | assertNotNull(root.get("file")); 47 | assertEquals(dummySession.getAbsolutePath(), root.get("file").asText()); 48 | } 49 | 50 | @Test 51 | public void testDeleteSession() throws Exception { 52 | Response result = target("/v1/session").request().delete(); 53 | assertNotNull(result); 54 | assertFalse(result.getStatus() == 500); 55 | System.out.println("res: " + result.toString()); 56 | MediaType type = result.getMediaType(); 57 | System.out.println("media type: " + type.toString()); 58 | assertEquals(MediaType.APPLICATION_JSON, type.toString()); 59 | String val = result.readEntity(String.class); 60 | System.out.println("value: " + val); 61 | final JsonNode root = mapper.readTree(val); 62 | assertTrue(root.isObject()); 63 | assertNotNull(root.get("message")); 64 | assertEquals("New session created.", root.get("message").asText()); 65 | } 66 | 67 | 68 | @Test 69 | public void testSaveSession() throws Exception { 70 | final Entity entity = Entity.entity("", MediaType.APPLICATION_JSON_TYPE); 71 | File dummySession = new File("test1.cys"); 72 | System.out.println("original file: " + dummySession.getAbsolutePath()); 73 | 74 | Response result = target("/v1/session").queryParam("file", dummySession.getName()).request().post(entity); 75 | assertNotNull(result); 76 | assertFalse(result.getStatus() == 500); 77 | System.out.println("res: " + result.toString()); 78 | MediaType type = result.getMediaType(); 79 | System.out.println("media type: " + type.toString()); 80 | assertEquals(MediaType.APPLICATION_JSON, type.toString()); 81 | String val = result.readEntity(String.class); 82 | System.out.println("value: " + val); 83 | final JsonNode root = mapper.readTree(val); 84 | assertTrue(root.isObject()); 85 | assertNotNull(root.get("file")); 86 | assertEquals(dummySession.getAbsolutePath(), root.get("file").asText()); 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /src/test/java/org/cytoscape/rest/service/UiResourceTest.java: -------------------------------------------------------------------------------- 1 | package org.cytoscape.rest.service; 2 | 3 | import static org.junit.Assert.assertEquals; 4 | import static org.junit.Assert.assertFalse; 5 | import static org.junit.Assert.assertNotNull; 6 | import static org.junit.Assert.assertTrue; 7 | 8 | import javax.ws.rs.InternalServerErrorException; 9 | import javax.ws.rs.client.Entity; 10 | import javax.ws.rs.core.Application; 11 | import javax.ws.rs.core.MediaType; 12 | import javax.ws.rs.core.Response; 13 | 14 | import org.cytoscape.rest.internal.resource.UIResource; 15 | import org.glassfish.jersey.server.ResourceConfig; 16 | import org.junit.Test; 17 | 18 | import com.fasterxml.jackson.databind.JsonNode; 19 | import com.fasterxml.jackson.databind.ObjectMapper; 20 | 21 | public class UiResourceTest extends BasicResourceTest { 22 | 23 | private ObjectMapper mapper = new ObjectMapper(); 24 | 25 | @Override 26 | protected Application configure() { 27 | return new ResourceConfig(UIResource.class); 28 | } 29 | 30 | @Test 31 | public void testGetUI() throws Exception { 32 | final Response result = target("/v1/ui").request().get(); 33 | assertNotNull(result); 34 | assertFalse(result.getStatus() == 500); 35 | assertEquals(200, result.getStatus()); 36 | System.out.println("res: " + result.toString()); 37 | final String body = result.readEntity(String.class); 38 | System.out.println(body); 39 | final JsonNode root = mapper.readTree(body); 40 | assertTrue(root.isObject()); 41 | assertTrue(root.get("isDesktopAvailable").asBoolean()); 42 | } 43 | 44 | 45 | @Test 46 | public void testGetPanels() throws Exception { 47 | final Response result = target("/v1/ui/panels").request().get(); 48 | assertNotNull(result); 49 | assertTrue(result.getStatus() == 500); 50 | // TODO: prepare mock 51 | } 52 | 53 | 54 | @Test 55 | public void testPanelStatus() throws Exception { 56 | Response result = target("/v1/ui/panels/WEST").request().get(); 57 | assertNotNull(result); 58 | System.out.println(result); 59 | assertTrue(result.getStatus() == 500); 60 | 61 | result = target("/v1/ui/panels/FOO").request().get(); 62 | assertNotNull(result); 63 | System.out.println(result); 64 | assertTrue(result.getStatus() == 500); 65 | // TODO: prepare mock 66 | } 67 | 68 | 69 | @Test 70 | public void testUpdateLod() throws Exception { 71 | Entity entity = Entity.entity("", MediaType.APPLICATION_JSON_TYPE); 72 | final Response result = target("/v1/ui/lod").request().put(entity); 73 | assertNotNull(result); 74 | assertTrue(result.getStatus() == 500); 75 | // TODO: prepare mock 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /src/test/resources/node_test.js: -------------------------------------------------------------------------------- 1 | function testResult() { 2 | 3 | print("Given String = " + result + "\n"); 4 | 5 | var objResult = eval("(" + result + ")"); 6 | print("Result as JS Object = " + objResult + "\n"); 7 | 8 | if(objResult == null) 9 | return false; 10 | 11 | if(objResult.DecCol != 5.67) 12 | return false; 13 | 14 | var listArray = objResult.TheList; 15 | if(listArray.length != 2) 16 | return false; 17 | 18 | if(listArray[0] != 5.2) 19 | return false; 20 | if(listArray[1] != 4.5) 21 | return false; 22 | 23 | 24 | return true; 25 | } 26 | 27 | testResult(); -------------------------------------------------------------------------------- /src/test/resources/small.el: -------------------------------------------------------------------------------- 1 | YKR026C YGL122C 2 | YGR218W YGL097W 3 | YGL097W YOR204W 4 | YLR249W YPR080W 5 | YLR249W YBR118W 6 | YLR293C YGL097W 7 | YMR146C YDR429C 8 | YDR429C YFL017C 9 | YPR080W YAL003W 10 | YBR118W YAL003W 11 | YOL123W YGL044C 12 | YPL211W YGR014W 13 | YJL030W YGL229C 14 | YJL013C YGL229C 15 | YGL122C YOL123W 16 | YGR014W YJL030W 17 | YGR014W YJL013C 18 | YGR203W YIL061C 19 | YCR084C YBR112C 20 | YCR084C YCL067C 21 | YER112W YOR167C 22 | YJR022W YNR050C 23 | YJR022W YNL050C 24 | YJR022W YEL015W 25 | YJR022W YOR167C 26 | YJR022W YLR264W 27 | YJR022W YNR053C 28 | YER116C YDL013W 29 | YNL307C YAL038W 30 | YNL216W YCR012W 31 | YNL216W YGR254W 32 | YNL216W YHR174W 33 | YNL216W YIL133C 34 | YNL216W YLR044C 35 | YNL216W YOL120C 36 | YNL216W YNL301C 37 | YNL216W YCL030C 38 | YNL216W YDR171W 39 | YNL216W YBR093C 40 | YNL216W YER074W 41 | YNL216W YIL069C 42 | YNL216W YAL038W 43 | YNL216W YOL127W 44 | YNL216W YDR050C 45 | YNL216W YOL086C 46 | YAL030W YER143W 47 | YOR327C YER143W 48 | YER062C YPL201C 49 | YDR412W YCR086W 50 | YDR412W YGL013C 51 | YDR412W YLR117C 52 | YDR412W YPR119W 53 | YDL014W YOR310C 54 | YER179W YLR044C 55 | YER179W YLR134W 56 | YER179W YIL105C 57 | YOR361C YMR309C 58 | YOR361C YDR429C 59 | YOR326W YGL106W 60 | YMR186W YBR155W 61 | YEL009C YMR108W 62 | YEL009C YOR202W 63 | YEL009C YCL030C 64 | YEL009C YBR248C 65 | YEL009C YOL058W 66 | YEL009C YMR300C 67 | YMR138W YHR141C 68 | YMR138W YLR109W 69 | YCL032W YDR032C 70 | YCL032W YLR362W 71 | YCL032W YDR103W 72 | YCR012W YJR060W 73 | YBR019C YOL051W 74 | YBR019C YGL035C 75 | YOL051W YBR020W 76 | YOL051W YLR081W 77 | YOL051W YPL248C 78 | YOL051W YBR018C 79 | YIR009W YKR099W 80 | YIR009W YIL143C 81 | YIR009W YDR184C 82 | YIR009W YNL091W 83 | YNL236W YKL012W 84 | YML032C YNL312W 85 | YLR116W YKL012W 86 | YCR086W YOR264W 87 | YDR309C YLR229C 88 | YGR058W YOR264W 89 | YJR109C YOR303W 90 | YLR256W YML054C 91 | YLR256W YJR048W 92 | YLR256W YEL039C 93 | YGL237C YJR048W 94 | YBL021C YJR048W 95 | YDR311W YKL028W 96 | YPL149W YHR171W 97 | YPL149W YBR217W 98 | YKL109W YGL237C 99 | YKL109W YBL021C 100 | YKL109W YJR048W 101 | YKL109W YGL035C 102 | YMR043W YIL015W 103 | YMR043W YJL159W 104 | YMR043W YKR097W 105 | YMR043W YGR108W 106 | YMR043W YDR461W 107 | YMR043W YNL145W 108 | YMR043W YJL157C 109 | YMR043W YFL026W 110 | YHR171W YDR412W 111 | YHR171W YNR007C 112 | YNR050C YMR138W 113 | YJL203W YOL136C 114 | YLL021W YLR362W 115 | YGL013C YJL219W 116 | YGL013C YOL156W 117 | YKL101W YBR160W 118 | YCL067C YIL015W 119 | YCL067C YMR043W 120 | YCL067C YDR461W 121 | YCL067C YFL026W 122 | YBL005W YJL219W 123 | YDR323C YOR036W 124 | YGL008C YMR043W 125 | YER040W YPR035W 126 | YER040W YGR019W 127 | YNL098C YLR310C 128 | YGL115W YGL208W 129 | YPL089C YHR030C 130 | YJL089W YER065C 131 | YJL089W YKR097W 132 | YJL089W YLR377C 133 | YMR021C YLR214W 134 | YDR335W YDR174W 135 | YLL028W YGL166W 136 | YIL143C YDR311W 137 | YDL081C YLR340W 138 | YKL012W YKL074C 139 | YEL015W YML064C 140 | YHR135C YNL116W 141 | YMR309C YNL047C 142 | YNL154C YKL204W 143 | ? YKR099W 144 | YJR066W YLR116W 145 | YDR382W YDL130W 146 | YDR382W YFL039C 147 | YFL039C YCL040W 148 | YFL039C YHR179W 149 | YPL075W YCR012W 150 | YPL075W YGR254W 151 | YPL075W YHR174W 152 | YPL075W YNL199C 153 | YPL075W YDR050C 154 | YPL075W YOL086C 155 | YNL199C YPR048W 156 | ? YGL035C 157 | YLR321C YDR412W 158 | YBR072W YGL073W 159 | YCL030C YKR099W 160 | YBL069W YGL008C 161 | YNL189W YDL236W 162 | YNL189W YPL111W 163 | YNL189W YER065C 164 | YNL189W YPR062W 165 | YDR184C YLR319C 166 | YNL311C YKL001C 167 | YOL058W YNL189W 168 | YOL016C YBR109C 169 | YJL036W YDL113C 170 | YEL041W YHR115C 171 | YNL167C YOR202W 172 | YDL063C YPL131W 173 | YGL161C YDR100W 174 | YMR183C YGR009C 175 | YMR291W YGL115W 176 | YGR048W YPL222W 177 | YAL040C YMR043W 178 | YFR034C YBR093C 179 | YFR037C YOR290C 180 | YER133W YDR412W 181 | YER133W YOR178C 182 | YER133W YOR315W 183 | YER133W YMR311C 184 | YER133W YBR050C 185 | YGL035C YLR044C 186 | YGL035C YLR377C 187 | YGL035C YIL162W 188 | YFL038C YOR036W 189 | YOR355W YNL091W 190 | YML074C YJL190C 191 | YMR058W YER145C 192 | YML123C YFR034C 193 | YPL031C YHR071W 194 | YAL038W YPL075W 195 | YML051W YBR020W 196 | YML051W YDR009W 197 | YLL019C YIL113W 198 | YML024W YNL216W 199 | YOR039W YOR303W 200 | YER111C YMR043W 201 | YDR146C YMR043W 202 | YDR146C YGL035C 203 | YKL211C YER090W 204 | YDR354W YEL009C 205 | YNL113W YPR110C 206 | YLR310C YER103W 207 | YNL047C YIL105C 208 | YBR160W YMR043W 209 | YBR160W YGR108W 210 | YIL113W YHR030C 211 | YLR117C YBR190W 212 | YFL017C YOL059W 213 | YFL017C YER102W 214 | YFL017C YOR362C 215 | YMR044W YIL061C 216 | YOL149W YOR167C 217 | YOR036W YDR100W 218 | YOR036W YGL161C 219 | YLR191W YGL153W 220 | YER110C YML007W 221 | YBR135W YER102W 222 | YNL214W YGL153W 223 | YJR060W YPR167C 224 | YOR089C YDR323C 225 | YNL117W YJL089W 226 | YLR175W YNL307C 227 | YDR167W YLR432W 228 | YGR108W YBR135W 229 | YDR244W YLR191W 230 | YDR244W YGL153W 231 | YDR244W YNL214W 232 | YDR244W YDR142C 233 | YDR244W YDL078C 234 | YPR119W YMR043W 235 | YDR142C YGL153W 236 | YDR142C YIL160C 237 | YBR020W YGL035C 238 | YDR009W YGL035C 239 | YPL248C YBR019C 240 | YPL248C ? 241 | YPL248C YJR048W 242 | YPL248C YGL035C 243 | YPL248C YML051W 244 | YPL248C YML051W 245 | YPL248C YBR020W 246 | YPL248C YLR081W 247 | YPL248C YBR018C 248 | YAR007C YML032C 249 | YAR007C YPL111W 250 | YKL161C YPL089C 251 | YNL312W YPL111W 252 | YLR075W YPR102C 253 | YLR229C YJL157C 254 | YPL240C YBR155W 255 | YPL240C YOR036W 256 | YOL156W YBL005W 257 | YML064C YHR198C 258 | YML064C YLR284C 259 | YML064C YDR174W 260 | YER052C YNL135C 261 | YPR124W YMR021C 262 | YGL166W YHR053C 263 | YGL166W YHR055C 264 | YGL134W YPL031C 265 | YGL134W YLR258W 266 | YJL194W YMR043W 267 | YLR264W YER112W 268 | YLR264W YOL149W 269 | YLR264W YBL026W 270 | YBL050W YOR036W 271 | YNL145W YCL067C 272 | YNL145W YHR084W 273 | YBR274W YMR255W 274 | YLR452C YHR005C 275 | YDR299W YJL194W 276 | YIL074C YNL311C 277 | YLR319C YLR362W 278 | YGL073W YOR178C 279 | YGL073W YHR053C 280 | YGL073W YHR055C 281 | YGL073W YER103W 282 | YOR120W YPL248C 283 | YPR041W YOR361C 284 | YPR041W YMR309C 285 | YNL135C YDR174W 286 | YBR217W YNR007C 287 | YMR255W YGL122C 288 | YLR258W YIL045W 289 | YLR258W YBR274W 290 | YDL215C YER040W 291 | YDL215C YLR432W 292 | YER079W YHR135C 293 | YER079W YNL154C 294 | YDL030W YDL013W 295 | YDL030W YMR005W 296 | YLR362W YER124C 297 | YLR362W YMR186W 298 | YLR362W YPL240C 299 | YHR084W YMR043W 300 | YHR084W YDR461W 301 | YHR084W YFL026W 302 | YGR085C YLR075W 303 | YGR085C YDR395W 304 | YKL074C YGL035C 305 | YGR088W YLR256W 306 | YER081W YIL074C 307 | YPR113W YMR043W 308 | YIL070C YML054C 309 | YIL061C YDL013W 310 | YIL061C YNL199C 311 | YIL061C YLR153C 312 | YGR046W YNL236W 313 | YNL091W YNL164C 314 | YHR030C YLL021W 315 | YHR030C YER111C 316 | YPR048W YOR355W 317 | YPR048W YDL215C 318 | YHR005C YLR362W 319 | YDR070C YFL017C 320 | YJL157C YAL040C 321 | YJL157C YOR212W 322 | YNL036W YIR009W 323 | YML114C YDR167W 324 | YMR117C YCL032W 325 | YMR117C YPR010C 326 | YHR115C YOR215C 327 | YGR009C YAL030W 328 | YGR009C YOR327C 329 | YGR009C YDR335W 330 | YGR009C YBL050W 331 | YDL088C YER110C 332 | YLR197W YDL014W 333 | YLR197W YOR310C 334 | YGL202W YGR074W 335 | YIL162W YNL167C 336 | YBR170C YGR048W 337 | YOR212W YLR362W 338 | YDR103W YLR362W 339 | YDL023C YJL159W 340 | YGR136W YGR058W 341 | YBR109C YOR326W 342 | YBR109C YFR014C 343 | YDR395W YDL075W 344 | YDR395W YIL133C 345 | YDR395W YNL069C 346 | YDR395W YER056CA 347 | YDR395W YIL052C 348 | YDR395W YOL127W 349 | YDR395W YPR102C 350 | YLR345W YLR321C 351 | YBL079W YDL088C 352 | YBR045C YIL045W 353 | YBR045C YOR178C 354 | YER054C YER133W 355 | YER054C YBR045C 356 | YPR145W YMR117C 357 | YNR053C YJL203W 358 | YNR053C YDL030W 359 | YGR074W YBR043C 360 | YDR277C YJR022W 361 | YDR277C YDL194W 362 | YBL026W YOR167C 363 | -------------------------------------------------------------------------------- /src/test/resources/table_test.js: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | */ 4 | 5 | function testResult() { 6 | print("Given table string = " + result + "\n"); 7 | 8 | var objResult = eval("(" + result + ")"); 9 | print("Result as JS Object = " + objResult + "\n"); 10 | 11 | if(objResult === null || objResult === undefined) { 12 | print("objResult undefined.\n"); 13 | return false; 14 | } 15 | 16 | if(objResult.length !== 1) { 17 | print("Array length is not 1.\n"); 18 | return false; 19 | } 20 | 21 | var table1 = objResult[0]; 22 | var rows = table1['rows']; 23 | if(rows === null || rows === undefined) { 24 | print("rows undefined.\n"); 25 | return false; 26 | } 27 | 28 | if(table1['primaryKey'] !== 'SUID') { 29 | print("Primary key test failed.\n"); 30 | return false; 31 | } 32 | 33 | 34 | return true; 35 | } 36 | 37 | testResult(); --------------------------------------------------------------------------------