예제 #1
0
파일: Snmp.py 프로젝트: delian/testerman
def initialize(address):
    global TheSnmpServer
    if address is None:
        address = (ConfigManager.get("snmp.ip", ""),
                   int(ConfigManager.get("snmp.port", "1161")))
    TheSnmpServer = SnmpServer(address)
    TheSnmpServer.start()
예제 #2
0
 def SavePreview(self, frame):
     dir = os.path.join(config.GetScriptDir(), "web/static/previews/",
                        self.name + ".jpg")
     if os.path.exists(dir):
         os.remove(dir)
     self.SaveImage(frame, dir)
     self.nextPreviewTime = time.time() + config.GetValue("previewTimer")
예제 #3
0
    def destroy(self):
        writeToLog("New Interval: " + self.intervalEntry.get() + " minute(s)\n")

        cm.setTimeInterval(self.intervalEntry.get())

        os.chdir(cm.SRC_LOCATION)
        self.intervalWindow.destroy()
예제 #4
0
    def __init__(self, parent, uiObj):
        #Declare Project Variables
        self.__configFile = os.path.join(
            os.path.expanduser(os.path.join('~', ".sift")), 'sf_config.ini')
        self.loadedProjName = ''
        self.loadedProjPath = ''
        self.loadedProjType = ''

        #Determine the path to sift.py
        self.baseDir = self.initBaseDir()

        #Declare all Managers
        self.uiObj = uiObj
        self.parent = parent
        self.treeViewMgr = TreeviewManager(self, self.uiObj.treeWidget_proj,
                                           self.uiObj.treeWidget_nonProj,
                                           self.uiObj.tabWidget_treeview)
        self.fileMgr = FileManager(self)
        self.viewMgr = ViewManager(self, self.uiObj.tabWidget_viewer)
        self.messageMgr = MessageManager(self, self.uiObj.statusbar)
        self.configMgr = ConfigManager(self)

        #Pass Managers to other Managers that need them
        #(Basically this simulates the Singleton pattern since python can't do it natively)
        self.viewMgr.setFileManager(self.fileMgr)
        self.treeViewMgr.setFileManager(self.fileMgr)
        self.treeViewMgr.setViewManager(self.viewMgr)

        #Load up things needed to happen at start up, but after the managers are all loaded
        self.viewMgr.resetMainViewer()
예제 #5
0
def addBackupLocation():
    location = str(askdirectory())

    writeToLog("New Location Added:")
    writeToLog(location + "\n")

    cm.setLocations(location)
    os.chdir(cm.SRC_LOCATION)
예제 #6
0
    def destroy(self):
        writeToLog("File Types to be Backed Up:")
        writeToLog(', '.join(self.typeEntry.get().split(',')) + "\n")

        cm.setFileTypes(self.typeEntry.get())

        os.chdir(cm.SRC_LOCATION)
        self.typeWindow.destroy()
예제 #7
0
def Start():
    ConfigManager.init()
    logMaster.init()

    logMaster.logInfo(
        "About to Start Chatbox Server on the port: " + str(ConfigManager.Port))
    WebManager.Start(ConfigManager.Port)
    logMaster.log("Server Closed")
예제 #8
0
def addBackupDestination():
    destination = str(askdirectory())

    writeToLog("New Destination Added:")
    writeToLog(destination + "\n")

    cm.setDestination(destination)
    os.chdir(cm.SRC_LOCATION)
예제 #9
0
def Start():
    ConfigManager.init()
    logMaster.init()

    logMaster.logInfo("About to Start Chatbox Server on the port: " +
                      str(ConfigManager.Port))
    WebManager.Start(ConfigManager.Port)
    logMaster.log("Server Closed")
예제 #10
0
 def get(self):
     self.set_header('Content-Type', 'application/json; charset=UTF-8')
     proxyData = CM.getProxySetting()
     pathData = CM.getPath()
     self.write(
         json.dumps({
             "ret": True,
             "proxyData": proxyData,
             "pathData": pathData
         }))
예제 #11
0
def run():
    writeToLog("Starting Backup...")
    totalFiles = 0

    for location in cm.getLoctations():
        backup = fm.BackupFromLocation(location)
        backup.backupFromLocation()
        writeToLog("Backing up " + str(backup.getNumFiles()) + " files from: " + location)
        totalFiles += backup.getNumFiles()

    writeToLog(str(totalFiles) + " Files Located In: \n" + '\n'.join(cm.getDestination()))
    writeToLog("Backup Finished")
예제 #12
0
 def post(self, *args, **kwargs):
     data = tornado.escape.json_decode(self.request.body)
     typ = data['type']
     self.set_header('Content-Type', 'application/json; charset=UTF-8')
     if typ == "proxy":
         if not data['proxyType'] == "none":
             CM.saveProxy({'type': data['proxyType'], 'port': data['port']})
         else:
             CM.saveProxy()
     else:
         print("todo")
     self.write(json.dumps({"ret": True}))
예제 #13
0
    def destroy(self):
        writeToLog("Locations Set:")

        if self.destinationEntry.get() != '':
            writeToLog(', '.join(self.destinationEntry.get().split(',')) + '\n')
        else:
            writeToLog("None\n")

        cm.editDestinations(self.destinationEntry.get().split(','))

        os.chdir(cm.SRC_LOCATION)
        self.destinationWindow.destroy()
예제 #14
0
def getXcInterfaceAddress():
	"""
	Gets the Xc interface address.
	
	@since: 1.0

	@rtype: dict { 'ip': string, 'port': integer }
	@returns: the Xc interface IP + port
	"""
	getLogger().info(">> getXcInterfaceAddress()")
	ret = { 'ip': ConfigManager.instance().get('interface.xc.ip'), 'port': ConfigManager.instance().get('interface.xc.port') }
	getLogger().info("<< getXcInterfaceAddress: %s" % str(ret))
	return ret
예제 #15
0
def configPage():
    if request.method == "GET":
        config_data = config.AsString()
        return render_template("config.html", config_data=config_data)
    elif request.method == "POST":
        data = request.form.get("data")
        data = json.loads(data)
        config.SaveConfig(data)
        return Response("Config Saved! Restart server for changes to take effect", 200)
    elif request.method == "DELETE":
        config.RestoreConfig()
        return Response("Config Restored", 200)
    else:
        abort(400)
예제 #16
0
 def testSetGetLists(self):
     cm = ConfigManager.ConfigManager('testSetGetLists.JSON')
     cm.set_key_values(self.key_list, self.value_list)
     saved_values = cm.get_key_values(self.key_list)
     self.assertEqual(len(saved_values), len(self.value_list))
     for index in range(0, len(saved_values)):
         self.assertEqual(self.value_list[index], saved_values[index])
예제 #17
0
    def get():
        config = ConfigManager()
        loc = locale.getdefaultlocale()[0]
        if loc == "en_US":
            font = "Bold 'times new roman' 22 windows-1252"
        if loc == "ja_JP":
            font = "bold 'MS ゴシック' 22 windows-932"
        config["general"] = {
            "language": "",
            "fileVersion": "100",
            "locale": loc,
            "update": True,
            "timeout": 3
        }

        config["view"] = {"font": font, "colorMode": "white"}
        config["speech"] = {"reader": "AUTO"}

        config["mainView"] = {}

        config["network"] = {"auto_proxy": True}

        config["ocr"] = {
            "tmpdir": os.path.join(os.environ["TEMP"], "soc"),
            "saveSourceDir": True,
            "savedir": os.path.join(os.environ["userprofile"], "Documents")
        }
        return config
예제 #18
0
    def __init__(self, parent, uiObj):
        #Declare Project Variables
        self.__configFile = os.path.join(os.path.expanduser(os.path.join('~',".sift")),'sf_config.ini')
        self.loadedProjName = ''
        self.loadedProjPath = ''
        self.loadedProjType = ''

        #Determine the path to sift.py
        self.baseDir = self.initBaseDir()

        #Declare all Managers
        self.uiObj = uiObj
        self.parent = parent
        self.treeViewMgr = TreeviewManager(self, 
                                           self.uiObj.treeWidget_proj, 
                                           self.uiObj.treeWidget_nonProj,
                                           self.uiObj.tabWidget_treeview)
        self.fileMgr = FileManager(self)
        self.viewMgr = ViewManager(self, self.uiObj.tabWidget_viewer)
        self.messageMgr = MessageManager(self, self.uiObj.statusbar)
        self.configMgr = ConfigManager(self)        

        #Pass Managers to other Managers that need them
        #(Basically this simulates the Singleton pattern since python can't do it natively)
        self.viewMgr.setFileManager(self.fileMgr) 
        self.treeViewMgr.setFileManager(self.fileMgr)
        self.treeViewMgr.setViewManager(self.viewMgr)

        #Load up things needed to happen at start up, but after the managers are all loaded
        self.viewMgr.resetMainViewer()
예제 #19
0
def app_main():
    try:
        logger = lgr.Logger()
        print("--------application starting--------------")
        logger.info("--------application starting--------------")
        print("--------loading data----------------------")
        logger.info("--------loading data----------------------")
        dl = dataLoader.DataLoader()
        train_X, test_X = train_test_split(dl.DataFrame.copy(),
                                           test_size=0.3,
                                           random_state=42)
        # label = train_X["median_house_value"].copy()
        # housing = train_X.drop("median_house_value", axis=1)
        housing = test_X.drop("median_house_value", axis=1)
        #label_test = test_X["median_house_value"].copy()
        numeric_cols = list(housing.columns.values)
        category_cols = ["ocean_proximity"]
        numeric_cols.remove("ocean_proximity")
        dp = preproc.DataPreProcess(numeric_cols, category_cols)
        print("--------processing data-------------------")
        dataProcessed = dp.getProcessedData(housing)
        print(dataProcessed.shape)
        configMagt = cmfmagt.ConfigManager()
        engine = mlEngine.ModelEngine()
        print("------------loading model------------------")
        bestModel = engine.loadML(configMagt.config["APPSETTING"]["ml_path"])
        result = bestModel.predict(dataProcessed)
        print(result.shape)
    except Exception as e:
        print("Error : ", str(e))
예제 #20
0
def getXcInterfaceAddress():
    """
	Gets the Xc interface address.
	
	@since: 1.0

	@rtype: dict { 'ip': string, 'port': integer }
	@returns: the Xc interface IP + port
	"""
    getLogger().info(">> getXcInterfaceAddress()")
    ret = {
        'ip': ConfigManager.instance().get('interface.xc.ip'),
        'port': ConfigManager.instance().get('interface.xc.port')
    }
    getLogger().info("<< getXcInterfaceAddress: %s" % str(ret))
    return ret
예제 #21
0
def set_messages(state):
    enabled = (state == "true" or state == "on")
    config.SetValue(enabled, "email", "enabled")
    response = json.dumps({
        "enabled": enabled
    })
    return Response(response, 200)
예제 #22
0
def getVariables(component="ts"):
    """
	Returns all persisted and transient variables for the provided server component, with
	their different default/user-provided/actual values.
	
	Replaces getConfigInformation.
	
	The result is a dict containing 2 entries,
	each containing a list of dict representing the variables:
	dict[persistent]: list of dict(key, actual, default, user, type, dynamic)
	dict[transient]: list of dict(key, value)
	
	@since: 1.4

	@type  component: string
	@param component: the server component to retrieve variables from.
	ts = testerman server; tacs = connected TACS

	@rtype: a dict[string] of list of dict
	@returns: the 2 classes of internal variables for the server component
	"""

    if component == "ts":
        cm = ConfigManager.instance()
        variables = dict(persistent=cm.getVariables(),
                         transient=cm.getTransientVariables())
        return variables
    elif component == "tacs":
        return None  # To be implemented
    else:
        return None
예제 #23
0
	def __init__(self, loginUrl):
		super(AccountManager, self).__init__()
		self.accountSession = requests.Session()
		self.accountSession.proxies = CM.getProxy()
		self.accountSession.headers.update(CM.loginHeaders)
		self.accountSession.cookies = cookielib.LWPCookieJar(filename='cookies')
		self.loginUrl = loginUrl
예제 #24
0
def getVariables(component = "ts"):
	"""
	Returns all persisted and transient variables for the provided server component, with
	their different default/user-provided/actual values.
	
	Replaces getConfigInformation.
	
	The result is a dict containing 2 entries,
	each containing a list of dict representing the variables:
	dict[persistent]: list of dict(key, actual, default, user, type, dynamic)
	dict[transient]: list of dict(key, value)
	
	@since: 1.4

	@type  component: string
	@param component: the server component to retrieve variables from.
	ts = testerman server; tacs = connected TACS

	@rtype: a dict[string] of list of dict
	@returns: the 2 classes of internal variables for the server component
	"""
	
	if component == "ts":
		cm = ConfigManager.instance()
		variables = dict(persistent = cm.getVariables(), transient = cm.getTransientVariables())
		return variables
	elif component == "tacs":
		return None # To be implemented
	else:
		return None
예제 #25
0
    def GetOuputDir(self):
        outputDir = os.path.abspath(config.GetValue("outputDir"))
        outputDir = os.path.join(outputDir, self.name)

        if not os.path.exists(outputDir):
            os.makedirs(outputDir)
        return outputDir
예제 #26
0
    def SaveVideo(self):
        outputDir = self.GetOuputDir()

        fileName = str(int(time.time())) + ".mp4"
        fileName = os.path.join(outputDir, fileName)

        height, width = self.cap.read().shape[:2]
        print("Size: ", width, "x", height)
        print("fps:", self.fps)
        print("Saving video to: " + fileName + "...", end="")

        #videoWriter = cv2.VideoWriter(fileName, cv2.VideoWriter_fourcc(*"mp4v"), int(self.fps), (width, height))
        self.videoWriter.Start(fileName, self.fps, width, height, "mp4v")
        videoLength = config.GetValue("saveVideoLength")

        if self.prevFrames:
            self.videoWriter.Feed(self.prevFrames.pop())

        saveFrame = None

        sent = False
        count = 0
        startTime = time.time()
        while time.time() - startTime < videoLength:
            self.prevFrames.appendleft(self.cap.read())

            frame = self.prevFrames.pop()
            self.videoWriter.Feed(frame)
            #cv2.imshow(self.name + " Security Feed", frame)
            count += 1

            if time.time() - startTime > videoLength / 2 and not sent:
                sent = True
                saveFrame = frame

        fps = count / (time.time() - startTime)
        print("Actual FPS:", fps)
        self.videoWriter.Stop()

        self.compareFrame = None
        if config.GetValue("email", "enabled"):
            fileName = self.SaveImage(frame)
            email.SendImage(fileName)
        #os.sys("ffmpeg -y -r 30 -i 6bad.mp4 6out.mp4")

        print("Done!")
        return fileName
예제 #27
0
 def test_func_type_cast_for_none_2( self ):
     """ Test func_type_case for none 2 """
     str_answer = "None"
     x_value = "None"
     str_type = Arguments.C_STR_INT_TYPE
     cfmg_test = ConfigManager.ConfigManager(self.str_config_default)
     str_result = cfmg_test._func_type_cast(str_type, x_value)
     self.func_test_equals( str_answer, str(str_result) )
예제 #28
0
 def test_func_type_cast_for_int( self ):
     """ Test func_type_case for int """
     x_answer = 1
     str_value = "1"
     str_type = Arguments.C_STR_INT_TYPE
     cfmg_test = ConfigManager.ConfigManager(self.str_config_default)
     x_result = cfmg_test._func_type_cast(str_type, str_value)
     self.func_test_equals( x_answer, str(x_result) )
예제 #29
0
 def test_func_type_cast_for_float( self ):
     """ Test func_type_case for float """
     x_answer = 0.0
     str_value = "0.0"
     str_type = Arguments.C_STR_FLOAT_TYPE
     cfmg_test = ConfigManager.ConfigManager(self.str_config_default)
     x_result = cfmg_test._func_type_cast(str_type, str_value)
     self.func_test_equals( x_answer, str(x_result) )
예제 #30
0
 def test_func_type_cast_for_bool_false( self ):
     """ Test func_type_case for bool false """
     x_answer = False
     str_value = "False"
     str_type = Arguments.C_STR_BOOL_TYPE
     cfmg_test = ConfigManager.ConfigManager(self.str_config_default)
     x_result = cfmg_test._func_type_cast(str_type, str_value)
     self.func_test_equals( x_answer, str(x_result) )
예제 #31
0
 def test_func_type_cast_for_list( self ):
     """ Test func_type_case for list """
     x_answer = sorted([1,1.22,"hello",[]])
     str_value = '[[],"hello",1,1.22]'
     str_type = Arguments.C_STR_LIST_TYPE
     cfmg_test = ConfigManager.ConfigManager(self.str_config_default)
     x_result = sorted(cfmg_test._func_type_cast(str_type, str_value))
     self.func_test_equals( x_answer, str(x_result) )
예제 #32
0
 def test_func_type_cast_for_string( self ):
     """ Test func_type_case for bool string """
     x_answer = "string"
     str_value = "string"
     str_type = Arguments.C_STR_STRING_TYPE
     cfmg_test = ConfigManager.ConfigManager(self.str_config_default)
     x_result = cfmg_test._func_type_cast(str_type, str_value)
     self.func_test_equals( x_answer, str(x_result) )
예제 #33
0
 def test_func_normalize_argument_for_present_string( self ):
     """ Test func_normalize_argument for a string that is present """
     str_env = os.path.join(self.str_test_directory, "func_normalize_argument_for_present_string")
     str_answer = "copy"
     str_argument = "COPY"
     dict_args = {"COPY":"copy"}
     cfmg_test = ConfigManager.ConfigManager(self.str_config_default)
     str_result = cfmg_test.func_normalize_argument(str_argument, dict_args )
     self.func_test_equals( str_answer, str_result )
예제 #34
0
 def testCompareDicts(self):
     cm = ConfigManager.ConfigManager('testCompareDicts.JSON')
     cm.set_key_values(self.key_list, self.value_list)
     saved_values = cm.get_key_values(self.key_list)
     new_dict = dict()
     for index in range(0, len(self.key_list)):
         new_dict[self.key_list[index]] = saved_values[index]
     self.assertEqual(cm.compare_cfg_dict(new_dict), True)
     self.assertEqual(cm.compare_cfg_dict(self.sample_wrong_cfg), False)
예제 #35
0
def getConfigInformation():
	"""
	Returns the current internal configuration values.
	
	@since: 1.0
	@deprecated: 1.4 - use getVariables() instead.

	@rtype: a dict[string] of strings
	@returns: a dict containing the configuration values, indexed by their keys
	"""	
	ret = {}
	for variable in ConfigManager.instance().getVariables():
		ret[variable['key']] = str(variable.get('actual'))
	return ret
예제 #36
0
    def initialize(self):
        config = ConfigManager.get_data()
        for reference in config['references']:
            self.add_reference_from_yaml(reference)

        machines = models.ManagedMachine.select()
        for machine in machines:
            reference = machine.reference_image
            reference = self._reference_machines[reference]

            self.add_machine_from_database(machine, reference)

            name = machine.image_name
            machine = self._managed_machines[name]
            machine.start()
예제 #37
0
class TrapGen:
    def __init__(self):
        self.data = ""
        self.dictionary = {}
        self.dev_cilly = self.getDeviceCLLI()
        self.cm = ConfigManager()
        self.getDictionary()

    def send_trap(self):
        self.generate()

        ntfOrg = ntforg.NotificationOriginator()

        ntfOrg.sendNotification(
        ntforg.CommunityData('public'),
        ntforg.UdpTransportTarget((self.cm.getTrapIp(), 5050)),
        'trap',
        ntforg.MibVariable('SNMPv2-MIB', 'sysLocation'),
        ('1.3.6.1.6.3.1.1.5.4', v2c.OctetString(self.data)))

        #print "Trap has been sent:" + ' ' + self.data

    def generate(self):
        ts = time.time()

        self.data = str(self.dev_cilly[ random.randint( 0,len(self.dev_cilly)-1 ) ]) +'|'+ str(self.dictionary[random.randint(0,13)])+'|'+str(ts)

    def getDictionary(self):
        with open("/home/max/TF/NetworkManagmentTool/data/traps.txt",'r') as infile:
            for line in infile:
                key,value = line.split(':')
                self.dictionary[int(key)] = str(value).rstrip()

    def getDeviceCLLI(self):
        con = cx_Oracle.connect('orcdb/[email protected]/orcl')
        print "Connected"

        data = []
        cur = con.cursor()
        cur.execute("select ID from SYSTEM.DEVICE")
        for item in cur.fetchall():
            data.append(item[0])
        return data
예제 #38
0
파일: Snmp.py 프로젝트: rolfschr/testerman
def initialize(address):
	global TheSnmpServer
	if address is None:
		address = (ConfigManager.get("snmp.ip", ""), int(ConfigManager.get("snmp.port", "1161")))
	TheSnmpServer = SnmpServer(address)
	TheSnmpServer.start()
예제 #39
0
# This module is responsible for managing (mainly remote) probes, on the Testerman Server
# side only.
#
# - It enables dynamic probe deployment using ssh or on localhost.
# - Limitation: no ability to stop probes
#
##

import ConfigManager
import EventManager
import TestermanAgentControllerClient as TACC

import logging


cm = ConfigManager.instance()

################################################################################
# Logging
################################################################################

def getLogger():
	return logging.getLogger('TS.ProbeManager')


################################################################################
# TACS Client
################################################################################

class ProbeManager:
	"""
예제 #40
0
 def __init__(self):
     self.data = ""
     self.dictionary = {}
     self.dev_cilly = self.getDeviceCLLI()
     self.cm = ConfigManager()
     self.getDictionary()
예제 #41
0
class SFLibManager():
    def __init__(self, parent, uiObj):
        #Declare Project Variables
        self.__configFile = os.path.join(os.path.expanduser(os.path.join('~',".sift")),'sf_config.ini')
        self.loadedProjName = ''
        self.loadedProjPath = ''
        self.loadedProjType = ''

        #Determine the path to sift.py
        self.baseDir = self.initBaseDir()

        #Declare all Managers
        self.uiObj = uiObj
        self.parent = parent
        self.treeViewMgr = TreeviewManager(self, 
                                           self.uiObj.treeWidget_proj, 
                                           self.uiObj.treeWidget_nonProj,
                                           self.uiObj.tabWidget_treeview)
        self.fileMgr = FileManager(self)
        self.viewMgr = ViewManager(self, self.uiObj.tabWidget_viewer)
        self.messageMgr = MessageManager(self, self.uiObj.statusbar)
        self.configMgr = ConfigManager(self)        

        #Pass Managers to other Managers that need them
        #(Basically this simulates the Singleton pattern since python can't do it natively)
        self.viewMgr.setFileManager(self.fileMgr) 
        self.treeViewMgr.setFileManager(self.fileMgr)
        self.treeViewMgr.setViewManager(self.viewMgr)

        #Load up things needed to happen at start up, but after the managers are all loaded
        self.viewMgr.resetMainViewer()

    # - - - - - - - - - - - - - - - - 
    # - Name: loadProject()
    # - Parameters: file_dirs, projPath - provided by sift
    # - Description: Loads the project from the .all by creating a list of all .fml + paths.
    # - Lastly the treeview is populate to allow the user to navigate through the flows
    def loadProject(self, fileDirs, projPath, projName, projType):
        #Reset the main viewer back the welcome tab in case we're opening a project while already opened
        self.viewMgr.resetMainViewer()

        #Make sure fileDirs is a list
        if(not isinstance(fileDirs, list)):
            fileDirs = [fileDirs]

        #Make sure fileDirs is a correct form
        if((len(fileDirs) == 0) or
           (not isinstance(fileDirs[0], QtCore.QString) and not isinstance(fileDirs[0], str)) or
           fileDirs[0] == ''):
            self.printError("Project path is incorrect or not a string",
                                       "Project NOT loaded successfully!", 10)
            return

        #Get data from the .all
        self.loadedProjName = projName
        self.loadedProjPath = projPath
        self.loadedProjType = projType

        #Load project into file manager and populate the treeview, if they fail, tell the user
        if (self.fileMgr.loadProject(fileDirs) and self.treeViewMgr.loadTreeviewProject()):
            self.uiObj.tabWidget_treeview.setCurrentIndex(0)
            self.out("Project loaded successfully", 6) 
        else:
            msg =  "Project data incorrect, try loading project in sift using the open button.\n"
            msg +=  "\tIf this is a Lua project, loading lua files on windows is not yet implemented."
            self.printError(msg, "Project NOT loaded successfully", 10) 

    # - - - - - - - - - - - - - - - - 
    # - Name: loadFiles()
    # - Parameters: fileList
    # - Description: Loads individual files given by the user that are not associated with a .all/project
    def loadFiles(self, fileList):
        #Pass to fileMgr to load, if any are already loaded in proj, remove and warn user
        filesNotAdded = self.fileMgr.addFiles(fileList)

        #If any files were tossed, tell the user
        if(len(filesNotAdded) > 0):
            self.messageMgr.loadedFilesTossedBox(filesNotAdded)

        #If any files were actually loaded, update and switch to nonproj treeview
        if(len(filesNotAdded) < len(fileList)):
            #Populate the treeview
            self.treeViewMgr.loadTreeviewNonProject()
            self.uiObj.tabWidget_treeview.setCurrentIndex(1)

            #Tell user project is loaded
            self.out(str(len(fileList) - len(filesNotAdded)) + " of " + str(len(fileList)) + " file(s) loaded successfully", 6)
                

    # - - - - - - - - - - - - - - - - 
    # - Name: reloadFile()
    # - Parameters: path
    # - Description: Reloads a file if it is currently being viewed. If there are unsaved changes
    # - prompt the user for what they want to do
    def reloadFile(self, fileName, pathOrProj):
        #Get List of all tabs displaying something from the file
        displayedIndexs = self.viewMgr.getDisplayedFileIndexsList(fileName, pathOrProj)
        unsavedChanges = []

        #For every item being displayed that doesn't have unsaved changes, just reload them without bothering user
        #But if there are one or more with changes give the user a warning.
        for index in displayedIndexs:
            if(not self.viewMgr.doesTabHaveStatus("unsaved", index)):
                self.viewMgr.reloadTab(index)

            #If there are unsaved changes, we need to know what the user wants since just saving over
            #their changes may cause unwanted fury.
            else:
                unsavedChanges.append(index)

        #If any tab had unsaved changes, tell the user and see what they want to do
        if (len(unsavedChanges) > 0):
            result = self.messageMgr.conflictMessageBox(fileName)
            #User wants to discard their changes, and reload the viewer with the external changes
            if result == 'discard':
                for index in unsavedChanges:
                    self.viewMgr.reloadTab(index)

            #User wants to Ignore the external changes and overwrite them with whats in the viewer
            #Add the conflict status so they can see that the viewer and file are out of sync
            elif result == 'ignore':
                for index in unsavedChanges:
                    self.viewMgr.addStatus('conflict', index)

    # - - - - - - - - - - - - - - - - 
    # - Name: reloadFileTreeview()
    # - Parameters: path
    # - Description: Reloads a file entry in the treeview, if it exists
    def reloadFileTreeview(self, fileName, pathOrProj):
        self.treeViewMgr.reloadFileTreeview(fileName, pathOrProj)

    # - - - - - - - - - - - - - - - - 
    # - Name: *Update() 
    # - Parameters: None
    # - Description: update the flow that is being viewed in the main viewer. When
    # - a new selection is made in the treeview an event calls these functions, which
    # - are passed to the treeview where it then calls the view manager, giving it the 
    # - name of the flow that needs to be displayed in the view
    def tvProjUpdate(self):
        self.treeViewMgr.projUpdate()

    def tvNonProjUpdate(self):
        self.treeViewMgr.nonProjUpdate()

    # - - - - - - - - - - - - - - - - 
    # - Name: resizeTreeview() 
    # - Parameters: None
    # - Description: When something on the window is moved, resize the tree widgets
    # - so they always match the tab widgets size.
    def resizeTreeview(self):
        #First resize the tab widget to the containing frames size, then
        #use that to resize the treeviews that reside in the tab widget
        self.treeViewMgr.resizeTreeviews(self.uiObj.tabWidget_treeview.size())

    # - - - - - - - - - - - - - - - - 
    # - Name: out 
    # - Parameters: 
    # - Description: Print normal messages to the user in the appropriate fields depending on 
    # - the arguments passed in.
    # - Usage: out("Message to the output box"), out("Message to the status bar",  10 [time to show message in seconds])
    # -        out("Message to output box", "Message to status bar", 10 [time to show message in seconds])
    def out(self, text, *args):
        self.messageMgr.out(text, args)

    # - - - - - - - - - - - - - - - - 
    # - Name: printError
    # - Parameters: 
    # - Description: Similar to out, but for error messages
    def printError(self, text, *args):
        self.messageMgr.printError(text, args)

    # - - - - - - - - - - - - - - - - 
    # - Name: displayFlow
    # - Parameters: dIndex - If there are duplicate flows in an fml, the index of 
    # - which copy this is
    # - Description: Calls viewmgr to display the flow in an appropriate veiwer tab
    def displayFlow(self, fileName, pathOrProj, flowName, dIndex=None):
        self.viewMgr.displayFlow(fileName, pathOrProj, flowName, dIndex=dIndex)

    # - - - - - - - - - - - - - - - - 
    # - Name: displayFml
    # - Parameters:  
    # - Description: Calls the view manager to display the fml in an appropriate tab
    def displayFml(self, fileName, pathOrProj):
        self.viewMgr.displayFml(fileName, pathOrProj)

    # - - - - - - - - - - - - - - - - 
    # - Name: addFindHistoryEntry(combobox)
    # - Parameters: combobox - the combobox ui element to add the text from
    # - Description: adds the current text in the combobox to the config history
    def addFindHistoryEntry(self, combobox):
        self.configMgr.addFindHistoryEntry(combobox)

    # - - - - - - - - - - - - - - - - 
    # - Name: addReplaceHistoryEntry(combobox)
    # - Parameters: combobox - the combobox ui element to add the text from
    # - Description: adds the current text in the combobox to the config history
    def addReplaceHistoryEntry(self, combobox):
        self.configMgr.addReplaceHistoryEntry(combobox)

    # - - - - - - - - - - - - - - - - 
    # - Name: addRecentPath(flowName, fmlPath)
    # - Description: adds a flowname and fml path to the config history for the recent menu
    def addRecentPath(self, fileName, pathOrProj, flowName=None, dIndex=None):
        #Need to store both path and proj in the config file
        path = self.fileMgr.getFilePath(fileName, pathOrProj)
        proj = self.fileMgr.getFileProj(fileName, pathOrProj)
        self.configMgr.addRecentPath(fileName, path, proj, flowName, dIndex)

    def getRecentList(self):
        return self.configMgr.getRecentList()

    # - - - - - - - - - - - - - - - - 
    # - Name: updateComboHistoryEntry(text)
    # - Parameters: combobox - the combobox ui element to add the text from
    # - Description: moves the current text in the combobox to the top of the config history (technically bottom
    # - of the xml nodes since it can only be appended to. String list is flipped in loadCombo())
    def updateComboHistoryEntry(self, combobox):
        self.configMgr.updateComboHistoryEntry(combobox)

    # - - - - - - - - - - - - - - - - 
    # - Name: updateFindOptions(text)
    # - Parameters: ops_d - a dictionary of all the options checked in the dialog
    # - Description: saves all the options in config.ini, updates if they already exist
    def updateConfigOptions(self, ops_d, comp):
        self.configMgr.updateConfigOptions(ops_d, comp)

    # - - - - - - - - - - - - - - - - 
    # - Name: loadCombo(combobox)
    # - Parameters: combobox - the combobox ui element to add the text from
    # - Description: Fills the combo box with the items in the config file
    def loadCombo(self, combobox):
        self.configMgr.loadCombo(combobox)

    # - - - - - - - - - - - - - - - - 
    # - Name: getFindConfigDict()
    # - Description: Get the dictionary of the windows radio and check states
    def getConfigDict(self, comp):
        return self.configMgr.getConfigDict(comp)

    # - - - - - - - - - - - - - - - - 
    # - Name: findTextCurrent()
    # - Description: Get the next occurrence of text in the currently selected tab of main viewer
    def findTextCurrent(self, text, flags, flip=False):
        return self.viewMgr.findTextCurrent(text, flags, flip)

    #-- Return True if the newly found match is within the search area boundaries
    def isCursorInSearchArea(self):
        saBeg = self.viewMgr.getSearchAreaBeginning()
        saEnd = self.viewMgr.getSearchAreaEnd()
        cEnd = self.viewMgr.getCursorEnd()

        if(self.docCoordIsGreater(cEnd, saBeg) and self.docCoordIsLess(cEnd, saEnd)):
            return True
        else:
            return False

    def docCoordIsGreater(self, coord1, coord2):
        #is coord1 greater than (its position is passed) coord2
        if((coord1[0] == coord2[0] and coord1[1] > coord2[1]) or
            (coord1[0] > coord2[0])):
            return True

        return False

    def docCoordIsLess(self, coord1, coord2):
        #is coor1 less than (its position is before) coord2
        if((coord1[0] == coord2[0] and coord1[1] < coord2[1]) or
            (coord1[0] < coord2[0])):
            return True

        return False

    def setCursorToReference(self, line, pos):
        self.viewMgr.setCursorToReference(line, pos)

    def getCursorBeginning(self):
        return self.viewMgr.getCursorBeginning()

    def getCursorEnd(self):
        return self.viewMgr.getCursorEnd()

    def getSearchAreaBeginning(self):
        return self.viewMgr.getSearchAreaBeginning()

    def getSearchAreaEnd(self):
        return self.viewMgr.getSearchAreaEnd()

    def setSearchArea(self):
        return self.viewMgr.setSearchArea()

    def unsetSearchArea(self):
        self.viewMgr.unsetSearchArea()

    def reselectSearchArea(self):
        self.viewMgr.reselectSearchArea()

    def getSelectionText(self):
        return self.viewMgr.getSelectionText()

    def isDisplayed(self, fileName, pathOrProj):
        return self.viewMgr.isDisplayed(fileName, pathOrProj)

    # - - - - - - - - - - - - - - - - 
    # - Name: findAllOpenFmls()
    # - Description: Find every file with a reference of text and open them in a new tab
    def findAllOpenFmls(self, text, flags):
        #Get list of [fileNames, pathorProj] the text occurs in
        findList = self.fileMgr.findAllInFiles(text, flags)

        #Open every member of list in a new tab, if tab already exists don't create a new one
        for item in findList:
            self.viewMgr.displayFml(item[0], item[1]) #display item in tab named item

    # - - - - - - - - - - - - - - - - 
    # - Name: findReferences()
    # - Parameters: text - string - text for which to search
    # -             flags - search flags
    # -             isCurrent - bool - is the user searching the current page, False if searching selection
    # - Description: If there is a match for text then return a list of all line numbers and lines the match
    # - occurs in. Handle searching in a selection.
    def findReferences(self, text, flags, isCurrent):
        #Search all lines
        reg = text = re.escape(str(text))
        flag = re.I

        if(flags['wo']):
            reg = '^' + text + '$|'             #text by itself
            reg += '^' + text + '(?=[\s\n])|'       #text at start of line
            reg += '[\s]' + text + '(?=[\s\n])|'    #text in a line
            reg += '[\s]' + text + '$'          #text at the end

        if(flags['cs']):
            flag = 0        

        if(isCurrent):
            return self.viewMgr.getCurrentReferences(reg, flag)
        else:
            return self.viewMgr.getSelectionReferences(reg, flag)

    # - - - - - - - - - - - - - - - - 
    # - Name: findReferencesInFiles()
    # - Parameters: text - string - text for which to search
    # -             flags - search flags
    # - Description: If there is a match for text then display the line number and line in
    # - the output box. Searches all fml files.
    def findReferencesInFiles(self, text, flags):
        return self.fileMgr.findReferences(text, flags)

    # - - - - - - - - - - - - - - - - 
    # - Name: getCount()
    # - Description: Returns the number of matches for a given search
    def getCount(self, text, flags, isCurrent):
        #Search all lines
        reg = text = str(text)
        flag = re.I

        if(flags['wo']):
            reg = '^' + text + '$|'             #text by itself
            reg += '^' + text + '(?=[\s\n])|'       #text at start of line
            reg += '[\s]' + text + '(?=[\s\n])|'    #text in a line
            reg += '[\s]' + text + '$'          #text at the end
            

        if(flags['cs']):
            flag = 0        

        if(isCurrent):
            count = self.viewMgr.getCountCurrent(reg, flag)
        else:
            count = self.viewMgr.getCountSelection(reg, flag)
        return count

    def isFileLoaded(self, fileName, path):
        return self.fileMgr.isFileLoaded(fileName, path)

    def isProjLoaded(self, proj=None):
        if(proj and self.loadedProjName == proj):
            return True
        elif(not proj and self.loadedProjName != ''):
            return True

        return False

    def getDownloadFileList(self):
        return self.fileMgr.getDownloadFileList(self.loadedProjName, self.loadedProjPath)

    def tabAlreadyExists(self, tabName):
        return self.viewMgr.tabAlreadyExists(tabName)

    def tabContainsPos(self, pos):
        return self.viewMgr.tabContainsPos(pos)

    def getCurrentTabText(self):
        return self.viewMgr.getCurrentTabText()

    def isFirstSearch(self):
        #If the search tag is in the tab title, then its not the first search
        if(self.viewMgr.doesTabHaveStatus('search')):
            return False
        return True

    def finishSearch(self):
        self.viewMgr.removeStatus('search')
        self.viewMgr.unsetSearchArea()

    def finishAllSearchs(self):
        self.viewMgr.removeAllStatus('search')
        self.viewMgr.unsetAllSearchAreas()

    def startSearch(self):
        self.viewMgr.addStatus('search')

    def addStatus(self, status):
        self.viewMgr.addStatus(status)

    def selectionToFill(self, selection):
        #Determine if selection is ok to post in the find textbox when find dialog opens
        selection = selection.strip(' \n(') #strip leading/trailing spaces and new lines
        
        #If its empty, just return it
        if(selection == ''):
            return selection

        #If its a flow or keyword (ie has letters numbers or underscores uninterrupted)
        if(re.search('^(flow|cmd)?[_\w\d]+$', selection)):
            return selection

        #If what remains isn't a consecutive group of letters, numbers, underscores
        return ''

    # --- Config Save/Load Methods --- #
    def saveWindowState(self, width, height, tvWidth):
        self.configMgr.addWindowSize(width, height)
        self.configMgr.addTreeviewWidth(tvWidth)
        self.configMgr.save()

    def getWindowSize(self):
        return self.configMgr.getWindowSize()

    def getTreeviewWidth(self):
        return self.configMgr.getTreeviewWidth()
        
    def setLastOpenDir(self, path):
        self.configMgr.addLastOpenDir(path)

    def getLastOpenDir(self):
        return self.configMgr.getLastOpenDir()

    #--- Edit Related Methods ---#

    def cut(self):
        self.viewMgr.cut()

    def copy(self):
        self.viewMgr.copy()

    def paste(self):
        self.viewMgr.paste()

    def undo(self):
        self.viewMgr.undo()

    def redo(self):
        self.viewMgr.redo()

    def indent(self):
        self.viewMgr.indent()

    def unindent(self):
        self.viewMgr.unindent()

    def comment(self):
        self.viewMgr.comment()

    def uncomment(self):
        self.viewMgr.uncomment()

    def replace(self, text):
        self.viewMgr.replace(text)

    def beginUndoAction(self):
        self.viewMgr.beginUndoAction()

    def endUndoAction(self):
        self.viewMgr.endUndoAction()

    #--- Saving ---#
    def saveCurrentTab(self):
        result = self.viewMgr.saveTab()

        #If the tab failed to save, let the user know
        if (len(result) > 0):
            self.messageMgr.failedSaveBox(result)
            return False

        return True

    def saveAllTabs(self):
        #result will be the fileNames of what failed to save, if empty nothing failed
        result = self.viewMgr.saveAllTabs()

        if(len(result) > 0):
            self.messageMgr.failedSaveBox(result)
            return False

        return True

    def anyUnsavedChanges(self):
        return self.viewMgr.anyUnsavedChanges()

    def saveAnyUnsavedChanges(self):
        self.viewMgr.saveAnyUnsavedChanges()

    def getRepo(self):
        return self.fileMgr.getRepo()

    def initBaseDir(self):
        dir = sys.path[0]

        #If there is a file on the end (cause of randals windows bug) remove it
        parts = os.path.split(dir)
        if(re.search('.*\..*', parts[1])):
            dir = parts[0]

        return dir

    #--- Getters ---#
    def getFileNameFromFuncName(self, projName, funcName):
        return self.fileMgr.getFuncParent(projName, funcName)

    def getBaseDir(self):
        return self.baseDir

    def getAboutText(self):
        return self.fileMgr.getAboutText()

    def getDocDir(self):
        dir = self.getBaseDir()

        if(os.path.exists(os.path.join(dir, 'SiftFlow'))):
            return os.path.join(dir, 'SiftFlow', 'docs')

        #if all else fails, return str to avoid None type cat error
        return dir

    def getIconDir(self):
        #Find the resource path that has SiftFlow, add the images folder to it
        dir = self.getBaseDir()       

        if(os.path.exists(os.path.join(dir, 'SiftFlow'))):
            return os.path.join(dir, 'SiftFlow', 'images')

        #If all else fails, return a string to get around a None type str cat error
        return dir

    def getConfigFile(self):
        return self.__configFile

    def getLineNumberOffset(self):
        return self.viewMgr.getLineNumberOffset()

    def getLoadedProjName(self):
        return self.loadedProjName

    def getLoadedProjType(self):
        return self.loadedProjType

    def getLoadedProjPath(self):
        return self.loadedProjPath

    def getMainUiActions(self):
        #Return all the menu actions from the main window ui
        actions = {
            'cut':          self.uiObj.actionCut,
            'copy':         self.uiObj.actionCopy,
            'paste':        self.uiObj.actionPaste,
            'find':         self.uiObj.actionFind,
            'findinfiles':  self.uiObj.actionFindInFiles,
            'currentReferences': self.uiObj.actionReference,
            'referenceInFiles': self.uiObj.actionReferenceInFiles
        }
        return actions
예제 #42
0
파일: main.py 프로젝트: c0ns0le/Pythonista
import FileManager
reload(FileManager)
import HTMLEditor
reload(HTMLEditor)
import ServerEditor
reload(ServerEditor)
import ConfigManager
reload(ConfigManager)

DEBUG = True

fm = FileManager.Manager()
fv = FileManager.FileViewer(fm)
c = ConfigManager.Config()
cv = ConfigManager.load_view(c)
cv.set_config(c)
print fv.name

class MainView(ui.View):
    def __init__(self, *args, **kwargs):
        ui.View.__init__(self, *args, **kwargs)
        self.htmlEditorView = ui.View()
        self.serverEditorView = ui.View()
        
        global cv
        self.config_view = cv
    
    def did_load(self):
        print "%r did load" % self
        
	def onRequest(self, channel, transactionId, request):
		self.getLogger().debug("New request received:\n%s" % str(request))
		try:
			method = request.getMethod()

			# Probe-targeted requests
			if method == "TRI-EXECUTE-TESTCASE":
				# Forward the body as is, with possible parameters
				self._controller.triExecuteTestCase(request.getUri(), request)
				self.sendResponse(channel, transactionId, Messages.Response(200, "OK"))
			elif method == "TRI-SEND":
				# Probe send - we forward the body as is, with the original encoding and type.
				self._controller.triSend(request.getUri(), request)
				self.sendResponse(channel, transactionId, Messages.Response(200, "OK"))
			elif method == "TRI-SA-RESET":
				self._controller.triSaReset(request.getUri())
				self.sendResponse(channel, transactionId, Messages.Response(200, "OK"))
			elif method == "TRI-MAP":
				self._controller.triMap(request.getUri())
				self.sendResponse(channel, transactionId, Messages.Response(200, "OK"))
			elif method == "TRI-UNMAP":
				self._controller.triUnmap(request.getUri())
				self.sendResponse(channel, transactionId, Messages.Response(200, "OK"))

			# TACS-targeted requests
			elif method == "LOCK":
				self._controller.lockProbe(channel, request.getHeader('Probe-Uri'))
				response = Messages.Response(200, "OK")
				self.sendResponse(channel, transactionId, response)
			elif method == "UNLOCK":
				self._controller.unlockProbe(channel, request.getHeader('Probe-Uri'))
				self.sendResponse(channel, transactionId, Messages.Response(200, "OK"))
			elif method == "GET-PROBES":
				probes = self._controller.getRegisteredProbes()
				resp = Messages.Response(200, "OK")
				resp.setApplicationBody(probes)
				self.sendResponse(channel, transactionId, resp)
			elif method == "GET-AGENTS":
				probes = self._controller.getRegisteredAgents()
				resp = Messages.Response(200, "OK")
				resp.setApplicationBody(probes)
				self.sendResponse(channel, transactionId, resp)
			elif method == "GET-VARIABLES":
				cm = ConfigManager.instance()
				variables = dict(persistent = cm.getVariables(), transient = cm.getTransientVariables())
				resp = Messages.Response(200, "OK")
				resp.setApplicationBody(variables)
				self.sendResponse(channel, transactionId, resp)
			elif method == "GET-PROBE":
				probeUri = request.getHeader('Probe-Uri')
				info = self._controller.getProbeInfo(probeUri)
				if info:
					resp = Messages.Response(200, "OK")
					resp.setApplicationBody(info)
				else:
					resp = Messages.Response(404, "Not found")
				self.sendResponse(channel, transactionId, resp)
			elif method == "SUBSCRIBE": # Notification or Request ??
				self._controller.subscribe(channel, request.getUri())
				self.sendResponse(channel, transactionId, Messages.Response(200, "OK"))
			elif method == "UNSUBSCRIBE": # Notification or Request ??
				self._controller.unsubscribe(channel, request.getUri())
				self.sendResponse(channel, transactionId, Messages.Response(200, "OK"))

			# Agent-targeted requests
			elif method == "DEPLOY":
				probeInfo = request.getApplicationBody()
				agentUri = request.getHeader('Agent-Uri')
				self._controller.deployProbe(agentUri = agentUri, probeName = probeInfo['probe-name'], probeType = probeInfo['probe-type'])
				self.sendResponse(channel, transactionId, Messages.Response(200, "OK"))
			elif method == "UNDEPLOY":
				probeInfo = request.getApplicationBody()
				agentUri = request.getHeader('Agent-Uri')
				self._controller.undeployProbe(agentUri = agentUri, probeName = probeInfo['probe-name'])
				self.sendResponse(channel, transactionId, Messages.Response(200, "OK"))
			elif method == "RESTART":
				agentUri = request.getHeader('Agent-Uri')
				self._controller.restartAgent(agentUri = agentUri)
				self.sendResponse(channel, transactionId, Messages.Response(200, "OK"))
			elif method == "UPDATE":
				agentUri = request.getHeader('Agent-Uri')
				self._controller.updateAgent(agentUri = agentUri)
				self.sendResponse(channel, transactionId, Messages.Response(200, "OK"))
			else:
				raise IaException("Unsupported method", 505, "Not Supported")

		except TacsException, e:
			resp = Messages.Response(e.code, e.reason)
			resp.setBody(str(e))
			self.sendResponse(channel, transactionId, resp)