Exemplo n.º 1
0
def version():
    global VERSION_RESPONSE
    if VERSION_RESPONSE is None:
        filename = data_filename(os.path.join('weblab','version.json'))
        contents = None

        if filename is not None and os.path.exists(filename):
            version_contents = open(filename).read()
            try:
                version_contents_value = json.loads(version_contents)
            except Exception:
                pass
            else:
                message = r"""WebLab-Deusto r<a href=\"https://github.com/weblabdeusto/weblabdeusto/commits/{version}\">{number}</a> | Last update: {date}""".format(
                    version = version_contents_value['version'],
                    number = version_contents_value['version_number'],
                    date = version_contents_value['date']
                )
                contents = 'var weblab_version = %s;\nvar wlVersionMessage = "%s";' % (version_contents, message)

        if contents is None:
            contents = 'var weblab_version = {};\nvar wlVersionMessage = null;'

        VERSION_RESPONSE = contents

    response = make_response(VERSION_RESPONSE)
    response.content_type = 'text/javascript'
    response.last_modified = datetime.datetime.utcnow()
    response.add_etag()
    return response.make_conditional(request)
Exemplo n.º 2
0
def version():
    global VERSION_RESPONSE
    if VERSION_RESPONSE is None:
        filename = data_filename(os.path.join('weblab', 'version.json'))
        contents = None

        if filename is not None and os.path.exists(filename):
            version_contents = open(filename).read()
            try:
                version_contents_value = json.loads(version_contents)
            except Exception:
                pass
            else:
                message = r"""WebLab-Deusto r<a href=\"https://github.com/weblabdeusto/weblabdeusto/commits/{version}\">{number}</a> | Last update: {date}""".format(
                    version=version_contents_value['version'],
                    number=version_contents_value['version_number'],
                    date=version_contents_value['date'])
                contents = 'var weblab_version = %s;\nvar wlVersionMessage = "%s";' % (
                    version_contents, message)

        if contents is None:
            contents = 'var weblab_version = {};\nvar wlVersionMessage = null;'

        VERSION_RESPONSE = contents

    response = make_response(VERSION_RESPONSE)
    response.content_type = 'text/javascript'
    response.last_modified = datetime.datetime.utcnow()
    response.add_etag()
    return response.make_conditional(request)
Exemplo n.º 3
0
    def __init__(self, coord_address, locator, cfg_manager, *args, **kwargs):
        super(UdPic18Experiment, self).__init__(*args, **kwargs)
        self._coord_address = coord_address
        self._locator = locator
        self._cfg_manager = cfg_manager

        self._programmer = UdXilinxProgrammer.create(self._cfg_manager)
        self._command_sender = UdXilinxCommandSender.create(self._cfg_manager)
        self.conf_demo = self._cfg_manager.get_value("demo", False)
        self.webcam_url = self._cfg_manager.get_value("webcam_url", None)
        self.mjpeg_url = self._cfg_manager.get_value("mjpeg_url", None)
        self.mjpeg_width = self._cfg_manager.get_value("mjpeg_width", None)
        self.mjpeg_height = self._cfg_manager.get_value("mjpeg_height", None)

        self._programming_thread = None
        self._current_state = STATE_NOT_READY
        self._programmer_time = self._cfg_manager.get_value(
            'programmer_time', "25")  # Seconds
        self._switches_reversed = self._cfg_manager.get_value(
            'switches_reversed', False)  # Seconds
        self.demo = False

        file_path = data_filename(os.path.join(module_directory, 'demo.hex'))
        self.file_content = ExperimentUtil.serialize(
            open(file_path, "rb").read())
Exemplo n.º 4
0
    def __init__(self, coord_address, locator, cfg_manager, *args, **kwargs):
        super(Submarine, self).__init__(*args, **kwargs)

        thermometer_svg_path = data_filename(
            os.path.join(module_directory, 'submarine-thermometer.svg'))
        self.thermometer = open(thermometer_svg_path, "rb").read()

        self._cfg_manager = cfg_manager

        self._lock = threading.Lock()
        self._feed_lock = threading.Lock()
        self._latest_feed_time = datetime.datetime.now()

        self.debug = self._cfg_manager.get_value('debug', False)
        self.debug_dir = self._cfg_manager.get_value('debug_dir', None)
        self.real_device = self._cfg_manager.get_value('real_device', True)
        self.lights_on_time = self._cfg_manager.get_value('lights_on_time', 10)
        self.lights_off_time = self._cfg_manager.get_value(
            'lights_off_time', 15)
        self.feed_period = self._cfg_manager.get_value('feed_period', 8)
        self.pic_location = self._cfg_manager.get_value(
            'submarine_pic_location', 'http://192.168.0.90/')
        self.webcams_info = self._cfg_manager.get_value('webcams_info', [])
        self.thermometer_path = self._cfg_manager.get_value(
            'thermometer_path', None)

        self.up = False
        self.down = False
        self.left = False
        self.right = False
        self.forward = False
        self.backward = False

        self.opener = urllib2.build_opener(urllib2.ProxyHandler({}))

        self.initial_configuration = {}
        for pos, webcam_config in enumerate(self.webcams_info):
            num = pos + 1
            webcam_url = webcam_config.get('webcam_url')
            mjpeg_url = webcam_config.get('mjpeg_url')
            mjpeg_width = webcam_config.get('mjpeg_width')
            mjpeg_height = webcam_config.get('mjpeg_height')

            if webcam_url is not None:
                self.initial_configuration['webcam%s' % num] = webcam_url
            if mjpeg_url is not None:
                self.initial_configuration['mjpeg%s' % num] = mjpeg_url
            if mjpeg_width is not None:
                self.initial_configuration['mjpegWidth%s' % num] = mjpeg_width
            if mjpeg_height is not None:
                self.initial_configuration['mjpegHeight%s' %
                                           num] = mjpeg_height

        self.in_use = False
        self.since_tick = False

        self.correct_lights()
        event_manager = EventManager(self)
        event_manager.start()
Exemplo n.º 5
0
def logo_impl(logo_path):
    logo_path = os.path.abspath(logo_path)
    if not os.path.exists(logo_path):
        print("Error:", logo_path, "not found")
        logo_path = data_filename("weblab/admin/logo-not-found.jpg")
    response = send_file(logo_path, as_attachment = False, conditional = True, add_etags = True, cache_timeout=0)
    response.headers['Cache-Control'] = 'max-age=0'
    return response
Exemplo n.º 6
0
 def __init__(self, coord_address, locator, cfg_manager, *args, **kwargs):
     super(UdDemoXilinxExperiment,
           self).__init__(coord_address, locator, cfg_manager, *args,
                          **kwargs)
     file_path = data_filename(
         os.path.join(module_directory, self.FILES[self._board_type]))
     self.file_content = ExperimentUtil.serialize(
         open(file_path, "rb").read())
Exemplo n.º 7
0
def gwt(path = ''):
    # If it's the index, generate something
    if path in ('', 'index.html', 'index.htm'):
        return _process_index()
    
    # Otherwise, just
    base_directory = data_filename('war')
    return send_from_directory(base_directory, path)
Exemplo n.º 8
0
def gwt(path=''):
    # If it's the index, generate something
    if path in ('', 'index.html', 'index.htm'):
        return _process_index()

    # Otherwise, just
    base_directory = data_filename('war')
    return send_from_directory(base_directory, path)
Exemplo n.º 9
0
    def check_schema(self, xmlfile_path, xsdfile_path):
        if not LXML_AVAILABLE:
            global MESSAGE_SHOWN
            if not MESSAGE_SHOWN:
                msg = "The optional library 'lxml' is not available. The syntax of the configuration files will not be checked."
                print >> sys.stderr, msg
                log.log(SchemaChecker, log.level.Warning, msg)
                MESSAGE_SHOWN = True
            return

        xmlfile_content = self._read_xml_file(xmlfile_path)
        xsdfile_full_path = data_filename(
            os.path.join(module_directory, 'xsd', xsdfile_path))
        try:
            xsdfile_content = self._read_xsd_file(xsdfile_full_path)
        except:
            msg = "The XSD file %s could not be loaded. The syntax of the configuration files will not be checked." % xsdfile_full_path
            print >> sys.stderr, msg
            log.log(SchemaChecker, log.level.Warning, msg)
            return

        try:
            sio_xsd = StringIO(xsdfile_content)
            xmlschema_doc = etree.parse(sio_xsd)
            xmlschema = etree.XMLSchema(xmlschema_doc)
        except Exception as e:
            log.log(
                SchemaChecker, log.level.Warning,
                'Invalid syntax file configuration: File %s: %s' %
                (xsdfile_path, e))
            log.log_exc(SchemaChecker, log.level.Info)
            raise LoaderErrors.InvalidSyntaxFileConfigurationError(
                e, xsdfile_path)

        try:
            sio_xml = StringIO(xmlfile_content)
            xml_doc = etree.parse(sio_xml)
            xmlschema.assertValid(xml_doc)
        except etree.DocumentInvalid as di:
            log.log(
                SchemaChecker, log.level.Warning,
                'Not a valid configuration file. Check it with a XML Schema validator: File %s'
                % (xmlfile_path))
            raise LoaderErrors.InvalidSyntaxFileConfigurationError(
                'Not a valid configuration file. Check it with a XML Schema validator. %s'
                % di.args, xmlfile_path)
        except Exception as e:
            log.log(
                SchemaChecker, log.level.Warning,
                'Invalid syntax file configuration: File %s: %s' %
                (xmlfile_path, e))
            log.log_exc(SchemaChecker, log.level.Info)
            raise LoaderErrors.InvalidSyntaxFileConfigurationError(
                e, xmlfile_path)
Exemplo n.º 10
0
    def __init__(self, coord_address, locator, cfg_manager, *args, **kwargs):
        super(Submarine, self).__init__(*args, **kwargs)

        thermometer_svg_path = data_filename(os.path.join(module_directory, 'submarine-thermometer.svg'))
        self.thermometer     = open(thermometer_svg_path, "rb").read()

        self._cfg_manager    = cfg_manager

        self._lock           = threading.Lock()
        self._feed_lock      = threading.Lock()
        self._latest_feed_time = datetime.datetime.now()

        self.debug           = self._cfg_manager.get_value('debug', False)
        self.debug_dir       = self._cfg_manager.get_value('debug_dir', None)
        self.real_device     = self._cfg_manager.get_value('real_device', True)
        self.lights_on_time  = self._cfg_manager.get_value('lights_on_time',  10)
        self.lights_off_time = self._cfg_manager.get_value('lights_off_time', 15)
        self.feed_period     = self._cfg_manager.get_value('feed_period', 8)
        self.pic_location    = self._cfg_manager.get_value('submarine_pic_location', 'http://192.168.0.90/')
        self.webcams_info    = self._cfg_manager.get_value('webcams_info', [])
        self.thermometer_path = self._cfg_manager.get_value('thermometer_path', None)

        self.up              = False
        self.down            = False
        self.left            = False
        self.right           = False
        self.forward         = False
        self.backward        = False
        
        self.opener          = urllib2.build_opener(urllib2.ProxyHandler({}))
        
        self.initial_configuration = {}
        for pos, webcam_config in enumerate(self.webcams_info):
            num = pos + 1
            webcam_url   = webcam_config.get('webcam_url')
            mjpeg_url    = webcam_config.get('mjpeg_url')
            mjpeg_width  = webcam_config.get('mjpeg_width')
            mjpeg_height = webcam_config.get('mjpeg_height')

            if webcam_url is not None:
                self.initial_configuration['webcam%s' % num] = webcam_url
            if mjpeg_url is not None:
                self.initial_configuration['mjpeg%s' % num] = mjpeg_url
            if mjpeg_width is not None:
                self.initial_configuration['mjpegWidth%s' % num] = mjpeg_width
            if mjpeg_height is not None:
                self.initial_configuration['mjpegHeight%s' % num] = mjpeg_height

        self.in_use     = False
        self.since_tick = False

        self.correct_lights()
        event_manager = EventManager(self)
        event_manager.start()
Exemplo n.º 11
0
def logo_impl(logo_path):
    logo_path = os.path.abspath(logo_path)
    if not os.path.exists(logo_path):
        print("Error:", logo_path, "not found")
        logo_path = data_filename("weblab/admin/logo-not-found.jpg")
    response = send_file(logo_path,
                         as_attachment=False,
                         conditional=True,
                         add_etags=True,
                         cache_timeout=0)
    response.headers['Cache-Control'] = 'max-age=0'
    return response
Exemplo n.º 12
0
def httpd_config_generate(directory):
    debugging_variables = {}
    execfile(os.path.join(directory, 'debugging.py'), debugging_variables)
    ports = debugging_variables.get('PORTS', {}).get('json')
    base_url = debugging_variables.get('BASE_URL', '')
    if base_url in ('','/'):
        base_url = ''

    static_directories = OrderedDict() #{
        # url path : disk path
    # }
    static_directories[base_url + '/weblab/client'] =                            data_filename('weblab/core/static/oldclient').replace('\\','/') # \ => / for Windows
    flask_admin_static = os.path.join(os.path.dirname(flask_admin.__file__), 'static')
    static_directories[base_url + '/weblab/admin/static'] =                      flask_admin_static.replace('\\','/')
    # TODO: Avoid repeated paths
    static_directories[base_url + '/weblab/instructor/static'] =                 data_filename('weblab/admin/web/static').replace('\\','/')
    static_directories[base_url + '/weblab/profile/static'] =                    data_filename('weblab/admin/web/static').replace('\\','/')
    static_directories[base_url + '/weblab/web/static'] =                        data_filename('weblab/core/static').replace('\\','/')
    static_directories[base_url + '/weblab/static'] =                            data_filename('weblab/core/static').replace('\\','/')
    static_directories[base_url + '/weblab/gwt/weblabclientlab'] =               data_filename('war/weblabclientlab').replace('\\','/')
    static_directories[base_url + '/weblab/web/pub'] =                           os.path.abspath(os.path.join(directory, 'pub')).replace('\\','/')

    files = {}
    apache_contents = _apache_generation(directory, base_url, ports, static_directories)
    files['apache'] = _set_contents(directory, 'httpd/apache_weblab_generic.conf', apache_contents)
    simple_httpd_contents = _simple_httpd_generation(directory, base_url, ports, static_directories)
    files['simple'] = _set_contents(directory, 'httpd/simple_server_config.py', simple_httpd_contents)
    
    # TODO: support nginx

    return files
def httpd_config_generate(directory):
    debugging_variables = {}
    execfile(os.path.join(directory, 'debugging.py'), debugging_variables)
    ports = debugging_variables.get('PORTS', {}).get('json')
    base_url = debugging_variables.get('BASE_URL', '')
    if base_url in ('', '/'):
        base_url = ''

    static_directories = OrderedDict()  #{
    # url path : disk path
    # }
    static_directories[base_url + '/weblab/client'] = data_filename(
        'weblab/core/static/oldclient').replace('\\',
                                                '/')  # \ => / for Windows
    flask_admin_static = os.path.join(os.path.dirname(flask_admin.__file__),
                                      'static')
    static_directories[base_url +
                       '/weblab/admin/static'] = flask_admin_static.replace(
                           '\\', '/')
    # TODO: Avoid repeated paths
    static_directories[base_url + '/weblab/instructor/static'] = data_filename(
        'weblab/admin/web/static').replace('\\', '/')
    static_directories[base_url + '/weblab/profile/static'] = data_filename(
        'weblab/admin/web/static').replace('\\', '/')
    static_directories[base_url + '/weblab/web/static'] = data_filename(
        'weblab/core/static').replace('\\', '/')
    static_directories[base_url + '/weblab/static'] = data_filename(
        'weblab/core/static').replace('\\', '/')
    static_directories[base_url +
                       '/weblab/gwt/weblabclientlab'] = data_filename(
                           'war/weblabclientlab').replace('\\', '/')
    static_directories[base_url + '/weblab/web/pub'] = os.path.abspath(
        os.path.join(directory, 'pub')).replace('\\', '/')

    files = {}
    apache_contents = _apache_generation(directory, base_url, ports,
                                         static_directories)
    files['apache'] = _set_contents(directory,
                                    'httpd/apache_weblab_generic.conf',
                                    apache_contents)
    simple_httpd_contents = _simple_httpd_generation(directory, base_url,
                                                     ports, static_directories)
    files['simple'] = _set_contents(directory, 'httpd/simple_server_config.py',
                                    simple_httpd_contents)

    # TODO: support nginx

    return files
Exemplo n.º 14
0
    def check_schema(self, xmlfile_path, xsdfile_path):
        if not LXML_AVAILABLE:
            global MESSAGE_SHOWN
            if not MESSAGE_SHOWN:
                msg = "The optional library 'lxml' is not available. The syntax of the configuration files will not be checked."
                print >> sys.stderr, msg
                log.log( SchemaChecker, log.level.Warning, msg )
                MESSAGE_SHOWN = True
            return
        
        xmlfile_content = self._read_xml_file(xmlfile_path)
        xsdfile_full_path = data_filename(os.path.join(module_directory, 'xsd', xsdfile_path))
        try:
            xsdfile_content   = self._read_xsd_file(xsdfile_full_path)
        except:
            msg = "The XSD file %s could not be loaded. The syntax of the configuration files will not be checked." % xsdfile_full_path
            print >> sys.stderr, msg
            log.log( SchemaChecker, log.level.Warning, msg )
            return

        try:
            sio_xsd = StringIO(xsdfile_content)
            xmlschema_doc = etree.parse(sio_xsd)
            xmlschema = etree.XMLSchema(xmlschema_doc)
        except Exception as e:
            log.log( SchemaChecker, log.level.Warning, 'Invalid syntax file configuration: File %s: %s' % (xsdfile_path, e))
            log.log_exc( SchemaChecker, log.level.Info)
            raise LoaderErrors.InvalidSyntaxFileConfigurationError( e, xsdfile_path )

        try:
            sio_xml = StringIO(xmlfile_content)
            xml_doc = etree.parse(sio_xml)
            xmlschema.assertValid(xml_doc)
        except etree.DocumentInvalid as di:
            log.log( SchemaChecker, log.level.Warning, 'Not a valid configuration file. Check it with a XML Schema validator: File %s' % (xmlfile_path))
            raise LoaderErrors.InvalidSyntaxFileConfigurationError( 'Not a valid configuration file. Check it with a XML Schema validator. %s' % di.args, xmlfile_path)
        except Exception as e:
            log.log( SchemaChecker, log.level.Warning, 'Invalid syntax file configuration: File %s: %s' % (xmlfile_path, e))
            log.log_exc( SchemaChecker, log.level.Info)
            raise LoaderErrors.InvalidSyntaxFileConfigurationError( e, xmlfile_path)
Exemplo n.º 15
0
    def __init__(self, coord_address, locator, cfg_manager, *args, **kwargs):
        super(UdPic18Experiment,self).__init__(*args, **kwargs)
        self._coord_address = coord_address
        self._locator = locator
        self._cfg_manager = cfg_manager

        self._programmer     = UdXilinxProgrammer.create(self._cfg_manager)
        self._command_sender = UdXilinxCommandSender.create(self._cfg_manager)
        self.conf_demo       = self._cfg_manager.get_value("demo",         False)
        self.webcam_url      = self._cfg_manager.get_value("webcam_url",   None)
        self.mjpeg_url       = self._cfg_manager.get_value("mjpeg_url",    None)
        self.mjpeg_width     = self._cfg_manager.get_value("mjpeg_width",  None)
        self.mjpeg_height    = self._cfg_manager.get_value("mjpeg_height", None)
        
        self._programming_thread = None
        self._current_state = STATE_NOT_READY
        self._programmer_time = self._cfg_manager.get_value('programmer_time', "25") # Seconds
        self._switches_reversed = self._cfg_manager.get_value('switches_reversed', False) # Seconds
        self.demo = False
        
        file_path = data_filename(os.path.join(module_directory, 'demo.hex'))
        self.file_content = ExperimentUtil.serialize(open(file_path, "rb").read())
Exemplo n.º 16
0
    def __init__(self, coord_address, locator, cfg_manager, *args, **kwargs):
        super(BinaryExperiment,self).__init__(coord_address, locator, cfg_manager, *args, **kwargs)

        self._cfg_manager = cfg_manager

        self.exercises = {
            'bcd'    : ['cod1', 'cod2',     'cod3',    'cod4',  'cod5'],
            'other'  : ['cod1', 'cod_gray', 'cod_xs3', 'cod_gray_xs3'],
        }

        # module_directory = os.path.join(*__name__.split('.')[:-1])
        module_directory = ('experiments', 'binary')
        self.contents = {}
        for values in self.exercises.values():
            for value in values:
                if value not in self.contents:
                    filename = value + '.jed'
                    full_relative_path_tuple = module_directory + (filename,)
                    full_relative_path = os.path.join(*full_relative_path_tuple)
                    file_path = data_filename( full_relative_path )
                    self.contents[value] = open(file_path, 'rb').read()

        self.current_labels = []
Exemplo n.º 17
0
def version():
    filename = data_filename(os.path.join('weblab', 'version.json'))
    contents = None

    if filename is not None and os.path.exists(filename):
        version_contents = open(filename).read()
        try:
            version_contents_value = json.loads(version_contents)
        except Exception:
            pass
        else:
            message = r"""WebLab-Deusto r<a href=\"https://github.com/weblabdeusto/weblabdeusto/commits/{version}\">{number}</a> | Last update: {date}""".format(
                version=version_contents_value['version'],
                number=version_contents_value['version_number'],
                date=version_contents_value['date'])
            contents = 'var weblab_version = %s;\nvar wlVersionMessage = "%s";' % (
                version_contents, message)

    if contents is None:
        contents = 'var weblab_version = {};\nvar wlVersionMessage = null;'

    response = make_response(contents)
    response.content_type = 'text/javascript'
    return response
Exemplo n.º 18
0
def version():
    filename = data_filename(os.path.join('weblab','version.json'))
    contents = None

    if filename is not None and os.path.exists(filename):
        version_contents = open(filename).read()
        try:
            version_contents_value = json.loads(version_contents)
        except Exception:
            pass
        else:
            message = r"""WebLab-Deusto r<a href=\"https://github.com/weblabdeusto/weblabdeusto/commits/{version}\">{number}</a> | Last update: {date}""".format(
                version = version_contents_value['version'],
                number = version_contents_value['version_number'],
                date = version_contents_value['date']
            )
            contents = 'var weblab_version = %s;\nvar wlVersionMessage = "%s";' % (version_contents, message)

    if contents is None:
        contents = 'var weblab_version = {};\nvar wlVersionMessage = null;'

    response = make_response(contents)
    response.content_type = 'text/javascript';
    return response
Exemplo n.º 19
0
def locales():
    lang = request.args.get('lang')
    if not lang:
        # Default language is English
        lang = 'en'

    try:
        babel.Locale.parse(lang)
    except (babel.core.UnknownLocaleError, ValueError) as e:
        # Avoid storing fake languages
        return "Invalid language", 400

    lang_contents = PER_LANG.get(lang)

    if lang_contents is None:
        # 
        # If the language has not been previously calculated, it is calculated as follows:
        # - first, check the modified date of the locales.json and messages.mo file
        # - then, generate the file using render_template
        # - store it in the local cache, and then check the etag and so on
        # 
        fname = data_filename('weblab/core/templates/webclient/locales.json')
        try:
            modification_time = os.stat(fname).st_mtime
            last_modified = datetime.datetime.fromtimestamp(modification_time)
        except Exception as e:
            print("Could not calculate the time for %s" % fname)
            traceback.print_exc()
            last_modified = datetime.datetime.now()

        messages_directory = data_filename('weblab/core/translations')
        messages_file = data_filename('weblab/core/translations/{0}/LC_MESSAGES/messages.mo'.format(lang))
        if os.path.exists(messages_file):
            try:
                messages_modification_time = os.stat(fname).st_mtime
                messages_last_modified = datetime.datetime.fromtimestamp(messages_modification_time)
            except Exception as e:
                messages_last_modified = datetime.datetime.now()

            last_modified = max(last_modified, messages_last_modified)
            
        def ng_gettext(text):
            """Wrapper of gettext. It uses the messages_file to load particular translations (e.g. if 'es' is requested, it uses the translations for Spanish)."""
            translation = babel.support.Translations.load(messages_directory, lang)
            translated_text = translation.gettext(text)
            return translated_text

        contents = render_template('webclient/locales.json', ng_gettext=ng_gettext)
        etag = hashlib.new('sha1', contents).hexdigest()
        
        lang_contents = {
            'last_modified' : last_modified.replace(microsecond=0),
            'contents' : contents,
            'etag' : etag,
        }

        PER_LANG[lang] = lang_contents
    
    # At this point, lang_contents exists, and contains:
    #    last_modified: pointing at the latest point where the contents where modified
    #    contents: the string with the processed contents
    #    etag: with the hash of the contents
    
    # First we check etag (and return 304 if the contents were not changed)
    if request.if_none_match is not None and request.if_none_match.contains(lang_contents['etag']):
        return Response(status=304)

    # Then the date (and return 304 if the date is correct)
    if request.if_modified_since is not None and request.if_modified_since >= lang_contents['last_modified']:
        return Response(status=304)
    
    # Otherwise, we create the response
    response = Response(lang_contents['contents'])
    response.mimetype = 'application/json'
    response.last_modified = lang_contents['last_modified']
    response.set_etag(lang_contents['etag'])
    return response
Exemplo n.º 20
0
def _apache_generation(directory, base_url, ports, static_directories):
    apache_conf = (
    "\n"
    """<LocationMatch (.*)nocache\.js$>\n"""
    """   Header Set Cache-Control "max-age=0, no-store"\n"""
    """</LocationMatch>\n"""
    """\n"""
    """<Files *.cache.*>\n"""
    """   Header Set Cache-Control "max-age=2592000"\n"""
    """</Files>\n"""
    """\n"""
    """# Apache redirects the regular paths to the particular directories \n"""
#    """RedirectMatch ^%(root)s$ %(root)s/weblab/\n"""
#    """RedirectMatch ^%(root)s/$ %(root)s/weblab/\n"""
    """RedirectMatch ^%(root)s/weblab$ %(root)s/weblab/\n"""
    """RedirectMatch ^%(root)s/weblab/client/$ %(root)s/weblab/client/index.html\n"""
    """\n""")
    
    for static_url, static_directory in static_directories.items():
        apache_conf += """Alias %(static_url)s   %(static_directory)s\n""" % dict(static_url=static_url, static_directory=static_directory)

    apache_conf += (
    """\n"""
    """<Location %(root)s/weblab/>\n"""
    """    <IfModule authz_core_module>\n"""
    """        Require all granted\n"""
    """    </IfModule>\n"""
    """\n"""
    """    <IfModule !authz_core_module>\n"""
    """        Order allow,deny\n"""
    """        Allow from All\n"""
    """    </IfModule>\n"""
    """</Location>\n"""
    """\n"""
    """<Directory "%(directory)s">\n"""
    """    Options Indexes\n"""
    """\n"""
    """    <IfModule authz_core_module>\n"""
    """        Require all granted\n"""
    """    </IfModule>\n"""
    """\n"""
    """    <IfModule !authz_core_module>\n"""
    """        Order allow,deny\n"""
    """        Allow from All\n"""
    """    </IfModule>\n"""
    """</Directory>\n"""
    """\n""")

    previous = []
    for static_directory in static_directories.values():
        if static_directory in previous:
            continue
        previous.append(static_directory)
        apache_conf += ("""<Directory "%(static_directory)s">\n"""
        """    Options Indexes FollowSymLinks\n"""
        """\n"""
        """    <IfModule authz_core_module>\n"""
        """        Require all granted\n"""
        """    </IfModule>\n"""
        """\n"""
        """    <IfModule !authz_core_module>\n"""
        """        Order allow,deny\n"""
        """        Allow from All\n"""
        """    </IfModule>\n"""
        """</Directory>\n"""
        """\n""") % dict(static_directory=static_directory)

    apache_conf += (
    """# Apache redirects the requests retrieved to the particular server, using a stickysession if the sessions are based on memory\n"""
    """ProxyPreserveHost On\n"""
    """ProxyVia On\n"""
    """\n""")

    for static_url, static_directory in static_directories.items():
        apache_conf += """ProxyPass %(static_url)s !\n""" % dict(static_url=static_url)

    apache_conf += (
    """\n"""
    """ProxyPass                       %(root)s/weblab/                 balancer://%(root-no-slash)s_weblab_cluster/           stickysession=weblabsessionid lbmethod=bybusyness\n"""
    """ProxyPassReverse                %(root)s/weblab/                 balancer://%(root-no-slash)s_weblab_cluster/           stickysession=weblabsessionid\n"""
    "\n")
    apache_conf += "\n"
    apache_conf += """<Proxy balancer://%(root-no-slash)s_weblab_cluster>\n"""

    for pos, port in enumerate(ports):
        d = { 'port' : port, 'route' : 'route%s' % (pos+1), 'root' : '%(root)s' }
        apache_conf += """    BalancerMember http://localhost:%(port)s/weblab route=%(route)s\n""" % d

    apache_conf += """</Proxy>\n"""
    apache_img_dir = '/client/images'

    apache_root_without_slash = base_url[1:] if base_url.startswith('/') else base_url

    server_conf_dict = { 'root' : base_url,  'root-no-slash' : apache_root_without_slash.replace('/','_'),
                'directory' : os.path.abspath(directory).replace('\\','/'),
                'war_path' : data_filename('war').replace('\\','/') }

    apache_conf = apache_conf % server_conf_dict
    apache_conf_path = os.path.join('', 'apache_weblab_generic.conf')
    return apache_conf 
Exemplo n.º 21
0
import StringIO
from flask import Response, make_response, request, send_file
from weblab.core.web import weblab_api, get_argument
from weblab.util import data_filename
import tempfile
import traceback
from weblab.data.command import Command
# To convert from HTTP date to standard time
import email.utils as eut
import time

import os

import hashlib

VISIR_RELATIVE_PATH = data_filename(
    os.path.join('war', 'weblabclientlab', 'visir')) + os.sep

VISIR_LOCATION = VISIR_RELATIVE_PATH
VISIR_TEMP_FILES = os.sep.join((VISIR_LOCATION, 'temp')) + os.sep

BASE_HTML_TEMPLATE = """<?xml version="1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
    <head>
        <title>WebLab visir</title>
    </head>
    <body>%(MESSAGE)s</body>
</html>
"""

SUCCESS_HTML_TEMPLATE = BASE_HTML_TEMPLATE % {"MESSAGE": "SUCCESS@%(RESULT)s"}
Exemplo n.º 22
0
 def __init__(self, coord_address, locator, cfg_manager, *args, **kwargs):
     super(UdDemoXilinxExperiment,self).__init__(coord_address, locator, cfg_manager, *args, **kwargs)
     file_path = data_filename(os.path.join(module_directory, self.FILES[self._xilinx_device]))
     self.file_content = ExperimentUtil.serialize(open(file_path, "rb").read())
Exemplo n.º 23
0
def locales():
    lang = request.args.get('lang')
    if not lang:
        # Default language is English
        lang = 'en'

    try:
        babel.Locale.parse(lang)
    except (babel.core.UnknownLocaleError, ValueError) as e:
        # Avoid storing fake languages
        return "Invalid language", 400

    lang_contents = PER_LANG.get(lang)

    if lang_contents is None:
        #
        # If the language has not been previously calculated, it is calculated as follows:
        # - first, check the modified date of the locales.json and messages.mo file
        # - then, generate the file using render_template
        # - store it in the local cache, and then check the etag and so on
        #
        fname = data_filename('weblab/core/templates/webclient/locales.json')
        try:
            modification_time = os.stat(fname).st_mtime
            last_modified = datetime.datetime.fromtimestamp(modification_time)
        except Exception as e:
            print("Could not calculate the time for %s" % fname)
            traceback.print_exc()
            last_modified = datetime.datetime.now()

        messages_directory = data_filename('weblab/core/translations')
        messages_file = data_filename(
            'weblab/core/translations/{0}/LC_MESSAGES/messages.mo'.format(
                lang))
        if os.path.exists(messages_file):
            try:
                messages_modification_time = os.stat(fname).st_mtime
                messages_last_modified = datetime.datetime.fromtimestamp(
                    messages_modification_time)
            except Exception as e:
                messages_last_modified = datetime.datetime.now()

            last_modified = max(last_modified, messages_last_modified)

        def ng_gettext(text):
            """Wrapper of gettext. It uses the messages_file to load particular translations (e.g. if 'es' is requested, it uses the translations for Spanish)."""
            translation = babel.support.Translations.load(
                messages_directory, lang)
            translated_text = translation.gettext(text)
            return translated_text

        contents = render_template('webclient/locales.json',
                                   ng_gettext=ng_gettext)
        etag = hashlib.new('sha1', contents).hexdigest()

        lang_contents = {
            'last_modified': last_modified.replace(microsecond=0),
            'contents': contents,
            'etag': etag,
        }

        PER_LANG[lang] = lang_contents

    # At this point, lang_contents exists, and contains:
    #    last_modified: pointing at the latest point where the contents where modified
    #    contents: the string with the processed contents
    #    etag: with the hash of the contents

    # First we check etag (and return 304 if the contents were not changed)
    if request.if_none_match is not None and request.if_none_match.contains(
            lang_contents['etag']):
        return Response(status=304)

    # Then the date (and return 304 if the date is correct)
    if request.if_modified_since is not None and request.if_modified_since >= lang_contents[
            'last_modified']:
        return Response(status=304)

    # Otherwise, we create the response
    response = Response(lang_contents['contents'])
    response.mimetype = 'application/json'
    response.last_modified = lang_contents['last_modified']
    response.set_etag(lang_contents['etag'])
    return response
def _apache_generation(directory, base_url, ports, static_directories):
    apache_conf = (
        "\n"
        """<LocationMatch (.*)nocache\.js$>\n"""
        """   Header Set Cache-Control "max-age=0, no-store"\n"""
        """</LocationMatch>\n"""
        """\n"""
        """<Files *.cache.*>\n"""
        """   Header Set Cache-Control "max-age=2592000"\n"""
        """</Files>\n"""
        """\n"""
        """# Apache redirects the regular paths to the particular directories \n"""
        #    """RedirectMatch ^%(root)s$ %(root)s/weblab/\n"""
        #    """RedirectMatch ^%(root)s/$ %(root)s/weblab/\n"""
        """RedirectMatch ^%(root)s/weblab$ %(root)s/weblab/\n"""
        """RedirectMatch ^%(root)s/weblab/client/$ %(root)s/weblab/client/index.html\n"""
        """\n""")

    for static_url, static_directory in static_directories.items():
        apache_conf += """Alias %(static_url)s   %(static_directory)s\n""" % dict(
            static_url=static_url, static_directory=static_directory)

    apache_conf += ("""\n"""
                    """<Location %(root)s/weblab/>\n"""
                    """    <IfModule authz_core_module>\n"""
                    """        Require all granted\n"""
                    """    </IfModule>\n"""
                    """\n"""
                    """    <IfModule !authz_core_module>\n"""
                    """        Order allow,deny\n"""
                    """        Allow from All\n"""
                    """    </IfModule>\n"""
                    """</Location>\n"""
                    """\n"""
                    """<Directory "%(directory)s">\n"""
                    """    Options Indexes\n"""
                    """\n"""
                    """    <IfModule authz_core_module>\n"""
                    """        Require all granted\n"""
                    """    </IfModule>\n"""
                    """\n"""
                    """    <IfModule !authz_core_module>\n"""
                    """        Order allow,deny\n"""
                    """        Allow from All\n"""
                    """    </IfModule>\n"""
                    """</Directory>\n"""
                    """\n""")

    previous = []
    for static_directory in static_directories.values():
        if static_directory in previous:
            continue
        previous.append(static_directory)
        apache_conf += ("""<Directory "%(static_directory)s">\n"""
                        """    Options Indexes FollowSymLinks\n"""
                        """\n"""
                        """    <IfModule authz_core_module>\n"""
                        """        Require all granted\n"""
                        """    </IfModule>\n"""
                        """\n"""
                        """    <IfModule !authz_core_module>\n"""
                        """        Order allow,deny\n"""
                        """        Allow from All\n"""
                        """    </IfModule>\n"""
                        """</Directory>\n"""
                        """\n""") % dict(static_directory=static_directory)

    apache_conf += (
        """# Apache redirects the requests retrieved to the particular server, using a stickysession if the sessions are based on memory\n"""
        """ProxyPreserveHost On\n"""
        """ProxyVia On\n"""
        """\n""")

    for static_url, static_directory in static_directories.items():
        apache_conf += """ProxyPass %(static_url)s !\n""" % dict(
            static_url=static_url)

    apache_conf += (
        """\n"""
        """ProxyPass                       %(root)s/weblab/                 balancer://%(root-no-slash)s_weblab_cluster/           stickysession=weblabsessionid lbmethod=bybusyness\n"""
        """ProxyPassReverse                %(root)s/weblab/                 balancer://%(root-no-slash)s_weblab_cluster/           stickysession=weblabsessionid\n"""
        "\n")
    apache_conf += "\n"
    apache_conf += """<Proxy balancer://%(root-no-slash)s_weblab_cluster>\n"""

    for pos, port in enumerate(ports):
        d = {'port': port, 'route': 'route%s' % (pos + 1), 'root': '%(root)s'}
        apache_conf += """    BalancerMember http://localhost:%(port)s/weblab route=%(route)s\n""" % d

    apache_conf += """</Proxy>\n"""
    apache_img_dir = '/client/images'

    apache_root_without_slash = base_url[1:] if base_url.startswith(
        '/') else base_url

    server_conf_dict = {
        'root': base_url,
        'root-no-slash': apache_root_without_slash.replace('/', '_'),
        'directory': os.path.abspath(directory).replace('\\', '/'),
        'war_path': data_filename('war').replace('\\', '/')
    }

    apache_conf = apache_conf % server_conf_dict
    apache_conf_path = os.path.join('', 'apache_weblab_generic.conf')
    return apache_conf
Exemplo n.º 25
0
#         Luis Rodriguez <*****@*****.**>
#
from __future__ import print_function, unicode_literals

import os
import codecs
import json
import traceback

from flask import Response

from weblab.core.wl import weblab_api
from weblab.util import data_filename

try:
    I18N = json.load(codecs.open(data_filename(os.path.join('weblab', 'i18n.json')), encoding = 'utf-8'))
except:
    print("Error loading weblab/i18n.json. Did you run weblab-admin upgrade? Check the file")
    traceback.print_exc()
    I18N = {
        'generic_experiments' : {},
        'experiments' : {}
    }

@weblab_api.route_web('/i18n/<category_name>/<experiment_name>/')
def i18n(category_name, experiment_name):
    mails = [ mail.strip() for mail in weblab_api.config.get('server_admin', '').split(',') if mail.strip() ]
    response = {
        'translations' : {
        # lang : {
        #    key : {
Exemplo n.º 26
0
import StringIO
from flask import Response, make_response, request, send_file
from weblab.core.web import weblab_api, get_argument
from weblab.util import data_filename
import tempfile
import traceback
from weblab.data.command import Command
# To convert from HTTP date to standard time
import email.utils as eut
import time

import os

import hashlib

VISIR_RELATIVE_PATH = data_filename(os.path.join('war','weblabclientlab','visir')) + os.sep

VISIR_LOCATION = VISIR_RELATIVE_PATH
VISIR_TEMP_FILES = os.sep.join((VISIR_LOCATION, 'temp')) + os.sep

BASE_HTML_TEMPLATE="""<?xml version="1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
    <head>
        <title>WebLab visir</title>
    </head>
    <body>%(MESSAGE)s</body>
</html>
"""

SUCCESS_HTML_TEMPLATE = BASE_HTML_TEMPLATE % {
Exemplo n.º 27
0
#
from __future__ import print_function, unicode_literals

import os
import codecs
import json
import traceback

from flask import Response

from weblab.core.wl import weblab_api
from weblab.util import data_filename

try:
    I18N = json.load(
        codecs.open(data_filename(os.path.join('weblab', 'i18n.json')),
                    encoding='utf-8'))
except:
    print(
        "Error loading weblab/i18n.json. Did you run weblab-admin upgrade? Check the file"
    )
    traceback.print_exc()
    I18N = {'generic_experiments': {}, 'experiments': {}}


@weblab_api.route_web('/i18n/<category_name>/<experiment_name>/')
def i18n(category_name, experiment_name):
    mails = [
        mail.strip()
        for mail in weblab_api.config.get('server_admin', '').split(',')
        if mail.strip()