new django app descriptionhandler

Change-Id: I0d7bdece62413ad1a9aa30c64fbd9f785705dc8e
Signed-off-by: lombardofr <lombardo@everyup.it>
diff --git a/descriptorhandler/__init__.py b/descriptorhandler/__init__.py
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/descriptorhandler/__init__.py
diff --git a/descriptorhandler/apps.py b/descriptorhandler/apps.py
new file mode 100644
index 0000000..9d952fc
--- /dev/null
+++ b/descriptorhandler/apps.py
@@ -0,0 +1,23 @@
+#
+#   Copyright 2018 EveryUP Srl
+#
+#   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  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.
+#
+
+from __future__ import unicode_literals
+
+from django.apps import AppConfig
+
+
+class DescriptorhandlerConfig(AppConfig):
+    name = 'descriptorhandler'
diff --git a/descriptorhandler/models.py b/descriptorhandler/models.py
new file mode 100644
index 0000000..ed2a5ae
--- /dev/null
+++ b/descriptorhandler/models.py
@@ -0,0 +1,21 @@
+#
+#   Copyright 2018 EveryUP Srl
+#
+#   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  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.
+#
+
+from __future__ import unicode_literals
+
+from django.db import models
+
+# Create your models here.
diff --git a/descriptorhandler/template/composer.html b/descriptorhandler/template/composer.html
new file mode 100644
index 0000000..cad68fa
--- /dev/null
+++ b/descriptorhandler/template/composer.html
@@ -0,0 +1,80 @@
+{% extends "base.html" %}
+{% load get %}
+{% load staticfiles %}
+
+
+
+{% block head_block %}
+    {{ block.super }}
+
+<!-- TopologyComposer D3 -->
+    <link rel="stylesheet" href="/static/TopologyComposer/css/composer.css">
+    <link rel="stylesheet" href="/static/TopologyComposer/css/d3-context-menu.css">
+
+
+{% endblock %}
+{% block title_header_big %}
+    {{ block.super }}
+{% endblock %}
+{% block left_sidebar %}
+    {% include 'osm/osm_project_left_sidebar.html' %}
+{% endblock %}
+
+
+{% block breadcrumb_body %}
+    {{ block.super }}
+    {% comment %}<li><a href="{% url 'projects:descriptors:list_descriptors'  type=type %}">{{ type|upper }} Descriptors</a></li>
+    <li><a href="#"><i class="fa fa-sitemap"></i> {{ type|upper }} Topology</a></li>{% endcomment %}
+{% endblock %}
+
+{% block content_body %}
+    {{ block.super }}
+    {% csrf_token %}
+    <div class="container-fluid">
+        <div id="main" class="row">
+            <div id="leftside">
+
+            </div>
+            <div id="graph_editor_container" class="col">
+                <div class="btn-group left-tool-bar-monitoring">
+                    <button id="topology_force" type="button" class="btn btn btn-default" onclick="handleForce(this)"
+                            data-toggle="button" aria-pressed="false" autocomplete="off"><i
+                            class="fas fa-thumbtack"></i></button>
+                    <button id="reset_filter" type="button" class="btn btn btn-default" onclick="resetFilters(this)"><i
+                            class="fa fa-backward"></i></button>
+                </div>
+                <div id="legenda">
+                </div>
+            </div>
+            <div id="side">
+
+            </div>
+        </div>
+    </div>
+
+{% endblock %}
+
+{% block resource_block %}
+    {{ block.super }}
+    <script>
+        var topology_data = {};//{{topology_data|safe }};
+    </script>
+    <!-- d3.js -->
+    <script src="/static/bower_components/d3/d3.js"></script>
+
+    <!-- TopologyComposer D3 -->
+    <script src="/static/TopologyComposer/js/event.js"></script>
+    <script src="/static/TopologyComposer/js/settings.js"></script>
+    <script src="/static/TopologyComposer/js/graph_editor.js"></script>
+    <script src="/static/TopologyComposer/js/model_graph_editor.js"></script>
+    <script src="/static/TopologyComposer/js/d3-context-menu.js"></script>
+
+
+    <script src="/static/src/osm_gui_properties.js"></script>
+{#    <script src="/static/src/instancehandler/instance_topology_view.js"></script>#}
+
+{% endblock %}
+
+{% block footer %}
+    {% include "footer.html" %}
+{% endblock %}
diff --git a/descriptorhandler/template/descriptor_new.html b/descriptorhandler/template/descriptor_new.html
new file mode 100644
index 0000000..2551f30
--- /dev/null
+++ b/descriptorhandler/template/descriptor_new.html
@@ -0,0 +1,67 @@
+{% extends "/descriptor_view_base.html" %}
+
+{% load staticfiles %}
+
+
+{% block title_header_big %}
+{{ block.super }}
+Onboard new {{ descriptor_type }} package
+{% endblock %}
+
+{% block left_sidebar %}
+{% include 'osm/osm_project_left_sidebar.html' %}
+{% endblock %}
+
+{% block breadcrumb_body %}
+{{ block.super }}
+<li><a href="{% url 'projects:open_project'  %}">{{project_id}}</a></li>
+<li><a href="{% url 'projects:open_project'  %}descriptors/{{descriptor_type}}">{{ descriptor_type }}  Descriptors</a></li>
+<li>Create Descriptor</li>
+{% endblock %}
+
+{% block tab_pane_button_list %}
+{{ block.super }}
+<li id="file_li" class="active"><a href="#upload" data-toggle="tab"><i class="fa fa-upload"></i> Onboard Package</a></li>
+{% endblock %}
+
+{% block nav_buttons_list %}
+{{ block.super }}
+<li class="pull-right">
+    <button id="cancel" type="button" class="btn btn-block btn-primary btn-sm" onclick="cancel(this.id)"><i
+            class="fa fa-times"></i> Cancel
+    </button>
+</li>
+{% endblock %}
+
+{% block tab_pane_list %}
+{{ block.super }}
+
+<div class="tab-pane active" id="upload">
+
+    <h4>Drag and drop file below</h4>
+    <div class="upload-drop-zone" id="drop-zone">
+            Just drag and drop files here
+    </div>
+</div>
+{% endblock %}
+
+
+{% block resource_block %}
+{{ block.super }}
+
+<script>
+    var descr_list_url = '{% url "projects:descriptors:list_descriptors"   descriptor_type=descriptor_type%}';
+    var csrf_token = '{{csrf_token}}';
+    var new_desc_url ="{% url 'projects:descriptors:new_descriptor'  descriptor_type=descriptor_type %}"
+
+    function cancel(id) {
+        window.location.href = descr_list_url
+    }
+
+</script>
+    <script src="/static/src/projecthandler/onboard_package.js"></script>
+{% endblock %}
+
+{% block footer %}
+    {% include "footer.html" %}
+{% endblock %}
diff --git a/descriptorhandler/template/descriptor_view.html b/descriptorhandler/template/descriptor_view.html
new file mode 100644
index 0000000..2a18666
--- /dev/null
+++ b/descriptorhandler/template/descriptor_view.html
@@ -0,0 +1,132 @@
+{% extends "descriptor_view_base.html" %}
+
+{% load staticfiles %}
+
+
+{% block title_header_big %}
+{{ block.super }}
+Edit {{ descriptor_type|upper }} Descriptor
+{% endblock %}
+
+
+{% block left_sidebar %}
+{% include 'osm/osm_project_left_sidebar.html' %}
+{% endblock %}
+
+{% block breadcrumb_body %}
+{{ block.super }}
+<li><a href="{% url 'projects:open_project' %}">{{project_id}}</a></li>
+<li><a href="{% url 'projects:descriptors:list_descriptors' descriptor_type=descriptor_type %}">{{ descriptor_type }} Descriptors</a></li>
+<li><a>{{descriptor_id}}</a></li>
+{% endblock %}
+
+{% block tab_pane_button_list %}
+{{ block.super }}
+<li class="active" id="yaml_li"><a href="#yaml" data-toggle="tab"><i class="fa fa-file-code-o"></i> YAML</a></li>
+<li id="json_li"><a href="#json" data-toggle="tab"><i class="fa fa-file-code-o"></i> JSON</a></li>
+{% endblock %}
+
+{% block nav_buttons_list %}
+    {{ block.super }}
+    <li class="pull-right"><button id="save" type="button" class="btn btn-block btn-primary btn-sm"  onclick="update(this.id)" ><i class="fa fa-save"></i> Update</button></li>
+    <li class="pull-right"><button id="save_show_graph" type="button" class="btn btn-block btn-primary btn-sm"  onclick="update(this.id)" disabled><i class="fa fa-save"></i> Update and Show Graph</button></li>
+    <li class="pull-right"><button type="button" class="btn btn-block btn-primary btn-sm"  onclick="goToGraph()" disabled><i class="fa fa-sitemap"></i> Show Graph</button></li>
+
+{% endblock %}
+
+{% block tab_pane_list %}
+{{ block.super }}
+
+<!-- /.tab-pane -->
+<div class="active tab-pane" id="yaml">
+    <textarea id="code_editor_yaml">
+    </textarea>
+</div>
+<!-- /.tab-pane-->
+
+<div class="tab-pane" id="json">
+    <textarea id="code_editor_json">
+    </textarea>
+</div>
+
+{% endblock %}
+
+{% block resource_block %}
+{{ block.super }}
+
+
+<script>
+    var editorJSON;
+    var editorYaml;
+
+    $(document).ready(function () {
+        //var cmjsoneditor = CodeMirror.fromTextArea(document.getElementById("code_editor"), json_editor_settings);
+        var myJsonTextArea = document.getElementById("code_editor_json");
+        editorJSON = CodeMirror(function (elt) {
+            myJsonTextArea.parentNode.replaceChild(elt, myJsonTextArea);
+        }, json_editor_settings);
+        editorJSON.setValue(JSON.stringify({{descriptor_strings.descriptor_string_json | safe}}, null, "\t"));
+        editorJSON.setOption("autoRefresh", true);
+        editorJSON.setSize("auto", "auto");
+
+        var myYamlTextArea = document.getElementById("code_editor_yaml");
+        editorYaml = CodeMirror(function (elt) {
+            myYamlTextArea.parentNode.replaceChild(elt, myYamlTextArea);
+        }, yaml_editor_settings);
+        var des_strings = {{descriptor_strings | safe}};
+        editorYaml.setValue(des_strings.descriptor_string_yaml);
+        editorYaml.setSize("auto", "auto");
+    });
+
+
+    function update(e) {
+        var dialog = bootbox.dialog({
+            message: '<div class="text-center"><i class="fa fa-spin fa-spinner"></i> Loading...</div>',
+            closeButton: false
+        });
+
+        var id = $('.nav-tabs .active').attr('id');
+        var type, text;
+        switch (id) {
+            case 'yaml_li':
+                type = 'yaml';
+                text = editorYaml.getValue();
+                break;
+            case 'json_li':
+                type = 'json';
+                text = editorJSON.getValue();
+                break;
+        }
+        $.ajax({
+            url: "/projects/descriptors/{{descriptor_type}}/{{descriptor_id}}/",
+            type: 'POST',
+            dataType: 'json',
+            data: {
+                'csrfmiddlewaretoken': '{{csrf_token}}',
+                'type': type,
+                'text': text
+            },
+            success: function (result) {
+                dialog.modal('hide');
+                $("#success-alert").fadeTo(2000, 500).slideDown(500, function(){
+                    setTimeout(function () {
+                        $("#success-alert").slideUp(500);
+                    }, 2000);
+
+                });
+            },
+            error: function (result) {
+                console.log(result);
+                dialog.modal('hide');
+                bootbox.alert(result);
+            }
+        });
+    }
+
+</script>
+{% endblock %}
+
+
+{% block footer %}
+    {% include "footer.html" %}
+{% endblock %}
diff --git a/descriptorhandler/template/descriptor_view_base.html b/descriptorhandler/template/descriptor_view_base.html
new file mode 100644
index 0000000..918e810
--- /dev/null
+++ b/descriptorhandler/template/descriptor_view_base.html
@@ -0,0 +1,141 @@
+{% extends "base.html" %}
+
+{% load staticfiles %}
+
+{% block head_block %}
+  	{{ block.super }}
+
+
+    <!-- Codemirror core CSS -->
+    <link rel="stylesheet" href="/static/bower_components/codemirror/lib/codemirror.css" >
+    <link rel="stylesheet" href="/static/bower_components/codemirror/addon/fold/foldgutter.css"  />
+    <link rel="stylesheet" href="/static/bower_components/codemirror/theme/neat.css" >
+    <link rel="stylesheet" href="/static/bower_components/codemirror/addon/dialog/dialog.css" >
+    <link rel="stylesheet" href="/static/bower_components/codemirror/addon/display/fullscreen.css" >
+
+{% endblock %}
+
+
+
+
+{% block content_body %}
+  	{{ block.super }}
+<div class="row">
+    <div class="col-md-12">
+    <div class="nav-tabs-custom" style="position: relative;">
+    <ul class="nav nav-tabs" >
+        {% block tab_pane_button_list %}
+
+        {% endblock %}
+
+        {% block nav_buttons_list %}
+
+        {% endblock %}
+
+    </ul>
+        <div class="alert alert-success" id="success-alert" style="position: absolute; z-index: 100; top: 44px; left: 0;
+    width: 100%;
+    border-radius: 1px;
+    background-color: rgba(0, 166, 90, 0.8) !important;
+    text-align: center;
+    border-color: rgba(0, 141, 76, 0.4);" hidden>
+            <button type="button" class="close" onclick="$('#success-alert').toggle()">x</button>
+            <strong>Success! </strong>
+            Descriptor updated!
+        </div>
+    <div class="tab-content">
+        {% block tab_pane_list %}
+
+        {% endblock %}
+    </div>
+    <!-- /.tab-content -->
+
+
+
+
+</div>
+
+    </div>
+</div>
+{% endblock %}
+
+{% block resource_block %}
+  	{{ block.super }}
+
+
+    <script src="/static/bower_components/codemirror/lib/codemirror.js" ></script>
+    <script src="/static/bower_components/codemirror/addon/fold/foldcode.js" ></script>
+    <script src="/static/bower_components/codemirror/addon/fold/foldgutter.js" ></script>
+    <script src="/static/bower_components/codemirror/addon/fold/brace-fold.js" ></script>
+    <script src="/static/bower_components/codemirror/mode/javascript/javascript.js" ></script>
+    <script src="/static/bower_components/codemirror/mode/yaml/yaml.js" ></script>
+    <script src="/static/bower_components/codemirror/mode/markdown/markdown.js" ></script>
+    <script src="/static/bower_components/codemirror/addon/search/searchcursor.js" ></script>
+    <script src="/static/bower_components/codemirror/addon/search/search.js" ></script>
+    <script src="/static/bower_components/codemirror/addon/dialog/dialog.js" ></script>
+    <script src="/static/bower_components/codemirror/addon/display/autorefresh.js" ></script>
+    <script src="/static/bower_components/codemirror/addon/edit/matchbrackets.js" ></script>
+    <script src="/static/bower_components/codemirror/addon/edit/closebrackets.js" ></script>
+    <script src="/static/bower_components/codemirror/addon/display/fullscreen.js" ></script>
+    <script src="/static/bower_components/codemirror/keymap/sublime.js" ></script>
+
+
+    <script>
+
+        var json_editor_settings = {
+            mode: "javascript",
+            showCursorWhenSelecting: true,
+            autofocus: true,
+            lineNumbers: true,
+            lineWrapping: true,
+            foldGutter: true,
+            gutters: ["CodeMirror-linenumbers", "CodeMirror-foldgutter"],
+            autoCloseBrackets: true,
+            matchBrackets: true,
+            extraKeys: {
+                "F11": function (cm) {
+                    cm.setOption("fullScreen", !cm.getOption("fullScreen"));
+                },
+                "Esc": function (cm) {
+                    if (cm.getOption("fullScreen")) cm.setOption("fullScreen", false);
+                },
+                "Ctrl-Q": function (cm) {
+                    cm.foldCode(cm.getCursor());
+                }
+            },
+            theme: "neat",
+            keyMap: "sublime"
+        };
+
+        var yaml_editor_settings = {
+            mode: "yaml",
+            showCursorWhenSelecting: true,
+            autofocus: true,
+            autoRefresh: true,
+            lineNumbers: true,
+            lineWrapping: true,
+            foldGutter: true,
+            gutters: ["CodeMirror-linenumbers", "CodeMirror-foldgutter"],
+            autoCloseBrackets: true,
+            matchBrackets: true,
+            extraKeys: {
+                "F11": function (cm) {
+                    cm.setOption("fullScreen", !cm.getOption("fullScreen"));
+                },
+                "Esc": function (cm) {
+                    if (cm.getOption("fullScreen")) cm.setOption("fullScreen", false);
+                },
+                "Ctrl-Q": function (cm) {
+                    cm.foldCode(cm.getCursor());
+                }
+            },
+            theme: "neat",
+            keyMap: "sublime"
+        };
+
+
+        function goToGraph() {
+            window.location.href = '/projects/graph?type={{descriptor_type}}&id={{descriptor_id}}'
+        }
+    </script>
+{% endblock %}
diff --git a/descriptorhandler/template/descriptorlist.html b/descriptorhandler/template/descriptorlist.html
new file mode 100644
index 0000000..9d86624
--- /dev/null
+++ b/descriptorhandler/template/descriptorlist.html
@@ -0,0 +1,47 @@
+{% load staticfiles %}
+{% load get %}
+<div class="col-md-12">
+
+    <div class="box">
+        <div class="box-header with-border">
+            <h3 class="box-title">
+            </h3>
+            <div class="box-tools">
+                <div class="btn-group">
+
+                </div>
+            </div>
+        </div>
+        <div class="box-body">
+            <table id="descriptors_table" class="table table-bordered table-striped dataTable"
+                   role="grid">
+                <thead>
+                <tr role="row">
+                    <th>Name</th>
+                    <th>Identified</th>
+                    <th>Description</th>
+                    <th style="width:10%">Vendor</th>
+                    <th style="width:5%">Version</th>
+                    <th style="width:35%">Actions</th>
+                </tr>
+                </thead>
+                <tbody>
+
+                </tbody>
+
+            </table>
+        </div>
+    </div>
+</div>
+
+<div class="col-sm-12">
+    <div class="box box-solid">
+        <div class="box-body">
+
+            <div class="upload-drop-zone" id="drop-zone">
+               <i class="fa fa-upload"></i> Just drag and drop files here
+            </div>
+        </div>
+    </div>
+</div>
+
diff --git a/descriptorhandler/template/modal/choose_node_id.html b/descriptorhandler/template/modal/choose_node_id.html
new file mode 100644
index 0000000..91c4d20
--- /dev/null
+++ b/descriptorhandler/template/modal/choose_node_id.html
@@ -0,0 +1 @@
+{% extends "descriptor/modal/choose_node_id.html" %}
\ No newline at end of file
diff --git a/descriptorhandler/template/modal/create_link_chooser.html b/descriptorhandler/template/modal/create_link_chooser.html
new file mode 100644
index 0000000..ed9a4a5
--- /dev/null
+++ b/descriptorhandler/template/modal/create_link_chooser.html
@@ -0,0 +1,21 @@
+<div class="modal" id="modal_create_link_chooser">
+  <div class="modal-dialog">
+    <div class="modal-content">
+      <div class="modal-header">
+        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
+          <span aria-hidden="true">×</span></button>
+        <h4 class="modal-title" id="modal_chooser_title">Default Modal</h4>
+      </div>
+      <div class="modal-body" >
+          <select class="form-control" id="selection_chooser">
+          </select>
+    </div>
+      <div class="modal-footer">
+        <button type="button" class="btn btn-default pull-left" data-dismiss="modal">Close</button>
+        <button type="button" class="btn btn-primary" id="save_chooser">Save changes</button>
+      </div>
+    </div>
+    <!-- /.modal-content -->
+  </div>
+  <!-- /.modal-dialog -->
+</div>
\ No newline at end of file
diff --git a/descriptorhandler/urls.py b/descriptorhandler/urls.py
new file mode 100644
index 0000000..c6e987e
--- /dev/null
+++ b/descriptorhandler/urls.py
@@ -0,0 +1,30 @@
+#
+#   Copyright 2018 EveryUP Srl
+#
+#   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  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.
+#
+
+from django.conf.urls import url
+from descriptorhandler import views
+
+urlpatterns = [
+    url(r'(?P<descriptor_type>\w+)/list$', views.show_descriptors, name='list_descriptors'),
+    url(r'(?P<descriptor_type>\w+)/(?P<descriptor_id>[-\w]+)(/$)', views.edit_descriptor, name='edit_descriptor'),
+    url(r'(?P<descriptor_type>\w+)/(?P<descriptor_id>[-\w]+)/delete$', views.delete_descriptor, name='delete_descriptor'),
+    url(r'(?P<descriptor_type>\w+)/(?P<descriptor_id>[-\w]+)/clone', views.clone_descriptor, name='clone_descriptor'),
+    url(r'(?P<descriptor_type>\w+)/(?P<descriptor_id>[-\w]+)/action/(?P<action_name>[-\w]+)',views.custom_action,
+        name='custom_action'),
+    url(r'(?P<descriptor_type>\w+)/new$', views.new_descriptor, name='new_descriptor'),
+    url(r'composer$', views.open_composer, name='open_composer'),
+    url(r'availablenodes', views.get_available_nodes, name='get_available_nodes'),
+]
diff --git a/descriptorhandler/views.py b/descriptorhandler/views.py
new file mode 100644
index 0000000..8b902af
--- /dev/null
+++ b/descriptorhandler/views.py
@@ -0,0 +1,458 @@
+#
+#   Copyright 2018 EveryUP Srl
+#
+#   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  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.
+#
+
+import json
+import logging
+
+import yaml
+from sf_t3d.decorators import login_required
+from django.http import HttpResponse
+from django.shortcuts import render, redirect
+
+
+from lib.util import Util
+from lib.osm.osmclient.clientv2 import Client
+import authosm.utils as osmutils
+
+logging.basicConfig(level=logging.DEBUG)
+log = logging.getLogger('descriptorhandler/view.py')
+
+
+@login_required
+def show_descriptors(request, descriptor_type=None):
+    user = osmutils.get_user(request)
+    project_id = user.project_id
+    client = Client()
+    print descriptor_type
+    try:
+        if descriptor_type == 'nsd':
+            descriptors = client.nsd_list(user.get_token())
+        elif descriptor_type == 'vnfd':
+            descriptors = client.vnfd_list(user.get_token())
+    except Exception as e:
+        log.exception(e)
+        descriptors = []
+
+    url = 'osm/osm_project_descriptors.html'
+    return __response_handler(request, {
+        'descriptors': descriptors['data'] if descriptors and descriptors['error'] is False else [],
+        'project_id': project_id,
+        'project_type': 'osm',
+        'descriptor_type': descriptor_type
+    }, url)
+
+
+@login_required
+def delete_descriptor(request, descriptor_type=None, descriptor_id=None):
+    user = osmutils.get_user(request)
+    project_id = user.project_id
+    try:
+        client = Client()
+        if descriptor_type == 'nsd':
+            result = client.nsd_delete(user.get_token(), descriptor_id)
+        elif descriptor_type == 'vnfd':
+            result = client.vnfd_delete(user.get_token(), descriptor_id)
+    except Exception as e:
+        log.exception(e)
+        result = {'error': True, 'data': str(e)}
+
+    url = 'osm/osm_project_descriptors.html'
+    descriptors = {}
+    try:
+        if descriptor_type == 'nsd':
+            descriptors = client.nsd_list(user.get_token())
+        elif descriptor_type == 'vnfd':
+            descriptors = client.vnfd_list(user.get_token())
+    except Exception as e:
+        log.exception(e)
+
+    return __response_handler(request, {
+        'descriptors': descriptors['data'] if descriptors and descriptors['error'] is False else [],
+        'project_id': project_id,
+        'project_type': 'osm',
+        'descriptor_type': descriptor_type,
+        'alert_message': {
+            'success': False if result['error'] is True else True,
+            'message': 'An error occurred while processing your request.' if result and result['error'] is True else "Record deleted successfully"}
+    }, url)
+
+
+@login_required
+def clone_descriptor(request, descriptor_type=None, descriptor_id=None):
+    user = osmutils.get_user(request)
+    project_id = user.project_id
+
+    try:
+        client = Client()
+        if descriptor_type == 'nsd':
+            result = client.nsd_clone(user.get_token(), descriptor_id)
+        elif descriptor_type == 'vnfd':
+            result = client.vnfd_clone(user.get_token(), descriptor_id)
+        else:
+            log.debug('Update descriptor: Unknown data type')
+            result = {'error': True, 'data': 'Update descriptor: Unknown data type'}
+    except Exception as e:
+        log.exception(e)
+        result = {'error': True, 'data': str(e)}
+    if result['error'] == True:
+        return __response_handler(request, result['data'], url=None,
+                                  status=result['data']['status'] if 'status' in result['data'] else 500)
+
+    else:
+        return __response_handler(request, {}, url=None, status=200)
+
+
+@login_required
+def new_descriptor(request, descriptor_type=None):
+    user = osmutils.get_user(request)
+    project_id = user.project_id
+    page = 'descriptor_new.html'
+    if request.method == 'GET':
+        request_id = request.GET.get('id', '')
+
+        return __response_handler(request,  {
+            'project_id': project_id,
+            'descriptor_type': descriptor_type,
+            'descriptor_id': request_id,
+        }, page)
+    elif request.method == 'POST':
+        data_type = request.POST.get('type')
+        if data_type == "file":
+            file_uploaded = request.FILES['file']
+
+            try:
+                client = Client()
+                if descriptor_type == 'nsd':
+                    result = client.nsd_onboard(user.get_token(), file_uploaded)
+                elif descriptor_type == 'vnfd':
+                    result = client.vnfd_onboard(user.get_token(), file_uploaded)
+                else:
+                    log.debug('Create descriptor: Unknown data type')
+                    result = {'error': True, 'data': 'Create descriptor: Unknown data type'}
+
+            except Exception as e:
+                log.exception(e)
+                result = {'error': True, 'data': str(e)}
+        else:
+            result = {'error': True, 'data': 'Create descriptor: Unknown data type'}
+
+        if result['error']:
+            return __response_handler(request, result['data'], url=None, status=result['data']['status'] if 'status' in result['data'] else 500)
+        else:
+            return __response_handler(request, {}, url=None, status=200)
+
+
+@login_required
+def edit_descriptor(request, descriptor_id=None, descriptor_type=None):
+    user = osmutils.get_user(request)
+    project_id = user.project_id
+    if request.method == 'POST':
+        new_data = request.POST.get('text'),
+        data_type = request.POST.get('type')
+        #print new_data
+        try:
+            client = Client()
+            if descriptor_type == 'nsd':
+                if data_type == 'yaml':
+                    new_data = yaml.load(request.POST.get('text'))
+                elif data_type == 'json':
+                    new_data = json.loads(request.POST.get('text'))
+                result = client.nsd_update(user.get_token(), descriptor_id, new_data)
+            elif descriptor_type == 'vnfd':
+                if data_type == 'yaml':
+                    new_data = yaml.load(request.POST.get('text'))
+                elif data_type == 'json':
+                    new_data = json.loads(request.POST.get('text'))
+                result = client.vnfd_update(user.get_token(), descriptor_id, new_data)
+
+            else:
+                log.debug('Update descriptor: Unknown data type')
+                result = {'error': True, 'data': 'Update descriptor: Unknown data type'}
+        except Exception as e:
+            log.exception(e)
+            result = {'error': True, 'data': str(e)}
+        if result['error'] == True:
+            return __response_handler(request, result['data'], url=None, status=result['data']['status'] if 'status' in result['data'] else 500)
+
+        else:
+            return __response_handler(request, {}, url=None, status=200)
+
+    elif request.method == 'GET':
+
+        page = 'descriptor_view.html'
+        try:
+            client = Client()
+            if descriptor_type == 'nsd':
+                result = client.nsd_get(user.get_token(), descriptor_id)
+            elif descriptor_type == 'vnfd':
+                result = client.vnfd_get(user.get_token(), descriptor_id)
+
+        except Exception as e:
+            log.exception(e)
+            result = {'error': True, 'data': str(e)}
+
+        if isinstance(result, dict) and 'error' in result and result['error']:
+            return render(request, 'error.html')
+
+        descriptor_string_json = json.dumps(result, indent=2)
+        descriptor_string_yaml = Util.json2yaml(result)
+        # print descriptor
+        return render(request, page, {
+            'project_id': project_id,
+            'descriptor_id': descriptor_id,
+            'descriptor_type': descriptor_type,
+            'descriptor_strings': {'descriptor_string_yaml': descriptor_string_yaml,
+                                   'descriptor_string_json': descriptor_string_json}})
+
+
+@login_required
+def get_package_files_list(request, descriptor_id, descriptor_type):
+    user = osmutils.get_user(request)
+    try:
+        client = Client()
+        if descriptor_type == 'nsd':
+            artifacts_res = client.nsd_artifacts(user.get_token(), descriptor_id)
+        elif descriptor_type == 'vnfd':
+            artifacts_res = client.vnf_packages_artifacts(user.get_token(), descriptor_id)
+        else:
+            return False
+
+        files_list = yaml.load(artifacts_res['data'] if artifacts_res and artifacts_res['error'] is False else [])
+        result = {'files': files_list}
+    except Exception as e:
+        log.exception(e)
+        url = 'error.html'
+        result = {'error_msg': 'Unknown error.'}
+    return __response_handler(request, result)
+
+
+@login_required
+def download_pkg(request, descriptor_id, descriptor_type):
+    user = osmutils.get_user(request)
+    file_name = "osm_export.tar.gz"
+    tar_pkg = None
+    try:
+        client = Client()
+        if descriptor_type == 'nsd':
+            tar_pkg = client.get_nsd_pkg(user.get_token(), descriptor_id)
+        elif descriptor_type == 'vnfd':
+            tar_pkg = client.get_vnfd_pkg(user.get_token(), descriptor_id)
+
+    except Exception as e:
+        log.exception(e)
+
+    response = HttpResponse(content_type="application/tgz")
+    response["Content-Disposition"] = "attachment; filename="+ file_name
+    response.write(tar_pkg.getvalue())
+    return response
+
+@login_required
+def open_composer(request):
+    user = osmutils.get_user(request)
+    project_id = user.project_id
+    result = {'project_id': project_id,
+              'vertices': [
+                  {"info": {"type": "vnf", "property": {"custom_label": ""},
+                            "group": []}, "id": "vm"},
+                  {"info": {"type": "vnf", "property": {"custom_label": ""},
+                            "group": []}, "id": "vlan"},
+                  {"info": {"type": "vnf", "property": {"custom_label": ""},
+                            "group": []}, "id": "firewall"},
+                  {"info": {"type": "vnf", "property": {"custom_label": ""},
+                            "group": []}, "id": "ping"},
+
+                  {"info": {"type": "ns_vl", "property": {"custom_label": ""},
+                            "group": []}, "id": "vl1"},
+                  {"info": {"type": "ns_vl", "property": {"custom_label": ""},
+                            "group": []}, "id": "vl2"},
+                  {"info": {"type": "ns_vl", "property": {"custom_label": ""},
+                            "group": []}, "id": "vl3"},
+              ],
+              'edges': [
+                  {"source": "vm", "group": [], "target": "vl3", "view": "ns"},
+                  {"source": "vlan", "group": [], "target": "vl3", "view": "ns"},
+                  {"source": "vlan", "group": [], "target": "vl1", "view": "ns"},
+                  {"source": "firewall", "group": [], "target": "vl1", "view": "ns"},
+                  {"source": "firewall", "group": [], "target": "vl2", "view": "ns"},
+                  {"source": "ping", "group": [], "target": "vl2", "view": "ns"},
+              ],
+              'model': {
+                "layer": {
+
+                    "ns": {
+                        "nodes": {
+                            "vnf": {
+                                "addable": {
+                                    "callback": "addNode"
+                                },
+                                "removable": {
+                                    "callback": "removeNode"
+                                },
+                                "expands": "vnf"
+                            },
+                            "ns_vl": {
+                                "addable": {
+                                    "callback": "addNode"
+                                },
+                                "removable": {
+                                    "callback": "removeNode"
+                                }
+                            },
+
+                        },
+                        "allowed_edges": {
+                            "ns_vl": {
+                                "destination": {
+                                    "vnf": {
+                                        "callback": "addLink",
+                                        "direct_edge": False,
+                                        "removable": {
+                                            "callback": "removeLink"
+                                        }
+                                    }
+                                }
+                            },
+                            "vnf": {
+                                "destination": {
+                                    "ns_vl": {
+                                        "callback": "addLink",
+                                        "direct_edge": False,
+                                        "removable": {
+                                            "callback": "removeLink"
+                                        }
+                                    },
+
+                                }
+                            }
+
+                        }
+                    },
+                    "vnf": {
+                        "nodes": {
+                            "vdu": {
+                                "addable": {
+                                    "callback": "addNode"
+                                },
+                                "removable": {
+                                    "callback": "removeNode"
+                                }
+                            },
+                            "cp": {
+                                "addable": {
+                                    "callback": "addNode"
+                                },
+                                "removable": {
+                                    "callback": "removeNode"
+                                }
+                            },
+
+                        },
+                        "allowed_edges": {
+                            "vdu": {
+                                "destination": {
+                                    "cp": {
+                                        "callback": "addLink",
+                                        "direct_edge": False,
+                                        "removable": {
+                                            "callback": "removeLink"
+                                        }
+                                    }
+                                }
+                            },
+                            "cp": {
+                                "destination": {
+                                    "vdu": {
+                                        "callback": "addLink",
+                                        "direct_edge": False,
+                                        "removable": {
+                                            "callback": "removeLink"
+                                        }
+                                    }
+                                }
+                            }
+                        }
+                    },
+                    "name": "OSM",
+                    "version": 1,
+                    "nodes": {
+                        "vnf": {
+                            "label": "vnf"
+                        },
+                        "ns_vl": {
+                            "label": "vl"
+                        },
+                        "cp": {
+                            "label": "cp"
+                        },
+                        "vdu": {
+                            "label": "vdu"
+                        }
+                    },
+                    "description": "osm",
+                    "callback": {
+                        "addNode": {
+                            "file": "osm_controller.js",
+                            "class": "OsmController"
+                        },
+                        "removeNode": {
+                            "file": "osm_controller.js",
+                            "class": "OsmController"
+                        },
+                        "addLink": {
+                            "file": "osm_controller.js",
+                            "class": "OsmController"
+                        },
+                        "removeLink": {
+                            "file": "osm_controller.js",
+                            "class": "OsmController"
+                        }
+                    }
+
+                }
+            }}
+    return __response_handler(request, result, 'composer.html')
+
+
+def get_available_nodes(request):
+
+    params = request.GET.dict()
+    nodes = {
+        'ns': [{"types": [{"name": "Generic", "id": "vnf"},
+                          {"name": "ping", "id": "vnf"},
+                          {"name": "pong", "id": "vnf"},
+                          {"name": "hackfest1-vm", "id": "vnf"}], "category_name": "Vnf"},
+               {"types": [{"name": "VL", "id": "ns_vl"}], "category_name": "VirtualLink"}],
+        'vnf': [{"types": [{"name": "VDU", "id": "vdu"}], "category_name": "Vdu"},
+                {"types": [{"name": "CP", "id": "cp"}], "category_name": "CP"}]
+    }
+
+    return __response_handler(request, nodes[params['layer']])
+
+
+@login_required
+def custom_action(request, descriptor_id=None, descriptor_type=None, action_name=None):
+    if request.method == 'GET':
+        return globals()[action_name](request, descriptor_id, descriptor_type)
+
+
+def __response_handler(request, data_res, url=None, to_redirect=None, *args, **kwargs):
+    raw_content_types = request.META.get('HTTP_ACCEPT', '*/*').split(',')
+    if 'application/json' in raw_content_types or url is None:
+        return HttpResponse(json.dumps(data_res), content_type="application/json", *args, **kwargs)
+    elif to_redirect:
+        return redirect(url, *args, **kwargs)
+    else:
+        return render(request, url, data_res)