Ejemplo n.º 1
0
 def delete_index(self):
     strRootDir = request.getServletContext().getRealPath("/")
     _s = strRootDir + "index.html"
     indexHtmlFile = File(_s)
     if indexHtmlFile.exists():
         indexHtmlFile.delete()                
     request.setAttribute("errorMessage", u"首页缓存文件删除完毕!")
Ejemplo n.º 2
0
def load_from_file(file_package,expected_class):
    print("loading %s from %s" % (expected_class,file_package))

    compiled_file = File(file_package.replace(".", "/") + "/" + expected_class + "$py.class")
    source_file = File(file_package.replace(".", "/") + "/" + expected_class + ".py")
    print("get request for controller %s. Compiled file outdated."%expected_class)
    if compiled_file.exists():
        if compiled_file.lastModified()<source_file.lastModified():
            print("get request for controller %s. Compiled file outdated."%expected_class)
            compiled_file.delete()
        else:
            print("get request for controller %s. Compiled file is up-to-date."%expected_class)
    else:
        print("get request for controller %s. Compiled file does not exists."%expected_class)
    py_mod = imp.load_source("module_"+expected_class, source_file.getAbsolutePath())


    if hasattr(py_mod, expected_class):
        class_inst = getattr(py_mod,expected_class)

    else:
        class_inst =None

    print(class_inst.__doc__)
    print(class_inst.__name__)
    return class_inst
Ejemplo n.º 3
0
 def delete_subject_nav(self):
     strRootDir = request.getServletContext().getRealPath("/")
     strHtmlDir = strRootDir + "html" + File.separator
     _s = strHtmlDir + "subject_nav.html"
     subjectNavFile = File(_s)
     if subjectNavFile.exists():
         subjectNavFile.delete()         
     request.setAttribute("errorMessage", u"学科导航缓存文件删除完毕!")
Ejemplo n.º 4
0
 def empty_updateinfo(self):
     strRootDir = request.getServletContext().getRealPath("/")
     strHtmlDir = strRootDir + "html" + File.separator
     _s = strHtmlDir + "updateinfo.htm"
     updateinfoFile = File(_s)
     if updateinfoFile.exists():
         updateinfoFile.delete()
     updateinfoFile.createNewFile()
     request.setAttribute("errorMessage", u"清空或者新建网站更新信息文件完毕!")
Ejemplo n.º 5
0
def deleteGRLoaderXmlInputFile(fileName):
    xmlInputFileStr = "%s%s%s" % (adapterResWorkDir, FILE_SEPARATOR, fileName)
    try:
        logger.debug("\tDeleting GRLoader input XML file: %s" % xmlInputFileStr)
        xmlInputFile = File(xmlInputFileStr)
        xmlInputFile.delete()
    except:
        raise Exception, "Unable to delete GR Loader Input XML File"
    logger.debug("\tDeleted GRLoader input XML file: %s" % xmlInputFileStr)
Ejemplo n.º 6
0
def deleteGRLoaderXmlInputFile(fileName):
    xmlInputFileStr = "%s%s%s" % (adapterResWorkDir, FILE_SEPARATOR, fileName)
    try:
        logger.debug("\tDeleting GRLoader input XML file: %s" %
                     xmlInputFileStr)
        xmlInputFile = File(xmlInputFileStr)
        xmlInputFile.delete()
    except:
        raise Exception, "Unable to delete GR Loader Input XML File"
    logger.debug("\tDeleted GRLoader input XML file: %s" % xmlInputFileStr)
Ejemplo n.º 7
0
def removedirs(dir):
	if not isinstance(dir, File):
		dir = File(dir)
	list = dir.listFiles()
	if list is None:
		return
	for file in list:
		if file.isDirectory():
			removedirs(file)
		elif file.isFile():
			file.delete();
	dir.delete()
Ejemplo n.º 8
0
def removedirs(dir):
    if not isinstance(dir, File):
        dir = File(dir)
    list = dir.listFiles()
    if list is None:
        return
    for file in list:
        if file.isDirectory():
            removedirs(file)
        elif file.isFile():
            file.delete()
    dir.delete()
Ejemplo n.º 9
0
 def deleteDirectory(self, sPath):
     # 如果sPath不以文件分隔符结尾,自动添加文件分隔符  
     dirFile = File(sPath)
     # 如果dir对应的文件不存在,或者不是一个目录,则退出  
     if dirFile.exists() == False or dirFile.isDirectory() == False:
         return
     # 删除文件夹下的所有文件(包括子目录)
     files = dirFile.listFiles()
     for f in files:
         # 删除子文件
         if f.isFile():
             f.delete()
         else:
             self.deleteDirectory(f.getAbsolutePath())
     #/删除当前目录  
     dirFile.delete()
     dirFile = None
Ejemplo n.º 10
0
def rmdir(path):
    """rmdir(path)

    Remove a directory."""
    f = File(sys.getPath(path))
    if not f.exists():
        raise OSError(errno.ENOENT, errno.strerror(errno.ENOENT), path)
    elif not f.isDirectory():
        raise OSError(errno.ENOTDIR, errno.strerror(errno.ENOTDIR), path)
    elif not f.delete():
        raise OSError(0, "couldn't delete directory", path)
Ejemplo n.º 11
0
def rmdir(path):
    """rmdir(path)

    Remove a directory."""
    f = File(sys.getPath(path))
    if not f.exists():
        raise OSError(errno.ENOENT, strerror(errno.ENOENT), path)
    elif not f.isDirectory():
        raise OSError(errno.ENOTDIR, strerror(errno.ENOTDIR), path)
    elif not f.delete():
        raise OSError(0, "couldn't delete directory", path)
Ejemplo n.º 12
0
    def clearAllStaticCacheFile(self):
        #删除可能存在的静态文件
        strRootDir = request.getServletContext().getRealPath("/")
        strRootDir = URLDecoder.decode(strRootDir, "utf-8")
        #删除首页
        file = File(strRootDir + "index.html")
        if file.exists() and file.isFile():
            file.delete()
        file = File(strRootDir + "index.htm")
        if file.exists() and file.isFile():
            file.delete()

        strFile = strRootDir + "html" + File.separator + "subject_nav.html"
        file = File(strFile)
        if file.exists() and file.isFile():
            file.delete()

        strFile = strRootDir + "html" + File.separator + "user" + File.separator
        file = File(strFile)
        if file.exists():
            self.deleteDirectory(strFile)

        strFile = strRootDir + "html" + File.separator + "unit" + File.separator
        file = File(strFile)
        if file.exists():
            self.deleteDirectory(strFile)
        file = None
Ejemplo n.º 13
0
    def processItem(self, myMsg):
        msgIdLong = myMsg.getMessageId()
        msgIdStr = str(msgIdLong)
        printQueue.add("debug("+ self.name +"): worker thread processing msg " + msgIdStr)
        dxMsgFname = "/var/tmp/dx_msg" + msgIdStr + ".gz.enc"
        amMsgFname = "/var/tmp/am_msg" + msgIdStr + ".gz.enc"
        getMsgSuccess = True

        if not getMsgRaw(amMsgFname, myMsg, self.name):
            getMsgSuccess = False

        if getMsgSuccess and not getMsgDxDirect(msgIdLong, dxSl, dxMsgFname, self.name):
            getMsgSuccess = False

        if getMsgSuccess:
            compareFileHashes(dxMsgFname, amMsgFname, msgIdLong, self.name)

        contentFile = File(dxMsgFname)
        contentFile.delete()

        contentFile = File(amMsgFname)
        contentFile.delete()
Ejemplo n.º 14
0
def removeLocalScanLog(Framework):
    localScanLogName = InventoryUtils.generateScanLogName(Framework)
    localScanLogFolderPath = CollectorsParameters.PROBE_MGR_INVENTORY_XMLENRICHER_FILES_FOLDER + XmlEnricherConstants.LOGS_FOLDER_NAME + CollectorsParameters.FILE_SEPARATOR
    localScanLogFile = File(localScanLogFolderPath, localScanLogName)
    try:
        # if the local scan log exists, delete it before next steps
        if localScanLogFile.exists():
            logger.debug("local scan log file found, just delete it: ", localScanLogFile.getCanonicalPath())
            if not localScanLogFile.delete():
                logger.warn("delete scan log file failed, ensure the there's permission and it's not locked:", localScanLogFile.getCanonicalPath())
    except:
        logger.warn("delete scan log file failed: ", localScanLogFile.getCanonicalPath())

    Framework.setStepExecutionStatus(WorkflowStepStatus.SUCCESS)
Ejemplo n.º 15
0
    def processItem(self, rs):
        msgId = rs.getLong(1)
        msgIdLong = long(msgId)
        msgIdStr = str.strip(msgId)
        dxMsgFname = "/var/tmp/dx_msg" + msgIdStr + ".gz.enc"
        amMsgFname = "/var/tmp/am_msg" + msgIdStr + ".gz.enc"
        getMsgSuccess = True

        if not getMsgRaw(msgIdLong, rs):
            getMsgSuccess = False

        if getMsgSuccess and not getMsgDxDirect(msgIdLong, dxSl, dxMsgFname):
            getMsgSuccess = False

        if getMsgSuccess:
            compareFileHashes(dxMsgFname, amMsgFname, msgIdLong)

        contentFile = File(dxMsgFname)
        contentFile.delete()

        contentFile = File(amMsgFname)
        contentFile.delete()
        self.myList.remove(str(rs.getLong(1)))
Ejemplo n.º 16
0
    def process(self, dataSource, progressBar):

        # Set the ogress bar to an Indeterminate state for now
        progressBar.switchToIndeterminate()

        # Return if we're not running on a windows sytem
        if not PlatformUtil.isWindowsOS():
            self.log(Level.INFO,
                     "Ignoring data source.  Not running on Windows")
            return IngestModule.ProcessResult.OK

        # Verify we have a disk image and not a folder of files
        if not isinstance(dataSource, Image):
            self.log(Level.INFO, "Ignoring data source.  Not an image")
            return IngestModule.ProcessResult.OK

        # Get disk image paths
        imagePaths = dataSource.getPaths()

        # Save our output to a file in the reports folder
        #   named based on EXE and data source ID
        reportFile = File(Case.getCurrentCase().getCaseDirectory() +
                          "\\Reports" + "\\img_stat-" +
                          str(dataSource.getId()) + ".txt")

        # Run the EXE, saving output to the report
        # Check if the ingest is terminated and
        #   delete the incomplete report file
        self.log(Level.INFO, "Running program on data source")
        cmd = ArrayList()
        cmd.add(self.pathToEXE.toString())
        cmd.add(imagePaths[0])

        processBuilder = ProcessBuilder(cmd)
        processBuilder.redirectOutput(reportFile)
        ExecUtil.execute(processBuilder,
                         DataSourceIngestModuleProcessTerminator(self.context))

        # Add the report to the case, so it shows up in the tree
        if not self.context.dataSourceIngestIsCancelled():
            Case.getCurrentCase().addReport(reportFile.toString(), "Run EXE",
                                            "img_stat output")
        else:
            if reportFile.exists():
                if not reportFile.delete():
                    self.log(LEVEL.warning,
                             "Error deleting the incomplete report file")

        return IngestModule.ProcessResult.OK
Ejemplo n.º 17
0
def iconv(file):
	print 'Converting', file
	f = File(file)
	if not f.exists():
		print file, 'does not exist'
		sys.exit(1)
	buffer = ByteBuffer.allocate(f.length() * 2)
	input = FileInputStream(f)
	input.getChannel().read(buffer)
	buffer.limit(buffer.position())
	buffer.position(0)
	if buffer.limit() != f.length():
		print file, 'could not be read completely'
		sys.exit(1)
	input.close()
	buffer = encoder.encode(decoder.decode(buffer))
	buffer.position(0)
	output = FileOutputStream(file + '.cnv')
	if output.getChannel().write(buffer) != buffer.limit():
		print file, 'could not be reencoded'
		sys.exit(1)
	output.close()
	f.delete()
	File(file + '.cnv').renameTo(f)
Ejemplo n.º 18
0
    def deleteDirectory(self, sPath):
        # 如果sPath不以文件分隔符结尾,自动添加文件分隔符
        dirFile = File(sPath)
        # 如果dir对应的文件不存在,或者不是一个目录,则退出
        if dirFile.exists() == False or dirFile.isDirectory() == False:
            return

        FileUtils.deleteQuietly(dirFile)
        return
        """
        换一种新的方法,以下代码不用了
        """
        # 删除文件夹下的所有文件(包括子目录)
        files = dirFile.listFiles()
        if files == None or len(files) == 0: return
        for f in files:
            # 删除子文件
            if f.isFile():
                f.delete()
            else:
                self.deleteDirectory(f.getAbsolutePath())
        #/删除当前目录
        dirFile.delete()
        dirFile = None
Ejemplo n.º 19
0
def iconv(file):
    print 'Converting', file
    f = File(file)
    if not f.exists():
        print file, 'does not exist'
        sys.exit(1)
    buffer = ByteBuffer.allocate(f.length() * 2)
    input = FileInputStream(f)
    input.getChannel().read(buffer)
    buffer.limit(buffer.position())
    buffer.position(0)
    if buffer.limit() != f.length():
        print file, 'could not be read completely'
        sys.exit(1)
    input.close()
    buffer = encoder.encode(decoder.decode(buffer))
    buffer.position(0)
    output = FileOutputStream(file + '.cnv')
    if output.getChannel().write(buffer) != buffer.limit():
        print file, 'could not be reencoded'
        sys.exit(1)
    output.close()
    f.delete()
    File(file + '.cnv').renameTo(f)
Ejemplo n.º 20
0
    def process(self, dataSource, progressBar):

        # we don't know how much work there will be
        progressBar.switchToIndeterminate()
        # Example has only a Windows EXE, so bail if we aren't on Windows
        if not PlatformUtil.isWindowsOS():
            self.log(Level.INFO,
                     "Ignoring data source.  Not running on Windows")
            return IngestModule.ProcessResult.OK

        # Verify we have a disk image and not a folder of files
        if not isinstance(dataSource, Image):
            self.log(Level.INFO, "Ignoring data source.  Not an image")
            return IngestModule.ProcessResult.OK

        # Get disk image paths
        imagePaths = dataSource.getPaths()

        # We'll save our output to a file in the reports folder, named based on EXE and data source ID
        reportFile = File(Case.getCurrentCase().getCaseDirectory() +
                          "\\Reports" + "\\img_stat-" +
                          str(dataSource.getId()) + ".txt")
        # Run the EXE, saving output to the report
        # Check if the ingest is terminated and delete the incomplete report file
        # Do not add report to the case tree if the ingest is cancelled before finish.
        # This can be done by using IngestJobContext.dataSourceIngestIsCancelled
        # See: http://sleuthkit.org/autopsy/docs/api-docs/4.7.0/_ingest_job_context_8java.html
        self.log(Level.INFO, "Running program on data source")
        cmd = ArrayList()
        cmd.add(self.pathToEXE.toString())
        cmd.add(imagePaths[0])

        processBuilder = ProcessBuilder(cmd)
        processBuilder.redirectOutput(reportFile)
        ExecUtil.execute(processBuilder,
                         DataSourceIngestModuleProcessTerminator(self.context))

        # Add the report to the case, so it shows up in the tree
        if not self.context.dataSourceIngestIsCancelled():
            Case.getCurrentCase().addReport(reportFile.toString(), "Run EXE",
                                            "img_stat output")
        else:
            if reportFile.exists():
                if not reportFile.delete():
                    self.log(LEVEL.warning,
                             "Error deleting the incomplete report file")

        return IngestModule.ProcessResult.OK
Ejemplo n.º 21
0
def removeLocalScanLog(Framework):
    localScanLogName = InventoryUtils.generateScanLogName(Framework)
    localScanLogFolderPath = CollectorsParameters.PROBE_MGR_INVENTORY_XMLENRICHER_FILES_FOLDER + XmlEnricherConstants.LOGS_FOLDER_NAME + CollectorsParameters.FILE_SEPARATOR
    localScanLogFile = File(localScanLogFolderPath, localScanLogName)
    try:
        # if the local scan log exists, delete it before next steps
        if localScanLogFile.exists():
            logger.debug("local scan log file found, just delete it: ",
                         localScanLogFile.getCanonicalPath())
            if not localScanLogFile.delete():
                logger.warn(
                    "delete scan log file failed, ensure the there's permission and it's not locked:",
                    localScanLogFile.getCanonicalPath())
    except:
        logger.warn("delete scan log file failed: ",
                    localScanLogFile.getCanonicalPath())

    Framework.setStepExecutionStatus(WorkflowStepStatus.SUCCESS)
Ejemplo n.º 22
0
    def process(self, dataSource, progressBar):
        
        # we don't know how much work there will be
        progressBar.switchToIndeterminate()
        # Example has only a Windows EXE, so bail if we aren't on Windows
        if not PlatformUtil.isWindowsOS(): 
            self.log(Level.INFO, "Ignoring data source.  Not running on Windows")
            return IngestModule.ProcessResult.OK

        # Verify we have a disk image and not a folder of files
        if not isinstance(dataSource, Image):
            self.log(Level.INFO, "Ignoring data source.  Not an image")
            return IngestModule.ProcessResult.OK

        # Get disk image paths            
        imagePaths = dataSource.getPaths()
        
        # We'll save our output to a file in the reports folder, named based on EXE and data source ID
        reportFile = File(Case.getCurrentCase().getCaseDirectory() + "\\Reports" + "\\img_stat-" + str(dataSource.getId()) + ".txt")
        
        # Run the EXE, saving output to reportFile
        # We use ExecUtil because it will deal with the user cancelling the job
        self.log(Level.INFO, "Running program on data source")
        cmd = ArrayList()
        cmd.add(self.pathToEXE.toString())
        # Add each argument in its own line.  I.e. "-f foo" would be two calls to .add()
        cmd.add(imagePaths[0])
        
        processBuilder = ProcessBuilder(cmd);
        processBuilder.redirectOutput(reportFile)
        ExecUtil.execute(processBuilder, DataSourceIngestModuleProcessTerminator(self.context))
        
        # Add the report to the case, so it shows up in the tree
        # Do not add report to the case tree if the ingest is cancelled before finish.
        if not self.context.dataSourceIngestIsCancelled():
            Case.getCurrentCase().addReport(reportFile.toString(), "Run EXE", "img_stat output")
        else:
            if reportFile.exists():
                if not reportFile.delete():
                    self.log(LEVEL.warning,"Error deleting the incomplete report file")
            
        return IngestModule.ProcessResult.OK
Ejemplo n.º 23
0
    def process(self, dataSource, progressBar):
        
        # we don't know how much work there will be
        progressBar.switchToIndeterminate()
        # Example has only a Windows EXE, so bail if we aren't on Windows
        if not PlatformUtil.isWindowsOS(): 
            self.log(Level.INFO, "Ignoring data source.  Not running on Windows")
            return IngestModule.ProcessResult.OK

        # Verify we have a disk image and not a folder of files
        if not isinstance(dataSource, Image):
            self.log(Level.INFO, "Ignoring data source.  Not an image")
            return IngestModule.ProcessResult.OK

        # Get disk image paths            
        imagePaths = dataSource.getPaths()
        
        # We'll save our output to a file in the reports folder, named based on EXE and data source ID
        reportFile = File(Case.getCurrentCase().getCaseDirectory() + "\\Reports" + "\\img_stat-" + str(dataSource.getId()) + ".txt")
        # Run the EXE, saving output to the report
        # Check if the ingest is terminated and delete the incomplete report file
        # Do not add report to the case tree if the ingest is cancelled before finish.
        # This can be done by using IngestJobContext.dataSourceIngestIsCancelled
        # See: http://sleuthkit.org/autopsy/docs/api-docs/4.7.0/_ingest_job_context_8java.html
        self.log(Level.INFO, "Running program on data source")
        cmd = ArrayList()
        cmd.add(self.pathToEXE.toString())
        cmd.add(imagePaths[0])
        
        processBuilder = ProcessBuilder(cmd);
        processBuilder.redirectOutput(reportFile)
        ExecUtil.execute(processBuilder,DataSourceIngestModuleProcessTerminator(self.context))
        
        # Add the report to the case, so it shows up in the tree
        if not self.context.dataSourceIngestIsCancelled():
            Case.getCurrentCase().addReport(reportFile.toString(), "Run EXE", "img_stat output")
        else:
            if reportFile.exists():
                if not reportFile.delete():
                    self.log(LEVEL.warning,"Error deleting the incomplete report file")
            
        return IngestModule.ProcessResult.OK
Ejemplo n.º 24
0
def downloadLogsIfNeeded(Framework):
    platform = Framework.getProperty(InventoryUtils.STATE_PROPERTY_PLATFORM)
    logger.debug('Checking if to print install/uninstall logs')
    downloadMigrateLog = Framework.getProperty(
        AgentUtils.DOWNLOAD_MIGRATE_LOG_FILE)
    downloadInstallLog = Framework.getProperty(
        AgentUtils.DOWNLOAD_INSTALL_LOG_FILE)
    downloadUnInstallLog = Framework.getProperty(
        AgentUtils.DOWNLOAD_UNINSTALL_LOG_FILE)
    if not downloadMigrateLog and not downloadInstallLog and not downloadUnInstallLog:
        logger.debug('Migrate/Install/UnInstall log should not be downloaded')
        return

    try:
        logger.debug('Releasing old connection')
        InventoryUtils.releaseConnection(Framework)
        logger.debug('Preparing framework for new connection')
        AgentUtils.prepareFrameworkForShellOrAgentConnect(Framework)
    except:
        errorMessage = str(sys.exc_info()[1])
        logger.debugException(
            'Failed to initialize connection for downloading agent log files' +
            errorMessage)
        return

    if downloadMigrateLog:
        # If need to download migrate log, we need to connect to DDMi agent as well
        Framework.setProperty(InventoryUtils.STATE_PROPERTY_IS_MIGRATE,
                              str('true'))

    if not InventoryUtils.ensureConnection(Framework):
        logger.debug(
            'Failed to connect to the remote machine, no logs available')
    else:
        ip_address = Framework.getTriggerCIData('ip_address')
        localInstallFile = None
        localUnInstallFile = None
        try:
            try:
                agentsConfigFile = Framework.getConfigFile(
                    CollectorsConstants.AGENTSSBYPLATFORM_FILE_NAME)
                BASEDIR = Framework.getProperty(
                    InventoryUtils.STATE_PROPERTY_RESOLVED_BASEDIR)
                architecture = Framework.getProperty(
                    InventoryUtils.STATE_PROPERTY_ARCHITECTURE)
                agentPlatformConfig = agentsConfigFile.getPlatformConfiguration(
                    platform, architecture)
                ip_address_str = str(ip_address)
                if (ip_address_str.find(':') <> -1):
                    ip_address_str = ip_address_str.replace(':', '-')

                if downloadMigrateLog:
                    logger.debug('Download the migrate log')
                    installLogFile = agentPlatformConfig.getUpgradeLogFile()
                    localInstallFile = File(
                        AGENTS_LOGS_TEMP_DIR_FILE,
                        ip_address_str + '-' + installLogFile)
                    getLogFileContent(Framework, localInstallFile,
                                      str(BASEDIR) + installLogFile)
                if downloadInstallLog:
                    logger.debug('Download the install/update log')
                    if AgentUtils.isUpgradeByUDAgent(Framework):
                        installLogFile = agentPlatformConfig.getUpgradeLogFile(
                        )
                    else:
                        installLogFile = agentPlatformConfig.getInstallLogFile(
                        )
                    localInstallFile = File(
                        AGENTS_LOGS_TEMP_DIR_FILE,
                        ip_address_str + '-' + installLogFile)
                    getLogFileContent(Framework, localInstallFile,
                                      str(BASEDIR) + installLogFile)
                if downloadUnInstallLog:
                    logger.debug('Download the uninstall log')
                    unInstallLogFile = agentPlatformConfig.getUnInstallLogFile(
                    )
                    localUnInstallFile = File(
                        AGENTS_LOGS_TEMP_DIR_FILE,
                        ip_address_str + '-' + unInstallLogFile)
                    getLogFileContent(Framework, localUnInstallFile,
                                      str(BASEDIR) + unInstallLogFile)
            except:
                errorMessage = str(sys.exc_info()[1])
                logger.debugException(errorMessage)
                Framework.reportError(
                    inventoryerrorcodes.
                    INVENTORY_DISCOVERY_FAILED_EXECUTE_STEP,
                    ['FinalizeAndReleaseResources', errorMessage])
        finally:
            try:
                if localInstallFile and not localInstallFile.delete():
                    logger.debug('File was not deleted:' +
                                 localInstallFile.getCanonicalPath())
            except:
                logger.debugException('Failed to delete ' +
                                      localInstallFile.getCanonicalPath())
            try:
                logger.debug('Going to delete file ' +
                             localInstallFile.getCanonicalPath())
                if localUnInstallFile and not localUnInstallFile.delete():
                    logger.debug('File was not deleted:' +
                                 localUnInstallFile.getCanonicalPath())
            except:
                logger.debugException('Failed to delete ' +
                                      localUnInstallFile.getCanonicalPath())
Ejemplo n.º 25
0
    def on_saveBtn_clicked(self, event):
        """Read preferences from gui and save them to config.properties
           file
        """
        #print "\n- saving preferences to config file"
        onOff = {True: "on", False: "off"}

        #1 Tab
        #check for update
        self.app.properties.setProperty("check_for_update",
                                        onOff[self.updateCBtn.isSelected()])
        #tools status
        for toolIndex, tool in enumerate(self.app.realTools):
            prop = "tool.%s" % tool.name
            toolCBtn = self.toolsCBtns[toolIndex]
            self.app.properties.setProperty(prop,
                                            onOff[toolCBtn.isSelected()])

        #layers preferences
        for mode, button in self.layersRBtns.iteritems():
            if button.isSelected():
                self.app.properties.setProperty("layers_mode", mode)
                break

        #max errors number
        try:
            num = Integer.parseInt(self.maxErrorsNumberTextField.getText())
        except NumberFormatException:
            num = ""
        self.app.properties.setProperty("max_errors_number", str(num))

        #2 Tab
        #Favourite zones
        changes = {"new": [z for z in self.app.tempZones if not z in self.app.zones],
                   "deleted": [z for z in self.app.zones if not z in self.app.tempZones]}
        #delete files of removed favourite zones
        for zone in changes["deleted"]:
            f = File(File.separator.join([self.app.SCRIPTDIR,
                                          "configuration",
                                          "favourite_zones",
                                          "%s.txt" % zone.name]))
            f.delete()
        #create files for new favourite zones
        for zone in changes["new"]:
            print "\nsave new zone", zone.name
            fileName = File.separator.join([self.app.SCRIPTDIR,
                                            "configuration",
                                            "favourite_zones",
                                            "%s.txt" % zone.name])
            f = open(fileName, "w")
            zoneData = zone.geomString
            if zone.country != "":
                zoneData += "|" + zone.country
            f.write(zoneData.encode("utf-8"))
            f.close()

        self.app.zones = self.app.tempZones
        if len(self.app.zones) == 0:
            self.app.favZone = None
            self.app.properties.setProperty("favourite_area.name",
                                            "")
            self.favZoneStatusCBtn.setSelected(False)
        else:
            if len(self.zonesTable.getSelectedRows()) == 0:
                self.app.favZone = self.app.zones[0]
            else:
                self.app.favZone = self.app.zones[self.zonesTable.getSelectedRows()[0]]
            self.app.properties.setProperty("favourite_area.name",
                                            self.app.favZone.name)
        favZoneStatus = self.favZoneStatusCBtn.isSelected()
        self.app.properties.setProperty("favourite_area.status", onOff[favZoneStatus])
        self.app.favouriteZoneStatus = favZoneStatus

        #stats panel
        self.app.dlg.update_favourite_zone_indicator()
        self.app.dlg.update_statsPanel_status()

        #3 Tab
        #tools preferences
        for tool in self.app.allTools:
            if hasattr(tool, 'prefs') and tool.prefsGui is not None:
                for pref, value in tool.prefsGui.read_gui().iteritems():
                    prefKey = "tool.%s.%s" % (tool.name, pref)
                    self.app.properties.setProperty(prefKey, value)

        self.app.save_config()
        self.dispose()
Ejemplo n.º 26
0
    def show(self):
        #Root Pane
        root = VBox()
        #FXML Loader
        fxmlLoader = FXMLLoader()

        #TextArea
        from javafx.scene.control import TextArea
        textArea = TextArea("Loading . . .")

        #Configure Text Area
        textArea.setEditable(False)
        textArea.setPrefHeight(600)

        #Bottom Bar, Current Stylesheet
        if self.app.getCurrentTheme() == "Dark":
            fxmlLoader.setLocation(
                File("../resources/fxml/history_url_tab_dark.fxml").toURI().
                toURL())  #For some odd reason this is broken?
            bottom_bar = self.app.bottom_bar_dt
        elif self.app.getCurrentTheme() == "Light":
            fxmlLoader.setLocation(
                File("../resources/fxml/history_url_tab_light.fxml").toURI().
                toURL())
            bottom_bar = ImageView(
                Image(
                    String(
                        File('../resources/icons/bottom_bar_lt.png').toURI().
                        toString()), True))
        #Think about future themes
        else:
            pass

        #URL Bar
        try:
            url_bar = fxmlLoader.load(
            )  #BROKEN - For some reason this breaks after a couple toggles.
        except LoadException as e:
            print('Log: Exception: An FXML Load Exception has occured.' +
                  str(e.getCause()))

        #Add Children to root pane
        root.getChildren().addAll(url_bar, textArea, bottom_bar)

        #Fill Width, assume Theme of Main Stage
        root.setFillWidth(True)

        #Set scene, title
        scene = Scene(root, 1350, 625)

        #We are leaving the default controls for now.

        #Make sure the Text Area's scroll bar is always visible.
        scene.getStylesheets().add(
            File("../resources/themes/text-area_scroll-pane.css").toURI().
            toString())
        self.stage.setScene(scene)
        self.stage.setTitle("History - EmeraldFX")

        #Position History Stage
        self.stage.setX(self.app.getMainStage().getX())
        self.stage.setY(self.app.getMainStage().getY() + 52)

        #Display History Stage
        self.stage.show()

        #It is CSV, let us display as plain text.
        history_csv = File("../resources/history/HISTORY.csv")
        history_txt = File("../resources/history/HISTORY.txt")

        #Delete text copy if it exists
        history_txt.delete() if history_txt.exists() else None

        #Copy
        Files.copy(history_csv.toPath(), history_txt.toPath())

        #Prevent Resizing
        self.stage.setResizable(False)

        #Flush Stream
        self.BS.triggerHistoryWrite()

        #GetController instance
        controller = fxmlLoader.getController()
        ''' Failed Attempts '''

        #WebView
        # webView = WebView()
        #Grab Web Engine
        # webEng = webView.getEngine()
        #Enable JS
        # webEng.setJavaScriptEnabled(True)

        #Attempt #1 - Start scrolling from the bottom - FAILED
        # webEng.executeScript("window.scrollTo(" + "0" + ", " + "600" + ");")

        #Attempt #2 - Scroll Pane - FAILED
        # from javafx.scene.control import ScrollPane
        # wv_scroll = ScrollPane()
        # wv_scroll.setVbarPolicy(ScrollPane.ScrollBarPolicy.ALWAYS)
        # wv_scroll.setContent(webView)
        # wv_scroll.setFitToWidth(True)
        # wv_scroll.setFitToHeight(True)
        # wv_scroll.setVvalue(wv_scroll.getVmin())

        #Load History
        # try:
        # webEng.load(history_txt.toURI().toString())
        # except Exception as e:
        # print ('Log: Load Exception: Error Loading History: ' + str(e.getCause()))
        # return

        #Attempt #3 - Execute Script for Scroll Bar - FAILD
        # webEng.executeScript(
        # "function scrollDown() { window.scrollTo(0,400); }" +
        # "scrollDown();"
        # )

        #Set Position of Scroll Bar
        class AnonInnerCL_TA(ChangeListener):
            """Inner Class for Scrolling Down"""
            def __init__(self, textArea):
                self.textArea = textArea

            #@Override
            def changed(self, observable, old, new):
                if new > old:
                    from java.lang import Double
                    self.textArea.setScrollTop(Double.MAX_VALUE)
                else:
                    pass

        textArea.textProperty().addListener(AnonInnerCL_TA(textArea))

        #Show History after it is loaded
        if self.stage.isShowing(
        ):  #May or may not be broken. If there is litle to no delay, "Loading . . ." will not be noticed.
            #Load History on separate thread.
            #Clear initial text: Loading . . .
            textArea.clear()
            #Instantate Service
            service = HistoryService(history_txt, textArea)
            #Algorithm improved. Start service
            service.start()
        '''Add resources to controller'''
        #Theme Resources
        controller.addThemeResources(
            self.app.getMainStage(), self.stage,
            self.app.getMainStage().getScene(), self.app.getCurrentTheme(),
            textArea
        )  #(Stage mainStage, Stage histStage, Scene scene, String theme, TextArea textArea)
        #Clear Resource
        controller.addClearResources(self.BS.isHistoryCleared())  #(boolean)
        #Quit Resources
        controller.addQuitResources(
            self.app.getAllStages(),
            self.BS.getHistoryWriter())  #(List<Stages>, PrintWriter)
        #Media Resources
        MMC = self.app.getMediaControls()
        controller.addMediaResources(MMC)

        #Create Bidirectional Bindings between Main Stage's media controls and history's controls
        from javafx.beans.binding import Bindings

        MMC_IT = MMC.listIterator()
        HMC = controller.getMediaControls()

        #Set history media controls to current state
        class HMCC(Consumer):
            def __init__(self, MMC_IT):
                self.MMC_IT = MMC_IT

            #@Override
            def accept(self, button):
                button.setDisabled(MMC_IT.next().isDisabled())

        HMC.forEach(HMCC(MMC_IT))

        #Fails - first arg cannot be coerced into Consumer? Odd.
        # history_media_controls.forEach(lambda button: button.setDisabled( main_media_controls.forEach(lambda button: button.isDisabled()) ) )

        #Play
        #Won't work -- read only property does not inherit Property, seperate API.
        # Bindings.bindBidirectional(history_media_controls.get(0).disabledProperty(), main_media_controls[0].disabledProperty() )
        #Stop
        # Bindings.bindBidirectional(history_media_controls.get(1).disabledProperty(), main_media_controls[1].disabledProperty() )
        #Previous
        # Bindings.bindBidirectional(history_media_controls.get(2).disabledProperty(), main_media_controls[2].disabledProperty() )
        #Next
        # Bindings.bindBidirectional(history_media_controls.get(3).disabledProperty(), main_media_controls[3].disabledProperty() )

        #Shortcut Keys Allowed for History (CTRL + D, CTRL + Q, CTRL + T)
        scene.addEventFilter(
            KeyEvent.KEY_PRESSED, lambda event: self.handleHistoryShortcuts(
                event, self.BS, controller.getToggleTheme(),
                controller.getClearHistory()))

        #Python needs to fix lambdas so we don't have to resort to wrapping inner classes in collections. Yuck.
        class HistoryClosed:
            @staticmethod
            def printClosed():
                print("Log: Quit Action: History just closed.")

        #Switch back to the main stage
        self.stage.setOnCloseRequest(lambda event: [
            self.app.getMainStage().toFront(),
            self.stage.close(),
            HistoryClosed.printClosed()
        ])

        #Log
        print('Log: History Notification: History data displayed @ ' +
              str(LocalDateTime.now()))
Ejemplo n.º 27
0
    def execute(self):
        cache = __jitar__.cacheProvider.getCache('main')
        cache.clear()
        cache_key_list = cache.getAllKeys()
        if cache_key_list != None:
            for key in cache_key_list:
                cache.remove(key)

        cacheService = __spring__.getBean("cacheService")

        cacheService.remove("new_user_list")
        cacheService.remove("rcmd_wr_list")
        cacheService.remove("hot_wr_list")
        cacheService.remove("rcmd_group_list")
        cacheService.remove("new_group_list")
        cacheService.remove("best_group_list")
        cacheService.remove("famous_teachers")
        cacheService.remove("expert_list")
        cacheService.remove("teacher_star")
        cacheService.remove("instructor_list")
        cacheService.remove("new_video_list")
        cacheService.remove("hot_video_list")
        cacheService.remove("school_list")
        cacheService.remove("course_list")
        cacheService.remove("special_subject_list")
        cacheService.remove("hot_photo_list")
        cacheService.remove("new_photo_list")
        cacheService.remove("site_stat")
        cacheService.remove("teacher_show")
        cacheService.remove("jitar_actions")
        cacheService.remove("famous_article_list")
        cacheService.remove("hot_article_list")
        cacheService.remove("newest_article_list")
        cacheService.remove("hot_resource_list")
        cacheService.remove("new_resource_list")
        cacheService.remove("site_placard_list")
        cacheService.remove("jitar_news")
        cacheService.remove("pic_news")
        cacheService.remove("show_custorm_part")

        cacheService.remove("all_subject")
        cacheService.remove("all_grade")
        cacheService.remove("all_meta_subject")

        cache = __jitar__.cacheProvider.getCache('siteTheme')
        cache.remove("siteTheme")

        cache = __jitar__.cacheProvider.getCache('user')
        cache.clear()

        cache = __jitar__.cacheProvider.getCache('group')
        cache.clear()

        cache = __jitar__.cacheProvider.getCache('page')
        cache.clear()

        cache = __jitar__.cacheProvider.getCache('category')
        cache.clear()

        cache = __jitar__.cacheProvider.getCache('subject')
        cache.clear()

        cache = __jitar__.cacheProvider.getCache('unit')
        cache.clear()

        cache = __jitar__.cacheProvider.getCache('defaultCache')
        cache.clear()

        cache = __jitar__.cacheProvider.getCache('rootUnit')
        cache.remove("rootUnit")

        subjectService = __jitar__.subjectService
        subjectService.clearCacheData()

        servlet_ctxt = request.getServletContext()
        servlet_ctxt.removeAttribute("metaGrade")
        servlet_ctxt.removeAttribute("meta_Grade")
        servlet_ctxt.removeAttribute("SubjectNav")
        servlet_ctxt.removeAttribute(ConfigService.CONFIG_KEY_NAME)

        siteNavigationService = __spring__.getBean("siteNavigationService")
        siteNavigationService.renderSiteNavition()

        self.params = ParamUtil(request)

        cachetype = self.params.safeGetStringParam("cachetype")
        if cachetype == "index":
            strFile = request.getServletContext().getRealPath("/")
            file = File(strFile + "index.html")
            if file.exists() and file.isFile():
                file.delete()
            file = None
        elif cachetype == "user":
            strFile = request.getServletContext().getRealPath("/")
            strFile = strFile + "html" + File.separator + "user" + File.separator
            file = File(strFile)
            if file.exists():
                self.deleteDirectory(strFile)
            file = None
        elif cachetype == "unit":
            strFile = request.getServletContext().getRealPath("/")
            strFile = strFile + "html" + File.separator + "unit" + File.separator
            file = File(strFile)
            if file.exists():
                self.deleteDirectory(strFile)
            file = None
        response.contentType = "text/html; charset=UTF-8"
        return "/WEB-INF/ftl/admin/clear_cache.ftl"
def downloadLogsIfNeeded(Framework):
    platform = Framework.getProperty(InventoryUtils.STATE_PROPERTY_PLATFORM)
    logger.debug('Checking if to print install/uninstall logs')
    downloadMigrateLog = Framework.getProperty(AgentUtils.DOWNLOAD_MIGRATE_LOG_FILE)
    downloadInstallLog = Framework.getProperty(AgentUtils.DOWNLOAD_INSTALL_LOG_FILE)
    downloadUnInstallLog = Framework.getProperty(AgentUtils.DOWNLOAD_UNINSTALL_LOG_FILE)
    if not downloadMigrateLog and not downloadInstallLog and not downloadUnInstallLog:
        logger.debug('Migrate/Install/UnInstall log should not be downloaded')
        return

    try:
        logger.debug('Releasing old connection')
        InventoryUtils.releaseConnection(Framework)
        logger.debug('Preparing framework for new connection')
        AgentUtils.prepareFrameworkForShellOrAgentConnect(Framework)
    except:
        errorMessage = str(sys.exc_info()[1])
        logger.debugException('Failed to initialize connection for downloading agent log files' + errorMessage)
        return

    if downloadMigrateLog:
        # If need to download migrate log, we need to connect to DDMi agent as well
        Framework.setProperty(InventoryUtils.STATE_PROPERTY_IS_MIGRATE, str('true'))

    if not InventoryUtils.ensureConnection(Framework):
        logger.debug('Failed to connect to the remote machine, no logs available')
    else:
        ip_address = Framework.getTriggerCIData('ip_address')
        localInstallFile = None
        localUnInstallFile = None
        try:
            try:
                agentsConfigFile = Framework.getConfigFile(CollectorsConstants.AGENTSSBYPLATFORM_FILE_NAME)
                BASEDIR = Framework.getProperty(InventoryUtils.STATE_PROPERTY_RESOLVED_BASEDIR)
                architecture = Framework.getProperty(InventoryUtils.STATE_PROPERTY_ARCHITECTURE)
                agentPlatformConfig = agentsConfigFile.getPlatformConfiguration(platform, architecture)
                ip_address_str = str(ip_address)
                if (ip_address_str.find(':') <> -1):
                    ip_address_str = ip_address_str.replace(':','-')

                if downloadMigrateLog:
                    logger.debug('Download the migrate log')
                    installLogFile = agentPlatformConfig.getUpgradeLogFile()
                    localInstallFile = File(AGENTS_LOGS_TEMP_DIR_FILE, ip_address_str + '-' + installLogFile)
                    getLogFileContent(Framework, localInstallFile, str(BASEDIR) + installLogFile)
                if downloadInstallLog:
                    logger.debug('Download the install/update log')
                    if AgentUtils.isUpgradeByUDAgent(Framework):
                        installLogFile = agentPlatformConfig.getUpgradeLogFile()
                    else:
                        installLogFile = agentPlatformConfig.getInstallLogFile()
                    localInstallFile = File(AGENTS_LOGS_TEMP_DIR_FILE, ip_address_str + '-' + installLogFile)
                    getLogFileContent(Framework, localInstallFile, str(BASEDIR) + installLogFile)
                if downloadUnInstallLog:
                    logger.debug('Download the uninstall log')
                    unInstallLogFile = agentPlatformConfig.getUnInstallLogFile()
                    localUnInstallFile = File(AGENTS_LOGS_TEMP_DIR_FILE, ip_address_str + '-' + unInstallLogFile)
                    getLogFileContent(Framework, localUnInstallFile, str(BASEDIR) + unInstallLogFile)
            except:
                errorMessage = str(sys.exc_info()[1])
                logger.debugException(errorMessage)
                Framework.reportError(inventoryerrorcodes.INVENTORY_DISCOVERY_FAILED_EXECUTE_STEP, ['FinalizeAndReleaseResources', errorMessage])
        finally:
            try:
                if localInstallFile and not localInstallFile.delete():
                    logger.debug('File was not deleted:' + localInstallFile.getCanonicalPath())
            except:
                logger.debugException('Failed to delete ' + localInstallFile.getCanonicalPath())
            try:
                logger.debug('Going to delete file ' + localInstallFile.getCanonicalPath())
                if localUnInstallFile and not localUnInstallFile.delete():
                    logger.debug('File was not deleted:' + localUnInstallFile.getCanonicalPath())
            except:
                logger.debugException('Failed to delete ' + localUnInstallFile.getCanonicalPath())
Ejemplo n.º 29
0
    def on_saveBtn_clicked(self, event):
        """Read preferences from gui and save them to config.properties
           file
        """
        #print "\n- saving preferences to config file"
        onOff = {True: "on", False: "off"}

        #1 Tab
        #check for update
        self.app.properties.setProperty("check_for_update",
                                        onOff[self.updateCBtn.isSelected()])
        #tools status
        for toolIndex, tool in enumerate(self.app.realTools):
            prop = "tool.%s" % tool.name
            toolCBtn = self.toolsCBtns[toolIndex]
            self.app.properties.setProperty(prop, onOff[toolCBtn.isSelected()])

        #layers preferences
        for mode, button in self.layersRBtns.iteritems():
            if button.isSelected():
                self.app.properties.setProperty("layers_mode", mode)
                break

        #max errors number
        try:
            num = Integer.parseInt(self.maxErrorsNumberTextField.getText())
        except NumberFormatException:
            num = ""
        self.app.properties.setProperty("max_errors_number", str(num))

        #2 Tab
        #Favourite zones
        changes = {
            "new": [z for z in self.app.tempZones if not z in self.app.zones],
            "deleted":
            [z for z in self.app.zones if not z in self.app.tempZones]
        }
        #delete files of removed favourite zones
        for zone in changes["deleted"]:
            f = File(
                File.separator.join([
                    self.app.SCRIPTDIR, "configuration", "favourite_zones",
                    "%s.txt" % zone.name
                ]))
            f.delete()
        #create files for new favourite zones
        for zone in changes["new"]:
            print "\nsave new zone", zone.name
            fileName = File.separator.join([
                self.app.SCRIPTDIR, "configuration", "favourite_zones",
                "%s.txt" % zone.name
            ])
            f = open(fileName, "w")
            zoneData = zone.geomString
            if zone.country != "":
                zoneData += "|" + zone.country
            f.write(zoneData.encode("utf-8"))
            f.close()

        self.app.zones = self.app.tempZones
        if len(self.app.zones) == 0:
            self.app.favZone = None
            self.app.properties.setProperty("favourite_area.name", "")
            self.favZoneStatusCBtn.setSelected(False)
        else:
            if len(self.zonesTable.getSelectedRows()) == 0:
                self.app.favZone = self.app.zones[0]
            else:
                self.app.favZone = self.app.zones[
                    self.zonesTable.getSelectedRows()[0]]
            self.app.properties.setProperty("favourite_area.name",
                                            self.app.favZone.name)
        favZoneStatus = self.favZoneStatusCBtn.isSelected()
        self.app.properties.setProperty("favourite_area.status",
                                        onOff[favZoneStatus])
        self.app.favouriteZoneStatus = favZoneStatus

        #stats panel
        self.app.dlg.update_favourite_zone_indicator()
        self.app.dlg.update_statsPanel_status()

        #3 Tab
        #tools preferences
        for tool in self.app.allTools:
            if hasattr(tool, 'prefs') and tool.prefsGui is not None:
                for pref, value in tool.prefsGui.read_gui().iteritems():
                    prefKey = "tool.%s.%s" % (tool.name, pref)
                    self.app.properties.setProperty(prefKey, value)

        self.app.save_config()
        self.dispose()