Skip to content
Snippets Groups Projects
Commit 47122ec1 authored by Swen Vermeul's avatar Swen Vermeul
Browse files

Merge tag '0.1.1' into develop

first version that works with pip install only
parents 27f9a44c c719f0aa
No related branches found
No related tags found
No related merge requests found
Showing
with 1949 additions and 1238 deletions
*.pyc *.pyc
.*.swp .*.swp
*~ *~
__pycache__
ubuntu-bionic-18.04-cloudimg-console.log
.vagrant
jupyter_openbis_extension.egg-info
venv
.ipynb_checkpoints
.DS_Store
*.ipynb
## new in jupyter-openbis-extension 0.1.1
- first version that cleanly works with pip install only
- bugfixes in setup.py
- typos in .json files in jupyter-config
- CHANGELOG added
## new in jupyter-openbis-extension 0.1.0
- separation of connection, down- and upload
- upload let you specify dataset type
- dataset type specific input fields (properties)
- input control for all properties
- checks for missing properties
- downloaded datasets are new parent datasets by default
- simplified way to upload files as part of the new dataset
## new in jupyter-openbis-extension 0.0.1
- first published version
LICENSE 0 → 100644
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
...@@ -4,6 +4,28 @@ ...@@ -4,6 +4,28 @@
The jupyter-openbis-extension needs at least **Python 3.3** in order to run. The Jupyter notebook server starts this extension during startup and must therefore run under the same Python version. The kernel can be anything (Python 2.7, Julia, R, Perl...) The jupyter-openbis-extension needs at least **Python 3.3** in order to run. The Jupyter notebook server starts this extension during startup and must therefore run under the same Python version. The kernel can be anything (Python 2.7, Julia, R, Perl...)
This extension has been successfully tested with Safari 12.0.3, Chrome 72.0 and Firefox 66.0. There is a known incompatibility before Firefox 61.0b13.
## Development with Vagrant
If you want to use a predefined development environment, follow these steps:
1. Install latest version of VirtualBox (<https://www.virtualbox.org>)
2. Install latest version of Vagrant (<https://www.vagrantup.com/downloads.html>)
3. vagrant plugin install vagrant-vbguest vagrant-notify-forwarder vagrant-disksize
4. cd vagrant
5. vagrant up
After the setup is complete, you'll have
* Jupyter with openBIS extension running at <http://localhost:8888>.
* openBIS running at <http://localhost:8122>, with credentials admin/password.
* Experiment /DEFAULT/DEFAULT with a lot of datasets for testing.
## Install the extension ## Install the extension
If you haven't done yet: download the latest jupyter-openbis-extension from pip. It will automatically install the various dependencies, e.g. Pandas and NumPy. If you haven't done yet: download the latest jupyter-openbis-extension from pip. It will automatically install the various dependencies, e.g. Pandas and NumPy.
...@@ -12,6 +34,19 @@ If you haven't done yet: download the latest jupyter-openbis-extension from pip. ...@@ -12,6 +34,19 @@ If you haven't done yet: download the latest jupyter-openbis-extension from pip.
pip install --upgrade jupyter-openbis-extension pip install --upgrade jupyter-openbis-extension
``` ```
or, if you would like to develop:
```
$ git clone git@sissource.ethz.ch:sispub/jupyter-openbis-extension.git
$ cd jupyter-openbis-extension
$ virtualenv venv
$ source venv/bin/activate
(venv) $ pip install -e .
(venv) $ jupyter serverextension enable --py jupyter-openbis-extension
(venv) $ jupyter nbextension install --py jupyter-openbis-extension --user --symlink
(venv) $ jupyter nbextension enable jupyter-openbis-extension --user --py
```
**Register the Jupyter server extension** which will communicate both with openBIS and the notebook: **Register the Jupyter server extension** which will communicate both with openBIS and the notebook:
``` ```
...@@ -50,20 +85,37 @@ connections: ...@@ -50,20 +85,37 @@ connections:
username : username username : username
password : password password : password
``` ```
**Note 1**: You do not need the usernames or passwords anymore. With the current version, you are able to enter username and password directly from within a Jupyter notebook.
**Note 2**: You can place this file in any of these directories (on Mac OS X):
```
/Users/your_username/jupyter-openbis-extension/notebooks
/Users/your_username/.jupyter
/Users/your_username/.pyenv/versions/3.6.0/etc/jupyter # or wherever your jupyter installation is located
/usr/local/etc/jupyter
/etc/jupyter
```
These directories are produced by Jupyters' `nb_server_app.config_file_paths` method.
## Launching Jupyter notebook
Now you are **ready to launch!** Now you are **ready to launch jupyter notebook!**
``` ```
$ jupyter notebook $ jupyter notebook
``` ```
Observe the terminal. It should tell you that the server(s) have been successfully connected: Observe the terminal. It should tell you which server(s) have been successfully connected (and which not):
``` ```
$ jupyter notebook $ jupyter notebook
connected to TEST local openBIS instance Registered: https://localhost:8443
connected to PRODUCTION openBIS instance Cannot establish connection to: https://localhost:8443
Registered: https://openbis.example.com
Successfully connected to: https://openbis.example.com
``` ```
**Congratulations!** **Congratulations!** You can retry non-successful connections later, directly from the GUI.
## Uninstall Jupyter extension ## Uninstall Jupyter extension
...@@ -142,4 +194,4 @@ Known nbextensions: ...@@ -142,4 +194,4 @@ Known nbextensions:
notebook section notebook section
jupyter-openbis-extension/dialog enabled jupyter-openbis-extension/dialog enabled
- Validating: OK - Validating: OK
``` ```
\ No newline at end of file
{
"NotebookApp": {
"nbserver_extensions": {
"jupyter-openbis-extension.server": true
}
}
}
{
"load_extensions": {
"jupyter-openbis-extension/main": true
}
}
name = 'jupyter-openbis-extension.server' name = 'jupyter-openbis-extension.server'
__author__ = 'Swen Vermeul' __author__ = 'Swen Vermeul'
__email__ = 'swen@ethz.ch' __email__ = 'swen@ethz.ch'
__version__ = '0.0.2' __version__ = '0.1.1'
def _jupyter_server_extension_paths(): def _jupyter_server_extension_paths():
return [{ return [{
...@@ -19,7 +19,7 @@ def _jupyter_nbextension_paths(): ...@@ -19,7 +19,7 @@ def _jupyter_nbextension_paths():
# # directory in the `nbextension/` namespace # # directory in the `nbextension/` namespace
'dest': "openbis", 'dest': "openbis",
# _also_ in the `nbextension/` namespace # _also_ in the `nbextension/` namespace
'require' : "openbis/dialog" 'require' : "openbis/main"
}] }]
def load_jupyter_server_extension(nbapp): def load_jupyter_server_extension(nbapp):
......
File deleted
import os
from pybis import Openbis
from notebook.base.handlers import IPythonHandler
openbis_connections = {}
def register_connection(connection_info):
conn = OpenBISConnection(
name = connection_info.get('name'),
url = connection_info.get('url'),
verify_certificates = connection_info.get('verify_certificates', False),
username = connection_info.get('username'),
password = connection_info.get('password'),
status = 'not connected',
)
openbis_connections[conn.name] = conn
return conn
class OpenBISConnection:
"""register an openBIS connection
"""
def __init__(self, **kwargs):
for needed_key in ['name', 'url']:
if needed_key not in kwargs:
raise KeyError("{} is missing".format(needed_key))
for key in kwargs:
setattr(self, key, kwargs[key])
openbis = Openbis(
url = self.url,
verify_certificates = self.verify_certificates
)
self.openbis = openbis
self.status = "not connected"
def is_session_active(self):
return self.openbis.is_session_active()
def check_status(self):
if self.openbis.is_session_active():
self.status = "connected"
else:
self.status = "not connected"
def login(self, username=None, password=None):
if username is None:
username=self.username
if password is None:
password=self.password
self.openbis.login(
username = username,
password = password
)
# store username and password in memory
self.username = username
self.password = password
self.status = 'connected'
def get_info(self):
return {
'name' : self.name,
'url' : self.url,
'status' : self.status,
'username': self.username,
'password': self.password,
}
class OpenBISConnections(IPythonHandler):
def post(self):
"""create a new connection
:return: a new connection object
"""
data = self.get_json_body()
conn = register_connection(data)
if conn.username and conn.password:
try:
conn.login()
except Exception:
pass
self.get()
return
def get(self):
"""returns all available openBIS connections
"""
connections= []
for conn in openbis_connections.values():
conn.check_status()
connections.append(conn.get_info())
self.write({
'status' : 200,
'connections': connections,
'cwd' : os.getcwd()
})
return
class OpenBISConnectionHandler(IPythonHandler):
"""Handle the requests to /openbis/conn
"""
def put(self, connection_name):
"""reconnect to a current connection
:return: an updated connection object
"""
data = self.get_json_body()
try:
conn = openbis_connections[connection_name]
except KeyError:
self.set_status(404)
self.write({
"reason" : 'No such connection: {}'.format(data)
})
return
try:
conn.login(data.get('username'), data.get('password'))
except ConnectionError:
self.set_status(500)
self.write({
"reason": "Could not establish connection to {}".format(connection_name)
})
return
except ValueError:
self.set_status(401)
self.write({
"reason": "Incorrect username or password for {}".format(connection_name)
})
return
self.write({
'status' : 200,
'connection': conn.get_info(),
'cwd' : os.getcwd()
})
def get(self, connection_name):
"""returns information about a connection name
"""
try:
conn = openbis_connections[connection_name]
except KeyError:
self.set_status(404)
self.write({
"reason" : 'No such connection: {}'.format(connection_name)
})
return
conn.check_status()
self.write({
'status' : 200,
'connection': conn.get_info(),
'cwd' : os.getcwd()
})
return
import os
from urllib.parse import unquote
from notebook.base.handlers import IPythonHandler
from .connection import openbis_connections
class DataSetDownloadHandler(IPythonHandler):
"""Handle the requests for /openbis/dataset/connection/permId"""
def download_data(self, conn, permId, downloadPath=None):
if not conn.is_session_active():
try:
conn.login()
except Exception as exc:
self.set_status(500)
self.write({
"reason" : 'connection to {} could not be established: {}'.format(conn.name, exc)
})
return
try:
dataset = conn.openbis.get_dataset(permId)
except Exception as exc:
self.set_status(404)
self.write({
"reason" : 'No such dataSet found: {}'.format(permId)
})
return
# dataset was found, download the data to the disk
try:
destination = dataset.download(destination=downloadPath)
except Exception as exc:
self.set_status(500)
self.write({
"reason": 'Data for DataSet {} could not be downloaded: {}'.format(permId, exc)
})
return
# return success message
path = os.path.join(downloadPath, dataset.permId)
self.write({
'url' : conn.url,
'permId' : dataset.permId,
'path' : path,
'dataStore' : dataset.dataStore,
'location' : dataset.physicalData.location,
'size' : dataset.physicalData.size,
'statusText': 'Data for DataSet {} was successfully downloaded to: {}.'.format(dataset.permId, path)
})
def get(self, **params):
"""Handle a request to /openbis/dataset/connection_name/permId
download the data and return a message
"""
try:
conn = openbis_connections[params['connection_name']]
except KeyError:
self.set_status(404)
self.write({
"reason":'connection {} was not found'.format(params['connection_name'])
})
return
results = self.download_data(conn=conn, permId=params['permId'], downloadPath=params['downloadPath'])
class DataSetTypesHandler(IPythonHandler):
def get(self, **params):
"""Handle a request to /openbis/datasetTypes/connection_name
"""
try:
conn = openbis_connections[params['connection_name']]
except KeyError:
self.set_status(404)
self.write({
"reason":'connection {} was not found'.format(params['connection_name'])
})
return
try:
dataset_types = conn.openbis.get_dataset_types()
dts = dataset_types.df.to_dict(orient='records')
# get property assignments for every dataset-type
# and add it to the dataset collection
for dt in dts:
dataset_type = conn.openbis.get_dataset_type(dt['code'])
pa = dataset_type.get_propertyAssignments(including_vocabulary=True)
pa_dicts = pa.to_dict(orient='records')
for pa_dict in pa_dicts:
if pa_dict['dataType'] == 'CONTROLLEDVOCABULARY':
terms = conn.openbis.get_terms(pa_dict['vocabulary']['code'])
pa_dict['terms'] = terms.df[['code','label','description','official','ordinal']].to_dict(orient='records')
dt['propertyAssignments'] = pa_dicts
self.write({
"dataSetTypes": dts
})
return
except Exception as e:
print(e)
self.set_status(500)
self.write({
"reason":'Could not fetch dataset-types: {}'.format(e)
})
return
class DataSetUploadHandler(IPythonHandler):
"""Handle the POST requests for /openbis/dataset/connection_name"""
def upload_data(self, conn, data):
if not conn.is_session_active():
try:
conn.login()
except Exception as e:
print(e)
self.set_status(500)
self.write({
"reason": 'connection to {} could not be established: {}'.format(conn.name, e)
})
return
errors = []
print("--------------_HERE_-----------1")
sample = None
experiment = None
if (data.get('entityIdentifier')):
try:
sample = conn.openbis.get_sample(data.get('entityIdentifier'))
except Exception as e:
pass
if sample is None:
try:
experiment = conn.openbis.get_experiment(data.get('entityIdentifier'))
except Exception as e:
pass
if sample is None and experiment is None:
errors.append(
{"entityIdentifier" : 'No such sample or experiment: {}'.format(data.get('entityIdentifier')) }
)
else:
errors.append(
{"entityIdentifier": "please provide a sample or experiment identifier"}
)
print("--------------_HERE_-----------2")
parents = []
if data.get('parents'):
parents = data.get('parents')
for parent in parents:
try:
conn.openbis.get_dataset(parent)
except Exception as e:
errors.append({
"parent": "Parent DataSet not found: {}".format(parent)
})
print("--------------_HERE_-----------2a")
filenames = []
for filename in data.get('files'):
filename = unquote(filename)
if os.path.isfile(filename):
filenames.append(filename)
else:
errors.append({
"file": "File not found: {}".format(filename)
})
print("--------------_HERE_-----------3")
try:
dataset = conn.openbis.new_dataset(
type = data.get('type'),
sample = sample,
parents = parents,
experiment = experiment,
files = filenames,
)
except Exception as e:
print(e)
errors.append({
"create": 'Error while creating the dataset: {}'.format(e)
})
print("--------------_HERE_-----------4")
# try to set the properties
if data.get('props'):
props = data.get('props')
for prop, value in props.items():
try:
setattr(dataset.props, prop.lower(), value)
except Exception as e:
errors.append({
"prop."+prop : str(e)
})
# check if any mandatory property is missing
for prop_name, prop in dataset.props._property_names.items():
if prop['mandatory']:
if getattr(dataset.props, prop_name) is None or getattr(dataset.props, prop_name) == "":
errors.append({
"prop."+prop_name : "is mandatory"
})
print("--------------_HERE_-----------5")
# write errors back if already occured
if errors:
self.set_status(500)
self.write({ "errors": errors })
return
print("--------------_HERE_-----------6")
try:
dataset.save()
except Exception as e:
errors.append({
"save": 'Error while saving the dataset: {}'.format(e)
})
print("--------------_HERE_-----------7")
# write errors back if they occured
if errors:
self.set_status(500)
self.write({ "errors": errors })
else:
# ...or return a success message
self.write({
'status': 200,
'statusText': 'Jupyter Notebook was successfully uploaded to: {} with permId: {}'.format(conn.name, dataset.permId)
})
print('Jupyter Notebook was successfully uploaded to: {} with permId: {}'.format(conn.name, dataset.permId))
print("--------------_HERE_-----------8")
def post(self, **params):
"""Handle a request to /openbis/dataset/connection_name/permId
download the data and return a message
"""
try:
conn = openbis_connections[params['connection_name']]
except KeyError:
self.write({
"reason": 'connection {} was not found'.format(params['connection_name'])
})
return
data = self.get_json_body()
print("Received DATA")
print(data)
self.upload_data(conn=conn,data=data)
class FileListHandler(IPythonHandler):
def get(self, **params):
"""
Returns the file list of the current working directory
:param params:
:return: dictionary of files, key is the fully qualified name,
value is the relative name (for display)
"""
cwd = os.getcwd()
files = {}
for (dirpath, dirnames, filenames) in os.walk(cwd):
if filenames:
for filename in filenames:
# ignore hidden files
if filename.startswith('.'):
continue
# ignore hidden folders
if os.path.relpath(dirpath) != '.' \
and os.path.relpath(dirpath).startswith('.'):
continue
fqn = os.path.join(dirpath, filename)
files[fqn] = os.path.relpath(fqn, cwd)
self.set_status(200)
self.write({
"files": files
})
from notebook.base.handlers import IPythonHandler
import numpy as np
import os
from .connection import openbis_connections
from urllib.parse import parse_qs
def get_entity_for_identifier(conn, identifier):
try:
entity = conn.openbis.get_sample(identifier)
except Exception as exc:
pass
if entity is None:
try:
entity = conn.openbis.get_experiment(identifier)
except Exception as exc:
pass
return entity
def get_datasets(entity, start_with=None, count=None):
datasets = entity.get_datasets(start_with=start_with, count=count)
totalCount = datasets.totalCount
df = datasets.df
df.replace({np.nan:None}, inplace=True) # replace NaN with None, otherwise we cannot convert it correctly
datasets_dict = df.to_dict(orient='records') # is too stupid to handle NaN
return {
"datasets_dict": datasets_dict,
"totalCount": totalCount
}
class SampleHandler(IPythonHandler):
"""Handle the requests for /openbis/sample/connection/permId"""
def get(self, **params):
"""Handle a request to /openbis/sample/connection_name/permId
download the dataset list and return a message
"""
try:
conn = openbis_connections[params['connection_name']]
except KeyError:
self.set_status(500)
self.write({
"reason" : 'connection {} was not found'.format(
params['connection_name']
)
})
return
if not conn.is_session_active():
try:
conn.login()
except Exception as exc:
self.set_status(500)
self.write({
"reason" : 'connection to {} could not be established: {}'.format(conn.name, exc)
})
return
entity = get_entity_for_identifier(conn, params['identifier'])
if entity is None:
self.set_status(404)
self.write({
"reason" : 'No such Sample or Experiment: {}'.format(params['identifier'])
})
return None
querystring = parse_qs(self.request.query)
start_with = querystring.get('start_with', ['0'])[0]
count = querystring.get('count', ['10'])[0]
datasets = get_datasets(entity, start_with=start_with, count=count)
if datasets is not None:
self.set_status(200)
self.write({
"dataSets" : datasets.get('datasets_dict'),
"entity_attrs": entity.attrs.all(),
"entity_props": entity.props.all(),
"start_with" : start_with,
"count" : count,
"totalCount" : datasets.get('totalCount'),
"cwd" : os.getcwd()
})
from notebook.utils import url_path_join from notebook.utils import url_path_join
from notebook.base.handlers import IPythonHandler
from pybis import Openbis
import numpy as np
import os import os
from urllib.parse import unquote
import yaml import yaml
openbis_connections = {} from .connection import OpenBISConnections, OpenBISConnectionHandler, register_connection
from .dataset import DataSetTypesHandler, DataSetDownloadHandler, DataSetUploadHandler, FileListHandler
from .sample import SampleHandler
def _jupyter_server_extension_paths(): def _jupyter_server_extension_paths():
...@@ -31,8 +28,8 @@ def _load_configuration(paths, filename='openbis-connections.yaml'): ...@@ -31,8 +28,8 @@ def _load_configuration(paths, filename='openbis-connections.yaml'):
config = yaml.safe_load(stream) config = yaml.safe_load(stream)
for connection in config['connections']: for connection in config['connections']:
connections.append(connection) connections.append(connection)
except yaml.YAMLexception as exc: except yaml.YAMLexception as e:
print(exc) print(e)
return None return None
return connections return connections
...@@ -69,6 +66,15 @@ def load_jupyter_server_extension(nb_server_app): ...@@ -69,6 +66,15 @@ def load_jupyter_server_extension(nb_server_app):
host_pattern = '.*$' host_pattern = '.*$'
base_url = web_app.settings['base_url'] base_url = web_app.settings['base_url']
# get the file list
web_app.add_handlers(
host_pattern,
[(url_path_join( base_url, '/general/filelist'),
FileListHandler
)]
)
# DataSet download # DataSet download
web_app.add_handlers( web_app.add_handlers(
host_pattern, host_pattern,
...@@ -81,10 +87,7 @@ def load_jupyter_server_extension(nb_server_app): ...@@ -81,10 +87,7 @@ def load_jupyter_server_extension(nb_server_app):
# DataSet upload # DataSet upload
web_app.add_handlers( host_pattern, [( web_app.add_handlers( host_pattern, [(
url_path_join( url_path_join( base_url, '/openbis/dataset/(?P<connection_name>.*)' ),
base_url,
'/openbis/dataset/(?P<connection_name>.*)'
),
DataSetUploadHandler DataSetUploadHandler
)] )]
) )
...@@ -93,9 +96,7 @@ def load_jupyter_server_extension(nb_server_app): ...@@ -93,9 +96,7 @@ def load_jupyter_server_extension(nb_server_app):
web_app.add_handlers( web_app.add_handlers(
host_pattern, host_pattern,
[( [(
url_path_join( url_path_join( base_url, '/openbis/datasetTypes/(?P<connection_name>.*)'
base_url,
'/openbis/datasetTypes/(?P<connection_name>.*)'
), ),
DataSetTypesHandler DataSetTypesHandler
)] )]
...@@ -107,7 +108,7 @@ def load_jupyter_server_extension(nb_server_app): ...@@ -107,7 +108,7 @@ def load_jupyter_server_extension(nb_server_app):
[( [(
url_path_join( url_path_join(
base_url, base_url,
'/openbis/sample/(?P<connection_name>.*)?/(?P<permId>.*)' '/openbis/sample/(?P<connection_name>.*)?/(?P<identifier>.*)'
), ),
SampleHandler SampleHandler
)] )]
...@@ -137,392 +138,4 @@ def load_jupyter_server_extension(nb_server_app): ...@@ -137,392 +138,4 @@ def load_jupyter_server_extension(nb_server_app):
)] )]
) )
print("pybis loaded: {}".format(Openbis))
def register_connection(connection_info):
conn = OpenBISConnection(
name = connection_info.get('name'),
url = connection_info.get('url'),
verify_certificates = connection_info.get('verify_certificates', False),
username = connection_info.get('username'),
password = connection_info.get('password'),
status = 'not connected',
)
openbis_connections[conn.name] = conn
return conn
class OpenBISConnection:
"""register an openBIS connection
"""
def __init__(self, **kwargs):
for needed_key in ['name', 'url']:
if needed_key not in kwargs:
raise KeyError("{} is missing".format(needed_key))
for key in kwargs:
setattr(self, key, kwargs[key])
openbis = Openbis(
url = self.url,
verify_certificates = self.verify_certificates
)
self.openbis = openbis
self.status = "not connected"
def is_session_active(self):
return self.openbis.is_session_active()
def check_status(self):
if self.openbis.is_session_active():
self.status = "connected"
else:
self.status = "not connected"
def login(self, username=None, password=None):
if username is None:
username=self.username
if password is None:
password=self.password
self.openbis.login(
username = username,
password = password
)
# store username and password in memory
self.username = username
self.password = password
self.status = 'connected'
def get_info(self):
return {
'name' : self.name,
'url' : self.url,
'status' : self.status,
'username': self.username,
'password': self.password,
}
class OpenBISConnections(IPythonHandler):
def post(self):
"""create a new connection
:return: a new connection object
"""
data = self.get_json_body()
conn = register_connection(data)
if conn.username and conn.password:
try:
conn.login()
except Exception:
pass
self.get()
return
def get(self):
"""returns all available openBIS connections
"""
connections= []
for conn in openbis_connections.values():
conn.check_status()
connections.append(conn.get_info())
self.write({
'status' : 200,
'connections': connections,
'cwd' : os.getcwd()
})
return
class OpenBISConnectionHandler(IPythonHandler):
"""Handle the requests to /openbis/conn
"""
def put(self, connection_name):
"""reconnect to a current connection
:return: an updated connection object
"""
data = self.get_json_body()
try:
conn = openbis_connections[connection_name]
except KeyError:
self.set_status(404)
self.write({
"reason" : 'No such connection: {}'.format(data)
})
return
try:
conn.login(data.get('username'), data.get('password'))
except ConnectionError:
self.set_status(500)
self.write({
"reason": "Could not establish connection to {}".format(connection_name)
})
return
except ValueError:
self.set_status(401)
self.write({
"reason": "Incorrect username or password for {}".format(connection_name)
})
return
self.write({
'status' : 200,
'connection': conn.get_info(),
'cwd' : os.getcwd()
})
def get(self, connection_name):
"""returns information about a connection name
"""
try:
conn = openbis_connections[connection_name]
except KeyError:
self.set_status(404)
self.write({
"reason" : 'No such connection: {}'.format(data)
})
return
conn.check_status()
self.write({
'status' : 200,
'connection': conn.get_info(),
'cwd' : os.getcwd()
})
return
class SampleHandler(IPythonHandler):
"""Handle the requests for /openbis/sample/connection/permId"""
def get_datasets(self, conn, permId):
if not conn.is_session_active():
try:
conn.login()
except Exception as exc:
self.write({
"reason" : 'connection to {} could not be established: {}'.format(conn.name, exc)
})
sample = None
try:
sample = conn.openbis.get_sample(permId)
except Exception as exc:
self.set_status(404)
self.write({
"reason" : 'No such sample: {}'.format(permId)
})
if sample is None:
return
datasets = sample.get_datasets().df
datasets.replace({np.nan:None}, inplace=True) # replace NaN with None, otherwise we cannot convert it correctly
return datasets.to_dict(orient='records') # is too stupid to handle NaN
def get(self, **params):
"""Handle a request to /openbis/sample/connection_name/permId
download the data and return a message
"""
try:
conn = openbis_connections[params['connection_name']]
except KeyError:
self.write({
"reason" : 'connection {} was not found'.format(
params['connection_name']
)
})
return
datasets = self.get_datasets(conn, params['permId'])
if datasets is not None:
self.set_status(200)
self.write({
"dataSets": datasets
})
class DataSetDownloadHandler(IPythonHandler):
"""Handle the requests for /openbis/dataset/connection/permId"""
def download_data(self, conn, permId, downloadPath=None):
if not conn.is_session_active():
try:
conn.login()
except Exception as exc:
self.set_status(500)
self.write({
"reason" : 'connection to {} could not be established: {}'.format(conn.name, exc)
})
return
try:
dataset = conn.openbis.get_dataset(permId)
except Exception as exc:
self.set_status(404)
self.write({
"reason" : 'No such dataSet found: {}'.format(permId)
})
return
# dataset was found, download the data to the disk
try:
destination = dataset.download(destination=downloadPath)
except Exception as exc:
self.set_status(500)
self.write({
"reason": 'Data for DataSet {} could not be downloaded: {}'.format(permId, exc)
})
return
# return success message
path = os.path.join(downloadPath, dataset.permId)
self.write({
'url' : conn.url,
'permId' : dataset.permId,
'path' : path,
'dataStore' : dataset.dataStore,
'location' : dataset.physicalData.location,
'size' : dataset.physicalData.size,
'statusText': 'Data for DataSet {} was successfully downloaded to: {}.'.format(dataset.permId, path)
})
def get(self, **params):
"""Handle a request to /openbis/dataset/connection_name/permId
download the data and return a message
"""
try:
conn = openbis_connections[params['connection_name']]
except KeyError:
self.set_status(404)
self.write({
"reason":'connection {} was not found'.format(params['connection_name'])
})
return
results = self.download_data(conn=conn, permId=params['permId'], downloadPath=params['downloadPath'])
class DataSetTypesHandler(IPythonHandler):
def get(self, **params):
"""Handle a request to /openbis/datasetTypes/connection_name
"""
try:
conn = openbis_connections[params['connection_name']]
except KeyError:
self.set_status(404)
self.write({
"reason":'connection {} was not found'.format(params['connection_name'])
})
return
try:
dataset_types = conn.openbis.get_dataset_types()
dts = dataset_types.df.to_dict(orient='records')
# get property assignments for every dataset-type
# and add it to the dataset collection
for dt in dts:
dataset_type = conn.openbis.get_dataset_type(dt['code'])
pa = dataset_type.get_propertyAssignments()
pa_dict = pa.to_dict(orient='records')
dt['propertyAssignments'] = pa_dict
self.write({
"dataSetTypes": dts
})
return
except Exception as e:
self.set_status(500)
self.write({
"reason":'Could not fetch dataset-types: {}'.format(e)
})
return
class DataSetUploadHandler(IPythonHandler):
"""Handle the requests for /openbis/dataset/connection"""
def upload_data(self, conn, data):
if not conn.is_session_active():
try:
conn.login()
except Exception as exc:
self.write({
"reason": 'connection to {} could not be established: {}'.format(conn.name, exc)
})
return
try:
sample = conn.openbis.get_sample(data.get('sampleIdentifier'))
except Exception as exc:
self.set_status(404)
self.write({
"reason" : 'No such sample: {}'.format(data.get('sampleIdentifier'))
})
return
filenames = []
for filename in data.get('files'):
filename = unquote(filename)
filenames.append(filename)
try:
ds = conn.openbis.new_dataset(
name = data.get('name'),
description = data.get('description'),
type = data.get('type'),
sample = sample,
files = filenames
)
except Exception as exc:
self.write({
"reason": 'Error while creating the dataset: {}'.format(exc)
})
return
try:
ds.save()
except Exception as exc:
self.write({
"reason": 'Error while saving the dataset: {}'.format(exc)
})
return
# return success message
self.write({
'status': 200,
'statusText': 'Jupyter Notebook was successfully uploaded to: {} with permId: {}'.format(conn.name, ds.permId)
})
def post(self, **params):
"""Handle a request to /openbis/dataset/connection_name/permId
download the data and return a message
"""
try:
conn = openbis_connections[params['connection_name']]
except KeyError:
self.write({
"reason": 'connection {} was not found'.format(params['connection_name'])
})
return
data = self.get_json_body()
results = self.upload_data(conn=conn,data=data)
define([
"base/js/namespace"
],
function (IPython) {
function createFeedback(type, content) {
var close = document.createElement("BUTTON")
close.className = "close"
close.setAttribute("data-dismiss", "alert")
close.setAttribute("aria-label", "Close")
var x = document.createElement("SPAN")
x.setAttribute("aria-hidden", true)
x.innerHTML = "&times;"
close.appendChild(x)
var feedbackBox = document.createElement("DIV")
feedbackBox.className = "openbis-feedback alert alert-dismissible alert-" + type
feedbackBox.setAttribute("role", "alert")
feedbackBox.innerHTML = content
feedbackBox.prepend(close)
var nb_container = document.getElementById('notebook-container')
nb_container.prepend(feedbackBox)
}
function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for(var i = 0; i <ca.length; i++) {
var c = ca[i];
while (c.charAt(0) === ' ') {
c = c.substring(1);
}
if (c.indexOf(name) === 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
return {
createFeedback: createFeedback,
getCookie: getCookie
}
}
)
\ No newline at end of file
define(
[
"base/js/dialog",
"jquery",
"./state",
"./connections"
],
function (dialog, $, state, connections) {
var currentDownloadPath = null
function show_available_connections(env, data, conn_table, onclick_cbf) {
if (!currentDownloadPath) {
currentDownloadPath = data.cwd
}
var table = document.createElement("TABLE")
table.className = 'table-bordered table-striped table-condensed'
var thead = table.createTHead()
var thead_row = thead.insertRow(0)
var titles = ['', 'Name', 'URL', 'Status', 'Username / Password']
for (title of titles) {
thead_row.insertCell().textContent = title
}
tbody = table.createTBody()
for (connection of data.connections) {
var conn = document.createElement("INPUT")
conn.type = "radio"
conn.name = "connection_name"
conn.value = connection.name
conn.setAttribute("url", connection.url)
conn.checked = connection.name === state.connection.candidateName;
if (onclick_cbf === undefined) {
conn.onclick = function () {
state.connection.candidateName = this.value
}
} else {
conn.onclick = onclick_cbf
}
var row = tbody.insertRow()
row.insertCell().appendChild(conn)
row.insertCell().textContent = connection.name
row.insertCell().textContent = connection.url
var status_cell = row.insertCell()
var status_badge = document.createElement("SPAN")
status_badge.id = connection.name + "-badge"
status_badge.textContent = connection.status
if (connection.status === "connected") {
status_badge.className = "label label-success"
} else {
status_badge.className = "label label-danger"
}
status_cell.appendChild(status_badge)
var username = document.createElement("INPUT")
username.type = "text"
username.name = "username"
username.autocomplete = "on"
username.value = connection.username
username.setAttribute("form", connection.name)
var password = document.createElement("INPUT")
password.type = "password"
password.name = "password"
password.autocomplete = "current-password"
password.value = connection.password
password.setAttribute("form", connection.name)
// Username / Password form
var pwform = document.createElement("FORM")
pwform.id = connection.name
pwform.onsubmit = function (event) {
var form_data = new FormData(this)
var status_badge = document.getElementById(this.id + "-badge")
connections.connect(env, this.id,
form_data.get("username"), form_data.get("password")
)
.then(function (response) {
//console.log(response)
if (status_badge.nextElementSibling !== null) {
status_badge.parentNode.removeChild(status_badge.nextElementSibling)
}
if (response.ok) {
status_badge.textContent = "connected"
status_badge.className = "label label-success"
} else {
status_badge.textContent = "not connected"
status_badge.className = "label label-danger"
message = document.createElement("p")
if (response.status === 401) {
message.textContent = "username/password incorrect"
} else if (response.status === 500) {
message.textContent = "Connection error"
} else {
message.textContent = "General error"
}
status_badge.parentNode.insertBefore(message, status_badge.nextSibling)
}
})
.catch(error => console.error("Error while attempting to reconnect: ", error))
return false
}
var connect_button = document.createElement("BUTTON")
connect_button.className = "btn btn-primary btn-xs"
connect_button.textContent = "connect"
pwform.appendChild(username)
pwform.appendChild(password)
pwform.appendChild(connect_button)
var cell = row.insertCell()
cell.appendChild(pwform)
}
// add row for new connection
var row = tbody.insertRow()
var conn_form = document.createElement("FORM")
conn_form.id = "new_connection"
conn_form.onsubmit = function (event) {
var inputs = document.querySelectorAll("input[form=new_connection]")
data = {}
for (input of inputs) {
data[input.name] = input.value
}
for (missing of ['connection_name', 'url', 'username', 'password']) {
if (data[missing] === "") {
alert("Please provide: " + missing)
return false
}
}
connections.create(env, data.connection_name, data.url, data.username, data.password)
.then(function (response) {
if (response.ok) {
response.json()
.then(function (data) {
show_available_connections(env, data, conn_table)
})
}
})
return false
}
var conn_name = document.createElement("INPUT")
conn_name.type = "input"
conn_name.name = "connection_name"
conn_name.setAttribute("form", conn_form.id)
conn_name.placeholder = "openBIS instance name"
row.insertCell().appendChild(conn_form)
row.insertCell().appendChild(conn_name)
var conn_url = document.createElement("INPUT")
conn_url.type = "input"
conn_url.name = "url"
conn_url.setAttribute("form", conn_form.id)
conn_url.placeholder = "https://openbis.domain:port"
row.insertCell().appendChild(conn_url)
row.insertCell()
var username = document.createElement("INPUT")
username.autocomplete = "off"
username.type = "text"
username.name = "username"
username.setAttribute("form", conn_form.id)
username.placeholder = "username"
var password = document.createElement("INPUT")
password.type = "password"
password.name = "password"
password.autocomplete = "new-password"
password.setAttribute("form", conn_form.id)
var create_btn = document.createElement("BUTTON")
create_btn.setAttribute("form", conn_form.id)
create_btn.textContent = "create"
var uname_pw_cell = row.insertCell()
uname_pw_cell.appendChild(username)
uname_pw_cell.appendChild(password)
uname_pw_cell.appendChild(create_btn)
conn_table.innerHTML = ""
table_title = document.createElement("STRONG")
table_title.textContent = "Please choose a connection"
conn_table.appendChild(table_title)
conn_table.appendChild(table)
}
return {
help: 'configure openBIS connections',
icon: 'fa-sliders',
help_index: '',
handler: function (env) {
conn_table = document.createElement("DIV")
var dst_title = document.createElement("STRONG")
dst_title.textContent = "DataSet type"
var dataset_types = document.createElement("SELECT")
dataset_types.id = "dataset_type"
dataset_types.className = "form-control select-xs"
var input_fields = document.createElement("DIV")
conn_table.id = "openbis_connections"
var onclick_cbf = function () {
state.connection.candidateName = this.value
}
connections.list(env)
.done(function (data) {
show_available_connections(env, data, conn_table, onclick_cbf)
})
.fail(function (data) {
alert(data.status)
})
var uploadDialogBox = $('<div/>').append(conn_table)
function onOk() {
state.connection.name = state.connection.candidateName
}
function onCancel() {
state.connection.candidateName = state.connection.name
}
dialog.modal({
body: uploadDialogBox,
title: 'Choose openBIS connection',
buttons: {
'Cancel': {
click: onCancel
},
'Choose connection': {
class: 'btn-primary btn-large',
click: onOk
}
},
notebook: env.notebook,
keyboard_manager: env.notebook.keyboard_manager
})
}
}
}
)
\ No newline at end of file
define([
"base/js/utils",
"./common"
],
function (utils, common) {
function list(env) {
var connectionsUrl = env.notebook.base_url + 'openbis/conns'
var settings = {
url: connectionsUrl,
processData: false,
type: 'GET',
dataType: 'json',
contentType: 'application/json'
}
return utils.ajax(settings)
}
function connect(env, connection, username, password) {
var url = env.notebook.base_url + 'openbis/conn/' + connection
body = {
"username": username,
"password": password
}
var xsrf_token = common.getCookie('_xsrf')
return fetch(url, {
method: "PUT",
headers: {
"Content-Type": "application/json",
"X-XSRFToken": xsrf_token,
"credentials": "same-origin",
},
body: JSON.stringify(body)
})
}
function create(env, connection_name, connection_url, username, password) {
var endpoint = env.notebook.base_url + 'openbis/conns'
body = {
"name": connection_name,
"url": connection_url,
"username": username,
"password": password
}
var xsrf_token = common.getCookie('_xsrf')
return fetch(endpoint, {
method: "POST",
headers: {
"Content-Type": "application/json",
"X-XSRFToken": xsrf_token,
"credentials": "same-origin",
},
body: JSON.stringify(body)
})
}
return {
list: list,
create: create,
connect: connect
}
}
)
\ No newline at end of file
This diff is collapsed.
define([
"base/js/dialog",
"./common",
"./state"
],
function (dialog, common, state) {
function writeMetaData(data) {
var notebook = IPython.notebook
if (typeof notebook.metadata.datasets === 'undefined') {
notebook.metadata.datasets = {}
}
// store metadata about the downloaded files into the notebook-metadata
if (data.permId) {
notebook.metadata.datasets[data.permId] = {
"permId": data.permId,
"path": data.path,
"dataStore": data.dataStore,
"location": data.location,
"size": data.size,
"status": data.statusText
}
}
}
function show_datasets_table(env, data, datasets_table, downloadPath, entityIdentifier) {
if (downloadPath.value === '') {
downloadPath.value = data.cwd
}
var table = document.createElement("TABLE")
table.className = "table-bordered table-striped table-condensed text-nowrap"
table.style.width = "100%"
var thead = table.createTHead()
var t_row = thead.insertRow()
var titles = ['', 'permId', 'Type', 'Experiment', 'Registration Date', 'Status', 'Size']
titles.forEach(function (title) {
t_row.insertCell().textContent = title
})
var tbody = table.createTBody()
for (dataSet of data.dataSets) {
const permId = document.createElement("INPUT")
permId.type = "checkbox"
permId.name = "permId"
permId.value = dataSet.permId
permId.checked = state.selectedDatasets.has(permId.value)
permId.onclick = () => permId.checked ? state.selectedDatasets.add(permId.value) : state.selectedDatasets.delete(permId.value)
var row = tbody.insertRow()
row.insertCell().appendChild(permId)
row.insertCell().textContent = dataSet.permId
row.insertCell().textContent = dataSet.type
row.insertCell().textContent = dataSet.experiment
row.insertCell().textContent = dataSet.registrationDate
row.insertCell().textContent = dataSet.status
row.insertCell().textContent = dataSet.size
}
while (datasets_table.firstChild) {
datasets_table.removeChild(datasets_table.firstChild);
}
datasets_table.appendChild(table)
const totalCount = parseInt(data.totalCount)
const count = parseInt(data.count)
const startWith = parseInt(data.start_with)
const hasNext = startWith + count < totalCount
const hasPrevious = startWith > 0
const nextCmd = () => getDatasets(env, startWith+5, 5, entityIdentifier, datasets_table, downloadPath)
const previousCmd = () => getDatasets(env, startWith-5, 5, entityIdentifier, datasets_table, downloadPath)
var previous = document.createElement("A")
var linkText = document.createTextNode("<<< Previous")
previous.appendChild(linkText)
previous.href = "#"
previous.onclick = previousCmd
var next = document.createElement("A")
var linkText = document.createTextNode("Next >>>")
next.appendChild(linkText)
next.href = "#"
next.onclick = nextCmd
next.style.float="right"
var paging = document.createElement("DIV")
paging.style.width = "100%"
if (hasPrevious) {
paging.appendChild(previous)
}
if (hasNext) {
paging.appendChild(next)
}
datasets_table.appendChild(paging)
}
function getDatasets(env, startWith, count, entityIdentifier, datasets_table, downloadPath) {
var connection_name = state.connection.name
if (!connection_name) {
alert('Please choose a connection')
return false
}
currentEntityIdentifier = entityIdentifier.value
if (!currentEntityIdentifier) {
alert('Please specify a Sample or Experiment identifier/permId')
return false
}
var url = env.notebook.base_url
+ 'openbis/sample/'
+ connection_name
+ '/'
+ encodeURIComponent(currentEntityIdentifier)
+ "?start_with="
+ startWith
+ "&count="
+ count
fetch(url)
.then(function (response) {
if (response.ok) {
response.json()
.then(function (data) {
show_datasets_table(env, data, datasets_table, downloadPath, entityIdentifier)
})
} else {
response.json()
.then(function (error) {
console.log(error.reason)
alert("Error: " + error.reason)
})
}
})
.catch(function (error) {
console.error('A serious network problem occured:', error)
})
}
return {
help: 'Download openBIS datasets to your local harddrive',
icon: 'fa-download',
help_index: '',
handler: function (env) {
state.selectedDatasets = new Set([])
conn_table = document.createElement("DIV")
conn_table.id = "openbis_connections"
var showDataSets = document.createElement("DIV")
var title = document.createElement("STRONG")
title.textContent = "Sample or Experiment identifier/permId: "
showDataSets.appendChild(title)
showDataSets.style.marginTop = '10px'
var entityIdentifier = document.createElement("INPUT")
entityIdentifier.type = "text"
entityIdentifier.name = "entityIdentifier"
entityIdentifier.size = 40
entityIdentifier.placeholder = "Sample or Experiment identifier/permId"
entityIdentifier.value = ''
var datasets_table = document.createElement("DIV")
var show_datasets_btn = document.createElement("BUTTON")
show_datasets_btn.className = "btn-info btn-xs"
show_datasets_btn.textContent = "show datasets"
show_datasets_btn.style.margin="10px"
showDataSets.appendChild(entityIdentifier)
showDataSets.appendChild(show_datasets_btn)
showDataSets.appendChild(datasets_table)
var dataset_direct = document.createElement("P")
dataset_direct.style.marginTop = '10px'
dataset_direct.innerHTML = '<strong>Enter DataSet permId directly: </strong>'
var datasetPermId = document.createElement("INPUT")
datasetPermId.type = "text"
datasetPermId.name = "datasetPermId"
datasetPermId.size = "40"
datasetPermId.placeholder = "dataSet permId"
dataset_direct.appendChild(datasetPermId)
var downloadPath = document.createElement("INPUT")
downloadPath.type = "text"
downloadPath.name = "downloadPath"
downloadPath.size = "90"
downloadPath.value = ''
show_datasets_btn.onclick =
() => getDatasets(env, 0, 5, entityIdentifier, datasets_table, downloadPath)
var path = document.createElement("DIV")
path.innerHTML = "<strong>download data to path: </strong>"
path.appendChild(downloadPath)
var download_dialog_box = document.createElement("DIV")
download_dialog_box.appendChild(conn_table)
download_dialog_box.appendChild(showDataSets)
download_dialog_box.appendChild(dataset_direct)
download_dialog_box.appendChild(path)
function downloadDataset(connection_name, selectedPermIds, downloadPath) {
for (permId of selectedPermIds) {
var downloadUrl = env.notebook.base_url + 'openbis/dataset/' +
connection_name + '/' + permId + '/' + encodeURIComponent(downloadPath)
fetch(downloadUrl)
.then(function (response) {
if (response.ok) {
response.json()
.then(function (data) {
common.createFeedback('success', data.statusText)
// successful download:
// write statusText from returned data to notebooks metadata
writeMetaData(data)
// keep current download path for later use
currentDownloadPath = downloadPath
})
} else {
response.json()
.then(function (error) {
console.log(error.reason)
alert("Error: " + error.reason)
})
}
})
.catch(function (error) {
console.error('A serious network problem occured:', error)
})
}
}
function onDownloadClick() {
var selected_conn = state.connection.name
if (!selected_conn) {
alert('please choose a connection')
return false
}
var selectedPermIds = []
for (row of state.selectedDatasets) {
selectedPermIds.push(row)
}
if (datasetPermId.value) {
selectedPermIds.push(datasetPermId.value)
}
if (!selectedPermIds) {
alert('please select a dataset or provide a permId')
return false
}
if (!downloadPath.value) {
alert('Please specify where you would like to download your files!')
return false
}
downloadDataset(selected_conn, selectedPermIds, downloadPath.value)
}
dialog.modal({
body: download_dialog_box,
title: 'Download openBIS DataSets',
buttons: {
'Cancel': {},
'Download': {
class: 'btn-primary btn-large',
click: onDownloadClick,
}
},
notebook: env.notebook,
keyboard_manager: env.notebook.keyboard_manager
})
}
}
}
)
\ No newline at end of file
define([
"base/js/namespace",
"./connectionDialog",
"./uploadDialog",
"./downloadDialog"
],
function (IPython, connectionDialog, uploadDialog, downloadDialog) {
var ds_type = document.createElement("SELECT")
ds_type.size = '40'
ds_type.className = "select-xs"
ds_type.id = "dataset_type"
function _onLoad() {
// show connections
var configure_openbis_connections = IPython.keyboard_manager.actions.register(
connectionDialog, 'openbis-connections', 'jupyter-openBIS')
// dnownload
var download_datasets = IPython.keyboard_manager.actions.register(
downloadDialog, 'openbis-dataset-download', 'jupyter-openBIS')
// upload
var upload_datasets = IPython.keyboard_manager.actions.register(
uploadDialog, 'openbis-dataset-upload', 'jupyter-openBIS')
// add button for new action
IPython.toolbar.add_buttons_group([configure_openbis_connections, download_datasets, upload_datasets])
}
return {
load_ipython_extension: _onLoad
}
})
\ No newline at end of file
define([],
function () {
return {
// connection dialog
connection: {
name: null,
candidateName: null
},
// upload dialog
uploadDataSetType: null,
uploadDataSetTypes: {},
uploadEntityIdentifier: '',
datasetCheckboxes: [],
fileCheckboxes: [],
selectedFiles: [],
unselectedDatasets: [],
// download dialog
selectedDatasets: new Set([])
}
}
)
\ No newline at end of file
define([
"base/js/dialog",
"base/js/utils",
"jquery",
"./state",
"./common",
],
function (dialog, utils, $, state, common) {
var errorElements = { }
function createErrorElement(name) {
var element = document.createElement("STRONG")
element.textContent = ""
element.style.marginLeft = "8px"
element.style.color = "red"
errorElements[name.toLowerCase()] = element
return element
}
function cleanErrors() {
Object.keys(errorElements).forEach(key => errorElements[key].textContent="")
}
var spinner = document.createElement("IMG")
spinner.className="openbis-feedback"
spinner.src=""
function showSpinner() {
spinner.src="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.5.8/ajax-loader.gif"
}
function hideSpinner() {
spinner.src=""
}
function get_file_list(env, container) {
var url = env.notebook.base_url + 'general/filelist'
fetch(url)
.then( function(response) {
if (response.ok) {
response.json()
.then(function(data){
var values = Object.keys(data.files)
values.sort()
state.fileCheckboxes = createSelectTable(values, container, false, state.selectedFiles)
})
}
else {
console.error(response.status)
}
})
}
function get_dataset_list(env, container) {
var datasets = env.notebook.metadata.datasets
if (datasets != null) {
var values = Object.keys(datasets)
values.sort()
state.datasetCheckboxes = createSelectTable(values, container, true, state.unselectedDatasets)
}
}
function getDatasetTypes(env, connection_name, dataset_types, input_fields) {
// get all DatasetTypes of a given connection
var url = env.notebook.base_url + 'openbis/datasetTypes/' + connection_name
fetch(url)
.then(function (response) {
if (response.ok) {
response.json()
.then(function (data) {
var change_input_fields = function () {
hideSpinner()
cleanErrors()
var oldType = state.uploadDataSetType
if (oldType != null && !(oldType in state.uploadDataSetTypes)) {
state.uploadDataSetTypes[oldType] = {}
}
state.uploadDataSetType = dataset_types.options[dataset_types.selectedIndex].value
// remove existing input fields
while (input_fields.firstChild) {
var element = input_fields.firstChild
if (element.nodeName === "INPUT" && state.uploadDataSetType != null) {
state.uploadDataSetTypes[oldType][element.name] = element.value
}
input_fields.removeChild(element)
}
// for every property assignment, create an input field.
for (pa of dts[dataset_types.selectedIndex].propertyAssignments) {
var input_title = document.createElement("STRONG")
input_title.textContent = pa.mandatory ? pa.label + " (mandatory)" : pa.label
var input_error = createErrorElement('prop.'+pa.code)
var input_field = document.createElement("INPUT")
input_field.type = "text"
input_field.name = pa.code
input_field.placeholder = pa.description ? pa.description : pa.label
input_field.size = 90
input_field.style.width="100%"
var mem = state.uploadDataSetTypes[dts[dataset_types.selectedIndex].code]
if (mem == null) {
mem = {}
}
input_field.value = pa.code in mem ? mem[pa.code] : ""
input_fields.appendChild(input_title)
input_fields.appendChild(input_error)
input_fields.appendChild(input_field)
input_fields.appendChild(document.createElement("BR"))
}
}
dataset_types.onchange = change_input_fields
// remove the old and add the new dataset-types
dts = data.dataSetTypes
while (dataset_types.firstChild) {
dataset_types.removeChild(dataset_types.firstChild);
}
var index = 0
var selectedIndex = -1
for (dt of dts) {
var option = document.createElement("OPTION")
option.value = dt.code
option.textContent = dt.description ? dt.code + ": " + dt.description : dt.code
dataset_types.appendChild(option)
if (dt.code === state.uploadDataSetType) {
selectedIndex = index
}
index++
}
dataset_types.selectedIndex = selectedIndex === -1 ? 0 : selectedIndex
// change the input fields, since we just received new datasetTypes
change_input_fields()
})
.catch(function (error) {
console.error("Error while parsing dataset types", error)
})
} else {
while (dataset_types.firstChild) {
dataset_types.removeChild(dataset_types.firstChild);
}
}
})
.catch(function (error) {
console.error("Error while fetching dataset types:", error)
})
}
function createSelectTable(values, container, checked, overrides) {
var table = document.createElement("TABLE")
table.className = 'table-bordered table-striped table-condensed'
table.style.width = "100%"
var body = table.createTBody()
var checkboxes = []
values.forEach( value => {
var row = body.insertRow()
var checkbox = document.createElement("INPUT")
checkbox.type = "checkbox"
checkbox.value = value
checkbox.checked = overrides.includes(value) ? !checked : checked
checkboxes.push(checkbox)
row.insertCell().appendChild(checkbox)
var valueCell = row.insertCell()
valueCell.textContent = value
valueCell.style.width = "100%"
})
container.appendChild(table)
return checkboxes
}
return {
help: 'upload Notebook and Data to openBIS',
icon: 'fa-upload',
help_index: '',
handler: function (env) {
var main_error = createErrorElement('main')
var dst_title = document.createElement("STRONG")
dst_title.textContent = "DataSet type"
var dataset_types = document.createElement("SELECT")
dataset_types.id = "dataset_type"
dataset_types.className = "form-control select-xs"
dataset_types.style.marginLeft = 0
dataset_types.style.padding = 0
var input_fields = document.createElement("DIV")
input_fields.setAttribute("id", "upload-input-fields");
getDatasetTypes(env, state.connection.name, dataset_types, input_fields)
var sample_title = document.createElement("STRONG")
sample_title.textContent = "Sample or Experiment identifier/permId"
var sample_error = createErrorElement('entityIdentifier')
var entityIdentifier = document.createElement("INPUT")
entityIdentifier.type = "text"
entityIdentifier.name = 'entityIdentifier'
entityIdentifier.placeholder = "Sample or Experiment identifier/permId"
entityIdentifier.value = state.uploadEntityIdentifier
entityIdentifier.size = "90"
entityIdentifier.style.width="100%"
var ds_title = document.createElement("STRONG")
var dataSetListContainer = document.createElement("DIV")
if (env.notebook.metadata.datasets) {
ds_title.textContent = "DataSets"
dataSetListContainer.style.maxHeight="150px"
dataSetListContainer.style.overflow="auto"
get_dataset_list(env, dataSetListContainer)
}
var files_title = document.createElement("STRONG")
files_title.textContent = "Files"
var fileListContainer = document.createElement("DIV")
fileListContainer.style.maxHeight="150px"
fileListContainer.style.overflow="auto"
get_file_list(env, fileListContainer)
var inputs = document.createElement("DIV")
inputs.style.marginTop = '10px'
inputs.appendChild(main_error)
inputs.appendChild(spinner)
inputs.appendChild(document.createElement("BR"))
inputs.appendChild(dst_title)
inputs.appendChild(dataset_types)
inputs.appendChild(input_fields)
inputs.appendChild(sample_title)
inputs.appendChild(sample_error)
inputs.appendChild(entityIdentifier)
inputs.appendChild(ds_title)
inputs.appendChild(dataSetListContainer)
inputs.appendChild(files_title)
inputs.appendChild(fileListContainer)
var uploadDialogBox = $('<div/>').append(inputs)
function saveState() {
state.uploadDataSetTypes[state.uploadDataSetType] = {}
for (element of input_fields.children) {
if (element.nodeName === "INPUT" && state.uploadDataSetType != null) {
state.uploadDataSetTypes[state.uploadDataSetType][element.name] = element.value
}
}
state.uploadEntityIdentifier = entityIdentifier.value
state.unselectedDatasets = state.datasetCheckboxes.filter(cb => !cb.checked).map(cb => cb.value)
state.selectedFiles = state.fileCheckboxes.filter(cb => cb.checked).map(cb => cb.value)
}
function onOk() {
var connection_name = state.connection.name
if (!connection_name) {
alert("No connection selected")
return false
}
var uploadUrl = env.notebook.base_url + 'openbis/dataset/' + connection_name
var notebook = IPython.notebook
var files = state.fileCheckboxes.filter(cb => cb.checked).map(cb => cb.value)
var re = /\/notebooks\/(.*?)$/
var filepath = window.location.pathname.match(re)[1]
files.push(filepath)
var props = {}
for (input of $('#upload-input-fields').find('input')) {
props[input.name] = input.value
}
var dataSetInfo = {
"type": dataset_types.value,
"files": files,
"parents": state.datasetCheckboxes.filter(cb => cb.checked).map(cb => cb.value),
"entityIdentifier": entityIdentifier.value,
"props": props
}
var settings = {
url: uploadUrl,
processData: false,
type: 'POST',
dataType: 'json',
data: JSON.stringify(dataSetInfo),
contentType: 'application/json',
success: function (data) {
saveState()
$('div.modal').remove()
$('div.modal-backdrop').remove()
common.createFeedback('success', data.statusText)
// write statusText from returned data to notebooks metadata
if (typeof notebook.metadata.openbis === 'undefined') {
notebook.metadata.openbis = {}
}
if (typeof notebook.metadata.openbis.permIds === 'undefined') {
notebook.metadata.openbis.permIds = {}
}
if (data.permId) {
notebook.metadata.openbis.permIds[data.permId] = data.statusText
}
},
error: function (data) {
hideSpinner()
if ("errors" in data.responseJSON) {
var errors = data.responseJSON.errors
for (error of errors) {
let key, value
Object.keys(error).forEach(k => {
key = k.toLowerCase()
value = error[k]
})
errorElements[key in errorElements ? key : "main"].textContent = value
}
} else {
errorElements["main"].textContent = "Server error"
}
}
}
showSpinner()
cleanErrors()
utils.ajax(settings)
return false
}
function onCancel() {
saveState()
return true
}
if (IPython.notebook.dirty === true) {
dialog.modal({
body: 'Please save the notebook before uploading it to openBIS.',
title: 'Save notebook first',
buttons: {
'Back': {}
},
notebook: env.notebook,
keyboard_manager: env.notebook.keyboard_manager
})
} else {
dialog.modal({
body: uploadDialogBox,
title: 'Upload openBIS DataSet',
buttons: {
'Cancel': {
click: onCancel
},
'Upload': {
class: 'btn-primary btn-large',
click: onOk
}
},
notebook: env.notebook,
keyboard_manager: env.notebook.keyboard_manager
})
}
}
}
}
)
\ No newline at end of file
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment