Ejemplo n.º 1
0
def plan_tests(request, plan_id, editable=True):
    templates = get_handlebars_templates(settings.XGDS_PLANNER2_HANDLEBARS_DIRS, 'XGDS_PLANNER2_HANDLEBARS_DIRS')

    plan = PLAN_MODEL.get().objects.get(pk=plan_id)
    plan_json = plan.jsonPlan
    if not plan_json.serverId:
        plan_json.serverId = plan.pk
    if "None" in plan_json.url:
        plan_json.url = plan.get_absolute_url()

    planSchema = models.getPlanSchema(plan_json.platform.name)
    
    return render(request,
                  'xgds_planner2/planner_tests.html',
                  {'templates': templates,
                   'plan_schema_json': planSchema.getJsonSchema(),  # xpjson.dumpDocumentToString(planSchema.getSchema()),
                   'plan_library_json': planSchema.getJsonLibrary(),  # xpjson.dumpDocumentToString(planSchema.getLibrary()),
                   'plan_json': json.dumps(plan_json),
                   'plan_name': plan.name,
                   'plan_index_json': json.dumps(plan_index_json()),
                   'editable': editable,
                   'simulatorUrl': planSchema.simulatorUrl,
                   'simulator': planSchema.simulator,
                   'placemark_circle_url': request.build_absolute_uri(staticfiles_storage.url('xgds_planner2/images/placemark_circle.png')),
                   'placemark_circle_highlighted_url': request.build_absolute_uri(staticfiles_storage.url('xgds_planner2/images/placemark_circle_highlighted.png')),
                   'plan_links_json': json.dumps(plan.getLinks()),
                   'plan_namedURLs_json': json.dumps(plan.namedURLs),
                   })
Ejemplo n.º 2
0
    def initPlan(self, plan, context):
        if not self.startTime:
            if context.startTime:
                self.startTime = context.startTime
            else:
                self.startTime = datetime.datetime.now(pytz.utc)
        try:
            fullPlanSchema = getPlanSchema(plan.platform.name)
            simulatorPath = fullPlanSchema.simulatorUrl
            if simulatorPath.startswith('/static/'):
                simulatorPath = simulatorPath[8:]
            fullpath = os.path.join(settings.STATIC_ROOT, simulatorPath)
            simulator_file = open(fullpath)  # urlopen
            simulator_contents = simulator_file.read()
            regex = re.compile('.*DRIVE_TIME_MULTIPLIER\s*=\s*(\d+\.*\d*);')
            searchResults = regex.search(simulator_contents)
            result = regex.findall(searchResults.group(0))
            if result:
                self.DRIVE_TIME_MULTIPLIER = float(result[0])

            regex = re.compile('.*ROTATION_ADDITION\s*=\s*(\d+\.*\d*);')
            searchResults = regex.search(simulator_contents)
            rotation_result = regex.findall(searchResults.group(0))
            if rotation_result:
                self.ROTATION_ADDITION = float(rotation_result[0])
        except:
            simulator_file.close()
            self.DRIVE_TIME_MULTIPLIER = 1.0
            self.ROTATION_ADDITION = 0.0
Ejemplo n.º 3
0
    def initPlan(self, plan, context):
        if not self.startTime:
            if context.startTime:
                self.startTime = context.startTime
            else:
                self.startTime = datetime.datetime.now(pytz.utc)
        try:
            fullPlanSchema = getPlanSchema(plan.platform.name)
            simulatorPath = fullPlanSchema.simulatorUrl
            if simulatorPath.startswith('/static/'):
                simulatorPath = simulatorPath[8:]
            fullpath = os.path.join(settings.STATIC_ROOT, simulatorPath)
            simulator_file = open(fullpath) # urlopen
            simulator_contents = simulator_file.read()
            regex = re.compile('.*DRIVE_TIME_MULTIPLIER\s*=\s*(\d+\.*\d*);')
            searchResults = regex.search(simulator_contents)
            result = regex.findall(searchResults.group(0))
            if result:
                self.DRIVE_TIME_MULTIPLIER = float(result[0])

            regex = re.compile('.*ROTATION_ADDITION\s*=\s*(\d+\.*\d*);')
            searchResults = regex.search(simulator_contents)
            rotation_result = regex.findall(searchResults.group(0))
            if rotation_result:
                self.ROTATION_ADDITION = float(rotation_result[0])
        except:
            simulator_file.close()
            self.DRIVE_TIME_MULTIPLIER = 1.0
            self.ROTATION_ADDITION = 0.0
Ejemplo n.º 4
0
def plan_tests(request, plan_id, editable=True):
    templates = get_handlebars_templates(settings.XGDS_PLANNER2_HANDLEBARS_DIRS, 'XGDS_PLANNER2_HANDLEBARS_DIRS')

    plan = PLAN_MODEL.get().objects.get(pk=plan_id)
    plan_json = plan.jsonPlan
    if not plan_json.serverId:
        plan_json.serverId = plan.pk
    if "None" in plan_json.url:
        plan_json.url = plan.get_absolute_url()

    planSchema = models.getPlanSchema(plan_json.platform.name)
#     print planSchema.getJsonSchema();
    return render_to_response(
        'xgds_planner2/planner_tests.html',
        RequestContext(request, {
            'templates': templates,
            'plan_schema_json': planSchema.getJsonSchema(),  # xpjson.dumpDocumentToString(planSchema.getSchema()),
            'plan_library_json': planSchema.getJsonLibrary(),  # xpjson.dumpDocumentToString(planSchema.getLibrary()),
            'plan_json': json.dumps(plan_json),
            'plan_name': plan.name,
            'plan_index_json': json.dumps(plan_index_json()),
            'editable': editable,
            'simulatorUrl': planSchema.simulatorUrl,
            'simulator': planSchema.simulator,
            'placemark_circle_url': request.build_absolute_uri(
                staticfiles_storage.url('xgds_planner2/images/placemark_circle.png')
            ),
            'placemark_circle_highlighted_url': request.build_absolute_uri(
                staticfiles_storage.url('xgds_planner2/images/placemark_circle_highlighted.png')
            ),
            'plan_links_json': json.dumps(plan.getLinks()),
            'plan_namedURLs_json': json.dumps(plan.namedURLs),
        }),
        # context_instance=RequestContext
    )
Ejemplo n.º 5
0
def planImport(request):
    if request.method == 'GET':
        messages.info(request, 'You can create a ' +  settings.XGDS_PLANNER2_PLAN_MONIKER + ' by importing a kml file containing a LineString.')
        messages.info(request, 'Alternately you can import a csv file, which must have column headers of latitude and longitude.')
        form = ImportPlanForm()
    elif request.method == 'POST':
        form = ImportPlanForm(request.POST, request.FILES)
        if form.is_valid():
            # add plan entry to database
            meta = dict([(f, form.cleaned_data[f])
                         for f in ('planNumber', 'planVersion')])
            meta['creator'] = request.user.username
            planSchema = models.getPlanSchema(form.cleaned_data['platform'])
            
            # set the site
            siteID = form.cleaned_data['site']
            if siteID:
                sites = planSchema.getLibrary().sites
                for site in sites:
                    if site.id == siteID:
                        # TODO FIX this has all sorts of formatting problems /n inserted.
                        # meta['site'] = xpjson.dumpDocumentToString(site)

                        hackSite = {"type": "Site",
                                    "name": site.name,
                                    "id": site.id,
                                    "notes": site.notes}
                        if site.bbox:
                            hackSite["bbox"] = site.bbox
                        if site.alternateCrs:
                            hackSite["alternateCrs"] = site.alternateCrs
                        meta['site'] = hackSite
                        break

            importer = choosePlanImporter.chooseImporter(form.cleaned_data['sourceFile'].name)
            f = request.FILES['sourceFile']
            buf = ''.join([chunk for chunk in f.chunks()])
    
            dbPlan = importer.importPlan('tempName',
                                         buf=buf,
                                         meta=meta,
                                         planSchema=planSchema)

            # bit of a hack, setting the name from the id
            planId = dbPlan.jsonPlan.id
            dbPlan.jsonPlan["name"] = planId
            dbPlan.jsonPlan["uuid"] = dbPlan.uuid # makeUuid()
            dbPlan.name = planId

            dbPlan.save()
            handleCallbacks(request, dbPlan, settings.SAVE)

            # redirect to plan editor on newly created plan
            return HttpResponseRedirect(reverse('planner2_edit', args=[dbPlan.pk]))
    else:
        return HttpResponseNotAllowed(['GET', 'POST'])
    return render(request,
                  'xgds_planner2/planCreate.html',
                  {'form': form,
                   'siteLabel': 'Import'})
Ejemplo n.º 6
0
def planImport(request):
    if request.method == 'GET':
        messages.info(request, 'You can create a ' +  settings.XGDS_PLANNER2_PLAN_MONIKER + ' by importing a kml file containing a LineString.')
        messages.info(request, 'Alternately you can import a csv file, which must have column headers of latitude and longitude.')
        form = ImportPlanForm()
    elif request.method == 'POST':
        form = ImportPlanForm(request.POST, request.FILES)
        if form.is_valid():
            # add plan entry to database
            meta = dict([(f, form.cleaned_data[f])
                         for f in ('planNumber', 'planVersion')])
            meta['creator'] = request.user.username
            planSchema = models.getPlanSchema(form.cleaned_data['platform'])
            
            # set the site
            siteID = form.cleaned_data['site']
            if siteID:
                sites = planSchema.getLibrary().sites
                for site in sites:
                    if site.id == siteID:
                        # TODO FIX this has all sorts of formatting problems /n inserted.
                        # meta['site'] = xpjson.dumpDocumentToString(site)

                        hackSite = {"type": "Site",
                                    "name": site.name,
                                    "id": site.id,
                                    "notes": site.notes}
                        if site.bbox:
                            hackSite["bbox"] = site.bbox
                        if site.alternateCrs:
                            hackSite["alternateCrs"] = site.alternateCrs
                        meta['site'] = hackSite
                        break

            importer = choosePlanImporter.chooseImporter(form.cleaned_data['sourceFile'].name)
            f = request.FILES['sourceFile']
            buf = ''.join([chunk for chunk in f.chunks()])
    
            dbPlan = importer.importPlan('tempName',
                                         buf=buf,
                                         meta=meta,
                                         planSchema=planSchema)

            # bit of a hack, setting the name from the id
            planId = dbPlan.jsonPlan.id
            dbPlan.jsonPlan["name"] = planId
            dbPlan.jsonPlan["uuid"] = dbPlan.uuid # makeUuid()
            dbPlan.name = planId

            dbPlan.save()
            handleCallbacks(request, dbPlan, settings.SAVE)

            # redirect to plan editor on newly created plan
            return HttpResponseRedirect(reverse('planner2_edit', args=[dbPlan.pk]))
    else:
        return HttpResponseNotAllowed(['GET', 'POST'])
    return render_to_response('xgds_planner2/planCreate.html',
                              RequestContext(request,{'form': form,
                                                      'siteLabel': 'Import'}))
Ejemplo n.º 7
0
def validateJson(newJsonObj):
    ''' Validate input json against defined schema
    '''
    try:
        theSchema = getPlanSchema(newJsonObj['platform']['name'])
        loadDocumentFromDict(convertToDotDictRecurse(newJsonObj), theSchema.schema)
        return True
    except Exception, e:
        return "Invalid JSON: " + str(e)
Ejemplo n.º 8
0
def plan_editor_app(request, plan_id=None, editable=True):
    templates = get_handlebars_templates(settings.XGDS_PLANNER2_HANDLEBARS_DIRS, 'XGDS_PLANNER2_HANDLEBARS_DIRS')

    plan = PLAN_MODEL.get().objects.get(pk=plan_id)
    dirty = False
    if not plan.jsonPlan.serverId:
        plan.jsonPlan.serverId = plan.pk
        dirty = True
    if "None" in plan.jsonPlan.url:
        plan.jsonPlan.url = plan.get_absolute_url()
        dirty = True
        
    if dirty:
        plan.save()

    planSchema = models.getPlanSchema(plan.jsonPlan.platform.name)
    pe = None
    try:
        if plan.executions and plan.executions.count() > 0:
            pe = json.dumps(plan.executions.all()[0].toSimpleDict(), cls=DatetimeJsonEncoder)
    except:
        pass

    context = {
            'templates': templates,
            'app': 'xgds_planner2/js/plannerApp.js',
            'saveSearchForm': MapSearchForm(),
            'searchForms': getSearchForms(),
            'flight_names': json.dumps(getAllFlightNames()),
            'plan_schema_json': planSchema.getJsonSchema(),  # xpjson.dumpDocumentToString(planSchema.getSchema()),
            'plan_library_json': planSchema.getJsonLibrary(),  # xpjson.dumpDocumentToString(planSchema.getLibrary()),
            'plan_json': json.dumps(plan.jsonPlan),
            'plan_name': plan.name,
            'plan_execution': pe,
            'plan_index_json': json.dumps(plan_index_json()),
            'editable': editable and not plan.readOnly,
            'simulatorUrl': planSchema.simulatorUrl,
            'simulator': planSchema.simulator,
            'placemark_circle_url': request.build_absolute_uri(
                staticfiles_storage.url('xgds_planner2/images/placemark_circle.png')
            ),
            'placemark_circle_highlighted_url': request.build_absolute_uri(
                staticfiles_storage.url('xgds_planner2/images/placemark_circle_highlighted.png')
            ),
            'placemark_directional_url': request.build_absolute_uri(
                staticfiles_storage.url('xgds_planner2/images/placemark_directional.png')
            ),
            'placemark_selected_directional_url': request.build_absolute_uri(
                staticfiles_storage.url('xgds_planner2/images/placemark_directional_highlighted.png')
            ),
            'plan_links_json': json.dumps(plan.getLinks())
        }

    return render_to_response(
        'xgds_planner2/planner_app.html',
        RequestContext(request, getClassByName(settings.XGDS_PLANNER2_EDITOR_CONTEXT_METHOD)(context)),
    )
Ejemplo n.º 9
0
def validateJson(newJsonObj):
    ''' Validate input json against defined schema
    '''
    try:
        theSchema = getPlanSchema(newJsonObj['platform']['name'])
        loadDocumentFromDict(convertToDotDictRecurse(newJsonObj), theSchema.schema)
        return True
    except Exception, e:
        return "Invalid JSON: " + str(e)
Ejemplo n.º 10
0
def planCreate(request):
    if request.method == 'GET':
        form = CreatePlanForm()
    elif request.method == 'POST':
        form = CreatePlanForm(request.POST)
        if form.is_valid():
            # add plan entry to database
            meta = dict([(f, form.cleaned_data[f])
                         for f in ('planNumber', 'planVersion')])
            meta['creator'] = request.user.username
            importer = planImporter.BlankPlanImporter()
            planSchema = models.getPlanSchema(form.cleaned_data['platform'])

            # set the site
            siteID = form.cleaned_data['site']
            if siteID:
                sites = planSchema.getLibrary().sites
                for site in sites:
                    if site.id == siteID:
                        # TODO FIX this has all sorts of formatting problems /n inserted.
                        # meta['site'] = xpjson.dumpDocumentToString(site)

                        hackSite = {"type": "Site",
                                    "name": site.name,
                                    "id": site.id,
                                    "notes": site.notes}
                        if site.bbox:
                            hackSite["bbox"] = site.bbox
                        if site.alternateCrs:
                            hackSite["alternateCrs"] = site.alternateCrs
                        meta['site'] = hackSite
                        break

            dbPlan = importer.importPlan('tempName',
                                         buf=None,
                                         meta=meta,
                                         planSchema=planSchema)

            # bit of a hack, setting the name from the id
            planId = dbPlan.jsonPlan.id
            dbPlan.jsonPlan["name"] = planId
            dbPlan.jsonPlan["uuid"] = dbPlan.uuid # makeUuid()
            dbPlan.name = planId

            dbPlan.save()
            handleCallbacks(request, dbPlan, settings.SAVE)


            # redirect to plan editor on newly created plan
            return HttpResponseRedirect(reverse('planner2_edit', args=[dbPlan.pk]))
    else:
        return HttpResponseNotAllowed(['GET', 'POST'])
    return render(request,
                  'xgds_planner2/planCreate.html',
                  {'form': form,
                   'siteLabel':'Create'})
Ejemplo n.º 11
0
def plan_editor_app(request, plan_id=None, editable=True):
    templates = get_handlebars_templates(settings.XGDS_PLANNER2_HANDLEBARS_DIRS, 'XGDS_PLANNER2_HANDLEBARS_DIRS')

    plan = PLAN_MODEL.get().objects.get(pk=plan_id)
    dirty = False
    if not plan.jsonPlan.serverId:
        plan.jsonPlan.serverId = plan.pk
        dirty = True
    if "None" in plan.jsonPlan.url:
        plan.jsonPlan.url = plan.get_absolute_url()
        dirty = True
        
    if dirty:
        plan.save()

    planSchema = models.getPlanSchema(plan.jsonPlan.platform.name)
    pe = None
    try:
        if plan.executions and plan.executions.count() > 0:
            pe = json.dumps(plan.executions.all()[0].toSimpleDict(), cls=DatetimeJsonEncoder)
    except:
        pass

    context = {
            'templates': templates,
            'app': 'xgds_planner2/js/plannerApp.js',
            'saveSearchForm': MapSearchForm(),
            'searchForms': getSearchForms(),
            'flight_names': json.dumps(getAllFlightNames()),
            'plan_schema_json': planSchema.getJsonSchema(),  # xpjson.dumpDocumentToString(planSchema.getSchema()),
            'plan_library_json': planSchema.getJsonLibrary(),  # xpjson.dumpDocumentToString(planSchema.getLibrary()),
            'plan_json': json.dumps(plan.jsonPlan),
            'plan_name': plan.name,
            'plan_execution': pe,
            'plan_index_json': json.dumps(plan_index_json()),
            'editable': editable and not plan.readOnly,
            'simulatorUrl': planSchema.simulatorUrl,
            'simulator': planSchema.simulator,
            'placemark_circle_url': request.build_absolute_uri(
                staticfiles_storage.url('xgds_planner2/images/placemark_circle.png')
            ),
            'placemark_circle_highlighted_url': request.build_absolute_uri(
                staticfiles_storage.url('xgds_planner2/images/placemark_circle_highlighted.png')
            ),
            'placemark_directional_url': request.build_absolute_uri(
                staticfiles_storage.url('xgds_planner2/images/placemark_directional.png')
            ),
            'placemark_selected_directional_url': request.build_absolute_uri(
                staticfiles_storage.url('xgds_planner2/images/placemark_directional_highlighted.png')
            ),
            'plan_links_json': json.dumps(plan.getLinks())
        }

    return render(request,
                  'xgds_planner2/planner_app.html',
                  getClassByName(settings.XGDS_PLANNER2_EDITOR_CONTEXT_METHOD)(context))
Ejemplo n.º 12
0
def planCreate(request):
    if request.method == 'GET':
        form = CreatePlanForm()
    elif request.method == 'POST':
        form = CreatePlanForm(request.POST)
        if form.is_valid():
            # add plan entry to database
            meta = dict([(f, form.cleaned_data[f])
                         for f in ('planNumber', 'planVersion')])
            meta['creator'] = request.user.username
            importer = planImporter.BlankPlanImporter()
            planSchema = models.getPlanSchema(form.cleaned_data['platform'])

            # set the site
            siteID = form.cleaned_data['site']
            if siteID:
                sites = planSchema.getLibrary().sites
                for site in sites:
                    if site.id == siteID:
                        # TODO FIX this has all sorts of formatting problems /n inserted.
                        # meta['site'] = xpjson.dumpDocumentToString(site)

                        hackSite = {"type": "Site",
                                    "name": site.name,
                                    "id": site.id,
                                    "notes": site.notes}
                        if site.bbox:
                            hackSite["bbox"] = site.bbox
                        if site.alternateCrs:
                            hackSite["alternateCrs"] = site.alternateCrs
                        meta['site'] = hackSite
                        break

            dbPlan = importer.importPlan('tempName',
                                         buf=None,
                                         meta=meta,
                                         planSchema=planSchema)

            # bit of a hack, setting the name from the id
            planId = dbPlan.jsonPlan.id
            dbPlan.jsonPlan["name"] = planId
            dbPlan.jsonPlan["uuid"] = dbPlan.uuid # makeUuid()
            dbPlan.name = planId

            dbPlan.save()
            handleCallbacks(request, dbPlan, settings.SAVE)


            # redirect to plan editor on newly created plan
            return HttpResponseRedirect(reverse('planner2_edit', args=[dbPlan.pk]))
    else:
        return HttpResponseNotAllowed(['GET', 'POST'])
    return render_to_response('xgds_planner2/planCreate.html',
                              RequestContext(request,{'form': form,
                                                      'siteLabel':'Create'}))
Ejemplo n.º 13
0
def plan_detail_doc(request, plan_id=None):
    plan = PLAN_MODEL.get().objects.get(pk=plan_id)
    plan_json = plan.jsonPlan
    if not plan_json.serverId:
        plan_json.serverId = plan.pk
    if "None" in plan_json.url:
        plan_json.url = plan.get_absolute_url()

    planSchema = models.getPlanSchema(plan_json.platform.name)
    return render(request,
                  'xgds_planner2/planDetailDoc.html',
                  {'plan_json': plan_json,
                   'plan_schema': json.loads(planSchema.getJsonSchema()),
                   'plan_library': json.loads(planSchema.getJsonLibrary())})
Ejemplo n.º 14
0
def plan_detail_doc(request, plan_id=None):
    plan = PLAN_MODEL.get().objects.get(pk=plan_id)
    plan_json = plan.jsonPlan
    if not plan_json.serverId:
        plan_json.serverId = plan.pk
    if "None" in plan_json.url:
        plan_json.url = plan.get_absolute_url()

    planSchema = models.getPlanSchema(plan_json.platform.name)
    return render_to_response(
        'xgds_planner2/planDetailDoc.html',
        RequestContext(request,
                       {'plan_json': plan_json,
                        'plan_schema': json.loads(planSchema.getJsonSchema()),
                        'plan_library': json.loads(planSchema.getJsonLibrary())}))
Ejemplo n.º 15
0
 def exportDbPlan(self, dbPlan):
     try:
         platform = dbPlan.jsonPlan['platform']
         planSchema = getPlanSchema(platform["name"])
         plan = dbPlan.toXpjson()
         try:
             if dbPlan.executions.count():
                 pe = dbPlan.executions.first()
                 self.startTime = pe.planned_start_time
                 self.vehicle = str(pe.flight.vehicle.name)
         except:
             pass
         return self.exportPlan(plan, planSchema.getSchema())
     except:
         logging.warning('exportDbPlan: could not save plan %s', dbPlan.name)
         raise  # FIX
Ejemplo n.º 16
0
 def exportDbPlan(self, dbPlan):
     try:
         platform = dbPlan.jsonPlan['platform']
         planSchema = getPlanSchema(platform["name"])
         plan = dbPlan.toXpjson()
         try:
             if dbPlan.executions.count():
                 pe = dbPlan.executions.first()
                 self.startTime = pe.planned_start_time
                 self.vehicle = str(pe.flight.vehicle.name)
         except:
             pass
         return self.exportPlan(plan, planSchema.getSchema())
     except:
         logging.warning('exportDbPlan: could not save plan %s',
                         dbPlan.name)
         raise  # FIX
Ejemplo n.º 17
0
def getSiteFrames():
    if not settings.XGDS_PLANNER2_SITE_FRAMES:
        platforms = sorted(settings.XGDS_PLANNER_SCHEMAS.keys())
        try:
            platforms.remove("test")
        except ValueError:
            pass

        for platform in platforms:
            schema = getPlanSchema(platform)
            library = schema.getLibrary()
            sites = library.sites
            if sites:
                for site in sites:
                    try:
                        if site.alternateCrs:
                            settings.XGDS_PLANNER2_SITE_FRAMES.append(site)
                    except:
                        pass
    return settings.XGDS_PLANNER2_SITE_FRAMES
Ejemplo n.º 18
0
def getSiteFrames():
    if not settings.XGDS_PLANNER2_SITE_FRAMES:
        platforms = sorted(settings.XGDS_PLANNER_SCHEMAS.keys())
        try:
            platforms.remove("test")
        except ValueError:
            pass

        for platform in platforms:
            schema = getPlanSchema(platform)
            library = schema.getLibrary()
            sites = library.sites
            if sites:
                for site in sites:
                    try:
                        if site.alternateCrs:
                            settings.XGDS_PLANNER2_SITE_FRAMES.append(site)
                    except:
                        pass
    return settings.XGDS_PLANNER2_SITE_FRAMES
Ejemplo n.º 19
0
    def __init__(self, *args, **kwargs):
        super(CreatePlanForm, self).__init__(*args, **kwargs)
        platforms = sorted(settings.XGDS_PLANNER_SCHEMAS.keys())
        try:
            platforms.remove("test")
        except ValueError:
            pass
        self.fields['platform'].choices = [(p, p) for p in platforms]

        # TODO right now this shows an alphabetically sorted list of all the sites together.
        # really what we want is to change the sites based on the chosen platform.
        allSites = []
        for platform in platforms:
            schema = getPlanSchema(platform)
            library = schema.getLibrary()
            sites = library.sites
            if sites:
                for site in sites:
                    allSites.append(site)
        sites = sorted(allSites, key=lambda site: site.name)
        self.fields['site'].choices = [(site.id, site.name) for site in sites]
Ejemplo n.º 20
0
    def __init__(self, *args, **kwargs):
        super(CreatePlanForm, self).__init__(*args, **kwargs)
        platforms = sorted(settings.XGDS_PLANNER_SCHEMAS.keys())
        try:
            platforms.remove("test")
        except ValueError:
            pass
        self.fields['platform'].choices = [(p, p) for p in platforms]

        # TODO right now this shows an alphabetically sorted list of all the sites together.
        # really what we want is to change the sites based on the chosen platform.
        allSites = []
        for platform in platforms:
            schema = getPlanSchema(platform)
            library = schema.getLibrary()
            sites = library.sites
            if sites:
                for site in sites:
                    allSites.append(site)
        sites = sorted(allSites, key=lambda site: site.name)
        self.fields['site'].choices = [(site.id, site.name) for site in sites]
Ejemplo n.º 21
0
    def importPlan(cls, name, buf, meta, planSchema=None, path=None):
        PLAN_MODEL = getModelByName(settings.XGDS_PLANNER_PLAN_MODEL)
        importer = cls()

        meta.setdefault('name', name)

        if not planSchema:
            try:
                wholePlatform = meta['platform']
                planSchema = models.getPlanSchema(wholePlatform.name)
            except:  # pylint: disable=W0702
                # bad news
                print "no platform, you need to pass the plan Schema" + name
                return
        importer.setDefaultMeta(meta, path, planSchema)
        planDoc = importer.importPlanFromBuffer(buf, meta, planSchema)

        dbPlan = PLAN_MODEL()

        dbPlan.jsonPlan = xpjson.dumpDocumentToDotDict(planDoc)
        dbPlan.extractFromJson(overWriteDateModified=False)

        return dbPlan
Ejemplo n.º 22
0
    def importPlan(cls, name, buf, meta, planSchema=None, path=None):
        PLAN_MODEL = getModelByName(settings.XGDS_PLANNER2_PLAN_MODEL)
        importer = cls()

        meta.setdefault('name', name)

        if not planSchema:
            try:
                wholePlatform = meta['platform']
                planSchema = models.getPlanSchema(wholePlatform.name)
            except:  # pylint: disable=W0702
                # bad news
                print "no platform, you need to pass the plan Schema" + name
                return
        importer.setDefaultMeta(meta, path, planSchema)

        planDoc = importer.importPlanFromBuffer(buf, meta, planSchema)

        dbPlan = PLAN_MODEL()

        dbPlan.jsonPlan = xpjson.dumpDocumentToDotDict(planDoc)
        dbPlan.extractFromJson(overWriteDateModified=False)
        
        return dbPlan
Ejemplo n.º 23
0
def plan_REST(request, plan_id, jsonPlanId):
    """
    Read and write plan JSON.
    jsonPlanId is ignored.  It's for human-readabilty in the URL
    """
    plan = PLAN_MODEL.get().objects.get(pk=plan_id)
    if request.method == "PUT":
        data = json.loads(request.body)
        for k, v in data.iteritems():
            if k == "_simInfo":
                continue
            plan.jsonPlan[k] = v
#         print json.dumps(data, indent=4, sort_keys=True)
        plan.extractFromJson(overWriteDateModified=True)
        plan.save()
        plan = handleCallbacks(request, plan, settings.SAVE)

    elif request.method == "POST":
        # we are doing a save as
        plan.jsonPlan.creator = request.user.username
        plan.creationDate = datetime.datetime.now(pytz.utc)
        plan.uuid = None
        plan.pk = None
        data = json.loads(request.body)
        for k, v in data.iteritems():
            if k == "_simInfo":
                continue
            plan.jsonPlan[k] = v
        plan.extractFromJson(overWriteDateModified=True, overWriteUuid=True)
        plan.name = plan.jsonPlan['planName']
        plan.jsonPlan['name'] = plan.jsonPlan['planName']

        # TODO I don't understand why this did not work above
        plan.creator = request.user
        plan.jsonPlan.creator = request.user.username

        #make sure it is not read only
        plan.readOnly = False
        plan.save()

        newid = plan.pk
        plan.jsonPlan["serverId"] = newid
        plan.jsonPlan["planNumber"] = newid
        plan.jsonPlan.url = plan.get_absolute_url()

        # we still need to renumber the plan
        schema = models.getPlanSchema(plan.jsonPlan.platform['name'])
        exporter = fillIdsPlanExporter.FillIdsPlanExporter()
        planDict = convertToDotDictRecurse(plan.jsonPlan)
        updateAllUuids(planDict)
        plan.jsonPlan = json.dumps(exporter.exportPlan(planDict, schema.schema))
        plan.uuid = planDict.uuid
        
        plan.save()
        handleCallbacks(request, plan, settings.SAVE)

        response = {}
        response["msg"] = "New plan created"
        response["data"] = newid
        return HttpResponse(json.dumps(response), content_type='application/json')

    return HttpResponse(json.dumps(plan.jsonPlan), content_type='application/json')
Ejemplo n.º 24
0
def plan_REST(request, plan_id, jsonPlanId):
    """
    Read and write plan JSON.
    jsonPlanId is ignored.  It's for human-readabilty in the URL
    """
    plan = PLAN_MODEL.get().objects.get(pk=plan_id)
    if request.method == "PUT":
        data = json.loads(request.body)
        for k, v in data.iteritems():
            if k == "_simInfo":
                continue
            plan.jsonPlan[k] = v
#         print json.dumps(data, indent=4, sort_keys=True)
        plan.extractFromJson(overWriteDateModified=True)
        plan.save()
        plan = handleCallbacks(request, plan, settings.SAVE)

    elif request.method == "POST":
        # we are doing a save as
        plan.jsonPlan.creator = request.user.username
        plan.creationDate = datetime.datetime.now(pytz.utc)
        plan.uuid = None
        plan.pk = None
        print "PLAN REST: POST body: %s" % request.body
        data = json.loads(request.body)
        for k, v in data.iteritems():
            if k == "_simInfo":
                continue
            plan.jsonPlan[k] = v
        plan.extractFromJson(overWriteDateModified=True, overWriteUuid=True)
#        plan.name = plan.jsonPlan['planName']
#        plan.jsonPlan['name'] = plan.jsonPlan['planName']

        # TODO I don't understand why this did not work above
        plan.creator = request.user
        plan.jsonPlan.creator = request.user.username

        #make sure it is not read only
        plan.readOnly = False
        plan.save()

        newid = plan.pk
        plan.jsonPlan["serverId"] = newid
        plan.jsonPlan["planNumber"] = newid
        plan.jsonPlan.url = plan.get_absolute_url()

        # we still need to renumber the plan
        schema = models.getPlanSchema(plan.jsonPlan.platform['name'])
        exporter = fillIdsPlanExporter.FillIdsPlanExporter()
        planDict = convertToDotDictRecurse(plan.jsonPlan)
        updateAllUuids(planDict)
        plan.jsonPlan = json.dumps(exporter.exportPlan(planDict, schema.schema))
        plan.uuid = planDict.uuid
        
        plan.save()
        handleCallbacks(request, plan, settings.SAVE)

        response = {}
        response["msg"] = "New plan created"
        response["data"] = newid
        return HttpResponse(json.dumps(response), content_type='application/json')

    return HttpResponse(json.dumps(plan.jsonPlan), content_type='application/json')