2 from django.shortcuts import render, render_to_response
3 from django.template import RequestContext
4 from django.template.loader import render_to_string
5 from django.views.generic import View
6 from django.core.mail import send_mail
7 from myslice.configengine import ConfigEngine
8 from unfold.loginrequired import FreeAccessView
9 from ui.topmenu import topmenu_items, the_user
10 from myslice.theme import ThemeView
11 from django.contrib.staticfiles.urls import staticfiles_urlpatterns
12 #from portal.forms import ReputationForm
14 from pprint import pprint
15 from manifold.core.query import Query
16 from manifoldapi.manifoldapi import execute_query,execute_admin_query
17 from portal.actions import is_pi, create_slice, create_pending_slice, clear_user_creds
18 from django.utils import simplejson
19 from django.http import *
25 from apgl.graph import *
26 from apgl.generator.ErdosRenyiGenerator import ErdosRenyiGenerator
27 from django.views.decorators.csrf import csrf_exempt
31 # splitting the 2 functions done here
32 # GET is for displaying the empty form
33 # POST is to process it once filled - or show the form again if anything is missing
34 def create_post(request):
36 if request.method == 'POST':
37 post_text = request.POST.get('the_post')
40 post = Post(text=post_text, author=request.user)
43 response_data['result'] = 'Create post successful!'
47 json.dumps(response_data),
48 content_type="application/json"
52 def response_mimetype(request):
55 if "application/json" in request.META['HTTP_ACCEPT']:
56 return "application/json"
60 def connected_graph(vert,possib):
62 ################################################
63 # Connected graph calculation
65 # Requirements for ErdosRenyiGenerator python function
67 # apt-get install gfortran libopenblas-dev liblapack-dev
71 ##################################################
74 #graph = SparseGraph(VertexList(vertices, 1))
75 #generator = ErdosRenyiGenerator(p, selfEdges=False)
77 #for i in range(0,10):
80 time_start = time.time()
82 while not found and time.time()-time_start < iter_time:
83 graph = SparseGraph(VertexList(vertices, 1))
84 generator = ErdosRenyiGenerator(p, selfEdges=False)
85 graph = generator.generate2(graph)
87 #print graph.getAllEdges()
91 #print graph.findConnectedComponents()
92 for list in graph.findConnectedComponents():
93 if len(list)==vertices:
96 if len(connected_list)==vertices:
98 edge_lst = graph.getAllEdges()
99 for item in range(0, len(edge_lst)):
100 links[item]=str(edge_lst[item][0]), str(edge_lst[item][1])
102 if len(connected_list)==vertices:
106 #print graph.getAllEdges()
107 #print connected_list
111 class UnboundReservationView (FreeAccessView, ThemeView):
112 def my_view(request):
114 preset_form = forms.PresetListForm()
116 return render_to_response('services.html', {'array': json.dumps(data, cls=SpecialEncoder),'preset_form': preset_form,
118 def create_post(request):
120 if request.method == 'POST':
121 print("mlsllslssll,sls*************")
122 post_text = request.POST.get('the_post')
125 post = Post(text=post_text, author=request.user)
128 response_data['result'] = 'Create post successful!'
132 json.dumps(response_data),
133 content_type="application/json"
137 json.dumps({"nothing to see": "this isn't happening"}),
138 content_type="application/json"
141 def quiz_guess(request, fact_id):
142 message = {"fact_type": "", "fact_note": ""}
143 if request.is_ajax():
144 fact = get_object_or_404(Fact, id=fact_id)
145 message['fact_type'] = fact.type
146 message['fact_note'] = fact.note
148 message = "You're the lying type, I can just tell."
149 json = simplejson.dumps(message)
150 return HttpResponse(json, mimetype='application/json')
151 def default_env (self):
153 'MANIFOLD_URL':ConfigEngine().manifold_url(),
155 def post (self, request):
156 env = self.default_env()
158 print(request.POST["b"])
160 body1= request.POST["mitsos"]
161 user_urn= request.POST["name"]
162 user_urn=str(user_urn)
164 buffer = StringIO.StringIO()
165 json_data=open('/home/coyiotis/test.json').read()
166 data1 = json.loads(json_data)
167 data=json.dumps(body1)
168 data2=str(unicode(data))
169 json_data_1 = json.loads(body1)
170 json_data_1=json.dumps(json_data_1)
171 json_data_1 =str(unicode(json_data_1))
173 print('*******************************nikos')
175 #print(json_data_1['data'])
176 if request.POST["b"]=="1":
178 c.setopt(pycurl.URL, 'https://194.177.207.2:8001/mapper/')
179 c.setopt(pycurl.HTTPHEADER, ['Content-Type: application/json','Accept: application/json'])
180 c.setopt(pycurl.POST, 1)
181 c.setopt(pycurl.SSL_VERIFYPEER, False)
182 c.setopt(pycurl.SSL_VERIFYHOST, False)
183 c.setopt(pycurl.POSTFIELDS, body1)
184 c.setopt(pycurl.WRITEDATA, buffer)
188 body = buffer.getvalue()
189 # Body is a string in some encoding.
190 # In Python 2, we can print it without knowing what the encoding is.
192 env['responsejson'] = json.dumps(body)
194 body = body.replace('\n', '')
195 #body = body.replace(' ', '')
196 #print(json.dumps(body))
198 #j = json.loads(body)
200 #parent = j["resource_response"]
206 decoded = json.loads(body)
208 # pretty printing of json-formatted string
209 print json.dumps(decoded, sort_keys=True, indent=4)
211 print "JSON parsing example: ", decoded['resource_response']
212 #print len(item_dict['result'][0]['run'])
219 for x in xrange(0, len(decoded['resource_response']['resources'])):
220 end_time=decoded['resource_response']['resources'][x]['valid_until']
221 start_time=decoded['resource_response']['resources'][x]['valid_from']
223 start_time=int(time.mktime(datetime.datetime.strptime(start_time, "%Y-%m-%d %H:%M:%S %Z").timetuple()))
224 end_time=int(time.mktime(datetime.datetime.strptime(end_time, "%Y-%m-%d %H:%M:%S %Z").timetuple()))
227 #print(calendar.timegm(start_time.utctimetuple()))
229 urn=decoded['resource_response']['resources'][x]['urn']
232 'start_time' : start_time,
233 'end_time' : end_time
235 leases_list.append(slice_params)
236 resources.append(urn)
238 print("chrysaAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA")
239 for keys,values in slice_params.items():
244 'resource' : resources,
245 'lease' : leases_list
247 #final_params=str(final_params)
248 #final_params=[{'resource': resources, 'leases':leases_list}]
252 final_params= ast.literal_eval(json.dumps(final_params))
253 query = Query.update('slice').filter_by('slice_hrn', '==', user_urn).set(final_params).select('slice_hrn')
254 #query = Query.update('myslice:slice').filter_by('slice_hrn', '==', user_urn).set(slice_params).select('slice_hrn')
255 results = execute_query(request,query)
256 print("________________________________________________________________________________")
258 print('________________________________________________________________________________')
260 return HttpResponse(json.dumps(body), mimetype='application/json')
261 #return render_to_response('workflow.html', env, context_instance=RequestContext(request))
262 #return render(request, 'workflow.html', {"variable_int" : 12})
263 def get (self, request):
264 buffer = StringIO.StringIO()
265 print("mlsllslssll,sls*************3")
266 #message = {"fact_type": "", "fact_note": ""}
273 if request.is_ajax():
274 print("mlsllslssll,sls*************4")
275 #fact = get_object_or_404(Fact, id=fact_id)
276 # message['fact_type'] = fact.type
277 # message['fact_note'] = fact.note
279 # message = "You're the lying type, I can just tell."
280 # json = simplejson.dumps(message)
281 if request.GET.has_key('node-num2'):
283 child="{\"type\":\"Node\",\"valid_form\":"+request.GET['fromdate']+",\"valid_until\":"+request.GET['todate']+",\"exclusive\": true}"
284 for index in range(int(request.GET['node-num'])):
287 child1=child1+",{\"type\":\"Node\",\"valid_form\":"+"\""+request.GET['fromdate']+"\""+",\"valid_until\":"+"\""+request.GET['todate']+"\""+",\"exclusive\":true}"
289 child1="{\"type\":\"Node\",\"valid_form\":"+"\""+request.GET['fromdate']+"\""+",\"valid_until\":"+"\""+request.GET['todate']+"\""+",\"exclusive\":true}"
294 jchilds="{\"resources\":["+child1+"]\"\"}"
295 #print(request.GET['jsondata'])
297 c.setopt(pycurl.URL, 'https://194.177.207.2:8001/mapper/')
298 c.setopt(pycurl.HTTPHEADER, ['Content-Type: application/json','Accept: application/json'])
299 c.setopt(pycurl.POST, 1)
300 c.setopt(pycurl.SSL_VERIFYPEER, False)
301 c.setopt(pycurl.SSL_VERIFYHOST, False)
302 c.setopt(pycurl.POSTFIELDS, request.GET['jsondata'])
303 c.setopt(pycurl.WRITEDATA, buffer)
307 body = buffer.getvalue()
309 #return HttpResponse(json.dumps(body), mimetype='application/json')
310 #response_dict = {'1':request.GET['node-
311 #jnum'], '2':request.GET['node-num2']}
312 #links = connected_graph(int(request.GET['node-num']),float(request.GET['node-num2'])/100)
313 #===================================================================
314 #for item in range(0,len(links)):
315 #child[item]=links[item]
316 #===== =============================================================
318 jsonchilds=json.dumps(childs)
320 json_stuff = simplejson.dumps({'links': links, 'body': body})
321 print '**********************************BP 1 *********************************'+request.GET['jsondata']
322 print '**********************************BP 2 *********************************'+body
323 if links == 'not_found':
324 #return HttpResponse(simplejson.dumps(['false']), content_type = response_mimetype(self.request))
325 return HttpResponse(content='false', mimetype=DEFAULT_CONTENT_TYPE)
327 return HttpResponse(json_stuff, content_type = response_mimetype(self.request))
328 #return HttpResponse(simplejson.dumps(response_dict), mimetype='application/javascript')
329 #return HttpResponse(json, mimetype='application/json')
330 return self._display (request)
332 def _display (self, request):
333 return render(request, 'workflow_b.html', {
334 'topmenu_items': topmenu_items('Unbound Request', request),
335 'username': the_user (request)