示例#1
0
def promptSaveDocumentAs(world, component, handleSaveDocumentAsFn, existingFilename=None):
	filename = None
	bFinished = False
	while not bFinished:
		saveDialog = JFileChooser()
		saveDialog.setFileFilter( FileNameExtensionFilter( 'Larch project (*.larch)', [ 'larch' ] ) )
		response = saveDialog.showSaveDialog( component )
		if response == JFileChooser.APPROVE_OPTION:
			sf = saveDialog.getSelectedFile()
			if sf is not None:
				if sf.exists():
					response = JOptionPane.showOptionDialog( component, 'File already exists. Overwrite?', 'File already exists', JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, None, [ 'Overwrite', 'Cancel' ], 'Cancel' )
					if response == JFileChooser.APPROVE_OPTION:
						filename = sf.getPath()
						bFinished = True
					else:
						bFinished = False
				else:
					filename = sf.getPath()
					bFinished = True
			else:
				bFinished = True
		else:
			bFinished = True

	if filename is not None:
		handleSaveDocumentAsFn( filename )
		return True
	else:
		return False
示例#2
0
 def openFile(self, fileext, filedesc, fileparm):
     myFilePath = ''
     chooseFile = JFileChooser()
     myFilter = FileNameExtensionFilter(filedesc, [fileext])
     chooseFile.setFileFilter(myFilter)
     ret = chooseFile.showOpenDialog(self.tab)
     if ret == JFileChooser.APPROVE_OPTION:
         file = chooseFile.getSelectedFile()
         myFilePath = str(file.getCanonicalPath()).lower()
         if not myFilePath.endswith(fileext):
             myFilePath += '.' + fileext
         okWrite = JOptionPane.YES_OPTION
         if os.path.isfile(myFilePath):
             okWrite = JOptionPane.showConfirmDialog(
                 self.tab, 'File already exists. Ok to over-write?', '',
                 JOptionPane.YES_NO_OPTION)
             if okWrite == JOptionPane.NO_OPTION:
                 return
         j = True
         while j:
             try:
                 f = open(myFilePath, mode=fileparm)
                 j = False
             except IOError:
                 okWrite = JOptionPane.showConfirmDialog(
                     self.tab, 'File cannot be opened. Correct and retry?',
                     '', JOptionPane.YES_NO_OPTION)
                 if okWrite == JOptionPane.NO_OPTION:
                     return None, False
         return f, True
示例#3
0
    def actionPerformed(self, event):
        """Delete the last row"""

        # Generate a save dialog
        dialog = JFileChooser(Prefs.get("roiGroup.importDir", ""))
        dialog.setSelectedFile(File("roiGroups.txt"))
        dialog.setFileFilter(FileNameExtensionFilter("Text file", ["txt"]))
        output = dialog.showOpenDialog(
            self.groupTable)  # could be None argument too

        if output in [JFileChooser.CANCEL_OPTION, JFileChooser.ERROR_OPTION]:
            return
        selectedFile = dialog.getSelectedFile()
        directory = selectedFile.getParent()
        Prefs.set("roiGroup.importDir", directory)
        if not selectedFile.isFile(): return
        filePath = selectedFile.getPath()

        # Read comma-separated group from file
        with open(filePath, "r") as textFile:
            stringGroup = textFile.readline().rstrip()

        # Update table with content of file
        tableModel = self.groupTable.tableModel
        tableModel.setGroupColumn(stringGroup)
示例#4
0
    def openFile(self, event=None):
        '''
        1. Check if current file in text area has unsaved changes
            1.1 Prompt user for file saving
                1.1.1 Save file
        2. Display browser for user to choose file
        3. Load file in text area
        4. Display file name in title bar
        '''
        if self.handleUnsaved():
            if self.currentFilename:
                default_path = os.path.dirname(self.currentFilename)
            else:
                default_path = os.getcwd()
            fileChooser = JFileChooser(default_path)
            file_filter = FileNameExtensionFilter("ATF files", ["atf"])
            fileChooser.setFileFilter(file_filter)
            status = fileChooser.showDialog(self.view, "Choose file")

            if status == JFileChooser.APPROVE_OPTION:
                atfFile = fileChooser.getSelectedFile()
                filename = atfFile.getCanonicalPath()
                basename = atfFile.getName()
                atfText = self.readTextFile(filename)
                self.currentFilename = atfFile.getCanonicalPath()
                # Clear ATF area before adding next text to clean up tooltips
                # and such
                self.atfAreaController.clearAtfArea()
                self.atfAreaController.setAtfAreaText(atfText)
                self.logger.debug("File %s successfully opened.", filename)
                self.view.setTitle(basename)
示例#5
0
    def openFile(self, event):
        '''
        1. Check if current file in text area has unsaved changes
            1.1 Prompt user for file saving
                1.1.1 Save file
        2. Display browser for user to choose file
        3. Load file in text area
        '''
        self.consoleController.addText("NammuController: Opening file...")

        self.handleUnsaved()

        fileChooser = JFileChooser()
        filter = FileNameExtensionFilter("ATF files", ["atf"])
        fileChooser.setFileFilter(filter)
        status = fileChooser.showDialog(self.view, "Choose file")

        if status == JFileChooser.APPROVE_OPTION:
            atfFile = fileChooser.getSelectedFile()
            filename = atfFile.getCanonicalPath()
            atfText = self.readTextFile(filename)
            self.currentFilename = atfFile.getCanonicalPath()
            self.atfAreaController.setAtfAreaText(atfText)

        #TODO: Else, prompt user to choose again before closing

        self.consoleController.addText(" OK\n")
示例#6
0
    def openFile(self, event=None):
        '''
        1. Check if current file in text area has unsaved changes
            1.1 Prompt user for file saving
                1.1.1 Save file
        2. Display browser for user to choose file
        3. Load file in text area
        4. Display file name in title bar
        '''
        if self.handleUnsaved():
            fileChooser = JFileChooser(self.get_working_dir())
            file_filter = FileNameExtensionFilter("ATF files", ["atf"])
            fileChooser.setFileFilter(file_filter)
            status = fileChooser.showDialog(self.view, "Choose file")

            if status == JFileChooser.APPROVE_OPTION:
                atfFile = fileChooser.getSelectedFile()
                filename = atfFile.getCanonicalPath()
                basename = atfFile.getName()
                atfText = self.readTextFile(filename)
                self.currentFilename = atfFile.getCanonicalPath()
                # Clear ATF area before adding next text to clean up tooltips
                # and such
                self.atfAreaController.clearAtfArea()
                self.atfAreaController.setAtfAreaText(atfText)
                self.logger.debug("File %s successfully opened.", filename)
                self.view.setTitle(basename)

            # TODO: Else, prompt user to choose again before closing

            # Update settings with current file's path
            self.update_config_element(self.get_working_dir(),
                                       'default', 'working_dir')
示例#7
0
def _buildProjectJar(element, document):
    component = element.getRootElement().getComponent()

    larchJarURL = app_in_jar.getLarchJarURL()
    chosenJarURL = None
    if larchJarURL is None:
        openDialog = JFileChooser()
        openDialog.setFileFilter(
            FileNameExtensionFilter('Larch executable JAR (*.jar)', ['jar']))
        response = openDialog.showDialog(component, 'Choose Larch JAR')
        if response == JFileChooser.APPROVE_OPTION:
            sf = openDialog.getSelectedFile()
            if sf is not None:
                chosenJarURL = sf.toURI().toURL()
        else:
            return

    jarFile = None
    bFinished = False
    while not bFinished:
        saveDialog = JFileChooser()
        saveDialog.setFileFilter(
            FileNameExtensionFilter('JAR file (*.jar)', ['jar']))
        response = saveDialog.showSaveDialog(component)
        if response == JFileChooser.APPROVE_OPTION:
            sf = saveDialog.getSelectedFile()
            if sf is not None:
                if sf.exists():
                    response = JOptionPane.showOptionDialog(
                        component, 'File already exists. Overwrite?',
                        'File already exists', JOptionPane.YES_NO_OPTION,
                        JOptionPane.WARNING_MESSAGE, None,
                        ['Overwrite', 'Cancel'], 'Cancel')
                    if response == JFileChooser.APPROVE_OPTION:
                        jarFile = sf
                        bFinished = True
                    else:
                        bFinished = False
                else:
                    jarFile = sf
                    bFinished = True
            else:
                bFinished = True
        else:
            bFinished = True

    if jarFile is not None:
        outStream = FileOutputStream(jarFile)

        documentBytes = document.writeAsBytes()

        nameBytesPairs = [('app.larch', documentBytes)]

        app_in_jar.buildLarchJar(outStream,
                                 nameBytesPairs,
                                 larchJarURL=chosenJarURL)

        outStream.close()
示例#8
0
    def createDialogBoxForImportExport(self, dialogTitle, extensionFilter, buttonText):

        # create frame
        frameImportExportDialogBox = JFrame()

        # try to load the last used directory
        try:
            # load the directory for future imports/exports
            fileChooserDirectory = self._callbacks.loadExtensionSetting("fileChooserDirectory")

        # there is not a last used directory
        except:
            # set the last used directory to blank
            fileChooserDirectory = ""

        # create file chooser
        fileChooserImportExportDialogBox = JFileChooser(fileChooserDirectory)

        # set dialog title
        fileChooserImportExportDialogBox.setDialogTitle(dialogTitle)

        # create extension filter
        filterImportExportDialogBox = FileNameExtensionFilter(extensionFilter[0], extensionFilter[1])

        # set extension filter
        fileChooserImportExportDialogBox.setFileFilter(filterImportExportDialogBox)

        # show dialog box and get value
        valueFileChooserImportExportDialogBox = fileChooserImportExportDialogBox.showDialog(frameImportExportDialogBox, buttonText)

        # check if a file was not selected
        if valueFileChooserImportExportDialogBox != JFileChooser.APPROVE_OPTION:
        
            # return no path/file selected
            return False, "No Path/File"

        # get the directory
        fileChooserDirectory = fileChooserImportExportDialogBox.getCurrentDirectory()

        # store the directory for future imports/exports
        self._callbacks.saveExtensionSetting("fileChooserDirectory", str(fileChooserDirectory))

        # get absolute path of file
        fileChosenImportExportDialogBox = fileChooserImportExportDialogBox.getSelectedFile().getAbsolutePath()

        # split name and extension
        fileNameImportExportDialogBox, fileExtensionImportExportDialogBox = os.path.splitext(fileChosenImportExportDialogBox)

        # check if file does not have an extention
        if fileExtensionImportExportDialogBox == "":

            # add extension to file
            fileChosenImportExportDialogBox = fileChosenImportExportDialogBox + extensionFilter[2]

        # return dialog box value and path/file
        return True, fileChosenImportExportDialogBox
示例#9
0
文件: imagetool.py 项目: bkap/MICT
	def get_image_file(self) :
		file_dialog = JFileChooser()
		#image files
		image_filter = FileNameExtensionFilter("Image Files", 
			["jpg","bmp","png","gif"])
		print image_filter.getExtensions()
		file_dialog.setFileFilter(image_filter)
		x = file_dialog.showOpenDialog(None)
		if x == JFileChooser.APPROVE_OPTION :
			return file_dialog.getSelectedFile()
		else :
			return None
示例#10
0
 def _configFileDialogue(self):
     from javax.swing import JFileChooser
     from javax.swing.filechooser import FileNameExtensionFilter
     fileDialogue = JFileChooser(self.dssFilePath)
     filter = FileNameExtensionFilter("Configuration file (*.yml; *.yaml)",
                                      ["yaml", "yml"])
     fileDialogue.setFileFilter(filter)
     ret = fileDialogue.showOpenDialog(self.mainWindow)
     if ret == JFileChooser.APPROVE_OPTION:
         return fileDialogue.getSelectedFile().getAbsolutePath()
     else:
         raise CancelledError("Config file selection was cancelled.")
示例#11
0
def multiple_file_location_chooser(default_directory):
	"""choose input data location with potential for being split over multiple files"""
	chooser = JFileChooser(default_directory);
	chooser.setDialogTitle("Choose one or more tiff files representing the data...");
	ext_filter = FileNameExtensionFilter("*.tif", ["tif", "tiff"]);
	chooser.setFileFilter(ext_filter);
	chooser.setMultiSelectionEnabled(True);
	chooser.showOpenDialog(None);
	file_paths = [f.toString() for f in chooser.getSelectedFiles()];
	if file_paths is None or len(file_paths)==0:
		raise IOError('no input file chosen');
	return file_paths;
示例#12
0
def promptOpenDocument(world, component, handleOpenedDocumentFn):
	openDialog = JFileChooser()
	openDialog.setFileFilter( FileNameExtensionFilter( 'Larch project (*.larch)', [ 'larch' ] ) )
	response = openDialog.showDialog( component, 'Open' )
	if response == JFileChooser.APPROVE_OPTION:
		sf = openDialog.getSelectedFile()
		if sf is not None:
			filename = sf.getPath()
			if filename is not None:
				document = Document.readFile( world, filename )
				if document is not None:
					handleOpenedDocumentFn( filename, document )
示例#13
0
    def openFile(self, event=None):
        '''
        1. Check if current file in text area has unsaved changes
            1.1 Prompt user for file saving
                1.1.1 Save file
        2. Display browser for user to choose file
        3. Load file in text area
        4. Display file name in title bar
        '''
        if self.handleUnsaved():
            fileChooser = JFileChooser(self.get_working_dir())
            file_filter = FileNameExtensionFilter("ATF files", ["atf"])
            fileChooser.setFileFilter(file_filter)
            status = fileChooser.showDialog(self.view, "Choose file")

            if status == JFileChooser.APPROVE_OPTION:
                atfFile = fileChooser.getSelectedFile()
                filename = atfFile.getCanonicalPath()
                basename = atfFile.getName()
                atfText = self.readTextFile(filename)
                self.currentFilename = atfFile.getCanonicalPath()
                # Clear ATF area before adding next text to clean up tooltips
                # and such
                self.atfAreaController.clearAtfArea()

                # Turn off caret movement and highligting for file load
                self.atfAreaController.caret.setUpdatePolicy(
                    DefaultCaret.NEVER_UPDATE)
                syntax_highlight = self.atfAreaController.syntax_highlighter
                syntax_highlight.syntax_highlight_on = False
                self.atfAreaController.setAtfAreaText(atfText)

                self.consoleController.clearConsole()
                self.logger.info("File %s successfully opened.", filename)
                self.view.setTitle(basename)

                # Re-enable caret updating and syntax highlighting after load
                self.atfAreaController.caret.setUpdatePolicy(
                    DefaultCaret.ALWAYS_UPDATE)
                syntax_highlight.syntax_highlight_on = True

                # Now dispatch syntax highlighting in a new thread so
                # we dont highlight before the full file is loaded
                runSwingLater(self.initHighlighting)

            # TODO: Else, prompt user to choose again before closing

            # Update settings with current file's path
            self.update_config_element(self.get_working_dir(), 'default',
                                       'working_dir')

            # Finally, refresh the edit area to propagate custom font settings
            self.atfAreaController.refreshEditArea()
示例#14
0
    def initUI(self):

        self.panel = JPanel()
        self.panel.setLayout(BorderLayout())

        chooseFile = JFileChooser()

        chooseFile.setDialogTitle("Select Access Database")
        fnfilter = FileNameExtensionFilter("Access Databases",
                                           ["mdb", "accdb"])
        chooseFile.setFileFilter(fnfilter)

        ret = chooseFile.showSaveDialog(self.panel)

        if ret == JFileChooser.APPROVE_OPTION:
            self.file_name = str(chooseFile.getSelectedFile())
示例#15
0
def openGVL():
    from javax.swing import JFileChooser
    GUIUtil=PluginServices.getPluginServices("com.iver.cit.gvsig.cad").getClassLoader().loadClass("com.iver.cit.gvsig.gui.GUIUtil")
    chooser = JFileChooser()
    chooser.setFileFilter(GUIUtil().createFileFilter("GVL Legend File",["gvl"]))
    from java.util.prefs import Preferences
    lastPath = Preferences.userRoot().node("gvsig.foldering").get("DataFolder", "null")
    chooser.setCurrentDirectory(File(lastPath))
    chooser.setFileSelectionMode(JFileChooser.FILES_ONLY)
    returnVal = chooser.showOpenDialog(None)
    if returnVal == chooser.APPROVE_OPTION:
        gvlPath = chooser.getSelectedFile().getPath()
    elif returnVal == chooser.CANCEL_OPTION:
        JOptionPane.showMessageDialog(None, "You have to open a .gvl file. Retry!","Batch Legend",JOptionPane.WARNING_MESSAGE)
        gvlPath = ""
    return gvlPath
示例#16
0
 def __init__(self, configFileName=None, dssFilePath=None):
     """
     A tool is defined by providing a `yaml` configuration file 
     ``configFileName`` and a HEC-DSS database ``dssFilePath`` to operate on.
     If ``dssFilePath`` is not set, the active DSS-file in the HEC-DSSVue
     window will be used. If ``configFileName`` is not set, a file selection
     dialogue is displayed prompting for a configuration file.
     
     The attribute :attr:`.config` will be set containing the parsed yaml 
     config file.
     """
     
     if dssFilePath:
         self.dssFilePath = dssFilePath
         self.mainWindow = None
     else:
         from hec.dssgui import ListSelection
         self.mainWindow = ListSelection.getMainWindow()
         self.dssFilePath = self.mainWindow.getDSSFilename()
         if not configFileName:
             from javax.swing import JFileChooser
             from javax.swing.filechooser import FileNameExtensionFilter
             fileDialogue = JFileChooser(self.dssFilePath)
             filter = FileNameExtensionFilter("Configuration file (*.yml; *.yaml)", 
                                              ["yaml", "yml"])
             fileDialogue.setFileFilter(filter)
             ret = fileDialogue.showOpenDialog(self.mainWindow)
             if ret == JFileChooser.APPROVE_OPTION:
                 self.configFilePath = (fileDialogue.getSelectedFile().
                                        getAbsolutePath())
             else:
                 raise CancelledError("Config file selection was cancelled.") 
     
     if configFileName:
         self.configFilePath = path.join(path.dirname(self.dssFilePath), 
                                         configFileName)
     elif dssFilePath:
         raise ValueError("`configFileName` argument must be provided if `dssFilePath` is specified.")
     
     #: Message to be displayed in HEC-DSSVue after running the tool. This 
     #: attribute is typically set in the :meth:`main`.
     self.message = ""
     
     if self._toolIsValid():
         with codecs.open(self.configFilePath, encoding='utf-8') as configFile:
             self.config = yaml.load(configFile.read())
         self._configIsValid()
示例#17
0
    def saveFile(self, event=None):
        '''
        If file being edited has a path, then overwrite with latest changes.
        If file was created from scratch and has no path, prompt JFileChooser
        to save in desired location.
        Also checks for project name, and if found, makes it default.
        '''
        atfText = self.atfAreaController.getAtfAreaText()
        if not self.currentFilename:
            fileChooser = JFileChooser(self.get_working_dir())
            file_filter = FileNameExtensionFilter("ATF files", ["atf"])
            fileChooser.setFileFilter(file_filter)
            status = fileChooser.showSaveDialog(self.view)
            if status == JFileChooser.APPROVE_OPTION:
                atfFile = fileChooser.getSelectedFile()
                filename = atfFile.getCanonicalPath()
                # Make sure users check before lightly overwriting a file
                # No need to ask if they choose to save on the file they are
                # currently and knowingly editing.
                if os.path.isfile(filename) and \
                   filename != self.currentFilename:
                    reply = JOptionPane.showConfirmDialog(
                        None, "Are you sure you want to overwrite that file?",
                        "Confirm replace file", JOptionPane.YES_NO_OPTION)
                    if reply == JOptionPane.NO_OPTION:
                        return
                filename = self.force_atf_extension(filename)
                self.currentFilename = filename
                self.view.setTitle(os.path.basename(filename))
            else:
                return
        try:
            self.writeTextFile(self.currentFilename, atfText)
        except:
            self.logger.error("There was an error trying to save %s.",
                              self.currentFilename)
        else:
            self.logger.info("File %s successfully saved.",
                             self.currentFilename)

        # Find project and language and add to settings.yaml as default
        self.update_config()
 def _import(actionEvent):
     openDialog = JFileChooser()
     openDialog.setFileFilter(
         FileNameExtensionFilter(pageImporter.fileType,
                                 [pageImporter.filePattern]))
     response = openDialog.showDialog(component, 'Import')
     if response == JFileChooser.APPROVE_OPTION:
         sf = openDialog.getSelectedFile()
         if sf is not None:
             filename = sf.getPath()
             if filename is not None:
                 pageName = os.path.splitext(filename)[0]
                 pageName = os.path.split(pageName)[1]
                 t1 = datetime.now()
                 page = pageImporter.importPage(pageName, filename)
                 t2 = datetime.now()
                 if page is not None:
                     print 'ProjectEditor.View: IMPORT TIME = %s' % (
                         t2 - t1, )
                     handleImportedPageFn(page)
示例#19
0
    def promptuser(self, wlist):
        fileChooser = JFileChooser()
        filter = FileNameExtensionFilter("Text Files", ["txt"])
        #shows only text files in the save menu prompt
        fileChooser.setFileFilter(filter)

        ret = fileChooser.showSaveDialog(self.panel)
        #if they have selected the save option
        if ret == JFileChooser.APPROVE_OPTION:
            file = fileChooser.getSelectedFile()
            #get the path that the user selected
            filepath = str(file.getCanonicalPath())

            with open(filepath, 'a+') as f:
                for word in sorted(wlist):
                    if word == '':
                        pass
                    else:
                        f.write(word + '\n')
            print 'Wordlist created at ' + filepath
            print '##########################################################################################################\n'
示例#20
0
   def onClick(self, e):

       print outputTextField.getText()
       chooseFile = JFileChooser()
       filter = ExampleFileFilter()
       filter.addExtension("txt")
       filter.setDescription("txt HL7 input files")
       chooseFile.setFileFilter(filter)
       

       ##ret = chooseFile.showDialog(self.panel, "Choose file")
       ret = chooseFile.showOpenDialog(self.panel)

       if ret == JFileChooser.APPROVE_OPTION:
           file = chooseFile.getSelectedFile()
           text = self.readFile(file)
           self.area.append(text)
           outputFile = outputTextField.getText()
           p1 = HL7RepClass.ParseORUClass(file.getCanonicalPath(), outputFile)
           p1.parseORU()
           print "\noutfile = ", outputFile
示例#21
0
    def actionPerformed(self, actionEvent):
        global yara_rules
        global yara_path

        if actionEvent.getSource() is self.menuItem:
            yara_path = self._yara_exe_txtField.getText()
            yara_rules = self._yara_rules_files
            t = Thread(self)
            t.start()
        elif actionEvent.getSource() is self._yara_clear_button:
            # Delete the LogEntry objects from the log
            row = self._log.size()
            self._lock.acquire()
            self._log.clear()

            # Update the Table
            self.fireTableRowsDeleted(0, row)

            # Clear data regarding any selected LogEntry objects from the request / response viewers
            self._requestViewer.setMessage([], True)
            self._responseViewer.setMessage([], False)
            self._currentlyDisplayedItem = None
            self._lock.release()
        elif actionEvent.getSource() is self._yara_rules_select_files_button:
            fileChooser = JFileChooser()
            yarFilter = FileNameExtensionFilter("Yara Rules", ["yar"])
            fileChooser.addChoosableFileFilter(yarFilter)
            fileChooser.setFileFilter(yarFilter)
            fileChooser.setMultiSelectionEnabled(True)
            fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY)
            ret = fileChooser.showOpenDialog(None)
            if ret == JFileChooser.APPROVE_OPTION:
                self._yara_rules_files.clear()
                for file in fileChooser.getSelectedFiles():
                    self._yara_rules_files.add(file.getPath())
                self._yara_rules_fileList.setListData(self._yara_rules_files)
        else:
            stdout.println("Unknown Event Received.")
示例#22
0
    def actionPerformed(self, event):
        """Delete the last row"""

        # Generate a save dialog
        dialog = JFileChooser(Prefs.get("roiGroup.exportDir", ""))
        dialog.setSelectedFile(File("roiGroups.txt"))
        dialog.setFileFilter(FileNameExtensionFilter("Text file", ["txt"]))

        output = dialog.showSaveDialog(
            self.groupTable)  # could be argument None too

        if output in [JFileChooser.CANCEL_OPTION, JFileChooser.ERROR_OPTION]:
            return
        selectedFile = dialog.getSelectedFile()
        directory = selectedFile.getParent()
        Prefs.set("roiGroup.exportDir", directory)
        filePath = selectedFile.getPath()
        if not ("." in filePath):
            filePath += ".txt"  # Add extension if missing

        # Write the groupString to the file
        groupString = self.groupTable.tableModel.getGroupString()
        with open(filePath, "w") as textFile:
            textFile.write(groupString)
示例#23
0
import glob

import jmri
import java
import com.csvreader
from javax.swing import JFileChooser, JOptionPane
from javax.swing.filechooser import FileNameExtensionFilter

dialogTitle = "Class Keys Report"
print "   {}".format(dialogTitle)
keyList = []

# Select a Java program or package directory to be analyzed.
fc = JFileChooser(FileUtil.getProgramPath())
fc.setDialogTitle(dialogTitle)
fc.setFileFilter(FileNameExtensionFilter("Java Program", ["java"]));
fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES)
ret = fc.showOpenDialog(None)
if ret == JFileChooser.APPROVE_OPTION:
    selectedItem = fc.getSelectedFile().toString()
else:
    print 'No file selected, bye'
    quit()

# RegEx patterns.  Capture the first word after the start of the match string.
# The first one looks for a word within double quotes.
# The second one looks for a plain word.
# A word contains a-z, A-Z, 0-9 or underscore characters.
reStrKey = re.compile('\W*"(\w+)"\W*[,)]')
reVarKey = re.compile('\W*(\w+)\W')
示例#24
0
from time import time

import jmri
import java
from javax.swing import JFileChooser, JOptionPane
from javax.swing.filechooser import FileNameExtensionFilter

dialogTitle = "Bundle Keys Report"

##
# Select a properties file to be anaylzed.  This will normally be the
# default (English) file.
##
fc = JFileChooser(FileUtil.getProgramPath())
fc.setDialogTitle(dialogTitle)
fc.setFileFilter(FileNameExtensionFilter("Bundle Properties", ["properties"]))
ret = fc.showOpenDialog(None)
if ret == JFileChooser.APPROVE_OPTION:
    selectedBundle = fc.getSelectedFile().toString()
    startTime = time()
else:
    print "No file selected, bye"
    quit()

# set up path info
bundleFile = os.path.basename(selectedBundle)
fullPath = os.path.dirname(selectedBundle)
splitPath = fullPath.split(os.sep + "src" + os.sep)
jmriPath = splitPath[0]
bundlePath = splitPath[1]
dotPath = ".".join(bundlePath.split(os.sep))
示例#25
0
class BurpExtender(IBurpExtender, ITab, IHttpListener,
                   IMessageEditorController, AbstractTableModel,
                   IContextMenuFactory, IScannerCheck):
    name = "Femida XSS"
    conf_path = "./config.py"
    _jTabbedPane = JTabbedPane()
    _jPanel = JPanel()
    _jAboutPanel = JPanel()
    _jPanelConstraints = GridBagConstraints()
    _jLabelParameters = None
    _jTextFieldParameters = None
    _jLabelTechniques = None
    _jTextFieldURL = None
    _jLabelFuzzFactor = None
    _jTextFieldFuzzFactor = None
    _jLabelAdditionalCmdLine = None
    _jTextFieldAdditionalCmdLine = None
    _jButtonSetCommandLine = None
    _jLabelAbout = None
    _overwriteHeader = False
    _overwriteParam = False
    _forkRequestParam = False

    def doActiveScan(self, baseRequestResponse, insertionPoint):
        scan_issues = []
        try:
            requestString = str(baseRequestResponse.getRequest().tostring())
            newRequestString = self.prepareRequest(requestString)

            vulnerable, verifyingRequestResponse = self.quickCheckScan(
                newRequestString, baseRequestResponse)

        except Exception as msg:
            print(msg)

        return []

    def quickCheckScan(self, preparedRequest, requestResponse):
        check = self._callbacks.makeHttpRequest(
            requestResponse.getHttpService(),
            self._helpers.stringToBytes(preparedRequest))
        vulner = self._helpers.analyzeResponse(
            check.getResponse()).getStatusCode() == 200
        return vulner, check

    #
    # implement IBurpExtender
    #
    def registerExtenderCallbacks(self, callbacks):
        self._callbacks = callbacks
        self._helpers = callbacks.getHelpers()
        self._callbacks.setExtensionName(self.name)
        self._callbacks.registerScannerCheck(self)

        self._dictPayloads = {}
        self._dictHeaders = {}
        self._dictParams = {}
        self.status_flag = False

        self.jfc = JFileChooser("./")
        self.jfc.setDialogTitle("Upload Payloads")
        self.jfc.setFileFilter(FileNameExtensionFilter("TXT file", ["txt"]))

        self._layout = GridBagLayout()
        self._jPanel.setLayout(self._layout)

        self._jLabelTechniques = JLabel("Press to start:")
        self.createAnyView(self._jLabelTechniques, 0, 0, 3, 1,
                           Insets(0, 0, 10, 0))

        self.submitSearchButton = swing.JButton(
            'Run proxy', actionPerformed=self.active_flag)
        self.submitSearchButton.setBackground(Color.WHITE)
        self.createAnyView(self.submitSearchButton, 3, 0, 6, 1,
                           Insets(0, 0, 10, 0))

        self._jPanel.setBounds(0, 0, 1000, 1000)
        self._jLabelTechniques = JLabel("Your URL (my.burpcollaborator.net):")
        self.createAnyView(self._jLabelTechniques, 0, 1, 3, 1,
                           Insets(0, 0, 10, 0))

        self._jTextFieldURL = JTextField("", 30)
        self._jTextFieldURL.addActionListener(self.setCallbackUrl)
        self.createAnyView(self._jTextFieldURL, 3, 1, 5, 1,
                           Insets(0, 0, 10, 0))

        self._forkRequestButton = swing.JButton(
            'Parallel Request', actionPerformed=self.forkRequest)
        self._forkRequestButton.setBackground(Color.WHITE)
        self.createAnyView(self._forkRequestButton, 8, 1, 1, 1,
                           Insets(0, 0, 10, 0))

        self._tableModelPayloads = DefaultTableModel()
        self._tableModelPayloads.addColumn("Payload")
        self._tableModelPayloads.addColumn("Active")

        self._tableModelHeaders = DefaultTableModel()
        self._tableModelHeaders.addColumn("Header")
        self._tableModelHeaders.addColumn("Active")

        self._tableModelParams = DefaultTableModel()
        self._tableModelParams.addColumn("Parameter")
        self._tableModelParams.addColumn("Active")

        self._payloadTable = self.createAnyTable(self._tableModelPayloads, 1,
                                                 Dimension(300, 200))
        self.createAnyView(self._payloadTable, 0, 2, 3, 1, Insets(0, 0, 0, 10))

        self._headerTable = self.createAnyTable(self._tableModelHeaders, 2,
                                                Dimension(300, 200))
        self.createAnyView(self._headerTable, 3, 2, 3, 1, Insets(0, 0, 0, 10))

        self._paramTable = self.createAnyTable(self._tableModelParams, 3,
                                               Dimension(300, 200))
        self.createAnyView(self._paramTable, 6, 2, 3, 1, Insets(0, 0, 0, 0))

        deletePayloadButton = swing.JButton(
            'Delete', actionPerformed=self.deleteToPayload)
        deletePayloadButton.setBackground(Color.WHITE)
        self.createAnyView(deletePayloadButton, 0, 3, 1, 1, Insets(3, 0, 0, 0))

        deletePayloadButton = swing.JButton(
            'Upload', actionPerformed=self.uploadToPayload)
        deletePayloadButton.setBackground(Color.WHITE)
        self.createAnyView(deletePayloadButton, 1, 3, 1, 1, Insets(3, 0, 0, 0))

        addPayloadButton = swing.JButton('Add',
                                         actionPerformed=self.addToPayload)
        addPayloadButton.setBackground(Color.WHITE)
        self.createAnyView(addPayloadButton, 2, 3, 1, 1, Insets(3, 0, 0, 10))

        deleteHeaderButton = swing.JButton('Delete',
                                           actionPerformed=self.deleteToHeader)
        deleteHeaderButton.setBackground(Color.WHITE)
        self.createAnyView(deleteHeaderButton, 3, 3, 1, 1, Insets(3, 0, 0, 0))

        self._overwriteHeaderButton = swing.JButton(
            'Overwrite', actionPerformed=self.overwriteHeader)
        self._overwriteHeaderButton.setBackground(Color.WHITE)
        self.createAnyView(self._overwriteHeaderButton, 4, 3, 1, 1,
                           Insets(3, 0, 0, 0))

        addHeaderButton = swing.JButton('Add',
                                        actionPerformed=self.addToHeader)
        addHeaderButton.setBackground(Color.WHITE)
        self.createAnyView(addHeaderButton, 5, 3, 1, 1, Insets(3, 0, 0, 10))

        deleteParamsButton = swing.JButton('Delete',
                                           actionPerformed=self.deleteToParams)
        deleteParamsButton.setBackground(Color.WHITE)
        self.createAnyView(deleteParamsButton, 6, 3, 1, 1, Insets(3, 0, 0, 0))

        self._overwriteParamButton = swing.JButton(
            'Overwrite', actionPerformed=self.overwriteParam)
        self._overwriteParamButton.setBackground(Color.WHITE)
        self.createAnyView(self._overwriteParamButton, 7, 3, 1, 1,
                           Insets(3, 0, 0, 0))

        addParamsButton = swing.JButton('Add',
                                        actionPerformed=self.addToParams)
        addParamsButton.setBackground(Color.WHITE)
        self.createAnyView(addParamsButton, 8, 3, 1, 1, Insets(3, 0, 0, 0))

        self._resultsTextArea = swing.JTextArea()
        resultsOutput = swing.JScrollPane(self._resultsTextArea)
        resultsOutput.setMinimumSize(Dimension(800, 200))
        self.createAnyView(resultsOutput, 0, 4, 9, 1, Insets(10, 0, 0, 0))

        self.clearSearchButton = swing.JButton(
            'Clear Search Output', actionPerformed=self.clearOutput)
        self.createAnyView(self.clearSearchButton, 3, 6, 3, 1,
                           Insets(3, 0, 0, 0))

        self._callbacks.customizeUiComponent(self._jPanel)
        self._callbacks.addSuiteTab(self)
        self.starterPack()

        self._callbacks.registerHttpListener(self)
        self._callbacks.registerContextMenuFactory(self)

        return

    def createAnyTable(self, table_model, table_number, min_size):
        _table = JTable(table_model)
        _table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS)
        for i in range(2):
            column = _table.getColumnModel().getColumn(i)
            if i == 0:
                column.setPreferredWidth(250)
            else:
                column.setPreferredWidth(50)

        _scrolltable = JScrollPane(_table)
        _scrolltable.setMinimumSize(min_size)
        return _scrolltable

    def insertAnyTable(self, table, data):
        def detectTable(table):
            name = table.getColumnName(0)
            if name == 'Payloads':
                return 0
            elif name == 'Headers':
                return 1
            elif name == 'Parameters':
                return 2

        tableNum = detectTable(table)
        new_data = [str(x) for x in data]
        table.insertRow(table.getRowCount(), new_data)
        return table.getRowCount()

    def replaceLine(self, file_path, new_line):
        from tempfile import mkstemp
        from shutil import move
        from os import fdopen, remove
        #Create temp file
        fh, abs_path = mkstemp()
        with fdopen(fh, 'w') as new_file:
            with open(file_path) as old_file:
                for line in old_file:
                    a = re.findall('^Callback_url[ =]+(.+)$', line)
                    if a:
                        for k in a:
                            temp = k.replace("\'", "").replace("\"", "")
                            new_file.write(line.replace(temp, new_line))
                    else:
                        new_file.write(line)
        #Remove original file
        remove(file_path)
        #Move new file
        move(abs_path, file_path)

    def createAnyView(self, _component, gridx, gridy, gridwidth, gridheight,
                      insets):
        self._jPanelConstraints.fill = GridBagConstraints.HORIZONTAL
        self._jPanelConstraints.gridx = gridx
        self._jPanelConstraints.gridy = gridy
        self._jPanelConstraints.gridwidth = gridwidth
        self._jPanelConstraints.gridheight = gridheight
        self._jPanelConstraints.insets = insets
        self._jPanel.add(_component, self._jPanelConstraints)

    def createMenuItems(self, contextMenuInvocation):
        context = contextMenuInvocation.getInvocationContext()
        filterMenu = JMenu("Femida XSS")
        self._contextMenuData = contextMenuInvocation
        if (context == 0 or context == 1 or context == 2 or context == 3
                or context == 8 or context == 9):
            filterMenu.add(
                JMenuItem("Add to Headers",
                          actionPerformed=self.addToHeadersItem))
            filterMenu.add(
                JMenuItem("Add to Parameters",
                          actionPerformed=self.addToParametersItem))
            return Arrays.asList(filterMenu)
        return Arrays.asList([])

    def addToHeadersItem(self, event):
        start, end = self._contextMenuData.getSelectionBounds()
        message = self._contextMenuData.getSelectedMessages()[0]
        ctx = self._contextMenuData.getInvocationContext()

        if ctx == 0 or ctx == 2:
            message = message.getRequest()
        elif ctx == 1 or ctx == 3:
            message = message.getResponse()
        else:
            print(ctx)
            return
        try:
            selected_text = self._helpers.bytesToString(message)[start:end]
            self.insertAnyTable(self._tableModelHeaders,
                                [str(selected_text), '1'])
        except Exception:
            pass

    def addToParametersItem(self, event):
        start, end = self._contextMenuData.getSelectionBounds()
        message = self._contextMenuData.getSelectedMessages()[0]
        ctx = self._contextMenuData.getInvocationContext()

        if ctx == 0 or ctx == 2:
            message = message.getRequest()
        elif ctx == 1 or ctx == 3:
            message = message.getResponse()
        else:
            print(ctx)
            return
        try:
            selected_text = self._helpers.bytesToString(message)[start:end]
            self.insertAnyTable(self._tableModelParams,
                                [str(selected_text), '1'])
        except Exception:
            pass

    def starterPack(self):
        self.addFromFileAsync(config.Payloads, self._tableModelPayloads)
        self.addFromFileAsync(config.Headers, self._tableModelHeaders)
        self.addFromFileAsync(config.Parameters, self._tableModelParams)
        self._jTextFieldURL.setText(config.Callback_url)
        self._tableModelPayloads.addTableModelListener(
            MyTableModelListener(self._tableModelPayloads, self,
                                 self._dictPayloads, config.Payloads))
        self._tableModelHeaders.addTableModelListener(
            MyTableModelListener(self._tableModelHeaders, self,
                                 self._dictHeaders, config.Headers))
        self._tableModelParams.addTableModelListener(
            MyTableModelListener(self._tableModelParams, self,
                                 self._dictParams, config.Parameters))

    def setCallbackUrl(self, event):
        self.replaceLine(self.conf_path, self._jTextFieldURL.getText())
        self.appendToResults('New url={} saved.'.format(
            self._jTextFieldURL.getText()))

    def addToPayload(self, button):
        self.insertAnyTable(self._tableModelPayloads, ['', '1'])

    def addToHeader(self, button):
        self.insertAnyTable(self._tableModelHeaders, ['', '1'])

    def addToParams(self, button):
        self.insertAnyTable(self._tableModelParams, ['', '1'])

    def uploadToPayload(self, button):
        self._returnFileChooser = self.jfc.showDialog(None, "Open")
        if (self._returnFileChooser == JFileChooser.APPROVE_OPTION):
            selectedFile = self.jfc.getSelectedFile()
            self.fileUpload(selectedFile, self._tableModelPayloads)

    def deleteToPayload(self, button):
        try:
            val = self._tableModelPayloads.getValueAt(
                self._tableModelPayloads.getRowCount() - 1, 0)
            self._tableModelPayloads.removeRow(
                self._tableModelPayloads.getRowCount() - 1)
            self._dictPayloads.pop(val)
            self.saveToFileAsync(config.Payloads, self._dictPayloads)
        except Exception as msg:
            # print(msg)
            pass

    def deleteToHeader(self, button):
        try:
            val = self._tableModelHeaders.getValueAt(
                self._tableModelHeaders.getRowCount() - 1, 0)
            self._tableModelHeaders.removeRow(
                self._tableModelHeaders.getRowCount() - 1)
            self._dictHeaders.pop(val)
            self.saveToFileAsync(config.Headers, self._dictHeaders)
        except Exception as msg:
            # print(msg)
            pass

    def deleteToParams(self, button):
        try:
            val = self._tableModelParams.getValueAt(
                self._tableModelParams.getRowCount() - 1, 0)
            self._tableModelParams.removeRow(
                self._tableModelParams.getRowCount() - 1)
            self._dictParams.pop(val)
            self.saveToFileAsync(config.Parameters, self._dictParams)
        except Exception as msg:
            # print(msg)
            pass

    def clearOutput(self, button):
        self._resultsTextArea.setText("")

    def fileUpload(self, path, table):
        with open(str(path), "r") as f:
            for line in f:
                self.insertAnyTable(table, [str(line), '1'])

    def active_flag(self, button):
        if not self.status_flag:
            self.status_flag = True
            self.submitSearchButton.setBackground(Color.GRAY)
            self.appendToResults("Proxy start...\n")
        else:
            self.status_flag = False
            self.submitSearchButton.setBackground(Color.WHITE)
            self.appendToResults("Proxy stop...\n")

    def overwriteHeader(self, button):
        if not self._overwriteHeader:
            self._overwriteHeader = True
            self._overwriteHeaderButton.setBackground(Color.GRAY)
        else:
            self._overwriteHeader = False
            self._overwriteHeaderButton.setBackground(Color.WHITE)

    def overwriteParam(self, button):
        if not self._overwriteParam:
            self._overwriteParam = True
            self._overwriteParamButton.setBackground(Color.GRAY)
        else:
            self._overwriteParam = False
            self._overwriteParamButton.setBackground(Color.WHITE)

    def forkRequest(self, button):
        if not self._forkRequestParam:
            self._forkRequestParam = True
            self._forkRequestButton.setBackground(Color.GRAY)
        else:
            self._forkRequestParam = False
            self._forkRequestButton.setBackground(Color.WHITE)

    def prepareRequest(self, requestString, messageInfo=None):
        requestString = str(requestString)
        listHeader = re.findall('([\w-]+):\s?(.*)', requestString)
        dictRealHeaders = {x[0].lower(): x[1] for x in listHeader}

        selectedPayloads = {}
        for ind, k in enumerate(self._dictPayloads):
            if self._dictPayloads[k] == '1':
                selectedPayloads[k] = '1'
            else:
                continue

        for index, key in enumerate(self._dictHeaders):
            if key.lower() in dictRealHeaders.keys(
            ) and self._dictHeaders[key] == '1':
                if len(self._dictPayloads.keys()) == 0:
                    pass
                elif self._overwriteHeader:
                    payload = random.choice(selectedPayloads.keys())
                    payload = payload.replace(r"{URL}",
                                              self._jTextFieldURL.getText(), 1)
                    requestString = requestString.replace(
                        dictRealHeaders.get(key.lower()), payload, 1)
                elif not self._overwriteHeader:
                    payload = random.choice(selectedPayloads.keys())
                    payload = payload.replace(r"{URL}",
                                              self._jTextFieldURL.getText(), 1)
                    payload = dictRealHeaders.get(key.lower()) + payload
                    requestString = requestString.replace(
                        dictRealHeaders.get(key.lower()), payload, 1)
            else:
                pass

        for index, key in enumerate(self._dictParams):
            analyzed = self._helpers.analyzeRequest(requestString.encode())
            param = analyzed.getParameters()
            dictRealParams = {
                x.getName().lower():
                [x.getValue(),
                 x.getValueStart(),
                 x.getValueEnd()]
                for x in param
            }
            if key.lower() in dictRealParams.keys(
            ) and self._dictParams[key] == '1':
                if len(self._dictPayloads.keys()) == 0:
                    pass
                elif self._overwriteParam:
                    payload = random.choice(selectedPayloads.keys())
                    payload = payload.replace(r"{URL}",
                                              self._jTextFieldURL.getText(), 1)
                    start_word = dictRealParams[key.lower()][1]
                    end_word = dictRealParams[key.lower()][2]
                    requestString = requestString[:
                                                  start_word] + payload + requestString[
                                                      end_word:]

                elif not self._overwriteParam:
                    payload = random.choice(selectedPayloads.keys())
                    payload = payload.replace(r"{URL}",
                                              self._jTextFieldURL.getText(), 1)
                    payload = dictRealParams[key.lower()][0] + payload
                    start_word = dictRealParams[key.lower()][1]
                    end_word = dictRealParams[key.lower()][2]
                    requestString = requestString[:
                                                  start_word] + payload + requestString[
                                                      end_word:]
            else:
                pass
        return requestString

    def processHttpMessage(self, toolFlag, messageIsRequest, messageInfo):
        if not self.status_flag:
            return
        # only process requests
        if not messageIsRequest:
            return

        if self._forkRequestParam:
            requestString = messageInfo.getRequest().tostring()
            # SOOOO HARD FIX! It should be better
            if requestString[0] == '@':
                messageInfo.setRequest(
                    self._helpers.stringToBytes(requestString[1:]))
            else:
                newRequestString = self.prepareRequest(requestString,
                                                       messageInfo)
                self.appendToResults('Parallel Request:')
                self.appendToResults(newRequestString.encode())
                newRequestString = '@' + newRequestString
                func = self._callbacks.makeHttpRequest
                thread = Thread(
                    target=func,
                    args=(messageInfo.getHttpService(),
                          self._helpers.stringToBytes(newRequestString)))
                thread.start()
        else:
            requestString = messageInfo.getRequest().tostring()
            newRequestString = self.prepareRequest(requestString, messageInfo)
            self.appendToResults(newRequestString.encode())
            messageInfo.setRequest(
                self._helpers.stringToBytes(newRequestString))

    # Fnction to provide output to GUI
    def appendToResults(self, s):
        def appendToResults_run(s):
            self._resultsTextArea.append(s)
            self._resultsTextArea.append('\n')

        swing.SwingUtilities.invokeLater(
            PyRunnable(appendToResults_run, str(s)))

    def addFromFileAsync(self, file, table):
        def addFromFile_run(file, table):
            if os.path.exists(file):
                with open(file, 'r') as f:
                    for row in f.readlines():
                        if row != '':
                            temp = row[:-1] if row[-1] == '\n' else row
                            self.insertAnyTable(table, [str(temp), '1'])

        swing.SwingUtilities.invokeLater(
            PyRunnable(addFromFile_run, file, table))

    def saveToFileAsync(self, file, data, isAppend=False):
        def saveToFile_run(file, data, isAppend):
            isAppend = 'w'
            with open(file, isAppend) as f:
                for i, k in enumerate(data):
                    f.write("{}\n".format(k))
                f.seek(-1, os.SEEK_END)
                f.truncate()

        swing.SwingUtilities.invokeLater(
            PyRunnable(saveToFile_run, file, data, isAppend))

    def getTabCaption(self):
        return self.name

    def getUiComponent(self):
        return self._jPanel
示例#26
0
import glob

import jmri
import java
import org.apache.commons.csv
from javax.swing import JFileChooser, JOptionPane
from javax.swing.filechooser import FileNameExtensionFilter

dialogTitle = "Class Keys Report"
print "   {}".format(dialogTitle)
keyList = []

# Select a Java program or package directory to be analyzed.
fc = JFileChooser(FileUtil.getProgramPath())
fc.setDialogTitle(dialogTitle)
fc.setFileFilter(FileNameExtensionFilter("Java Program", ["java"]));
fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES)
ret = fc.showOpenDialog(None)
if ret == JFileChooser.APPROVE_OPTION:
    selectedItem = fc.getSelectedFile().toString()
else:
    print 'No file selected, bye'
    quit()

# RegEx patterns.  Capture the first word after the start of the match string.
# The first one looks for a word within double quotes.
# The second one looks for a plain word.
# A word contains a-z, A-Z, 0-9 or underscore characters.
reStrKey = re.compile('\W*"(\w+)"\W*[,)]')
reVarKey = re.compile('\W*(\w+)\W')
示例#27
0
class BurpExtender(IBurpExtender, ITab, IMessageEditorController, AbstractTableModel, IContextMenuFactory):

    def registerExtenderCallbacks(self, callbacks):
        # keep a reference to our callbacks object
        self._callbacks = callbacks
        # obtain an extension helpers object
        self._helpers = callbacks.getHelpers()
        
        # set our extension name
        callbacks.setExtensionName("PT Vulnerabilities Manager")
        
        self.config = SafeConfigParser()
        self.createSection('projects')
        self.createSection('general')
        self.config.read('config.ini')
        self.chooser = JFileChooser()
        # create the log and a lock on which to synchronize when adding log entries
        self._log = ArrayList()
        self._lock = Lock()
        
        self.logTable = Table(self)
        self.logTable.getColumnModel().getColumn(0).setMaxWidth(35)
        self.logTable.getColumnModel().getColumn(1).setMinWidth(100)

        self._requestViewer = self._callbacks.createMessageEditor(self, False)
        self._responseViewer = self._callbacks.createMessageEditor(self, False)

        self.initVulnerabilityTab()
        self.initProjSettingsTab()
        self.initTabs()
        self.initCallbacks()

        if self.projPath.getText() != None:
            self.loadVulnerabilities(self.projPath.getText())

        print "Thank you for installing PT Vulnerabilities Manager v1.0 extension"
        print "by Barak Tawily\n\n\n"
        print "Disclaimer:\nThis extension might create folders and files in your hardisk which might be declared as sensitive information, make sure you are creating projects under encrypted partition"
        return

    def initVulnerabilityTab(self):
        #
        ##  init vulnerability tab
        #

        nameLabel = JLabel("Vulnerability Name:")
        nameLabel.setBounds(10, 10, 140, 30)

        self.addButton = JButton("Add",actionPerformed=self.addVuln)
        self.addButton.setBounds(10, 500, 100, 30) 

        rmVulnButton = JButton("Remove",actionPerformed=self.rmVuln)
        rmVulnButton.setBounds(465, 500, 100, 30)

        mitigationLabel = JLabel("Mitigation:")
        mitigationLabel.setBounds(10, 290, 150, 30)
        
        addSSBtn = JButton("Add SS",actionPerformed=self.addSS)
        addSSBtn.setBounds(750, 40, 110, 30) 

        deleteSSBtn = JButton("Remove SS",actionPerformed=self.removeSS)
        deleteSSBtn.setBounds(750, 75, 110, 30) 

        piclistLabel = JLabel("Images list:")
        piclistLabel.setBounds(580, 10, 140, 30)

        self.screenshotsList = DefaultListModel()
        self.ssList = JList(self.screenshotsList)
        self.ssList.setBounds(580, 40, 150, 250)
        self.ssList.addListSelectionListener(ssChangedHandler(self))
        self.ssList.setBorder(BorderFactory.createLineBorder(Color.GRAY))

        previewPicLabel = JLabel("Selected image preview: (click to open in image viewer)")
        previewPicLabel.setBounds(580, 290, 500, 30)


        copyImgMenu = JMenuItem("Copy")
        copyImgMenu.addActionListener(copyImg(self))

        self.imgMenu = JPopupMenu("Popup")
        self.imgMenu.add(copyImgMenu)

        self.firstPic = JLabel()
        self.firstPic.setBorder(BorderFactory.createLineBorder(Color.GRAY))
        self.firstPic.setBounds(580, 320, 550, 400)
        self.firstPic.addMouseListener(imageClicked(self))

        self.vulnName = JTextField("")
        self.vulnName.getDocument().addDocumentListener(vulnTextChanged(self))
        self.vulnName.setBounds(140, 10, 422, 30)

        sevirities = ["Unclassified", "Critical","High","Medium","Low"]
        self.threatLevel = JComboBox(sevirities);
        self.threatLevel.setBounds(140, 45, 140, 30)

        colors = ["Color:", "Green", "Red"]
        self.colorCombo = JComboBox(colors);
        self.colorCombo.setBounds(465, 45, 100, 30)
        self.colorCombo

        severityLabel = JLabel("Threat Level:")
        severityLabel.setBounds(10, 45, 100, 30)

        descriptionLabel = JLabel("Description:")
        descriptionLabel.setBounds(10, 80, 100, 30)

        self.descriptionString = JTextArea("", 5, 30)
        self.descriptionString.setWrapStyleWord(True);
        self.descriptionString.setLineWrap(True)
        self.descriptionString.setBounds(10, 110, 555, 175)
        descriptionStringScroll = JScrollPane(self.descriptionString)
        descriptionStringScroll.setBounds(10, 110, 555, 175)
        descriptionStringScroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED)


        self.mitigationStr = JTextArea("", 5, 30)
        self.mitigationStr.setWrapStyleWord(True);
        self.mitigationStr.setLineWrap(True)
        self.mitigationStr.setBounds(10, 320, 555, 175)

        mitigationStrScroll = JScrollPane(self.mitigationStr)
        mitigationStrScroll.setBounds(10, 320, 555, 175)
        mitigationStrScroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED)

        self.pnl = JPanel()
        self.pnl.setBounds(0, 0, 1000, 1000);
        self.pnl.setLayout(None);
        self.pnl.add(addSSBtn)
        self.pnl.add(piclistLabel)
        self.pnl.add(nameLabel)
        self.pnl.add(deleteSSBtn)
        self.pnl.add(rmVulnButton)
        self.pnl.add(severityLabel)
        self.pnl.add(mitigationLabel)
        self.pnl.add(descriptionLabel)
        self.pnl.add(previewPicLabel)
        self.pnl.add(mitigationStrScroll)
        self.pnl.add(descriptionStringScroll)
        self.pnl.add(self.ssList)
        self.pnl.add(self.firstPic)
        self.pnl.add(self.addButton)
        self.pnl.add(self.vulnName)
        self.pnl.add(self.threatLevel)
        self.pnl.add(self.colorCombo)
        
    def initProjSettingsTab(self):
        # init project settings 
        
        projNameLabel = JLabel("Name:")
        projNameLabel.setBounds(10, 50, 140, 30)

        self.projName = JTextField("")
        self.projName.setBounds(140, 50, 320, 30)
        self.projName.getDocument().addDocumentListener(projTextChanged(self))

        detailsLabel = JLabel("Details:")
        detailsLabel.setBounds(10, 120, 140, 30)

        reportLabel = JLabel("Generate Report:")
        reportLabel.setBounds(10, 375, 140, 30)

        types = ["DOCX","HTML","XLSX"]
        self.reportType = JComboBox(types)
        self.reportType.setBounds(10, 400, 140, 30)

        generateReportButton = JButton("Generate", actionPerformed=self.generateReport)
        generateReportButton.setBounds(160, 400, 90, 30)


        self.projDetails = JTextArea("", 5, 30)
        self.projDetails.setWrapStyleWord(True);
        self.projDetails.setLineWrap(True)

        projDetailsScroll = JScrollPane(self.projDetails)
        projDetailsScroll.setBounds(10, 150, 450, 175)
        projDetailsScroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED)

        projPathLabel = JLabel("Path:")
        projPathLabel.setBounds(10, 90, 140, 30)

        self.projPath = JTextField("")
        self.projPath.setBounds(140, 90, 320, 30)

        chooseProjPathButton = JButton("Browse...",actionPerformed=self.chooseProjPath)
        chooseProjPathButton.setBounds(470, 90, 100, 30)
        
        importProjButton = JButton("Import",actionPerformed=self.importProj)
        importProjButton.setBounds(470, 10, 100, 30)

        exportProjButton = JButton("Export",actionPerformed=self.exportProj)
        exportProjButton.setBounds(575, 10, 100, 30)

        openProjButton = JButton("Open Directory",actionPerformed=self.openProj)
        openProjButton.setBounds(680, 10, 130, 30)

        currentProjectLabel = JLabel("Current:")
        currentProjectLabel.setBounds(10, 10, 140, 30)

        projects = self.config.options('projects')
        self.currentProject = JComboBox(projects)
        self.currentProject.addActionListener(projectChangeHandler(self))
        self.currentProject.setBounds(140, 10, 140, 30)

        self.autoSave = JCheckBox("Auto Save Mode")
        self.autoSave.setEnabled(False)  # implement this feature
        self.autoSave.setBounds(300, 10, 140, 30)
        self.autoSave.setToolTipText("Will save any changed value while focus is out")

        addProjButton = JButton("Add / Update",actionPerformed=self.addProj)
        addProjButton.setBounds(10, 330, 150, 30)

        removeProjButton = JButton("Remove Current",actionPerformed=self.rmProj)
        removeProjButton.setBounds(315, 330, 146, 30)

        generalOptions = self.config.options('general')
        if 'default project' in generalOptions:
            defaultProj = self.config.get('general','default project')
            self.currentProject.getModel().setSelectedItem(defaultProj)
            self.projPath.setText(self.config.get('projects',self.currentProject.getSelectedItem()))

        self.clearProjTab = True
        self.projectSettings = JPanel()
        self.projectSettings.setBounds(0, 0, 1000, 1000)
        self.projectSettings.setLayout(None)
        self.projectSettings.add(reportLabel)
        self.projectSettings.add(detailsLabel)
        self.projectSettings.add(projPathLabel)
        self.projectSettings.add(addProjButton)
        self.projectSettings.add(openProjButton)
        self.projectSettings.add(projNameLabel)
        self.projectSettings.add(projDetailsScroll)
        self.projectSettings.add(importProjButton)
        self.projectSettings.add(exportProjButton)
        self.projectSettings.add(removeProjButton)
        self.projectSettings.add(generateReportButton)
        self.projectSettings.add(chooseProjPathButton)
        self.projectSettings.add(currentProjectLabel)
        self.projectSettings.add(self.projPath)
        self.projectSettings.add(self.autoSave)
        self.projectSettings.add(self.projName)
        self.projectSettings.add(self.reportType)
        self.projectSettings.add(self.currentProject)

    def initTabs(self):
        #
        ##  init autorize tabs
        #
        
        self._splitpane = JSplitPane(JSplitPane.HORIZONTAL_SPLIT)
        self.scrollPane = JScrollPane(self.logTable)
        self._splitpane.setLeftComponent(self.scrollPane)
        colorsMenu = JMenu("Paint")
        redMenu = JMenuItem("Red")
        noneMenu = JMenuItem("None")
        greenMenu = JMenuItem("Green")
        redMenu.addActionListener(paintChange(self, "Red"))
        noneMenu.addActionListener(paintChange(self, None))
        greenMenu.addActionListener(paintChange(self, "Green"))
        colorsMenu.add(redMenu)
        colorsMenu.add(noneMenu)
        colorsMenu.add(greenMenu)
        
        
        self.menu = JPopupMenu("Popup")
        self.menu.add(colorsMenu)

        self.tabs = JTabbedPane()
        
        self.tabs.addTab("Request", self._requestViewer.getComponent())
        self.tabs.addTab("Response", self._responseViewer.getComponent())

        self.tabs.addTab("Vulnerability", self.pnl)

        self.tabs.addTab("Project Settings", self.projectSettings)
        
        self.tabs.setSelectedIndex(2)
        self._splitpane.setRightComponent(self.tabs)

    def initCallbacks(self):
        #
        ##  init callbacks
        #

        # customize our UI components
        self._callbacks.customizeUiComponent(self._splitpane)
        self._callbacks.customizeUiComponent(self.logTable)
        self._callbacks.customizeUiComponent(self.scrollPane)
        self._callbacks.customizeUiComponent(self.tabs)
        self._callbacks.registerContextMenuFactory(self)
        # add the custom tab to Burp's UI
        self._callbacks.addSuiteTab(self)


    def loadVulnerabilities(self, projPath):
        self.clearList(None)
        selected = False
        for root, dirs, files in os.walk(projPath): # make it go only for dirs
            for dirName in dirs:
                xmlPath = projPath+"/"+dirName+"/vulnerability.xml"
                # xmlPath = xmlPath.replace("/","//")
                document = self.getXMLDoc(xmlPath)
                nodeList = document.getDocumentElement().getChildNodes()
                vulnName = nodeList.item(0).getTextContent()
                severity = nodeList.item(1).getTextContent()
                description = nodeList.item(2).getTextContent()
                mitigation = nodeList.item(3).getTextContent()
                color = nodeList.item(4).getTextContent()
                test = vulnerability(vulnName,severity,description,mitigation,color)
                self._lock.acquire()
                row = self._log.size()
                self._log.add(test)
                self.fireTableRowsInserted(row, row)
                self._lock.release()
                if vulnName == self.vulnName.getText():
                    self.logTable.setRowSelectionInterval(row,row)
                    selected = True
        if selected == False and self._log.size() > 0:
            self.logTable.setRowSelectionInterval(0, 0)
            self.loadVulnerability(self._log.get(0))
        
    def createSection(self, sectioName):
        self.config.read('config.ini')
        if not (sectioName in self.config.sections()):
            self.config.add_section(sectioName)
            cfgfile = open("config.ini",'w')
            self.config.write(cfgfile)
            cfgfile.close()

    def saveCfg(self):
        f = open('config.ini', 'w')
        self.config.write(f)
        f.close()

    def getXMLDoc(self, xmlPath):
        try:
            document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(xmlPath)
            return document
        except:
            self._extender.popup("XML file not found")
            return

    def saveXMLDoc(self, doc, xmlPath):
        transformerFactory = TransformerFactory.newInstance()
        transformer = transformerFactory.newTransformer()
        source = DOMSource(doc)
        result = StreamResult(File(xmlPath))
        transformer.transform(source, result)

    def generateReport(self,event):
        if self.reportType.getSelectedItem() == "HTML":
            path = self.reportToHTML()
        if self.reportType.getSelectedItem() == "XLSX":
            path = self.reportToXLS()
        if self.reportType.getSelectedItem() == "DOCX":
            path = self.generateReportFromDocxTemplate('template.docx',"newfile.docx", 'word/document.xml')
        n = JOptionPane.showConfirmDialog(None, "Report generated successfuly:\n%s\nWould you like to open it?" % (path), "PT Manager", JOptionPane.YES_NO_OPTION)
        if n == JOptionPane.YES_OPTION:
            os.system('"' + path + '"') # Bug! stucking burp until the file get closed

    def exportProj(self,event):
        self.chooser.setDialogTitle("Save project")
        Ffilter = FileNameExtensionFilter("Zip files", ["zip"])
        self.chooser.setFileFilter(Ffilter)
        returnVal = self.chooser.showSaveDialog(None)
        if returnVal == JFileChooser.APPROVE_OPTION:
            dst = str(self.chooser.getSelectedFile())
            shutil.make_archive(dst,"zip",self.getCurrentProjPath())
            self.popup("Project export successfuly")

    def importProj(self,event):
        self.chooser.setDialogTitle("Select project zip to directory")
        Ffilter = FileNameExtensionFilter("Zip files", ["zip"])
        self.chooser.setFileFilter(Ffilter)
        returnVal = self.chooser.showOpenDialog(None)
        if returnVal == JFileChooser.APPROVE_OPTION:
            zipPath = str(self.chooser.getSelectedFile())
            self.chooser.setDialogTitle("Select project directory")
            self.chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY)
            returnVal = self.chooser.showOpenDialog(None)
            if returnVal == JFileChooser.APPROVE_OPTION:
                projPath = str(self.chooser.getSelectedFile()) + "/PTManager"
                with zipfile.ZipFile(zipPath, "r") as z:
                    z.extractall(projPath)

                xmlPath = projPath + "/project.xml"
                document = self.getXMLDoc(xmlPath)
                nodeList = document.getDocumentElement().getChildNodes()
                projName = nodeList.item(0).getTextContent()
                nodeList.item(1).setTextContent(projPath)
                self.saveXMLDoc(document, xmlPath)
                self.config.set('projects', projName, projPath)
                self.saveCfg()
                self.reloadProjects()
                self.currentProject.getModel().setSelectedItem(projName)
                self.clearVulnerabilityTab() 

    def reportToXLS(self):
        if not xlsxwriterImported:
            self.popup("xlsxwriter library is not imported")
            return
        workbook = xlsxwriter.Workbook(self.getCurrentProjPath() + '/PT Manager Report.xlsx')
        worksheet = workbook.add_worksheet()
        bold = workbook.add_format({'bold': True})
        worksheet.write(0, 0, "Vulnerability Name", bold)
        worksheet.write(0, 1, "Threat Level", bold)
        worksheet.write(0, 2, "Description", bold)
        worksheet.write(0, 3, "Mitigation", bold)
        row = 1
        for i in range(0,self._log.size()):
            worksheet.write(row, 0, self._log.get(i).getName())
            worksheet.write(row, 1, self._log.get(i).getSeverity())
            worksheet.write(row, 2, self._log.get(i).getDescription())
            worksheet.write(row, 3, self._log.get(i).getMitigation())
            row = row + 1
            # add requests and images as well
        workbook.close()
        return self.getCurrentProjPath() + '/PT Manager Report.xlsx'
        
    def reportToHTML(self):
        htmlContent = """<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="he" dir="ltr">
    <head>
        <title>PT Manager Report</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <style>
        body {
        background-repeat: no-repeat;
        background-attachment: fixed;
        font-family: Arial,Tahoma,sens-serif;
        font-size: 13px;
        margin: auto;
        }

        #warpcenter {
            width: 900px;
            margin: 0px auto;
        }

        table {
            border: 2px dashed #000000;
        }

        td {
            border-top: 2px dashed #000000;
            padding: 10px;
        }

        img {
                border: 0px;
        }
</style>
<script language="javascript">
    function divHideShow(divToHideOrShow) 
    {
        var div = document.getElementById(divToHideOrShow);

        if (div.style.display == "block") 
        {
            div.style.display = "none";
        }
        else 
        {
            div.style.display = "block";
        }

        
    }         
</script>
    </head>

    <body>
        <div id="warpcenter">

<h1> PT Manager Report </h1>
<h2> Project: %s</h1>
    """ % (self.projName.getText())

        for i in range(0,self._log.size()):
            name = self._log.get(i).getName()
            request = "None"
            response = "None"
            path = self.getVulnReqResPath("request",name)
            if os.path.exists(path):
                request = self.newlineToBR(self.getFileContent(path))
                
            path = self.getVulnReqResPath("response",name)
            if os.path.exists(path):
                response = self.newlineToBR(self.getFileContent(path))
            images = ""
            for fileName in os.listdir(self.projPath.getText()+"/"+self.clearStr(name)):
                if fileName.endswith(".jpg"):
                    images += "%s<br><img src=\"%s\"><br><br>" % (fileName, self.projPath.getText()+"/"+self.clearStr(name) + "/" + fileName)
            description = self.newlineToBR(self._log.get(i).getDescription())
            mitigation = self.newlineToBR(self._log.get(i).getMitigation())
            htmlContent +=  self.convertVulntoTable(i,name,self._log.get(i).getSeverity(), description,mitigation, request, response, images)
        htmlContent += "</div></body></html>"
        f = open(self.getCurrentProjPath() + '/PT Manager Report.html', 'w')
        f.writelines(htmlContent)
        f.close()
        return self.getCurrentProjPath() + '/PT Manager Report.html'

    def newlineToBR(self,string):
        return "<br />".join(string.split("\n"))

    def getFileContent(self,path):
        f = open(path, "rb")
        content = f.read()
        f.close()
        return content

    def convertVulntoTable(self, number, name, severity, description, mitigation, request = "None", response = "None", images = "None"):
        return """<div style="width: 100%%;height: 30px;text-align: center;background-color:#E0E0E0;font-size: 17px;font-weight: bold;color: #000;padding-top: 10px;">%s <a href="javascript:divHideShow('Table_%s');" style="color:#191970">(OPEN / CLOSE)</a></div>
        <div id="Table_%s" style="display: none;">
            <table width="100%%" cellspacing="0" cellpadding="0" style="margin: 0px auto;text-align: left;border-top: 0px;">
                <tr>
                    <td>
                        <div style="font-size: 16px;font-weight: bold;">
                        <span style="color:#000000">Threat Level: </span> 
                        <span style="color:#8b8989">%s</span>
                                            </td>
                                        </tr>
                                        <tr>
                                            <td>
                        <div style="font-size: 16px;font-weight: bold;">
                        <span style="color:#000000">Description</span> 
                        <a href="javascript:divHideShow('Table_%s_Command_03');" style="color:#191970">OPEN / CLOSE >>></a>
                        </div>

                        <div id="Table_%s_Command_03" style="display: none;margin-top: 25px;">
                        %s
                        </div>
                                            </td>
                                        </tr>
                                        <tr>
                                            <td>
                        <div style="font-size: 16px;font-weight: bold;">
                        <span style="color:#000000">Mitigration</span> 
                        <a href="javascript:divHideShow('Table_%s_Command_04');" style="color:#191970">OPEN / CLOSE >>></a>
                        </div>

                        <div id="Table_%s_Command_04" style="display: none;margin-top: 25px;">
                        %s
                        <b>
                                            </td>
                                        </tr>

                                        <tr>
                                            <td>
                        <div style="font-size: 16px;font-weight: bold;">
                        <span style="color:#000000">Request</span> 
                        <a href="javascript:divHideShow('Table_%s_Command_05');" style="color:#191970">OPEN / CLOSE >>></a>
                        </div>

                        <div id="Table_%s_Command_05" style="display: none;margin-top: 25px;">
                        %s
                        <b>
                                            </td>
                                        </tr>


                                                        <tr>
                                            <td>
                        <div style="font-size: 16px;font-weight: bold;">
                        <span style="color:#000000">Response</span> 
                        <a href="javascript:divHideShow('Table_%s_Command_06');" style="color:#191970">OPEN / CLOSE >>></a>
                        </div>

                        <div id="Table_%s_Command_06" style="display: none;margin-top: 25px;">
                        %s
                        <b>
                                            </td>
                                        </tr>

                                                        <tr>
                                            <td>
                        <div style="font-size: 16px;font-weight: bold;">
                        <span style="color:#000000">Images</span> 
                        <a href="javascript:divHideShow('Table_%s_Command_07');" style="color:#191970">OPEN / CLOSE >>></a>
                        </div>

                        <div id="Table_%s_Command_07" style="display: none;margin-top: 25px;">
                        %s
                        <b>
                    </td>
                </tr>
            </table>
        </div><br><br>""" % (name,number,number,severity,number,number,description,number,number,mitigation,number,number,request,number,number,response,number,number,images)

    def clearVulnerabilityTab(self, rmVuln=True):
        if rmVuln:
            self.vulnName.setText("")
        self.descriptionString.setText("")
        self.mitigationStr.setText("")
        self.colorCombo.setSelectedIndex(0)
        self.threatLevel.setSelectedIndex(0)
        self.screenshotsList.clear()
        self.addButton.setText("Add")
        self.firstPic.setIcon(None)

    def saveRequestResponse(self, type, requestResponse, vulnName):
        path = self.getVulnReqResPath(type,vulnName)
        f = open(path, 'wb')
        f.write(requestResponse)
        f.close()

    def openProj(self, event):
        os.system('explorer ' + self.projPath.getText())

    def getVulnReqResPath(self, requestOrResponse, vulnName):
        return self.getCurrentProjPath() + "/" + self.clearStr(vulnName) + "/"+requestOrResponse+"_" + self.clearStr(vulnName)

    def htmlEscape(self,data):
        return data.replace('&', '&amp;').replace('<', '&lt;').replace('>', '&gt;').replace('"', '&quot;').replace("'", '&#39;')

    def generateReportFromDocxTemplate(self, zipname, newZipName, filename):      
        newZipName = self.getCurrentProjPath() + "/" + newZipName
        with zipfile.ZipFile(zipname, 'r') as zin:
            with zipfile.ZipFile(newZipName, 'w') as zout:
                zout.comment = zin.comment
                for item in zin.infolist():
                    if item.filename != filename:
                        zout.writestr(item, zin.read(item.filename))
                    else:
                        xml_content = zin.read(item.filename)
                        result = re.findall("(.*)<w:body>(?:.*)<\/w:body>(.*)",xml_content)[0]
                        newXML = result[0]
                        templateBody = re.findall("<w:body>(.*)<\/w:body>", xml_content)[0]
                        newBody = ""

                        for i in range(0,self._log.size()):
                            tmp = templateBody
                            tmp = tmp.replace("$vulnerability", self.htmlEscape(self._log.get(i).getName()))
                            tmp = tmp.replace("$severity", self.htmlEscape(self._log.get(i).getSeverity()))
                            tmp = tmp.replace("$description", self.htmlEscape(self._log.get(i).getDescription()))
                            tmp = tmp.replace("$mitigation", self.htmlEscape(self._log.get(i).getMitigation()))
                            newBody = newBody + tmp
                         
                        newXML = newXML + newBody
                        newXML = newXML + result[1]

        with zipfile.ZipFile(newZipName, mode='a', compression=zipfile.ZIP_DEFLATED) as zf:
            zf.writestr(filename, newXML)
        return newZipName


    def chooseProjPath(self, event):
        self.chooser.setDialogTitle("Select target directory")
        self.chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY)
        returnVal = self.chooser.showOpenDialog(None)
        if returnVal == JFileChooser.APPROVE_OPTION:
            projPath = str(self.chooser.getSelectedFile()) + "/PTManager"
            os.makedirs(projPath)
            self.projPath.setText(projPath)

    def reloadProjects(self):
        self.currentProject.setModel(DefaultComboBoxModel(self.config.options('projects')))

    def rmProj(self, event):
        if self.popUpAreYouSure() == JOptionPane.YES_OPTION:
            self._requestViewer.setMessage("None", False)
            self._responseViewer.setMessage("None", False)
            shutil.rmtree(self.projPath.getText())
            self.config.remove_option('projects',self.currentProject.getSelectedItem())
            self.reloadProjects()
            self.currentProject.setSelectedIndex(0)
            self.loadVulnerabilities(self.projPath.getText())

    def popup(self,msg):
        JOptionPane.showMessageDialog(None,msg)

    def addProj(self, event):
        projPath = self.projPath.getText()
        if projPath == None or projPath == "":
            self.popup("Please select path")
            return
        self.config.set('projects', self.projName.getText(), projPath)
        self.saveCfg()
        xml = ET.Element('project')
        name = ET.SubElement(xml, "name")
        path = ET.SubElement(xml, "path")
        details = ET.SubElement(xml, "details")
        autoSaveMode = ET.SubElement(xml, "autoSaveMode")

        name.text = self.projName.getText()
        path.text = projPath
        details.text = self.projDetails.getText()
        autoSaveMode.text = str(self.autoSave.isSelected())
        tree = ET.ElementTree(xml)
        try:
            tree.write(self.getCurrentProjPath()+'/project.xml')
        except:
            self.popup("Invalid path")
            return

        self.reloadProjects()
        self.clearVulnerabilityTab()
        self.clearList(None)
        self.currentProject.getModel().setSelectedItem(self.projName.getText())

    def resize(self, image, width, height):
        bi = BufferedImage(width, height, BufferedImage.TRANSLUCENT)
        g2d = bi.createGraphics()
        g2d.addRenderingHints(RenderingHints(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY))
        g2d.drawImage(image, 0, 0, width, height, None)
        g2d.dispose()
        return bi;

    def clearStr(self, var):
        return var.replace(" " , "_").replace("\\" , "").replace("/" , "").replace(":" , "").replace("*" , "").replace("?" , "").replace("\"" , "").replace("<" , "").replace(">" , "").replace("|" , "").replace("(" , "").replace(")" , "")

    def popUpAreYouSure(self):
        dialogResult = JOptionPane.showConfirmDialog(None,"Are you sure?","Warning",JOptionPane.YES_NO_OPTION)
        if dialogResult == 0:
            return 0
        return 1

    def removeSS(self,event):
        if self.popUpAreYouSure() == JOptionPane.YES_OPTION:
            os.remove(self.getCurrentVulnPath() + "/" + self.ssList.getSelectedValue())
            self.ssList.getModel().remove(self.ssList.getSelectedIndex())
            self.firstPic.setIcon(ImageIcon(None))
            # check if there is images and select the first one
            # bug in linux

    def addSS(self,event):
        clipboard = Toolkit.getDefaultToolkit().getSystemClipboard()
        try:
            image = clipboard.getData(DataFlavor.imageFlavor)
        except:
            self.popup("Clipboard not contains image")
            return
        vulnPath = self.projPath.getText() + "/" + self.clearStr(self.vulnName.getText())
        if not os.path.exists(vulnPath):
            os.makedirs(vulnPath)
        name = self.clearStr(self.vulnName.getText()) + str(random.randint(1, 99999))+".jpg"
        fileName = self.projPath.getText()+"/"+ self.clearStr(self.vulnName.getText()) + "/" + name
        file = File(fileName)
        bufferedImage = BufferedImage(image.getWidth(None), image.getHeight(None), BufferedImage.TYPE_INT_RGB);
        g = bufferedImage.createGraphics();
        g.drawImage(image, 0, 0, bufferedImage.getWidth(), bufferedImage.getHeight(), Color.WHITE, None);
        ImageIO.write(bufferedImage, "jpg", file)
        self.addVuln(self)
        self.ssList.setSelectedValue(name,True)

    def rmVuln(self, event):
        if self.popUpAreYouSure() == JOptionPane.YES_OPTION:
            self._requestViewer.setMessage("None", False)
            self._responseViewer.setMessage("None", False)
            shutil.rmtree(self.getCurrentVulnPath())
            self.clearVulnerabilityTab()
            self.loadVulnerabilities(self.getCurrentProjPath())

    def addVuln(self, event):
        if self.colorCombo.getSelectedItem() == "Color:":
            colorTxt = None
        else:
            colorTxt = self.colorCombo.getSelectedItem()
        self._lock.acquire()
        row = self._log.size()
        vulnObject = vulnerability(self.vulnName.getText(),self.threatLevel.getSelectedItem(),self.descriptionString.getText(),self.mitigationStr.getText() ,colorTxt)
        self._log.add(vulnObject) 
        self.fireTableRowsInserted(row, row)
        self._lock.release()

        vulnPath = self.projPath.getText() + "/" + self.clearStr(self.vulnName.getText())
        if not os.path.exists(vulnPath):
            os.makedirs(vulnPath)

        xml = ET.Element('vulnerability')
        name = ET.SubElement(xml, "name")
        severity = ET.SubElement(xml, "severity")
        description = ET.SubElement(xml, "description")
        mitigation = ET.SubElement(xml, "mitigation")
        color = ET.SubElement(xml, "color")
        name.text = self.vulnName.getText()
        severity.text = self.threatLevel.getSelectedItem()
        description.text = self.descriptionString.getText()
        mitigation.text = self.mitigationStr.getText()
        color.text = colorTxt
        tree = ET.ElementTree(xml)
        tree.write(vulnPath+'/vulnerability.xml')

        self.loadVulnerabilities(self.getCurrentProjPath())
        self.loadVulnerability(vulnObject)

    def vulnNameChanged(self):
            if os.path.exists(self.getCurrentVulnPath()) and self.vulnName.getText() != "":
                self.addButton.setText("Update")
            elif self.addButton.getText() != "Add":
                options = ["Create a new vulnerability", "Change current vulnerability name"]
                n = JOptionPane.showOptionDialog(None,
                    "Would you like to?",
                    "Vulnerability Name",
                    JOptionPane.YES_NO_CANCEL_OPTION,
                    JOptionPane.QUESTION_MESSAGE,
                    None,
                    options,
                    options[0]);

                if n == 0:
                    self.clearVulnerabilityTab(False)
                    self.addButton.setText("Add")
                else:
                    newName = JOptionPane.showInputDialog(
                    None,
                    "Enter new name:",
                    "Vulnerability Name",
                    JOptionPane.PLAIN_MESSAGE,
                    None,
                    None,
                    self.vulnName.getText())
                    row = self.logTable.getSelectedRow()
                    old = self.logTable.getValueAt(row,1)                   
                    self.changeVulnName(newName,old)
                
    def changeVulnName(self,new,old):
        newpath = self.getCurrentProjPath() + "/" + new
        oldpath = self.getCurrentProjPath() + "/" + old
        os.rename(oldpath,newpath)
        self.changeCurrentVuln(new,0, newpath + "/vulnerability.xml")

    def getCurrentVulnPath(self):
        return self.projPath.getText() + "/" + self.clearStr(self.vulnName.getText())

    def getCurrentProjPath(self):
        return self.projPath.getText()

    def loadSS(self, imgPath):
        image = ImageIO.read(File(imgPath))
        if image.getWidth() <= 550 and image.getHeight() <= 400:
            self.firstPic.setIcon(ImageIcon(image))
            self.firstPic.setSize(image.getWidth(),image.getHeight())
        else:
            self.firstPic.setIcon(ImageIcon(self.resize(image,550, 400)))
            self.firstPic.setSize(550,400)

    def clearProjectTab(self):
        self.projPath.setText("")
        self.projDetails.setText("")

    def clearList(self, event):
        self._lock.acquire()
        self._log = ArrayList()
        row = self._log.size()
        self.fireTableRowsInserted(row, row)
        self._lock.release()

    #
    # implement IContextMenuFactory
    #
    def createMenuItems(self, invocation):
        responses = invocation.getSelectedMessages();
        if responses > 0:
            ret = LinkedList()
            requestMenuItem = JMenuItem("Send to PT Manager");
            requestMenuItem.addActionListener(handleMenuItems(self,responses[0], "request"))
            ret.add(requestMenuItem);
            return(ret);
        return null;
    #
    # implement ITab
    #
    def getTabCaption(self):
        return "PT Manager"
    
    def getUiComponent(self):
        return self._splitpane

        #
    # extend AbstractTableModel
    #
    
    def getRowCount(self):
        try:
            return self._log.size()
        except:
            return 0

    def getColumnCount(self):
        return 3

    def getColumnName(self, columnIndex):
        if columnIndex == 0:
            return "#"
        if columnIndex == 1:
            return "Vulnerability Name"
        if columnIndex == 2:
            return "Threat Level"
        return ""

    def getValueAt(self, rowIndex, columnIndex):
        vulnObject = self._log.get(rowIndex)
        if columnIndex == 0:
            return rowIndex+1
        if columnIndex == 1:
            return vulnObject.getName()
        if columnIndex == 2:
            return vulnObject.getSeverity()
        if columnIndex == 3:
            return vulnObject.getMitigation()
        if columnIndex == 4:
            return vulnObject.getColor()

        return ""

    def changeCurrentVuln(self,value,fieldNumber, xmlPath = "def"):
        if xmlPath == "def":
            xmlPath = self.getCurrentVulnPath() + "/vulnerability.xml"
        document = self.getXMLDoc(xmlPath)
        nodeList = document.getDocumentElement().getChildNodes()
        nodeList.item(fieldNumber).setTextContent(value)
        self.saveXMLDoc(document, xmlPath)
        self.loadVulnerabilities(self.getCurrentProjPath())

    def loadVulnerability(self, vulnObject):
        self.addButton.setText("Update")
        self.vulnName.setText(vulnObject.getName())
        self.threatLevel.setSelectedItem(vulnObject.getSeverity())
        self.descriptionString.setText(vulnObject.getDescription())
        self.mitigationStr.setText(vulnObject.getMitigation())

        if vulnObject.getColor() == "" or vulnObject.getColor() == None:
            self.colorCombo.setSelectedItem("Color:")
        else:
            self.colorCombo.setSelectedItem(vulnObject.getColor())
        self.screenshotsList.clear()

        for fileName in os.listdir(self.projPath.getText()+"/"+self.clearStr(vulnObject.getName())):
            if fileName.endswith(".jpg"):
                self.screenshotsList.addElement(fileName)
                imgPath = self.projPath.getText()+"/"+self.clearStr(vulnObject.getName())+'/'+fileName
                # imgPath = imgPath.replace("/","//")
                self.loadSS(imgPath)

        if (self.screenshotsList.getSize() == 0):
            self.firstPic.setIcon(None)
        else:
            self.ssList.setSelectedIndex(0)

        path = self.getVulnReqResPath("request",vulnObject.getName())
        if os.path.exists(path):
            f = self.getFileContent(path)
            self._requestViewer.setMessage(f, False)
        else:
            self._requestViewer.setMessage("None", False)
        
        path = self.getVulnReqResPath("response",vulnObject.getName())
        if os.path.exists(path):
            f = self.getFileContent(path)
            self._responseViewer.setMessage(f, False)
        else:
            self._responseViewer.setMessage("None", False)
class SettingsTableFrame(JFrame):
    def __init__(self, *args, **kwargs):
        # do not create any class members before calling JFrame.__init__ !
        s, size, title, savemode = None, None, None, False
        self.OKstatus = True
        if 'settings_config' in kwargs:
            s = kwargs.pop('settings_config')
        else:
            s = None
        if 'size' in kwargs:
            size = kwargs.pop('size')
        else:
            size = (300, 300)
        if 'widget' in kwargs:
            widget = kwargs.pop('widget')
        else:
            widget = None
        if 'savemode' in kwargs:
            savemode = kwargs.pop('savemode')
        defaultdir = None
        if 'defaultdir' in kwargs:
            defaultdir = kwargs.pop('defaultdir')
        if len(args) > 0:
            title = args[0]
        else:
            title = 'Save Settings'
        JFrame.__init__(self, title, size=size, **kwargs)
        self.widget = widget
        if self.widget == None:
            print "Need to pass keyword argument widget=widget when creating SettingsTableFrame"
        self.s = s
        self.savemode = savemode
        self.defaultdir = defaultdir
        # create FileChooser, make its window bigger and choose smaller font
        if self.defaultdir != None:
            self.fc = JFileChooser(self.defaultdir)
        else:
            self.fc = JFileChooser()
        self.fc.setPreferredSize(Dimension(800, 600))
        smallfont = Font("Lucida Sans", Font.PLAIN, 12)
        SetFontRecursively(self.fc.getComponents(), smallfont)
        filefilter = FileNameExtensionFilter("Settings Files",
                                             (DEFAULT_EXTENSION, ))
        self.fc.setFileFilter(filefilter)
        # fill the table, in save mode only with the current values, in load mode with current and setting values
        self.prepare_tabledata()
        # if not savemode, we first pop up a filechooser to select a loadable setting
        if self.savemode == False:
            self.OKstatus = self.load_setting()
            if not self.OKstatus:
                return
        # listener for data edited by user, good for providing PV write access within the table to the user
        self.dataListener = MyTableModelListener(savemode=self.savemode)
        self.dataModel.addTableModelListener(self.dataListener)
        self.table = JTable(self.dataModel)
        # create Buttons
        self.bu_do_label = "Save" if self.savemode == True else "Load"
        self.bu_do_handler = self.bu_save_handler if self.savemode == True else self.bu_load_handler
        self.bu_do = JButton(self.bu_do_label,
                             actionPerformed=self.bu_do_handler)
        self.bu_cancel = JButton("Cancel",
                                 actionPerformed=self.bu_cancel_handler)
        # BEGIN visual adaptations of JTable
        self.table.setRowHeight(24)
        self.table.getColumnModel().getColumn(0).setMinWidth(200)
        if self.savemode:
            self.table.getColumnModel().getColumn(3).setMaxWidth(60)
        else:
            self.table.getColumnModel().getColumn(4).setMaxWidth(60)
        smallfontr = MyTableCellRenderer(font=FONT_FAMILY,
                                         style=Font.PLAIN,
                                         fontsize=10)
        smallfontr.setHorizontalAlignment(JLabel.CENTER)
        bigfontplainr = MyTableCellRenderer(font=FONT_FAMILY,
                                            style=Font.PLAIN,
                                            fontsize=18)
        bigfontplainr.setHorizontalAlignment(JLabel.CENTER)
        bigfontr = MyTableCellRenderer(font=FONT_FAMILY,
                                       style=Font.BOLD,
                                       fontsize=18)
        bigfontr.setHorizontalAlignment(JLabel.CENTER)
        self.table.getColumnModel().getColumn(0).setCellRenderer(smallfontr)
        self.table.getColumnModel().getColumn(1).setCellRenderer(bigfontplainr)
        self.table.getColumnModel().getColumn(2).setCellRenderer(bigfontr)
        if not self.savemode:
            self.table.getColumnModel().getColumn(3).setCellRenderer(bigfontr)
        # END visual adaptations of JTable
        ## BEGIN layout of window (JFrame)
        self.getContentPane().setLayout(BorderLayout())
        self.add(JScrollPane(self.table))
        self.bottompanel = JPanel()
        self.bottompanel.setLayout(
            BoxLayout(self.bottompanel, BoxLayout.LINE_AXIS))
        self.bottompanel.add(Box.createHorizontalGlue())
        self.bottompanel.add(self.bu_do)
        self.bottompanel.add(Box.createRigidArea(Dimension(20, 0)))
        self.bottompanel.add(self.bu_cancel)
        self.bottompanel.add(Box.createHorizontalGlue())
        self.add(self.bottompanel, BorderLayout.SOUTH)
        # END layout of window (JFrame)

    def bu_cancel_handler(self, event):
        self.dispose()

    def bu_save_handler(self, event):
        dlg_answer = self.fc.showSaveDialog(self)
        if dlg_answer == self.fc.CANCEL_OPTION:
            return
        if dlg_answer == self.fc.APPROVE_OPTION:  # user clicked SAVE
            f = self.fc.getSelectedFile().getAbsolutePath()
            if not str(f).endswith("." + DEFAULT_EXTENSION):
                f = f + "." + DEFAULT_EXTENSION
            if os.path.exists(
                    f):  # file already exists, let user confirm overwriting
                choice = JOptionPane.showConfirmDialog(
                    self, "The file exists, overwrite?", "Existing file",
                    JOptionPane.YES_NO_CANCEL_OPTION)
                if choice in (JOptionPane.NO_OPTION,
                              JOptionPane.CANCEL_OPTION):
                    return
                if choice == JOptionPane.YES_OPTION:
                    self.do_save(f)
                    self.dispose()
            else:  # file does not exist, yet -> don't need to ask
                self.do_save(f)
                self.dispose()

    def bu_load_handler(self, event):
        for i in range(self.dataModel.getRowCount()):
            if self.dataModel.getValueAt(i, RESTORE_COL_LOADMODE) == False:
                continue
            curval = self.dataModel.getValueAt(i, VALUE_COLUMN)
            setval = self.dataModel.getValueAt(i, SETTING_COLUMN)
            if curval == '---' or setval == '---':  # either PV does not exist or value missing in the settings file
                continue
            pvname = self.dataModel.getValueAt(i, PV_COLUMN)
            writejob = BackgroundPVWriter(pvname, setval)
            writejob.schedule()
        self.dispose()

    def load_setting(self):
        dlg_answer = self.fc.showOpenDialog(self)
        if dlg_answer == self.fc.CANCEL_OPTION:
            return False
        if dlg_answer == self.fc.APPROVE_OPTION:
            f = self.fc.getSelectedFile().getAbsolutePath()
            self.parse_setting(f)
            return True

    def parse_setting(self, fpath):  # compatible to old set files
        with open(fpath, "r") as f:
            idxset = set(range(self.dataModel.getRowCount()))
            #lbuf = [l for l in f] # need to create a file buffer to traverse twice through the file
            for l in f:
                if len(l) == 0 or l.startswith('#'):
                    continue
                els = l.split()
                idstr = els[0]
                checkcolumn = ID_COLUMN
                for i in idxset:
                    if self.dataModel.getValueAt(i, checkcolumn) == idstr:
                        self.dataModel.setValueAt(els[1], i, SETTING_COLUMN)
                        idxset.remove(i)

            # remove restore flag for PVs that were missing in the settings file
            for i in idxset:
                self.dataModel.setValueAt(False, i, RESTORE_COL_LOADMODE)

    def parse_setting_pvtable_format(self, fpath):
        with open(fpath, "r") as f:
            idxset = set(range(self.dataModel.getRowCount()))
            lbuf = [
                l for l in f
            ]  # need to create a file buffer to traverse twice through the file
            # parse ID PVNAME mappings if present
            mapping_header_found = False
            pv_to_id = dict()
            for l in lbuf:
                if not mapping_header_found:
                    if l.startswith("### Mapping ID to PV"):
                        mapping_header_found = True
                    continue
                if not l.startswith("# "):
                    continue
                els = l.split()
                idstr = els[1]
                pvstr = " ".join(
                    els[2:]
                )  # tango PVs may contain blanks if additional parameters were included
                pv_to_id[pvstr] = idstr
            # second run through file: fill our table with values read from the file
            for l in lbuf:
                if len(l) == 0 or l.startswith('#'):
                    continue
                els = l.split()
                # default to PVNAME comparison if no PVNAME->ID mapping exists
                idstr = els[0]
                checkcolumn = PV_COLUMN
                # check if mapping exists, and override if so
                if idstr in pv_to_id:
                    idstr = pv_to_id[idstr]  # (set idstr to the mapped ID)
                    checkcolumn = ID_COLUMN  # (tell the following code that ID_COLUMN has to be compared)
                for i in idxset:
                    if self.dataModel.getValueAt(i, checkcolumn) == idstr:
                        self.dataModel.setValueAt(els[1], i, SETTING_COLUMN)
                        idxset.remove(i)

            # remove restore flag for PVs that were missing in the settings file
            for i in idxset:
                self.dataModel.setValueAt(False, i, RESTORE_COL_LOADMODE)

    def do_save(self,
                filepath):  # creates something compatible to older set files
        now = datetime.datetime.now()
        with open(filepath, "w") as f:
            f.write("### ------------------------------------\n")
            f.write("### SETTING saved from CSS\n")
            f.write("### " + now.strftime("Date: %Y-%m-%d   Time: %H:%M") +
                    "\n")
            f.write("### ------------------------------------\n")
            for row_index in range(self.dataModel.getRowCount()):
                IDstr = str(self.dataModel.getValueAt(row_index, ID_COLUMN))
                valstr = str(self.dataModel.getValueAt(row_index,
                                                       VALUE_COLUMN))
                f.write("%s %s\n" % (IDstr, valstr))
            f.write("### Mapping ID to PV\n")
            for row_index in range(self.dataModel.getRowCount()):
                IDstr = str(self.dataModel.getValueAt(row_index, ID_COLUMN))
                PVstr = str(self.dataModel.getValueAt(row_index, PV_COLUMN))
                f.write("# %s %s\n" % (IDstr, PVstr))

    def do_save_pvtableformat(self, filepath):
        now = datetime.datetime.now()
        with open(filepath, "w") as f:
            f.write("# save/restore file generated by CSS PVTable, " +
                    now.strftime("%Y-%m-%d %H:%M:0.0") + "\n")
            for row_index in range(self.dataModel.getRowCount()):
                PVstr = str(self.dataModel.getValueAt(row_index, PV_COLUMN))
                valstr = str(self.dataModel.getValueAt(row_index,
                                                       VALUE_COLUMN))
                f.write("%s %s\n" % (PVstr, valstr))
            f.write("<END>\n")
            f.write("### ------------------------------------\n")
            f.write("### SETTING saved from CSS\n")
            f.write("### " + now.strftime("Date: %Y-%m-%d   Time: %H:%M") +
                    "\n")
            f.write("### ------------------------------------\n")
            f.write("### Mapping ID to PV\n")
            for row_index in range(self.dataModel.getRowCount()):
                IDstr = str(self.dataModel.getValueAt(row_index, ID_COLUMN))
                PVstr = str(self.dataModel.getValueAt(row_index, PV_COLUMN))
                f.write("# %s %s\n" % (IDstr, PVstr))

    def prepare_tabledata(self):
        if self.s == None:
            self.tableData = [['', '', '', '', False]]
        else:
            self.tableData = []
            for l in self.s:
                idstr = l[0]
                pvname = l[1]
                # read PV value
                curval = "---"
                restore_flag = l[2]
                try:
                    ipv = PVUtil.createPV(pvname, self.widget)
                    curval = PVUtil.getString(ipv)
                except:
                    restore_flag = False
                if self.savemode:
                    self.tableData.append(
                        [pvname, idstr, curval, restore_flag])
                else:
                    self.tableData.append(
                        [pvname, idstr, curval, '---', restore_flag])

        if self.savemode:
            self.colNames = TABLE_HEADER_SAVEMODE
        else:
            self.colNames = TABLE_HEADER_LOADMODE

        self.dataModel = MyTableModel(self.tableData,
                                      self.colNames,
                                      savemode=self.savemode)
示例#29
0
class tab():
    def __init__(self, callbacks):
        """ Method automatically called when memory is
        allocated for a new object, initiates tab object """

        print("Created a tab")
        self.callbacks = callbacks
        self.curRequest = None

        self.createTabGUI()

    def getFirstTab(self):
        """ Get the JPanel that represents the object's
        Timing Attack tab """

        self.scrollPane = JScrollPane(
            self.firstTab, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
            JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED)
        return self.scrollPane

    ###########################
    # SECTION 1: CREATING GUI #
    ###########################

    def createTabGUI(self):
        """ Create GUI for this tabbed pane """

        # panel for the whole tab
        self.firstTab = JPanel()

        # name of the extention
        self.titleTop = JLabel("Timing Attack")
        self.titleTop.setFont(Font("Tahoma", 1, 14))
        self.titleTop.setForeground(Color(255, 102, 51))

        # info about the extention
        self.infoTop = JLabel(
            "Timing Attack is a open source extention to inform how long the system takes to respond for a valid and an invalid authentication."
        )
        self.infoTop.setFont(Font("Tahoma", 0, 11))

        # labels and inputs on top half
        self.addTitle = JLabel("Enter a Valid and an Invalid Username")
        self.addTitle.setFont(Font("Tahoma", 1, 13))
        self.addTitle.setForeground(Color(255, 102, 51))
        self.validUsername = JLabel("Valid Username")
        self.validUsername.setFont(Font("Tahoma", 0, 12))
        self.invalidUsername = JLabel("Invalid Username")
        self.invalidUsername.setFont(Font("Tahoma", 0, 12))
        self.parameter = JLabel("Parameter")
        self.parameter.setFont(Font("Tahoma", 0, 12))
        self.average = JLabel("Sample Size")
        self.average.setFont(Font("Tahoma", 0, 12))
        self.addValid = JTextField("")
        self.addInvalid = JTextField("")
        self.addParameter = JTextField("")
        self.addAverage = JTextField("")
        self.submitButton1 = JButton("Submit",
                                     actionPerformed=self.timeTwoUsers)

        # result on top left
        self.resultTitle = JLabel("Result")
        self.resultTitle.setFont(Font("Tahoma", 1, 13))
        self.resultTitle.setForeground(Color(255, 102, 51))
        self.showResults = JTextArea("")
        self.showResults.setEditable(False)
        self.showResultsScroll = JScrollPane(self.showResults)
        self.twoUserViewResult = JButton("View Results",
                                         actionPerformed=self.showResultsTop)
        self.twoUserViewReq = JButton("View Request",
                                      actionPerformed=self.showRequestTop)
        self.twoUserViewValidResponse = JButton(
            "View Valid Response", actionPerformed=self.showValidResponseTop)
        self.twoUserViewInvalidResponse = JButton(
            "View Invalid Response",
            actionPerformed=self.showInvalidResponseTop)
        # Set top buttons to invisible until a request is submitted
        self.twoUserViewResult.setVisible(False)
        self.twoUserViewReq.setVisible(False)
        self.twoUserViewValidResponse.setVisible(False)
        self.twoUserViewInvalidResponse.setVisible(False)

        # labels, inputs and file on bottom half
        self.addTitleFile = JLabel("Input Username File")
        self.addTitleFile.setFont(Font("Tahoma", 1, 13))
        self.addTitleFile.setForeground(Color(255, 102, 51))
        self.inputFileButton = JButton("Choose File...",
                                       actionPerformed=self.chooseFile)
        self.separatorList = JLabel("Separator")
        self.separatorList.setFont(Font("Tahoma", 0, 12))
        self.parameterList = JLabel("Parameter")
        self.parameterList.setFont(Font("Tahoma", 0, 12))
        self.averageList = JLabel("Sample Size")
        self.averageList.setFont(Font("Tahoma", 0, 12))
        self.addSeparatorList = JTextField("")
        self.addParameterList = JTextField("")
        self.addAverageList = JTextField("")
        self.submitButton2 = JButton("Submit",
                                     actionPerformed=self.timeUserList)

        # result on bottom left
        self.resultTitleList = JLabel("Result")
        self.resultTitleList.setFont(Font("Tahoma", 1, 13))
        self.resultTitleList.setForeground(Color(255, 102, 51))
        self.showResultsList = JTextArea("")
        self.showResultsList.setEditable(False)
        self.showResultsListScroll = JScrollPane(self.showResultsList)
        self.downloadResultList = JButton("Download Display",
                                          actionPerformed=self.downloadResults)
        self.listViewResults = JButton("View Results",
                                       actionPerformed=self.showListResults)
        self.listViewReq = JButton("View Request",
                                   actionPerformed=self.showListRequest)
        self.listViewResponses = JButton(
            "View Responses", actionPerformed=self.showListResponses)
        # Set list buttons to invisible until a request is submitted
        self.downloadResultList.setVisible(False)
        self.listViewResults.setVisible(False)
        self.listViewReq.setVisible(False)
        self.listViewResponses.setVisible(False)

        # something wrong?
        self.somethingWrong = JLabel("Something Wrong?")
        self.debugOn = False
        self.viewDebug = JButton("View debug output",
                                 actionPerformed=self.showDebug)
        self.debugText = JTextArea("")
        self.debugTextScroll = JScrollPane(self.debugText)
        self.debugTextScroll.setVisible(False)

        # layout
        layout = GroupLayout(self.firstTab)
        self.firstTab.setLayout(layout)

        layout.setHorizontalGroup(
            layout.createParallelGroup(GroupLayout.Alignment.LEADING)
            # whole layout
            .addGroup(
                layout.createSequentialGroup().addGap(15)
                # title + description
                .addGroup(
                    layout.createParallelGroup(
                        GroupLayout.Alignment.LEADING).addComponent(
                            self.titleTop).addComponent(self.infoTop)
                    # titles
                    .addGroup(
                        layout.createSequentialGroup()
                        # title left
                        .addGroup(
                            layout.createParallelGroup(
                                GroupLayout.Alignment.LEADING).addComponent(
                                    self.addTitle)).addGap(168)
                        # title right
                        .addGroup(
                            layout.createParallelGroup(
                                GroupLayout.Alignment.LEADING).addComponent(
                                    self.resultTitle))).
                    addGroup(
                        layout.createSequentialGroup()
                        # left
                        .addGroup(
                            layout.createParallelGroup(
                                GroupLayout.Alignment.LEADING).addComponent(
                                    self.validUsername).addComponent(
                                        self.invalidUsername).addComponent(
                                            self.parameter).addComponent(
                                                self.average).addComponent(
                                                    self.addTitleFile).
                            addComponent(self.inputFileButton).addComponent(
                                self.separatorList).addComponent(
                                    self.parameterList).addComponent(
                                        self.averageList).addComponent(
                                            self.somethingWrong)).addGap(12).
                        addGroup(
                            layout.createParallelGroup(
                                GroupLayout.Alignment.LEADING).addComponent(
                                    self.addValid, GroupLayout.PREFERRED_SIZE,
                                    200,
                                    GroupLayout.PREFERRED_SIZE).addComponent(
                                        self.addInvalid,
                                        GroupLayout.PREFERRED_SIZE, 200,
                                        GroupLayout.PREFERRED_SIZE).
                            addComponent(
                                self.addParameter,
                                GroupLayout.PREFERRED_SIZE, 200,
                                GroupLayout.PREFERRED_SIZE).addComponent(
                                    self.addAverage,
                                    GroupLayout.PREFERRED_SIZE, 80,
                                    GroupLayout.PREFERRED_SIZE).addComponent(
                                        self.submitButton1).addComponent(
                                            self.addSeparatorList,
                                            GroupLayout.PREFERRED_SIZE, 200,
                                            GroupLayout.PREFERRED_SIZE).
                            addComponent(
                                self.addParameterList,
                                GroupLayout.PREFERRED_SIZE, 200,
                                GroupLayout.PREFERRED_SIZE).addComponent(
                                    self.addAverageList,
                                    GroupLayout.PREFERRED_SIZE, 80,
                                    GroupLayout.PREFERRED_SIZE).addComponent(
                                        self.submitButton2).addComponent(
                                            self.viewDebug)).addGap(50)
                        # right
                        .addGroup(
                            layout.createParallelGroup(
                                GroupLayout.Alignment.LEADING).addComponent(
                                    self.showResultsScroll,
                                    GroupLayout.PREFERRED_SIZE, 600,
                                    GroupLayout.PREFERRED_SIZE).
                            addGroup(layout.createSequentialGroup().addGroup(
                                layout.createParallelGroup(
                                    GroupLayout.Alignment.LEADING).
                                addComponent(self.twoUserViewResult)
                            ).addGap(15).addGroup(
                                layout.createParallelGroup(
                                    GroupLayout.Alignment.LEADING).
                                addComponent(
                                    self.twoUserViewReq)).addGap(15).addGroup(
                                        layout.createParallelGroup(
                                            GroupLayout.Alignment.LEADING).
                                        addComponent(
                                            self.twoUserViewValidResponse)
                                    ).addGap(15).addGroup(
                                        layout.createParallelGroup(
                                            GroupLayout.Alignment.LEADING).
                                        addComponent(
                                            self.twoUserViewInvalidResponse))).
                            addComponent(self.resultTitleList).addComponent(
                                self.showResultsListScroll,
                                GroupLayout.PREFERRED_SIZE, 600,
                                GroupLayout.PREFERRED_SIZE).addGroup(
                                    layout.createSequentialGroup().addGroup(
                                        layout.createParallelGroup(
                                            GroupLayout.Alignment.LEADING).
                                        addComponent(self.downloadResultList)).
                                    addGap(15).addGroup(
                                        layout.createParallelGroup(
                                            GroupLayout.Alignment.LEADING).
                                        addComponent(self.listViewResults)
                                    ).addGap(15).addGroup(
                                        layout.createParallelGroup(
                                            GroupLayout.Alignment.LEADING).
                                        addComponent(self.listViewReq)
                                    ).addGap(15).addGroup(
                                        layout.createParallelGroup(
                                            GroupLayout.Alignment.LEADING).
                                        addComponent(self.listViewResponses)
                                    )).addGap(10).addComponent(
                                        self.debugTextScroll,
                                        GroupLayout.PREFERRED_SIZE, 300,
                                        GroupLayout.PREFERRED_SIZE))))))

        layout.setVerticalGroup(
            layout.createParallelGroup(GroupLayout.Alignment.LEADING)
            # whole layout
            .addGroup(
                layout.createSequentialGroup().addGap(15).addComponent(
                    self.titleTop).addGap(10).addComponent(
                        self.infoTop).addGap(10)
                # titles
                .addGroup(
                    layout.createSequentialGroup()
                    # left
                    .addGroup(
                        layout.createParallelGroup(
                            GroupLayout.Alignment.LEADING).addComponent(
                                self.addTitle).addGap(25)
                        # right
                        .addGroup(
                            layout.createParallelGroup(
                                GroupLayout.Alignment.LEADING).addComponent(
                                    self.resultTitle))))
                # top half
                .addGroup(
                    layout.createSequentialGroup()
                    # left top half
                    .addGroup(
                        layout.createParallelGroup(
                            GroupLayout.Alignment.BASELINE).
                        addGroup(layout.createSequentialGroup().addGroup(
                            layout.createParallelGroup(
                                GroupLayout.Alignment.BASELINE).addComponent(
                                    self.validUsername).addGap(5).addComponent(
                                        self.addValid,
                                        GroupLayout.PREFERRED_SIZE,
                                        GroupLayout.DEFAULT_SIZE,
                                        GroupLayout.PREFERRED_SIZE)
                        ).addGap(5).addGroup(
                            layout.createParallelGroup(
                                GroupLayout.Alignment.BASELINE).addComponent(
                                    self.invalidUsername).addGap(
                                        5).addComponent(
                                            self.addInvalid,
                                            GroupLayout.PREFERRED_SIZE,
                                            GroupLayout.DEFAULT_SIZE,
                                            GroupLayout.PREFERRED_SIZE)
                        ).addGap(5).addGroup(
                            layout.createParallelGroup(
                                GroupLayout.Alignment.BASELINE).addComponent(
                                    self.parameter).addGap(5).addComponent(
                                        self.addParameter,
                                        GroupLayout.PREFERRED_SIZE,
                                        GroupLayout.DEFAULT_SIZE,
                                        GroupLayout.PREFERRED_SIZE)
                        ).addGap(5).addGroup(
                            layout.createParallelGroup(
                                GroupLayout.Alignment.BASELINE).addComponent(
                                    self.average).addGap(5).addComponent(
                                        self.addAverage,
                                        GroupLayout.PREFERRED_SIZE,
                                        GroupLayout.DEFAULT_SIZE,
                                        GroupLayout.PREFERRED_SIZE)
                        ).addGap(5).addGroup(
                            layout.createParallelGroup(
                                GroupLayout.Alignment.BASELINE).addComponent(
                                    self.submitButton1))).addGap(5)
                        # right top half
                        .addGroup(
                            layout.createParallelGroup(
                                GroupLayout.Alignment.BASELINE).addComponent(
                                    self.showResultsScroll,
                                    GroupLayout.PREFERRED_SIZE, 200,
                                    GroupLayout.PREFERRED_SIZE)))).addGap(5)
                # buttons + titles
                .addGroup(layout.createSequentialGroup().addGroup(
                    layout.createParallelGroup(
                        GroupLayout.Alignment.BASELINE).addComponent(
                            self.twoUserViewResult).addGap(20).addComponent(
                                self.twoUserViewReq).addGap(20).addComponent(
                                    self.twoUserViewValidResponse).addGap(20).
                    addComponent(
                        self.twoUserViewInvalidResponse)).addGap(10).addGroup(
                            layout.createParallelGroup(
                                GroupLayout.Alignment.BASELINE).addComponent(
                                    self.addTitleFile).addGap(25).addComponent(
                                        self.resultTitleList))).addGap(3)
                # bottom half
                .addGroup(
                    layout.createSequentialGroup()
                    # left bottom half
                    .addGroup(
                        layout.createParallelGroup(
                            GroupLayout.Alignment.BASELINE).
                        addGroup(layout.createSequentialGroup().addGroup(
                            layout.createParallelGroup(
                                GroupLayout.Alignment.BASELINE).addComponent(
                                    self.inputFileButton)
                        ).addGap(10).addGroup(
                            layout.createParallelGroup(
                                GroupLayout.Alignment.BASELINE).addComponent(
                                    self.separatorList).addGap(5).addComponent(
                                        self.addSeparatorList,
                                        GroupLayout.PREFERRED_SIZE,
                                        GroupLayout.DEFAULT_SIZE,
                                        GroupLayout.PREFERRED_SIZE)
                        ).addGap(5).addGroup(
                            layout.createParallelGroup(
                                GroupLayout.Alignment.BASELINE).addComponent(
                                    self.parameterList).addGap(5).addComponent(
                                        self.addParameterList,
                                        GroupLayout.PREFERRED_SIZE,
                                        GroupLayout.DEFAULT_SIZE,
                                        GroupLayout.PREFERRED_SIZE)
                        ).addGap(5).addGroup(
                            layout.createParallelGroup(
                                GroupLayout.Alignment.BASELINE).addComponent(
                                    self.averageList).addGap(5).addComponent(
                                        self.addAverageList,
                                        GroupLayout.PREFERRED_SIZE,
                                        GroupLayout.DEFAULT_SIZE,
                                        GroupLayout.PREFERRED_SIZE)
                        ).addGap(5).addGroup(
                            layout.createParallelGroup(
                                GroupLayout.Alignment.BASELINE).addComponent(
                                    self.submitButton2)
                        )).addGap(5).addGroup(
                            layout.createParallelGroup(
                                GroupLayout.Alignment.BASELINE).addComponent(
                                    self.showResultsListScroll,
                                    GroupLayout.PREFERRED_SIZE, 200,
                                    GroupLayout.PREFERRED_SIZE)))).addGap(5)
                # right bottom half
                .addGroup(layout.createSequentialGroup().addGroup(
                    layout.createParallelGroup(
                        GroupLayout.Alignment.BASELINE).addComponent(
                            self.downloadResultList).addGap(10).addComponent(
                                self.listViewResults).addGap(10).addComponent(
                                    self.listViewReq).addGap(10).addComponent(
                                        self.listViewResponses))).addGap(30)
                # something wrong section
                .addGroup(layout.createSequentialGroup().addGroup(
                    layout.createParallelGroup(
                        GroupLayout.Alignment.BASELINE).addComponent(
                            self.somethingWrong).addGap(10).addComponent(
                                self.viewDebug).addGap(10).addComponent(
                                    self.debugTextScroll,
                                    GroupLayout.PREFERRED_SIZE, 150,
                                    GroupLayout.PREFERRED_SIZE)))))
        return

    def chooseFile(self, event):
        """ Method that allows the user to choose a file of
        usernames, and it tries to load the last used directory """

        try:
            # load the directory for future imports/exports
            fileChooserDirectory = self._callbacks.loadExtensionSetting(
                "fileChooserDirectory")

        # there is not a last used directory
        except:
            # set the last used directory to blank
            fileChooserDirectory = ""

        self.chooser = JFileChooser(fileChooserDirectory)
        fileextensions = ["txt"]
        filter = FileNameExtensionFilter("TXT FILES", fileextensions)
        self.chooser.setFileFilter(filter)
        returnVal = self.chooser.showOpenDialog(self.chooser)
        if (returnVal == JFileChooser.APPROVE_OPTION):
            self.inputFileButton.text = self.chooser.getSelectedFile().getName(
            )

    ##################################
    # SECTION 2: SEND TIMING REQUEST #
    ##################################

    def timeTwoUsers(self, event):
        """ Method that sends the current request to getTwoUserTimes """

        if (self.curRequest == None):
            self.debugOutput("Timing Attack does not have a request")
            return

        # change button to say show request
        self.twoUserViewResult.setVisible(True)
        self.twoUserViewReq.setVisible(True)
        self.twoUserViewValidResponse.setVisible(True)
        self.twoUserViewInvalidResponse.setVisible(True)
        threading.Thread(target=self.getTwoUserTimes).start()
        return

    def getTwoUserTimes(self):
        """ Method that prints the time taken to return responses
        from one valid username and from one invalid username
        (called by timeTwoUsers) """

        self.twoUserViewReq.setVisible(True)
        validTime, self.validRequest, self.validResponse = self.getTime(
            self.addParameter.text, self.addValid.text, self.addAverage.text)
        invalidTime, self.invalidRequest, self.invalidResponse = self.getTime(
            self.addParameter.text, self.addInvalid.text, self.addAverage.text)
        self.showResults.text = "Valid username: "******"\t Time: "
        self.showResults.text += str(validTime) + "\n"
        self.showResults.text += "Invalid username: "******"\t Time: "
        self.showResults.text += str(invalidTime)
        self.twoUserResult = self.showResults.text

    def timeUserList(self, event):
        """ Method that reads the usernames from file and sends
            them to getUserListTimes, and if there is no file so the
            program is going to return anything """

        if (self.curRequest == None):
            self.debugOutput("Timing Attack does not have a request")
            return
        try:
            # stores the file
            file = self.chooser.getSelectedFile()

            # reads it
            scan = Scanner(file)
            readFile = ""
            while scan.hasNext():
                readFile += scan.nextLine()

            # divides the file to a list of usernames
            self.userList = readFile.split(self.addSeparatorList.text)

            # set all the list buttons to visible
            self.downloadResultList.setVisible(True)
            self.listViewResults.setVisible(True)
            self.listViewReq.setVisible(True)
            self.listViewResponses.setVisible(True)
            # gets the time for each username
            threading.Thread(target=self.getUserListTimes).start()

        # it will handle the error and send a message about it
        except:
            self.debugOutput("No File Submitted")
        return

    def getUserListTimes(self):
        """ Method that prints the time taken to return responses
        for each username from file (called by timeUserList) """

        self.listViewReq.setVisible(True)
        self.showResultsList.text = ""
        self.listResponses = ""
        self.listRequests = ""
        helpers = self.callbacks.getHelpers()
        for index, username in enumerate(self.userList):
            self.showResultsList.text += "Username: "******"\t Time: "
            time, request, response = self.getTime(self.addParameterList.text,
                                                   username,
                                                   self.addAverageList.text)
            self.showResultsList.text += str(time) + "\n"

            self.listResponses += ":: Response " + str(
                index) + " ::\n" + "Username: "******"\n\n"
            self.listResponses += helpers.bytesToString(
                response) + "\n\n\n\n\n"

            self.listRequests += ":: Request " + str(
                index) + " ::\n" + "Username: "******"\n\n"
            self.listRequests += helpers.bytesToString(request) + "\n\n\n\n\n"

        self.listResults = self.showResultsList.text
        return

    def getTime(self, paramName, paramInput, numTriesText):
        """ Method that takes in a username and returns the time taken to get
        its response (called by getTwoUserTimes and getUserListTimes) """

        try:
            numTries = int(numTriesText)
        except:
            self.debugOutput("Sample size must be an integer")

        # keeps a reference to helpers
        helpers = self.callbacks.getHelpers()

        # Get the request
        request = self.curRequest.getRequest()

        # Get request information
        requestInfo = helpers.analyzeRequest(request)

        # loop through parameters
        for i in requestInfo.getParameters():
            # find username parameter and change its value
            if (i.getName() == paramName):
                # it creates the request
                buildParam = helpers.buildParameter(paramName, paramInput,
                                                    i.getType())
                newRequest = helpers.updateParameter(request, buildParam)

        if 'newRequest' not in locals():
            self.debugOutput("Parameter " + paramName +
                             " cannot be found in request")
        # it builds an http service to send a request to the website
        httpService = self.curRequest.getHttpService()
        useHttps = True if httpService.getProtocol() == "https" else False
        httpService = helpers.buildHttpService(httpService.getHost(),
                                               httpService.getPort(), useHttps)

        getTime = 0
        for i in range(numTries):
            # starts the time and it sends the changed request with valid parameter
            start = time.clock()
            makeRequest = self.callbacks.makeHttpRequest(
                httpService, newRequest)
            makeRequest.getResponse()
            getTime += time.clock() - start

        makeRequest = self.callbacks.makeHttpRequest(httpService, newRequest)
        request = makeRequest.getRequest()
        response = makeRequest.getResponse()
        # return the response
        return getTime / numTries, request, response

    ####################################################
    # SECTION 3: VIEW REQUEST/RESPONSE/RESULTS BUTTONS #
    ####################################################

    def showListRequest(self, event):
        """ Method that shows the request from a file of usernames """
        helpers = self.callbacks.getHelpers()
        self.showResultsList.text = self.listRequests

    def showListResults(self, event):
        """ Show results for list """
        self.showResultsList.text = self.listResults

    def showListResponses(self, event):
        """ Show responses for list """
        self.showResultsList.text = self.listResponses

    def showResultsTop(self, event):
        """ Show results on top """
        self.showResults.text = self.twoUserResult

    def showRequestTop(self, event):
        """ Show request on top """
        helpers = self.callbacks.getHelpers()
        self.showResults.text = ":: Valid Request :: \n"
        self.showResults.text += helpers.bytesToString(self.validRequest)
        self.showResults.text += "\n\n\n:: Invalid Request :: \n"
        self.showResults.text += helpers.bytesToString(self.invalidRequest)

    def showValidResponseTop(self, event):
        """ Show valid response on top """
        helpers = self.callbacks.getHelpers()
        self.showResults.text = helpers.bytesToString(self.validResponse)

    def showInvalidResponseTop(self, event):
        """ Show invalid response on top """
        helpers = self.callbacks.getHelpers()
        self.showResults.text = helpers.bytesToString(self.invalidResponse)

    ##############################
    # SECTION 4: DOWNLOAD BUTTON #
    ##############################

    def downloadResults(self, event):
        """ Method that allows user to download file to get the response's time """
        try:
            if (self.showResultsList.text == ""):
                return
            file = open(self.get_download_path() + "/downloadresults.txt", "w")
            file.write(self.showResultsList.text)
            file.close()
            self.debugOutput(
                "Download successful! \nCheck your downloads folder for the file."
            )
        except:
            self.debugOutput("Download failed.")

    def get_download_path(self):
        """ Method to find path of download folder (called by downloadResults),
         and it returns the default downloads path for linux or windows """

        if os.name == 'nt':
            import winreg
            sub_key = r'SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders'
            downloads_guid = '{374DE290-123F-4565-9164-39C4925E467B}'
            with winreg.OpenKey(winreg.HKEY_CURRENT_USER, sub_key) as key:
                location = winreg.QueryValueEx(key, downloads_guid)[0]
            return location
        else:
            return os.path.join(os.path.expanduser('~'), 'downloads')

    ###########################
    # SECTION 5: DEBUG BUTTON #
    ###########################

    def debugOutput(self, message):
        """ Write a debug message in the debug box """

        self.debugText.text = message

        self.debugTextScroll.setVisible(True)
        self.viewDebug.setText("Close Debug Output")
        self.debugOn = True

    def showDebug(self, event):
        """ Open or close debug box """

        if self.debugOn:
            self.debugTextScroll.setVisible(False)
            self.viewDebug.setText("View Debug Output")
            self.debugOn = False
            self.debugText.text = ""
        else:
            self.debugTextScroll.setVisible(True)
            self.viewDebug.setText("Close Debug Output")
            self.debugOn = True

    ###################################
    # SECTION 6: TAB RECIEVES REQUEST #
    ###################################

    def getRequest(self, messageList):
        """ Method that stores the request sent from proxy """

        self.curRequest = messageList[0]

        # Show request in top box
        helpers = self.callbacks.getHelpers()
        self.showResults.text = helpers.bytesToString(
            self.curRequest.getRequest())
        # Show request in bottom box
        helpers = self.callbacks.getHelpers()
        self.showResultsList.text = helpers.bytesToString(
            self.curRequest.getRequest())
示例#30
0
from time import time

import jmri
import java
from javax.swing import JFileChooser, JOptionPane
from javax.swing.filechooser import FileNameExtensionFilter

dialogTitle = "Bundle Keys Report"

##
# Select a properties file to be anaylzed.  This will normally be the
# default (English) file.
##
fc = JFileChooser(FileUtil.getProgramPath())
fc.setDialogTitle(dialogTitle)
fc.setFileFilter(FileNameExtensionFilter("Bundle Properties", ["properties"]));
ret = fc.showOpenDialog(None)
if ret == JFileChooser.APPROVE_OPTION:
    selectedBundle = fc.getSelectedFile().toString()
    startTime = time()
else:
    print "No file selected, bye"
    quit()

# set up path info
bundleFile = os.path.basename(selectedBundle)
fullPath = os.path.dirname(selectedBundle)
splitPath = fullPath.split(os.sep + "src" + os.sep)
jmriPath = splitPath[0]
bundlePath = splitPath[1]
dotPath = ".".join(bundlePath.split(os.sep))
示例#31
0
    def actionPerformed(self, event):
        """Called when a button is pressed."""
        if event.getActionCommand() == "new-type":
            type_name = JOptionPane.showInputDialog("Enter new name")

            # Error out if already defined
            if type_name in blackboxprotobuf.known_messages:
                JOptionPane.showMessageDialog(
                    self._type_def_tab._component,
                    "Message type %s already exists" % type_name)
                return

            typedef_editor.TypeEditorWindow(
                self._type_def_tab._burp_callbacks, {},
                self.create_save_callback(type_name)).show()

        elif event.getActionCommand() == "edit-type":
            list_component = self._type_def_tab._type_list_component
            # Check if something is selected
            if list_component.isSelectionEmpty():
                return

            type_name = list_component.getSelectedValue()
            typedef_editor.TypeEditorWindow(
                self._type_def_tab._burp_callbacks,
                blackboxprotobuf.known_messages[type_name],
                self.create_save_callback(type_name)).show()

        elif event.getActionCommand() == "delete-type":
            list_component = self._type_def_tab._type_list_component
            # Check if something is selected
            if list_component.isSelectionEmpty():
                return

            type_name = list_component.getSelectedValue()
            #TODO Confirm delete?
            del blackboxprotobuf.known_messages[type_name]
            self._type_def_tab.updateList()

        elif event.getActionCommand() == 'save-types':
            chooser = JFileChooser()
            chooser.setFileFilter(
                FileNameExtensionFilter("JSON Type Definition", ["json"]))
            chooser.setMultiSelectionEnabled(False)

            action = chooser.showSaveDialog(
                self._type_def_tab.getUiComponent())
            if action == JFileChooser.CANCEL_OPTION or action == JFileChooser.ERROR_OPTION:
                return

            file_name = chooser.getSelectedFile().getCanonicalPath()
            ext = os.path.splitext(file_name)[1]
            if ext == '':
                #No extension, add .json
                file_name += '.json'

            with open(file_name, 'w+') as selected_file:
                json.dump(blackboxprotobuf.known_messages,
                          selected_file,
                          indent=4,
                          sort_keys=True)

        elif event.getActionCommand() == 'load-types':
            chooser = JFileChooser()
            chooser.setFileFilter(
                FileNameExtensionFilter("JSON Type Definition", ["json"]))
            chooser.setMultiSelectionEnabled(False)

            action = chooser.showOpenDialog(
                self._type_def_tab.getUiComponent())
            if action == JFileChooser.CANCEL_OPTION or action == JFileChooser.ERROR_OPTION:
                return

            file_name = chooser.getSelectedFile().getCanonicalPath()
            types = {}
            with open(file_name, 'r') as selected_file:
                types = json.load(selected_file)
            for key, value in types.items():
                blackboxprotobuf.known_messages[key] = value
            self._type_def_tab.updateList()
示例#32
0
class DataPanel(JPanel,MouseListener):
    def __init__(self,view):
        JPanel.__init__(self)
        self.view=view
        self.background=Color.white
        self.layout=BorderLayout()

        self.popup=JPopupMenu()
        self.popup_items={}

        self.add(self.make_controls(),BorderLayout.SOUTH)

        data,title=self.extract_data()
        self.table=JTable(DefaultTableModel(data,title))

        scroll=JScrollPane(self.table)
        self.add(scroll)

        scroll.addMouseListener(self)
        self.table.tableHeader.addMouseListener(self)
        self.table.addMouseListener(self)

        self.fileChooser=JFileChooser()
        self.fileChooser.setFileFilter(CSVFilter())
        self.fileChooser.setSelectedFile(File('%s.csv'%self.view.network.name))



    def make_controls(self):
        from timeview.components.timecontrol import Icon, ShadedIcon
        panel=JPanel(background=self.background)
        panel.add(JButton(Icon.refresh,actionPerformed=self.refresh,rolloverIcon=ShadedIcon.refresh,toolTipText='refresh',borderPainted=False,focusPainted=False,contentAreaFilled=False))

        filter=JPanel(layout=BorderLayout(),opaque=False)
        self.filter = JSpinner(SpinnerNumberModel(self.view.tau_filter,0,0.5,0.01),stateChanged=self.refresh)
        filter.add(self.filter)
        filter.add(JLabel('filter'),BorderLayout.NORTH)
        filter.maximumSize=filter.preferredSize
        panel.add(filter)

        decimals=JPanel(layout=BorderLayout(),opaque=False)
        self.decimals = JSpinner(SpinnerNumberModel(3,0,10,1),stateChanged=self.refresh)
        decimals.add(self.decimals)
        decimals.add(JLabel('decimal places'),BorderLayout.NORTH)
        decimals.maximumSize=decimals.preferredSize
        panel.add(decimals)

        panel.add(JButton(Icon.save,actionPerformed=self.save,rolloverIcon=ShadedIcon.save,toolTipText='save',borderPainted=False,focusPainted=False,contentAreaFilled=False))

        return panel

    def extract_data(self):
        pause_state=self.view.paused
        self.view.paused=True

        while self.view.simulating:
            java.lang.Thread.sleep(10)

        tau=float(self.filter.value)
        dt=self.view.dt
        if tau<dt: dt_tau=None
        else: dt_tau=dt/tau

        decimals=int(self.decimals.value)
        format='%%1.%df'%decimals

        start_index=max(0,self.view.timelog.tick_count-self.view.timelog.tick_limit+1)
        count=min(self.view.timelog.tick_limit,self.view.timelog.tick_count)
        start_time=start_index*self.view.dt

        data=None
        title=['t']
        keys = self.view.watcher.active.keys()
        keys.sort()
        for key in keys:
            watch = self.view.watcher.active[key]
            name,func,args=key

            code='%s.%s%s'%(name,func.__name__,args)
            if code not in self.popup_items:
                state=True
                if 'spike' in func.__name__: state=False
                if 'voltage' in func.__name__: state=False
                self.popup_items[code]=JCheckBoxMenuItem(code,state,stateChanged=self.refresh)
                self.popup.add(self.popup_items[code])

            if self.popup_items[code].state is False: continue

            d=watch.get(dt_tau=dt_tau,start=start_index,count=count)
            n=len(watch.get_first())
            if data is None:
                data=[]
                while len(data)<len(d):
                    data.append(['%0.4f'%(start_time+(len(data)+0)*self.view.dt)])


            for i in range(n):
                title.append('%s[%d]'%(code,i))
                for j in range(len(data)):
                    dd=d[j]
                    if dd is None: data[j].append('')
                    else: data[j].append(format%dd[i])

        self.view.paused=pause_state
        return data,title


    def save(self,event=None):
        if self.fileChooser.showSaveDialog(self)==JFileChooser.APPROVE_OPTION:
            f=self.fileChooser.getSelectedFile()
            writer=BufferedWriter(FileWriter(f))

            data,title=self.extract_data()
            title=[t.replace(',',' ') for t in title]
            writer.write(','.join(title)+'\n')
            for row in data:
                writer.write(','.join(row)+'\n')
            writer.close()

    def refresh(self,event=None):
        data,title=self.extract_data()
        self.table.model.setDataVector(data,title)

        
    def mouseClicked(self, event):     
        if event.button==MouseEvent.BUTTON3 or (event.button==MouseEvent.BUTTON1 and event.isControlDown()):
            if self.popup is not None:
                self.popup.show(event.source,event.x-5,event.y-5)
            
    def mouseEntered(self, event):
        pass
    def mouseExited(self, event):        
        pass
    def mousePressed(self, event):
        pass
    def mouseReleased(self, event):        
        pass
示例#33
0
    def actionPerformed(self, event):
        """Called when a button is pressed."""
        if event.getActionCommand() == "new-type":
            self._typedef_tab.add_typedef()

        elif event.getActionCommand() == "edit-type":
            self._typedef_tab.edit_typedef()

        elif event.getActionCommand() == "rename-type":
            list_component = self._typedef_tab._type_list_component
            # Check if something is selected
            if list_component.isSelectionEmpty():
                return

            # Get's only the first value
            previous_type_name = list_component.getSelectedValue()
            new_type_name = JOptionPane.showInputDialog(
                "Enter new name for %s:" % previous_type_name)
            if new_type_name in default_config.known_types:
                JOptionPane.showMessageDialog(
                    self._typedef_tab._component,
                    'Message type "%s" already exists' % new_type_name,
                )
                return
            if previous_type_name not in default_config.known_types:
                JOptionPane.showMessageDialog(
                    self._typedef_tab._component,
                    'Message type "%s" does not exist' % previous_type_name,
                )
                return
            if not NAME_REGEX.match(new_type_name):
                JOptionPane.showMessageDialog(
                    self._typedef_tab._component,
                    'Message type name "%s" is not valid.' % new_type_name,
                )
                return
            typedef = default_config.known_types[previous_type_name]
            default_config.known_types[new_type_name] = typedef
            del default_config.known_types[previous_type_name]
            # TODO should manage this centrally somewhere
            self._typedef_tab._extension.refresh_message_model()
            for key, typename in self._typedef_tab._extension.saved_types.items(
            ):
                if typename == previous_type_name:
                    self._typedef_tab._extension.saved_types[
                        key] = new_type_name

        elif event.getActionCommand() == "delete-type":
            list_component = self._typedef_tab._type_list_component
            # Check if something is selected
            if list_component.isSelectionEmpty():
                return

            type_names = list_component.getSelectedValuesList()
            # TODO Confirm delete?
            for type_name in type_names:
                del default_config.known_types[type_name]
            self._typedef_tab._extension.refresh_message_model()

        elif event.getActionCommand() == "save-types":
            chooser = JFileChooser()
            chooser.setFileFilter(
                FileNameExtensionFilter("JSON Type Definition", ["json"]))
            chooser.setMultiSelectionEnabled(False)

            action = chooser.showSaveDialog(self._typedef_tab.getUiComponent())
            if (action == JFileChooser.CANCEL_OPTION
                    or action == JFileChooser.ERROR_OPTION):
                return

            file_name = chooser.getSelectedFile().getCanonicalPath()
            ext = os.path.splitext(file_name)[1]
            if ext == "":
                # No extension, add .json
                file_name += ".json"

            with open(file_name, "w+") as selected_file:
                json.dump(
                    default_config.known_types,
                    selected_file,
                    indent=4,
                    sort_keys=True,
                )

        elif event.getActionCommand() == "load-types":
            chooser = JFileChooser()
            chooser.setFileFilter(
                FileNameExtensionFilter("JSON Type Definition", ["json"]))
            chooser.setMultiSelectionEnabled(False)

            action = chooser.showOpenDialog(self._typedef_tab.getUiComponent())
            if (action == JFileChooser.CANCEL_OPTION
                    or action == JFileChooser.ERROR_OPTION):
                return

            file_name = chooser.getSelectedFile().getCanonicalPath()
            types = {}
            with open(file_name, "r") as selected_file:
                types = json.load(selected_file)
            for key, value in types.items():
                # check to make sure we don't nuke existing messages
                if key in default_config.known_types:
                    overwrite = (JOptionPane.showConfirmDialog(
                        self._typedef_tab._component,
                        "Message %s already saved. Overwrite?" % key,
                    ) == 0)
                    if not overwrite:
                        continue
                default_config.known_types[key] = value
            self._typedef_tab._extension.refresh_message_model()
        elif event.getActionCommand() == "export-proto":
            chooser = JFileChooser()
            chooser.setFileFilter(
                FileNameExtensionFilter("Protobuf Type Definition", ["proto"]))
            chooser.setMultiSelectionEnabled(False)

            action = chooser.showSaveDialog(self._typedef_tab.getUiComponent())
            if (action == JFileChooser.CANCEL_OPTION
                    or action == JFileChooser.ERROR_OPTION):
                return

            file_name = chooser.getSelectedFile().getCanonicalPath()
            ext = os.path.splitext(file_name)[1]
            if ext == "":
                # No extension, add .proto
                file_name += ".proto"

            if os.path.exists(file_name):
                # 0 is the YES option
                overwrite = (JOptionPane.showConfirmDialog(
                    self._typedef_tab._component,
                    "File %s already exists. Overwrite?" % file_name,
                ) == 0)
                if not overwrite:
                    return
                print("overwriting file: %s" % file_name)
            try:
                blackboxprotobuf.export_protofile(default_config.known_types,
                                                  file_name)
            except Exception as exc:
                self._typedef_tab._burp_callbacks.printError(
                    traceback.format_exc())
                JOptionPane.showMessageDialog(
                    self._typedef_tab._component,
                    "Error saving .proto file: " + str(exc),
                )

        elif event.getActionCommand() == "import-proto":
            chooser = JFileChooser()
            chooser.setFileFilter(
                FileNameExtensionFilter("Protobuf Type Definition", ["proto"]))
            chooser.setMultiSelectionEnabled(False)

            action = chooser.showOpenDialog(self._typedef_tab.getUiComponent())
            if (action == JFileChooser.CANCEL_OPTION
                    or action == JFileChooser.ERROR_OPTION):
                return

            file_name = chooser.getSelectedFile().getCanonicalPath()
            if not os.path.exists(file_name):
                self._typedef_tab._burp_callbacks.printError(
                    "Attempted to import %s, but the file does not exist." %
                    file_name)
                JOptionPane.showMessageDialog(
                    self._typedef_tab._component,
                    "File %s does not exist to import." + str(exc),
                )
                return
            try:
                new_typedefs = blackboxprotobuf.import_protofile(
                    file_name, save_to_known=False)
                for key, value in new_typedefs.items():
                    # check to make sure we don't nuke existing messages
                    if key in default_config.known_types:
                        overwrite = (JOptionPane.showConfirmDialog(
                            self._typedef_tab._component,
                            "Message %s already saved. Overwrite?" % key,
                        ) == 0)
                        if not overwrite:
                            continue
                    else:
                        self._typedef_tab._extension.known_message_model.addElement(
                            key)
                    default_config.known_types[key] = value
            except Exception as exc:
                self._typedef_tab._burp_callbacks.printError(
                    traceback.format_exc())
                JOptionPane.showMessageDialog(
                    self._typedef_tab._component,
                    "Error loading .proto file: " + str(exc),
                )