Exemplo n.º 1
0
class DataSourcesPanelSettings(JPanel):
    serialVersionUID = 1L

    def __init__(self):
        self.pcs = PropertyChangeSupport(self)

        self.initComponents()
        self.customizeComponents()

    def getVersionNumber(self):
        return serialVersionUID

    #PROCESSOR LOGIC
    def run(self, progressMonitor, callback):
        threading.Thread(target=self.running, args=[progressMonitor,
                                                    callback]).start()

    def running(self, progressMonitor, callback):
        progressMonitor.setIndeterminate(True)
        newDataSources = []
        errors = []
        result = DataSourceProcessorCallback.DataSourceProcessorResult.NO_ERRORS

        try:
            extractor = Extractor(self.selected_apps, self.selected_devices,
                                  progressMonitor)
            folders = extractor.dump_apps()

            for serial, folder in folders.items():
                try:
                    data_source = PsyUtils.add_to_fileset("ADB_{}_{}".format(
                        serial, int(time.time())),
                                                          folder,
                                                          notify=False)
                    newDataSources.append(data_source)
                except Exception as e:
                    message = "Extractor Failed for {} for {}!".format(
                        serial, e)
                    logging.error(message)
                    errors.append(message)
                    result = DataSourceProcessorCallback.DataSourceProcessorResult.NONCRITICAL_ERRORS

        except Exception as e:
            message = "Global Extractor Failed. Aborting: {}".format(e)
            logging.error(message)
            errors.append(message)
            result = DataSourceProcessorCallback.DataSourceProcessorResult.CRITICAL_ERRORS

        if len(newDataSources) == 0:
            result = DataSourceProcessorCallback.DataSourceProcessorResult.CRITICAL_ERRORS

        callback.done(result, errors, newDataSources)

    #PROCESSOR JPANEL LOGIC
    def addPropertyChangeListener(self, pcl):
        super(DataSourcesPanelSettings, self).addPropertyChangeListener(pcl)
        self.pcs.addPropertyChangeListener(pcl)

    def fireUIUpdate(self):
        #Fire UI change, this is necessary to know if it's allowed to click next
        self.pcs.firePropertyChange(
            DataSourceProcessor.DSP_PANEL_EVENT.UPDATE_UI.toString(), False,
            True)

    def validatePanel(self):
        return (len(self.selected_apps) != 0
                and len(self.selected_devices) != 0)

    def initComponents(self):
        self.apps_checkboxes_list = []
        self.devices_checkboxes_list = []
        self.selected_apps = []
        self.selected_devices = []

        self.setLayout(BoxLayout(self, BoxLayout.PAGE_AXIS))
        self.setPreferredSize(
            Dimension(543, 172)
        )  #Max 544x173 https://www.sleuthkit.org/autopsy/docs/api-docs/3.1/interfaceorg_1_1sleuthkit_1_1autopsy_1_1corecomponentinterfaces_1_1_data_source_processor.html#a068919818c017ee953180cc79cc68c80

        # info menu
        self.p_info = SettingsUtils.createPanel()
        self.p_info.setPreferredSize(Dimension(543, 172))
        self.d_method = SettingsUtils.createPanel(pbottom=15)

        self.label = JLabel(
            'Press "Find Devices" to search for devices to extract information.'
        )
        self.label.setBorder(EmptyBorder(0, 0, 5, 0))
        self.d_method.add(self.label)

        self.label = JLabel('It will generate a file set per device.')
        self.label.setBorder(EmptyBorder(0, 0, 10, 0))
        self.d_method.add(self.label)

        self.label = JLabel(
            'This extract method requires ADB enabled on the device and may require root privilege for some paths.'
        )
        self.label.setFont(self.label.getFont().deriveFont(Font.BOLD, 11))
        self.label.setBorder(EmptyBorder(0, 0, 10, 0))
        self.d_method.add(self.label)

        self.search_devices = JButton('Find Devices',
                                      actionPerformed=self.findDevices)
        self.d_method.add(self.search_devices)

        self.p_method = SettingsUtils.createPanel(ptop=15)

        self.sp2 = SettingsUtils.createSeparators(0)
        self.p_info.add(self.sp2, BorderLayout.SOUTH)

        self.p_method.add(JLabel("Extract user data from:"))

        self.p_apps = SettingsUtils.createPanel(True, pbottom=10)
        self.p_devices = SettingsUtils.createPanel(True)
        self.choose_device = JLabel("Choose device:")
        self.choose_device.setVisible(False)

        self.appsBlock()

        self.add(self.d_method)
        self.add(JSeparator())
        self.add(self.p_method)
        self.add(self.p_apps)

        self.add(self.choose_device)
        self.add(self.p_devices)

        self.add(self.p_info)

        self.findDevices("")

    def customizeComponents(self):
        self.updateCheckboxes("")

    def updateCheckboxes(self, event):
        self.getSelectedApps(event)  #initialize selected apps
        self.getSelectedDevices(event)  #initialize selected devices
        self.fireUIUpdate()

    def findDevices(self, event):
        self.p_devices.removeAll()
        self.devices_checkboxes_list = []

        devices = DeviceCommunication.list_devices()
        for device in devices:
            checkbox = SettingsUtils.addDeviceCheckbox(device,
                                                       self.updateCheckboxes,
                                                       visible=True)
            self.devices_checkboxes_list.append(checkbox)
            self.p_devices.add(checkbox)

        self.choose_device.setVisible(len(self.devices_checkboxes_list) > 0)

        #refresh list
        self.p_devices.setVisible(False)
        self.p_devices.setVisible(True)

        self.updateCheckboxes(event)

    def appsBlock(self):
        sorted_items = OrderedDict(sorted(Utils.get_all_packages().items()))
        for app, app_id in sorted_items.iteritems():
            #(app, app_id)
            checkbox = SettingsUtils.addApplicationCheckbox(
                app, app_id, self.updateCheckboxes, visible=True)
            #self.add(checkbox)
            self.apps_checkboxes_list.append(checkbox)
            self.p_apps.add(checkbox)

    def getSelectedDevices(self, event):
        self.selected_apps = []

        for cb_app in self.apps_checkboxes_list:
            if cb_app.isSelected():
                self.selected_apps.append(cb_app.getActionCommand())

    def getSelectedApps(self, event):
        self.selected_devices = []

        for cb_app in self.devices_checkboxes_list:
            if cb_app.isSelected():
                self.selected_devices.append(cb_app.getActionCommand())
Exemplo n.º 2
0
f4_btn_directory = JButton("Browse", actionPerformed = f4_clic_browse1)
f4_btn_directory.setBounds(170,20,100,20)
f4_txt1 = JTextField(10)
f4_txt1.setBounds(280, 20, 120,20)

# Number of pixels to erode
f4_lbl2 = JLabel("Number of pixels to erode")
f4_lbl2.setBounds(40,50,160,20)
f4_txt2 = JTextField(10)
f4_txt2.setBounds(280, 50, 120,20)
f4_txt2.setText(str(0))

# Processing image label
f4_lbl3 = JLabel("")
f4_lbl3.setBounds(40,75,200,20)
f4_lbl3.setVisible(True)

# Progress Bar
f4_progressBar = JProgressBar(0, 100, value=0, stringPainted=True)
f4_progressBar.setBounds(40,100,360,20)

# Button Set Measurements
f4_btn_params = JButton("Set measurements", actionPerformed = f4_clic_measurements)
f4_btn_params.setBounds(145,135,150,20)

# Button Previous
f4_btn_prev = JButton("Previous", actionPerformed = f4_clic_prev)
f4_btn_prev.setBounds(40,135,100,20)

# Button Next
f4_btn_next = JButton("Run", actionPerformed = f4_clic_next)
Exemplo n.º 3
0
class QatDialog(ToggleDialog):
    """ToggleDialog for error type selection and buttons for reviewing
       errors in sequence
    """
    def __init__(self, name, iconName, tooltip, shortcut, height, app):
        ToggleDialog.__init__(self, name, iconName, tooltip, shortcut, height)
        self.app = app
        tools = app.tools

        #Main panel of the dialog
        mainPnl = JPanel(BorderLayout())
        mainPnl.setBorder(BorderFactory.createEmptyBorder(0, 1, 1, 1))

### First tab: errors selection and download ###########################
        #ComboBox with tools names
        self.toolsComboModel = DefaultComboBoxModel()
        for tool in tools:
            self.add_data_to_models(tool)
        self.toolsCombo = JComboBox(self.toolsComboModel,
                                    actionListener=ToolsComboListener(app))
        renderer = ToolsComboRenderer(self.app)
        renderer.setPreferredSize(Dimension(20, 20))
        self.toolsCombo.setRenderer(renderer)
        self.toolsCombo.setToolTipText(app.strings.getString("Select_a_quality_assurance_tool"))

        #ComboBox with categories names ("views"), of the selected tool
        self.viewsCombo = JComboBox(actionListener=ViewsComboListener(app))
        self.viewsCombo.setToolTipText(app.strings.getString("Select_a_category_of_error"))

        #Popup for checks table
        self.checkPopup = JPopupMenu()
        #add favourite check
        self.menuItemAdd = JMenuItem(self.app.strings.getString("Add_to_favourites"))
        self.menuItemAdd.setIcon(ImageIcon(File.separator.join([self.app.SCRIPTDIR,
                                                                "tools",
                                                                "data",
                                                                "Favourites",
                                                                "icons",
                                                                "tool_16.png"])))
        self.menuItemAdd.addActionListener(PopupActionListener(self.app))
        self.checkPopup.add(self.menuItemAdd)
        #remove favourite check
        self.menuItemRemove = JMenuItem(self.app.strings.getString("Remove_from_favourites"))
        self.menuItemRemove.setIcon(ImageIcon(File.separator.join([self.app.SCRIPTDIR,
                                                                   "tools",
                                                                   "data",
                                                                   "Favourites",
                                                                   "icons",
                                                                   "black_tool_16.png"])))
        self.menuItemRemove.addActionListener(PopupActionListener(self.app))
        self.checkPopup.add(self.menuItemRemove)
        #Help link for selected check
        self.menuItemHelp = JMenuItem(self.app.strings.getString("check_help"))
        self.menuItemHelp.setIcon(ImageIcon(File.separator.join([self.app.SCRIPTDIR,
                                                                 "images",
                                                                 "icons",
                                                                 "info_16.png"])))
        self.checkPopup.add(self.menuItemHelp)
        self.menuItemHelp.addActionListener(PopupActionListener(self.app))

        #Table with checks of selected tool and view
        self.checksTable = JTable()
        self.iconrenderer = IconRenderer()
        self.iconrenderer.setHorizontalAlignment(JLabel.CENTER)
        scrollPane = JScrollPane(self.checksTable)
        self.checksTable.setFillsViewportHeight(True)

        tableSelectionModel = self.checksTable.getSelectionModel()
        tableSelectionModel.addListSelectionListener(ChecksTableListener(app))

        self.checksTable.addMouseListener(ChecksTableClickListener(app,
            self.checkPopup,
            self.checksTable))

        #Favourite area status indicator
        self.favAreaIndicator = JLabel()
        self.update_favourite_zone_indicator()
        self.favAreaIndicator.addMouseListener(FavAreaIndicatorListener(app))

        #label with OSM id of the object currently edited and number of
        #errors still to review
        self.checksTextFld = JTextField("",
                                        editable=0,
                                        border=None,
                                        background=None)

        #checks buttons
        btnsIconsDir = File.separator.join([app.SCRIPTDIR, "images", "icons"])
        downloadIcon = ImageIcon(File.separator.join([btnsIconsDir, "download.png"]))
        self.downloadBtn = JButton(downloadIcon,
                                   actionPerformed=app.on_downloadBtn_clicked,
                                   enabled=0)
        startIcon = ImageIcon(File.separator.join([btnsIconsDir, "start_fixing.png"]))
        self.startBtn = JButton(startIcon,
                                actionPerformed=app.on_startBtn_clicked,
                                enabled=0)
        self.downloadBtn.setToolTipText(app.strings.getString("Download_errors_in_this_area"))
        self.startBtn.setToolTipText(app.strings.getString("Start_fixing_the_selected_errors"))

        #tab layout
        panel1 = JPanel(BorderLayout(0, 1))

        comboboxesPnl = JPanel(GridLayout(0, 2, 5, 0))
        comboboxesPnl.add(self.toolsCombo)
        comboboxesPnl.add(self.viewsCombo)

        checksPnl = JPanel(BorderLayout(0, 1))
        checksPnl.add(scrollPane, BorderLayout.CENTER)
        self.statsPanel = JPanel(BorderLayout(4, 0))
        self.statsPanel_def_color = self.statsPanel.getBackground()
        self.statsPanel.add(self.checksTextFld, BorderLayout.CENTER)
        self.statsPanel.add(self.favAreaIndicator, BorderLayout.LINE_START)
        checksPnl.add(self.statsPanel, BorderLayout.PAGE_END)

        checksButtonsPnl = JPanel(GridLayout(0, 2, 0, 0))
        checksButtonsPnl.add(self.downloadBtn)
        checksButtonsPnl.add(self.startBtn)

        panel1.add(comboboxesPnl, BorderLayout.PAGE_START)
        panel1.add(checksPnl, BorderLayout.CENTER)
        panel1.add(checksButtonsPnl, BorderLayout.PAGE_END)

### Second tab: errors fixing ##########################################
        #label with error stats
        self.errorTextFld = JTextField("",
                                       editable=0,
                                       border=None,
                                       background=None)
        #label with current error description
        self.errorDesc = JLabel("")
        self.errorDesc.setAlignmentX(0.5)

        #error buttons
        errorInfoBtnIcon = ImageProvider.get("info")
        self.errorInfoBtn = JButton(errorInfoBtnIcon,
                                    actionPerformed=app.on_errorInfoBtn_clicked,
                                    enabled=0)
        notErrorIcon = ImageIcon(File.separator.join([btnsIconsDir, "not_error.png"]))
        self.notErrorBtn = JButton(notErrorIcon,
                                   actionPerformed=app.on_falsePositiveBtn_clicked,
                                   enabled=0)
        ignoreIcon = ImageIcon(File.separator.join([btnsIconsDir, "skip.png"]))
        self.ignoreBtn = JButton(ignoreIcon,
                                 actionPerformed=app.on_ignoreBtn_clicked,
                                 enabled=0)
        correctedIcon = ImageIcon(File.separator.join([btnsIconsDir, "corrected.png"]))
        self.correctedBtn = JButton(correctedIcon,
                                    actionPerformed=app.on_correctedBtn_clicked,
                                    enabled=0)
        nextIcon = ImageIcon(File.separator.join([btnsIconsDir, "next.png"]))
        self.nextBtn = JButton(nextIcon,
                               actionPerformed=app.on_nextBtn_clicked,
                               enabled=0)
        #self.nextBtn.setMnemonic(KeyEvent.VK_RIGHT)
        self.errorInfoBtn.setToolTipText(app.strings.getString("open_error_info_dialog"))
        self.notErrorBtn.setToolTipText(app.strings.getString("flag_false_positive"))
        self.ignoreBtn.setToolTipText(app.strings.getString("Skip_and_don't_show_me_this_error_again"))
        self.correctedBtn.setToolTipText(app.strings.getString("flag_corrected_error"))
        self.nextBtn.setToolTipText(app.strings.getString("Go_to_next_error"))

        #tab layout
        self.panel2 = JPanel(BorderLayout())

        self.panel2.add(self.errorTextFld, BorderLayout.PAGE_START)
        self.panel2.add(self.errorDesc, BorderLayout.CENTER)

        errorButtonsPanel = JPanel(GridLayout(0, 5, 0, 0))
        errorButtonsPanel.add(self.errorInfoBtn)
        errorButtonsPanel.add(self.notErrorBtn)
        errorButtonsPanel.add(self.ignoreBtn)
        errorButtonsPanel.add(self.correctedBtn)
        errorButtonsPanel.add(self.nextBtn)
        self.panel2.add(errorButtonsPanel, BorderLayout.PAGE_END)

        #Layout
        self.tabbedPane = JTabbedPane()
        self.tabbedPane.addTab(self.app.strings.getString("Download"),
                               None,
                               panel1,
                               self.app.strings.getString("download_tab"))
        mainPnl.add(self.tabbedPane, BorderLayout.CENTER)
        self.createLayout(mainPnl, False, None)

    def add_data_to_models(self, tool):
        """Add data of a tool to the models of the dialog components
        """
        #tools combobox model
        if tool == self.app.favouritesTool:
            self.toolsComboModel.addElement(JSeparator())
        self.toolsComboModel.addElement(tool)

        #views combobox model
        tool.viewsComboModel = DefaultComboBoxModel()
        for view in tool.views:
            tool.viewsComboModel.addElement(view.title)

        #checks table, one TableModel for each view, of each tool
        columns = ["",
                   self.app.strings.getString("Check"),
                   self.app.strings.getString("Errors")]
        for view in tool.views:
            tableRows = []
            for check in view.checks:
                if check.icon is not None:
                    icon = check.icon
                else:
                    icon = ""
                errorsNumber = ""
                tableRows.append([icon, check.title, errorsNumber])
            view.tableModel = MyTableModel(tableRows, columns)

    def update_favourite_zone_indicator(self):
        #icon
        if self.app.favZone is not None:
            self.favAreaIndicator.setIcon(self.app.favZone.icon)
            #tooltip
            messageArguments = array([self.app.favZone.name], String)
            formatter = MessageFormat("")
            formatter.applyPattern(self.app.strings.getString("favAreaIndicator_tooltip"))
            msg = formatter.format(messageArguments)
            self.favAreaIndicator.setToolTipText(msg)
            #status
            self.favAreaIndicator.setVisible(self.app.favouriteZoneStatus)

    def set_checksTextFld_color(self, color):
        """Change color of textField under checksTable
        """
        colors = {"white": (255, 255, 255),
                  "black": (0, 0, 0),
                  "green": (100, 200, 0),
                  "red": (200, 0, 0)}
        if color == "default":
            self.statsPanel.background = self.statsPanel_def_color
            self.checksTextFld.foreground = colors["black"]
        else:
            self.statsPanel.background = colors[color]
            self.checksTextFld.foreground = colors["white"]

    def change_selection(self, source):
        """Change comboboxes and checks table selections after a
           selection has been made by the user
        """
        if source in ("menu", "layer", "add favourite"):
            self.app.selectionChangedFromMenuOrLayer = True
            self.toolsCombo.setSelectedItem(self.app.selectedTool)
            self.viewsCombo.setModel(self.app.selectedTool.viewsComboModel)
            self.viewsCombo.setSelectedItem(self.app.selectedView.title)

            self.checksTable.setModel(self.app.selectedTableModel)
            self.refresh_checksTable_columns_geometries()
            for i, c in enumerate(self.app.selectedView.checks):
                if c == self.app.selectedChecks[0]:
                    break
            self.checksTable.setRowSelectionInterval(i, i)
            self.app.selectionChangedFromMenuOrLayer = False
        else:
            self.app.selectionChangedFromMenuOrLayer = False
            if source == "toolsCombo":
                self.viewsCombo.setModel(self.app.selectedTool.viewsComboModel)
                self.viewsCombo.setSelectedIndex(0)
            elif source == "viewsCombo":
                self.checksTable.setModel(self.app.selectedTableModel)
                self.refresh_checksTable_columns_geometries()
                if self.app.selectedView.checks != []:  # favourite checks may be none
                    self.checksTable.setRowSelectionInterval(0, 0)

    def refresh_checksTable_columns_geometries(self):
        self.checksTable.getColumnModel().getColumn(0).setCellRenderer(self.iconrenderer)
        self.checksTable.getColumnModel().getColumn(0).setMaxWidth(25)
        self.checksTable.getColumnModel().getColumn(2).setMaxWidth(60)

    def activate_error_tab(self, status):
        if status:
            if self.tabbedPane.getTabCount() == 1:
                self.tabbedPane.addTab(self.app.strings.getString("Fix"),
                                       None,
                                       self.panel2,
                                       self.app.strings.getString("fix_tab"))
        else:
            if self.tabbedPane.getTabCount() == 2:
                self.tabbedPane.remove(1)

    def update_checks_buttons(self):
        """This method sets the status of downloadBtn and startBtn
        """
        #none check selected
        if len(self.app.selectedChecks) == 0:
            self.downloadBtn.setEnabled(False)
            self.startBtn.setEnabled(False)
        else:
            #some check selected
            self.downloadBtn.setEnabled(True)
            if len(self.app.selectedChecks) > 1:
                self.startBtn.setEnabled(False)
            else:
                #only one check is selected
                self.app.errors = self.app.selectedChecks[0].errors
                if self.app.errors is None or len(self.app.errors) == 0:
                    #errors file has not been downloaded and parsed yet
                    self.startBtn.setEnabled(False)
                else:
                    #errors file has been downloaded and parsed
                    if self.app.selectedChecks[0].toDo == 0:
                        #all errors have been corrected
                        self.startBtn.setEnabled(False)
                    else:
                        self.startBtn.setEnabled(True)
                        #self.nextBtn.setEnabled(True)

    def update_error_buttons(self, mode):
        """This method sets the status of:
           ignoreBtn, falsePositiveBtn, correctedBtn, nextBtn
        """
        if mode == "new error":
            status = True
        else:
            status = False
        if self.app.selectedChecks[0].tool.fixedFeedbackMode is None:
            self.correctedBtn.setEnabled(False)
        else:
            self.correctedBtn.setEnabled(status)
        if self.app.selectedChecks[0].tool.falseFeedbackMode is None:
            self.notErrorBtn.setEnabled(False)
        else:
            self.notErrorBtn.setEnabled(status)
        self.errorInfoBtn.setEnabled(status)
        self.ignoreBtn.setEnabled(status)

        if mode in ("reset", "review end"):
            self.nextBtn.setEnabled(False)
        elif mode in ("errors downloaded", "show stats", "new error"):
            self.nextBtn.setEnabled(True)

    def update_text_fields(self, mode, errorInfo=""):
        """This method updates the text in:
           checksTextFld, errorDesc, errorTextFld
        """
        self.errorDesc.text = ""
        if mode == "review end":
            cheksTextColor = "green"
            checksText = self.app.strings.getString("All_errors_reviewed.")
            errorText = self.app.strings.getString("All_errors_reviewed.")
        elif mode == "reset":
            cheksTextColor = "default"
            checksText = ""
            errorText = ""
        elif mode == "show stats":
            cheksTextColor = "default"
            checksText = "%s %d / %s" % (
                         self.app.strings.getString("to_do"),
                         self.app.selectedChecks[0].toDo,
                         len(self.app.selectedChecks[0].errors))
            #print "checks text", checksText
            errorText = "%s%s %d / %s" % (
                        errorInfo,
                        self.app.strings.getString("to_do"),
                        self.app.selectedChecks[0].toDo,
                        len(self.app.selectedChecks[0].errors))
            #print "error text", errorText
            if self.app.selectedError is not None and self.app.selectedError.desc != "":
                self.errorDesc.text = "<html>%s</html>" % self.app.selectedError.desc

        self.set_checksTextFld_color(cheksTextColor)
        self.checksTextFld.text = checksText
        self.errorTextFld.text = errorText
        self.update_statsPanel_status()

    def update_statsPanel_status(self):
        if self.checksTextFld.text == "" and not self.app.favouriteZoneStatus:
            self.statsPanel.setVisible(False)
        else:
            self.statsPanel.setVisible(True)
Exemplo n.º 4
0
class BugDialog(JDialog):
    """Represents the dialog."""

    # default issue to populate the panel with
    defaultIssue = Issue(name="Name",
                         severity="Critical",
                         host="Host",
                         path="Path",
                         description="Description",
                         remediation="",
                         reqResp=RequestResponse(request="default request",
                                                 response="default response"))

    def loadPanel(self, issue):
        # type: (Issue) -> ()
        """Populates the panel with issue."""
        if issue is None:
            return

        # check if the input is the correct object
        assert isinstance(issue, Issue)

        # set textfields and textareas
        # selectionStart=0 selects the text in the textfield when it is in focus
        self.textName.text = issue.name
        self.textName.selectionStart = 0
        self.textHost.text = issue.host
        self.textHost.selectionStart = 0
        self.textPath.text = issue.path
        self.textPath.selectionStart = 0
        self.textAreaDescription.text = issue.description
        self.textAreaDescription.selectionStart = 0
        self.textAreaRemediation.text = issue.remediation
        self.textAreaRemediation.selectionStart = 0
        # severity combobox
        # this is case-sensitive apparently
        self.comboSeverity.setSelectedItem(issue.severity)
        # request and response tabs
        # check if messages are null, some issues might not have responses.
        if issue.getRequest() is None:
            self.panelRequest.setMessage("", True)
        else:
            self.panelRequest.setMessage(issue.getRequest(), True)

        if issue.getResponse() is None:
            self.panelResponse.setMessage("", False)
        else:
            self.panelResponse.setMessage(issue.getResponse(), False)
        # reset the template combobox (only applicable to NewIssueDialog)
        self.comboTemplate.setSelectedIndex(-1)

    def loadTemplateIntoPanel(self, issue):
        # type: (Issue) -> ()
        """Populates the panel with the template issue.
        Does not overwrite:
        name (append), host, path, severity, request and response."""
        if issue is None:
            return

        # check if the input is the correct object
        assert isinstance(issue, Issue)

        # set textfields and textareas
        # selectionStart=0 selects the text in the textfield when it is in focus
        self.textName.text += " - " + issue.name
        self.textName.selectionStart = 0
        # self.textHost.text = issue.host
        # self.textHost.selectionStart = 0
        # self.textPath.text = issue.path
        # self.textPath.selectionStart = 0
        self.textAreaDescription.text = issue.description
        self.textAreaDescription.selectionStart = 0
        self.textAreaRemediation.text = issue.remediation
        self.textAreaRemediation.selectionStart = 0
        # severity combobox
        # this is case-sensitive apparently
        # self.comboSeverity.setSelectedItem(issue.severity)
        # request and response tabs
        # self.panelRequest.setMessage(issue.getRequest(), True)
        # self.panelResponse.setMessage(issue.getResponse(), False)
        # reset the template combobox (only applicable to NewIssueDialog)
        self.comboTemplate.setSelectedIndex(-1)

    def cancelButtonAction(self, event):
        """Close the dialog when the cancel button is clicked."""
        self.dispose()

    def resetButtonAction(self, event):
        """Reset the dialog."""
        self.loadPanel(self.defaultIssue)

    # Inheriting forms should implement this
    def saveButtonAction(self, event):
        """Save the current issue.
        Inheriting classes must implement this."""
        pass

    def __init__(self, callbacks, issue=defaultIssue, title="", modality=""):
        """Constructor, populates the dialog."""
        # set the title
        self.setTitle(title)
        # store the issue
        self.issue = issue

        from javax.swing import JFrame
        self.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE)

        if modality is not "":
            from java.awt.Dialog import ModalityType
            modality = modality.lower()
            # application blocks us from clicking anything else in Burp
            if modality == "application":
                self.setModalityType(ModalityType.APPLICATION_MODAL)
            if modality == "document":
                self.setModalityType(ModalityType.DOCUMENT_MODAL)
            if modality == "modeless":
                self.setModalityType(ModalityType.DOCUMENT_MODAL)
            if modality == "toolkit":
                self.setModalityType(ModalityType.DOCUMENT_MODAL)

        # assert isinstance(callbacks, IBurpExtenderCallbacks)
        # starting converted code from NetBeans
        self.labelPath = JLabel("Path")
        self.labelSeverity = JLabel("Severity")
        self.tabIssue = JTabbedPane()
        self.textAreaDescription = JTextArea()
        self.textAreaRemediation = JTextArea()
        # JScrollPanes to hold the two jTextAreas
        # put the textareas in JScrollPanes
        self.jsPaneDescription = JScrollPane(self.textAreaDescription)
        self.jsPaneRemediation = JScrollPane(self.textAreaRemediation)
        self.panelRequest = callbacks.createMessageEditor(None, True)
        self.panelResponse = callbacks.createMessageEditor(None, True)
        self.textName = JTextField()
        self.textHost = JTextField()
        self.textPath = JTextField()
        self.labelHost = JLabel("Host")
        self.labelName = JLabel("Name")

        # buttons
        self.buttonSave = JButton("Save",
                                  actionPerformed=self.saveButtonAction)
        self.buttonCancel = JButton("Cancel",
                                    actionPerformed=self.cancelButtonAction)
        self.buttonReset = JButton("Reset",
                                   actionPerformed=self.resetButtonAction)

        # description and remediation textareas
        from java.awt import Dimension
        self.textAreaDescription.setPreferredSize(Dimension(400, 500))
        self.textAreaDescription.setLineWrap(True)
        self.textAreaDescription.setWrapStyleWord(True)
        self.textAreaRemediation.setLineWrap(True)
        self.textAreaRemediation.setWrapStyleWord(True)
        self.tabIssue.addTab("Description", self.jsPaneDescription)
        self.tabIssue.addTab("Remediation", self.jsPaneRemediation)
        # request and response tabs
        # request tab
        self.panelRequest.setMessage("", True)
        self.tabIssue.addTab("Request", self.panelRequest.getComponent())
        # response tab
        self.panelResponse.setMessage("", False)
        self.tabIssue.addTab("Response", self.panelResponse.getComponent())
        # template
        self.labelTemplate = JLabel("Template")
        self.comboTemplate = JComboBox()

        # TODO: Populate this from outside using a config file from the
        # constructor? or perhaps the extension config
        self.comboSeverity = JComboBox(
            ["Critical", "High", "Medium", "Low", "Info"])
        self.comboSeverity.setSelectedIndex(-1)

        # add componentlistener
        dlgListener = DialogListener(self)
        self.addComponentListener(dlgListener)

        if issue is None:
            issue = self.defaultIssue
        # load the issue into the edit dialog.
        self.loadPanel(issue)

        # "here be dragons" GUI code
        layout = GroupLayout(self.getContentPane())
        self.getContentPane().setLayout(layout)
        layout.setHorizontalGroup(
            layout.createParallelGroup(GroupLayout.Alignment.CENTER).addGroup(
                layout.createSequentialGroup().addGroup(
                    layout.createParallelGroup(GroupLayout.Alignment.CENTER).
                    addGroup(layout.createSequentialGroup().addContainerGap(
                    ).addGroup(layout.createParallelGroup().addGroup(
                        layout.createSequentialGroup().addGroup(
                            layout.createParallelGroup().addComponent(
                                self.labelTemplate).addComponent(
                                    self.labelHost).
                            addComponent(self.labelName)).addPreferredGap(
                                LayoutStyle.ComponentPlacement.UNRELATED).
                        addGroup(layout.createParallelGroup().addGroup(
                            layout.createSequentialGroup().addComponent(
                                self.comboTemplate)
                        ).addGroup(layout.createSequentialGroup().addComponent(
                            self.textHost, GroupLayout.PREFERRED_SIZE, 212,
                            GroupLayout.PREFERRED_SIZE).addPreferredGap(
                                LayoutStyle.ComponentPlacement.UNRELATED
                            ).addComponent(self.labelPath).addPreferredGap(
                                LayoutStyle.ComponentPlacement.RELATED
                            ).addComponent(
                                self.textPath, GroupLayout.PREFERRED_SIZE,
                                GroupLayout.DEFAULT_SIZE, 800
                            )).addGroup(
                                GroupLayout.Alignment.TRAILING,
                                layout.createSequentialGroup().
                                addComponent(self.textName).addPreferredGap(
                                    LayoutStyle.ComponentPlacement.UNRELATED).
                                addComponent(
                                    self.labelSeverity).addPreferredGap(
                                        LayoutStyle.ComponentPlacement.
                                        UNRELATED).addComponent(
                                            self.comboSeverity,
                                            GroupLayout.PREFERRED_SIZE, 182,
                                            GroupLayout.PREFERRED_SIZE)))
                    ).addComponent(self.tabIssue))).addGroup(
                        layout.createSequentialGroup().addComponent(
                            self.buttonSave, GroupLayout.PREFERRED_SIZE,
                            GroupLayout.PREFERRED_SIZE,
                            GroupLayout.PREFERRED_SIZE).addComponent(
                                self.buttonReset, GroupLayout.PREFERRED_SIZE,
                                GroupLayout.PREFERRED_SIZE,
                                GroupLayout.PREFERRED_SIZE).addComponent(
                                    self.buttonCancel,
                                    GroupLayout.PREFERRED_SIZE,
                                    GroupLayout.PREFERRED_SIZE, GroupLayout.
                                    PREFERRED_SIZE))).addContainerGap()))

        # link size of buttons together
        from javax.swing import SwingConstants
        layout.linkSize(SwingConstants.HORIZONTAL,
                        [self.buttonCancel, self.buttonSave, self.buttonReset])

        layout.setVerticalGroup(layout.createParallelGroup().addGroup(
            GroupLayout.Alignment.TRAILING,
            layout.createSequentialGroup().addContainerGap().addGroup(
                layout.createParallelGroup(
                    GroupLayout.Alignment.BASELINE).addComponent(
                        self.labelName).addComponent(
                            self.textName, GroupLayout.PREFERRED_SIZE,
                            GroupLayout.DEFAULT_SIZE,
                            GroupLayout.PREFERRED_SIZE).addComponent(
                                self.labelSeverity).addComponent(
                                    self.comboSeverity,
                                    GroupLayout.PREFERRED_SIZE,
                                    GroupLayout.DEFAULT_SIZE,
                                    GroupLayout.PREFERRED_SIZE)).
            addPreferredGap(LayoutStyle.ComponentPlacement.RELATED).addGroup(
                layout.createParallelGroup(
                    GroupLayout.Alignment.BASELINE).addComponent(
                        self.textHost, GroupLayout.PREFERRED_SIZE,
                        GroupLayout.DEFAULT_SIZE,
                        GroupLayout.PREFERRED_SIZE).addComponent(
                            self.labelPath).addComponent(self.textPath).
                addComponent(self.labelHost)).addGroup(
                    layout.createParallelGroup(
                        GroupLayout.Alignment.BASELINE).addComponent(
                            self.comboTemplate, GroupLayout.PREFERRED_SIZE,
                            GroupLayout.DEFAULT_SIZE,
                            GroupLayout.PREFERRED_SIZE).addComponent(
                                self.labelTemplate)).addPreferredGap(
                                    LayoutStyle.ComponentPlacement.RELATED).
            addComponent(self.tabIssue).addPreferredGap(
                LayoutStyle.ComponentPlacement.RELATED).addGroup(
                    layout.createParallelGroup().addComponent(
                        self.buttonSave).addComponent(
                            self.buttonReset).addComponent(
                                self.buttonCancel)).addContainerGap()))
        # end of converted code from NetBeans

        # set the template label and combobox to invisible
        self.labelTemplate.setVisible(False)
        self.comboTemplate.setVisible(False)

    def display(self, parent):
        """packs and shows the frame."""
        self.pack()
        # setlocation must be AFTER pack
        # source: https://stackoverflow.com/a/22615038
        self.dlgParent = parent
        self.setLocationRelativeTo(self.dlgParent.panel)
        # self.show()
        self.setVisible(True)

    def loadTemplate(self):
        """Reads the template file and populates the combobox for NewIssueDialog.
        """
        templateFile = "data\\templates-cwe-1200.json"
        fi = open(templateFile, "r")
        from Utils import templateToIssue
        import json
        templateIssues = json.load(fi, object_hook=templateToIssue)
        self.templateIssues = templateIssues
        # templateNames = [t.name for t in self.templateIssues]
        for t in self.templateIssues:
            self.comboTemplate.addItem(t)
class BurpExtender(IBurpExtender, ISessionHandlingAction, ITab,
                   IContextMenuFactory, IContextMenuInvocation, ActionListener,
                   ITextEditor):

    #
    # implement IBurpExtender
    #

    def registerExtenderCallbacks(self, callbacks):
        # save the helpers for later
        self.helpers = callbacks.getHelpers()

        # set our extension name
        callbacks.setExtensionName("Custom Request Handler")
        callbacks.registerSessionHandlingAction(self)
        callbacks.registerContextMenuFactory(self)
        self._text_editor = callbacks.createTextEditor()
        self._text_editor.setEditable(False)

        #How much loaded the table row
        self.current_column_id = 0

        #GUI
        self._split_main = JSplitPane(JSplitPane.VERTICAL_SPLIT)
        self._split_top = JSplitPane(JSplitPane.HORIZONTAL_SPLIT)
        self._split_top.setPreferredSize(Dimension(100, 50))
        self._split_top.setDividerLocation(700)
        self._split_center = JSplitPane(JSplitPane.VERTICAL_SPLIT)

        boxVertical = swing.Box.createVerticalBox()
        box_top = swing.Box.createHorizontalBox()
        boxHorizontal = swing.Box.createHorizontalBox()
        buttonHorizontal = swing.Box.createHorizontalBox()
        boxVertical.add(boxHorizontal)

        box_regex = swing.Box.createVerticalBox()
        border = BorderFactory.createTitledBorder(LineBorder(Color.BLACK),
                                                  "Extract target strings",
                                                  TitledBorder.LEFT,
                                                  TitledBorder.TOP)
        box_regex.setBorder(border)

        self._add_btn = JButton("Add")
        self._add_btn.addActionListener(self)
        self._remove_btn = JButton("Remove")
        self._remove_btn.addActionListener(self)

        items = [
            'JSON',
            'Header',
        ]
        self._dropdown = JComboBox(items)
        type_panel = JPanel(FlowLayout(FlowLayout.LEADING))
        type_panel.add(JLabel('Type:'))
        type_panel.add(self._dropdown)

        self._jLabel_param = JLabel("Name:")
        self._param_error = JLabel("Name is required")

        self._param_error.setVisible(False)
        self._param_error.setFont(Font(Font.MONOSPACED, Font.ITALIC, 12))
        self._param_error.setForeground(Color.red)

        regex_checkbox = JPanel(FlowLayout(FlowLayout.LEADING))
        self._is_use_regex = JCheckBox("Extract from regex group")
        regex_checkbox.add(self._is_use_regex)
        self._jTextIn_param = JTextField(20)
        self._jLabel_regex = JLabel("Regex:")
        self._jTextIn_regex = JTextField(20)
        self._regex_error = JLabel("No group defined")
        self._regex_error.setVisible(False)
        self._regex_error.setFont(Font(Font.MONOSPACED, Font.ITALIC, 12))
        self._regex_error.setForeground(Color.red)

        self._param_panel = JPanel(FlowLayout(FlowLayout.LEADING))
        self._param_panel.add(self._jLabel_param)
        self._param_panel.add(self._jTextIn_param)
        self._param_panel.add(self._param_error)

        self._regex_panel = JPanel(FlowLayout(FlowLayout.LEADING))
        self._regex_panel.add(self._jLabel_regex)
        self._regex_panel.add(self._jTextIn_regex)
        self._regex_panel.add(self._regex_error)
        button_panel = JPanel(FlowLayout(FlowLayout.LEADING))
        #padding
        button_panel.add(JPanel())
        button_panel.add(JPanel())
        button_panel.add(JPanel())
        button_panel.add(self._add_btn)
        button_panel.add(self._remove_btn)
        box_regex.add(type_panel)
        box_regex.add(self._param_panel)
        box_regex.add(regex_checkbox)
        box_regex.add(self._regex_panel)
        buttonHorizontal.add(button_panel)
        box_regex.add(buttonHorizontal)
        boxVertical.add(box_regex)
        box_top.add(boxVertical)

        box_file = swing.Box.createHorizontalBox()
        checkbox_panel = JPanel(FlowLayout(FlowLayout.LEADING))
        border = BorderFactory.createTitledBorder(
            LineBorder(Color.BLACK), 'Payload Sets [Simple list]',
            TitledBorder.LEFT, TitledBorder.TOP)
        box_file.setBorder(border)

        box_param = swing.Box.createVerticalBox()
        box_param.add(checkbox_panel)

        file_column_names = [
            "Type",
            "Name",
            "Payload",
        ]
        data = []
        self.file_table_model = DefaultTableModel(data, file_column_names)
        self.file_table = JTable(self.file_table_model)
        self.file_table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF)

        column_model = self.file_table.getColumnModel()
        for count in xrange(column_model.getColumnCount()):
            column = column_model.getColumn(count)
            column.setPreferredWidth(160)

        self.file_table.preferredScrollableViewportSize = Dimension(500, 70)
        self.file_table.setFillsViewportHeight(True)

        panel_dropdown = JPanel(FlowLayout(FlowLayout.LEADING))
        self._file_dropdown = JComboBox(items)
        panel_dropdown.add(JLabel('Type:'))
        panel_dropdown.add(self._file_dropdown)
        box_param.add(panel_dropdown)
        box_param.add(JScrollPane(self.file_table))
        callbacks.customizeUiComponent(self.file_table)

        file_param_panel = JPanel(FlowLayout(FlowLayout.LEADING))

        self._file_param = JLabel("Name:")
        self._file_param_text = JTextField(20)

        file_param_panel.add(self._file_param)
        file_param_panel.add(self._file_param_text)
        self._error_message = JLabel("Name is required")
        self._error_message.setVisible(False)
        self._error_message.setFont(Font(Font.MONOSPACED, Font.ITALIC, 12))
        self._error_message.setForeground(Color.red)
        file_param_panel.add(self._error_message)
        box_param.add(file_param_panel)

        box_button_file = swing.Box.createVerticalBox()
        self._file_load_btn = JButton("Load")

        self._file_clear_btn = JButton("Clear")
        self._file_clear_btn.addActionListener(self)
        self._file_load_btn.addActionListener(self)
        box_button_file.add(self._file_load_btn)
        box_button_file.add(self._file_clear_btn)
        box_file.add(box_button_file)
        box_file.add(box_param)
        boxVertical.add(box_file)

        regex_column_names = [
            "Type",
            "Name",
            "Regex",
            "Start at offset",
            "End at offset",
        ]
        #clear target.json
        with open("target.json", "w") as f:
            pass
        data = []
        self.target_table_model = DefaultTableModel(data, regex_column_names)
        self.target_table = JTable(self.target_table_model)
        self.target_table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF)
        column_model = self.target_table.getColumnModel()
        for count in xrange(column_model.getColumnCount()):
            column = column_model.getColumn(count)
            column.setPreferredWidth(100)

        self.target_table.preferredScrollableViewportSize = Dimension(500, 70)
        self.target_table.setFillsViewportHeight(True)
        callbacks.customizeUiComponent(self.target_table)
        callbacks.customizeUiComponent(boxVertical)
        table_panel = swing.Box.createVerticalBox()
        table_panel.add(JScrollPane(self.target_table))
        box_top.add(table_panel)

        self._jScrollPaneOut = JScrollPane()
        #self._split_main.setBottomComponent(self._jScrollPaneOut)
        self._split_main.setBottomComponent(self._text_editor.getComponent())
        self._split_main.setTopComponent(box_top)
        self._split_main.setDividerLocation(450)
        callbacks.customizeUiComponent(self._split_main)
        callbacks.addSuiteTab(self)
        return

    def getTabCaption(self):
        return "CRH"

    def getUiComponent(self):
        return self._split_main

    def createMenuItems(self, invocation):
        menu = []
        ctx = invocation.getInvocationContext()
        menu.append(
            swing.JMenuItem("Send to CRH",
                            None,
                            actionPerformed=lambda x, inv=invocation: self.
                            menu_action(inv)))
        return menu if menu else None

    #
    # Implementation of Menu Action
    #
    def menu_action(self, invocation):
        try:
            invMessage = invocation.getSelectedMessages()
            message = invMessage[0].getResponse()
            res_info = self.helpers.analyzeResponse(message)
            send_res = message.tostring()
            self._text_editor.setText(send_res)
        except:
            print('Failed to add data to CRH tab.')

    #
    # Implementation of event action
    #
    def actionPerformed(self, actionEvent):

        # onclick add button of extract from regex group
        if actionEvent.getSource() is self._add_btn:
            start, end = self._text_editor.getSelectionBounds()
            value = None
            regex = None
            item = self._dropdown.getSelectedItem()
            param = self._jTextIn_param.getText()

            if len(param) is 0:
                self._param_error.setVisible(True)
                return
            self._param_error.setVisible(False)
            is_selected = self._is_use_regex.isSelected()
            if is_selected:
                start = None
                end = None
                regex = self._jTextIn_regex.getText()
                if len(regex) is 0:
                    self._regex_error.setVisible(True)
                    return

                req = self._text_editor.getText()
                try:
                    pattern = re.compile(regex)
                    match = pattern.search(req)
                    value = match.group(1) if match else None
                    if value is None:
                        raise IndexError
                except IndexError:
                    self._regex_error.setVisible(True)
                    return
                self._regex_error.setVisible(False)

            data = [
                item,
                param,
                regex,
                start,
                end,
            ]
            self.target_table_model.addRow(data)

            with open("target.json", "r+") as f:
                try:
                    json_data = json.load(f)
                except ValueError:
                    json_data = dict()
                if is_selected:
                    data = {
                        param: [
                            item,
                            regex,
                        ]
                    }
                else:
                    data = {
                        param: [
                            item,
                            start,
                            end,
                        ]
                    }
                json_data.update(data)
                self.write_file(f, json.dumps(json_data))

        # onclick remove button of extract from regex group
        if actionEvent.getSource() is self._remove_btn:
            rowno = self.target_table.getSelectedRow()
            if rowno != -1:
                column_model = self.target_table.getColumnModel()
                param_name = self.target_table_model.getValueAt(rowno, 1)
                start = self.target_table_model.getValueAt(rowno, 3)

                self.target_table_model.removeRow(rowno)
                with open("target.json", 'r+') as f:
                    try:
                        json_data = json.load(f)
                    except ValueError:
                        json_data = dict()

                    for key, value in json_data.items():
                        if value[1] == start and key == param_name:
                            try:
                                del json_data[key]
                            except IndexError:
                                print('Error: {0}: No such json key.'.format(
                                    key))
                    self.write_file(f, json.dumps(json_data))

        # onclick load button of payload sets
        if actionEvent.getSource() is self._file_load_btn:
            #clear table
            self.remove_all(self.file_table_model)
            self.current_column_id = 0

            target_param = self._file_param_text.getText()
            item = self._file_dropdown.getSelectedItem()

            if len(target_param) == 0:
                self._error_message.setVisible(True)
                return
            self._error_message.setVisible(False)

            chooser = JFileChooser()
            chooser.showOpenDialog(actionEvent.getSource())
            file_path = chooser.getSelectedFile().getAbsolutePath()
            with open(file_path, 'r') as f:
                while True:
                    line = f.readline().strip()
                    if not line:
                        break
                    data = [
                        item,
                        target_param,
                        line,
                    ]
                    self.file_table_model.addRow(data)

            with open('target.json', 'r+') as f:
                try:
                    json_data = json.load(f)
                except ValueError:
                    json_data = dict()

                json_data.update({target_param: [
                    item,
                    'Set payload',
                ]})
                self.write_file(f, json.dumps(json_data))

        # onclick clear button of payload sets
        if actionEvent.getSource() is self._file_clear_btn:
            self.remove_all(self.file_table_model)

            self.current_column_id = 0

            with open("target.json", 'r+') as f:
                try:
                    json_data = json.load(f)
                except:
                    json_data = dict()

                for key, value in json_data.items():
                    if isinstance(value[1], unicode):
                        if value[1].encode('utf-8') == 'Set payload':
                            try:
                                del json_data[key]
                            except IndexError:
                                print('Error: {0}: No such json key.'.format(
                                    key))
                self.write_file(f, json.dumps(json_data))

    #
    # Implementaion of ISessionHandlingAction
    #
    def getActionName(self):
        return "custom request handler"

    def performAction(self, current_request, macro_items):

        if len(macro_items) == 0:
            return

        # extract the response headers
        final_response = macro_items[len(macro_items) - 1].getResponse()
        if final_response is None:
            return

        req = self.helpers.analyzeRequest(current_request)

        try:
            with open('target.json', 'r') as f:
                read_data = f.read()
                self.read_data = json.loads(read_data)
        except ValueError:
            sys.stderr.write('Error: json.loads()')
            return

        for key, value in self.read_data.items():
            if value[0] == 'JSON':
                self.set_json_parameter(current_request, final_response, key,
                                        value)
            elif value[0] == 'Header':
                self.set_header(current_request, final_response, key, value)

    def set_json_parameter(self, current_request, final_response, key, value):
        req = self.helpers.analyzeRequest(current_request)

        if IRequestInfo.CONTENT_TYPE_JSON != req.getContentType():
            return False

        body = current_request.getRequest()[req.getBodyOffset():].tostring()
        json_data = json.loads(body, object_pairs_hook=collections.OrderedDict)

        target_keys = filter(lambda x: x == key, json_data.keys())
        if not target_keys:
            return

        req_data = json_data
        column_model = self.file_table.getColumnModel()
        row_count = self.file_table_model.getRowCount()
        for key in target_keys:
            if value[-1] == 'Set payload':
                if row_count > self.current_column_id:
                    req_value = self.file_table_model.getValueAt(
                        self.current_column_id, 2)
                    self.current_column_id += 1
            else:
                # No selected regex
                if len(value) > 2:
                    start, end = value[1:]
                    req_value = final_response[start:end].tostring()
                else:
                    regex = value[1]
                    match = re.search(regex, final_response.tostring())
                    req_value = match.group(1) if match else None

            req_data[key] = req_value

        req = current_request.getRequest()
        json_data_start = self.helpers.indexOf(req, bytearray(body), False, 0,
                                               len(req))

        # glue together header + customized json of request
        current_request.setRequest(
            req[0:json_data_start] +
            self.helpers.stringToBytes(json.dumps(req_data)))

    def set_header(self, current_request, final_response, key, value):
        req = self.helpers.analyzeRequest(current_request)
        headers = req.getHeaders()
        target_keys = []
        for header in headers:
            if header.startswith(key):
                target_keys += [key]

        if not target_keys:
            return

        column_model = self.file_table.getColumnModel()
        row_count = self.file_table_model.getRowCount()
        req = current_request.getRequest()

        for key in target_keys:
            if value[-1] == 'Set payload':
                if row_count > self.current_column_id:
                    req_value = self.file_table_model.getValueAt(
                        self.current_column_id, 2)
                    self.current_column_id += 1
            else:
                # No selected regex
                if len(value) > 2:
                    start, end = value[1:]
                    req_value = final_response[start:end].tostring()
                else:
                    regex = value[1]
                    match = re.search(regex, final_response.string())
                    req_value = match.group(1) if match else None

            key_start = self.helpers.indexOf(req,
                                             bytearray(key.encode('utf-8')),
                                             False, 0, len(req))
            key_end = self.helpers.indexOf(req, bytearray('\r\n'), False,
                                           key_start, len(req))

            keylen = len(key)

        # glue together first line + customized hedaer + rest of request
        current_request.setRequest(
            req[0:key_start] +
            self.helpers.stringToBytes("%s: %s" %
                                       (key.encode('utf-8'), req_value)) +
            req[key_end:])

    #
    # Implementation of function for Remove all for specific table data
    #
    def remove_all(self, model):
        count = model.getRowCount()
        for i in xrange(count):
            model.removeRow(0)

    #
    # Implementaion of function for write data for specific file
    #
    def write_file(self, f, data):
        f.seek(0)
        f.write(data)
        f.truncate()
        return
Exemplo n.º 6
0
class QatDialog(ToggleDialog):
    """ToggleDialog for error type selection and buttons for reviewing
       errors in sequence
    """
    def __init__(self, name, iconName, tooltip, shortcut, height, app):
        ToggleDialog.__init__(self, name, iconName, tooltip, shortcut, height)
        self.app = app
        tools = app.tools

        #Main panel of the dialog
        mainPnl = JPanel(BorderLayout())
        mainPnl.setBorder(BorderFactory.createEmptyBorder(0, 1, 1, 1))

        ### First tab: errors selection and download ###########################
        #ComboBox with tools names
        self.toolsComboModel = DefaultComboBoxModel()
        for tool in tools:
            self.add_data_to_models(tool)
        self.toolsCombo = JComboBox(self.toolsComboModel,
                                    actionListener=ToolsComboListener(app))
        renderer = ToolsComboRenderer(self.app)
        renderer.setPreferredSize(Dimension(20, 20))
        self.toolsCombo.setRenderer(renderer)
        self.toolsCombo.setToolTipText(
            app.strings.getString("Select_a_quality_assurance_tool"))

        #ComboBox with categories names ("views"), of the selected tool
        self.viewsCombo = JComboBox(actionListener=ViewsComboListener(app))
        self.viewsCombo.setToolTipText(
            app.strings.getString("Select_a_category_of_error"))

        #Popup for checks table
        self.checkPopup = JPopupMenu()
        #add favourite check
        self.menuItemAdd = JMenuItem(
            self.app.strings.getString("Add_to_favourites"))
        self.menuItemAdd.setIcon(
            ImageIcon(
                File.separator.join([
                    self.app.SCRIPTDIR, "tools", "data", "Favourites", "icons",
                    "tool_16.png"
                ])))
        self.menuItemAdd.addActionListener(PopupActionListener(self.app))
        self.checkPopup.add(self.menuItemAdd)
        #remove favourite check
        self.menuItemRemove = JMenuItem(
            self.app.strings.getString("Remove_from_favourites"))
        self.menuItemRemove.setIcon(
            ImageIcon(
                File.separator.join([
                    self.app.SCRIPTDIR, "tools", "data", "Favourites", "icons",
                    "black_tool_16.png"
                ])))
        self.menuItemRemove.addActionListener(PopupActionListener(self.app))
        self.checkPopup.add(self.menuItemRemove)
        #Help link for selected check
        self.menuItemHelp = JMenuItem(self.app.strings.getString("check_help"))
        self.menuItemHelp.setIcon(
            ImageIcon(
                File.separator.join(
                    [self.app.SCRIPTDIR, "images", "icons", "info_16.png"])))
        self.checkPopup.add(self.menuItemHelp)
        self.menuItemHelp.addActionListener(PopupActionListener(self.app))

        #Table with checks of selected tool and view
        self.checksTable = JTable()
        self.iconrenderer = IconRenderer()
        self.iconrenderer.setHorizontalAlignment(JLabel.CENTER)
        scrollPane = JScrollPane(self.checksTable)
        self.checksTable.setFillsViewportHeight(True)

        tableSelectionModel = self.checksTable.getSelectionModel()
        tableSelectionModel.addListSelectionListener(ChecksTableListener(app))

        self.checksTable.addMouseListener(
            ChecksTableClickListener(app, self.checkPopup, self.checksTable))

        #Favourite area status indicator
        self.favAreaIndicator = JLabel()
        self.update_favourite_zone_indicator()
        self.favAreaIndicator.addMouseListener(FavAreaIndicatorListener(app))

        #label with OSM id of the object currently edited and number of
        #errors still to review
        self.checksTextFld = JTextField("",
                                        editable=0,
                                        border=None,
                                        background=None)

        #checks buttons
        btnsIconsDir = File.separator.join([app.SCRIPTDIR, "images", "icons"])
        downloadIcon = ImageIcon(
            File.separator.join([btnsIconsDir, "download.png"]))
        self.downloadBtn = JButton(downloadIcon,
                                   actionPerformed=app.on_downloadBtn_clicked,
                                   enabled=0)
        startIcon = ImageIcon(
            File.separator.join([btnsIconsDir, "start_fixing.png"]))
        self.startBtn = JButton(startIcon,
                                actionPerformed=app.on_startBtn_clicked,
                                enabled=0)
        self.downloadBtn.setToolTipText(
            app.strings.getString("Download_errors_in_this_area"))
        self.startBtn.setToolTipText(
            app.strings.getString("Start_fixing_the_selected_errors"))

        #tab layout
        panel1 = JPanel(BorderLayout(0, 1))

        comboboxesPnl = JPanel(GridLayout(0, 2, 5, 0))
        comboboxesPnl.add(self.toolsCombo)
        comboboxesPnl.add(self.viewsCombo)

        checksPnl = JPanel(BorderLayout(0, 1))
        checksPnl.add(scrollPane, BorderLayout.CENTER)
        self.statsPanel = JPanel(BorderLayout(4, 0))
        self.statsPanel_def_color = self.statsPanel.getBackground()
        self.statsPanel.add(self.checksTextFld, BorderLayout.CENTER)
        self.statsPanel.add(self.favAreaIndicator, BorderLayout.LINE_START)
        checksPnl.add(self.statsPanel, BorderLayout.PAGE_END)

        checksButtonsPnl = JPanel(GridLayout(0, 2, 0, 0))
        checksButtonsPnl.add(self.downloadBtn)
        checksButtonsPnl.add(self.startBtn)

        panel1.add(comboboxesPnl, BorderLayout.PAGE_START)
        panel1.add(checksPnl, BorderLayout.CENTER)
        panel1.add(checksButtonsPnl, BorderLayout.PAGE_END)

        ### Second tab: errors fixing ##########################################
        #label with error stats
        self.errorTextFld = JTextField("",
                                       editable=0,
                                       border=None,
                                       background=None)
        #label with current error description
        self.errorDesc = JLabel("")
        self.errorDesc.setAlignmentX(0.5)

        #error buttons
        errorInfoBtnIcon = ImageProvider.get("info")
        self.errorInfoBtn = JButton(
            errorInfoBtnIcon,
            actionPerformed=app.on_errorInfoBtn_clicked,
            enabled=0)
        notErrorIcon = ImageIcon(
            File.separator.join([btnsIconsDir, "not_error.png"]))
        self.notErrorBtn = JButton(
            notErrorIcon,
            actionPerformed=app.on_falsePositiveBtn_clicked,
            enabled=0)
        ignoreIcon = ImageIcon(File.separator.join([btnsIconsDir, "skip.png"]))
        self.ignoreBtn = JButton(ignoreIcon,
                                 actionPerformed=app.on_ignoreBtn_clicked,
                                 enabled=0)
        correctedIcon = ImageIcon(
            File.separator.join([btnsIconsDir, "corrected.png"]))
        self.correctedBtn = JButton(
            correctedIcon,
            actionPerformed=app.on_correctedBtn_clicked,
            enabled=0)
        nextIcon = ImageIcon(File.separator.join([btnsIconsDir, "next.png"]))
        self.nextBtn = JButton(nextIcon,
                               actionPerformed=app.on_nextBtn_clicked,
                               enabled=0)
        #self.nextBtn.setMnemonic(KeyEvent.VK_RIGHT)
        self.errorInfoBtn.setToolTipText(
            app.strings.getString("open_error_info_dialog"))
        self.notErrorBtn.setToolTipText(
            app.strings.getString("flag_false_positive"))
        self.ignoreBtn.setToolTipText(
            app.strings.getString("Skip_and_don't_show_me_this_error_again"))
        self.correctedBtn.setToolTipText(
            app.strings.getString("flag_corrected_error"))
        self.nextBtn.setToolTipText(app.strings.getString("Go_to_next_error"))

        #tab layout
        self.panel2 = JPanel(BorderLayout())

        self.panel2.add(self.errorTextFld, BorderLayout.PAGE_START)
        self.panel2.add(self.errorDesc, BorderLayout.CENTER)

        errorButtonsPanel = JPanel(GridLayout(0, 5, 0, 0))
        errorButtonsPanel.add(self.errorInfoBtn)
        errorButtonsPanel.add(self.notErrorBtn)
        errorButtonsPanel.add(self.ignoreBtn)
        errorButtonsPanel.add(self.correctedBtn)
        errorButtonsPanel.add(self.nextBtn)
        self.panel2.add(errorButtonsPanel, BorderLayout.PAGE_END)

        #Layout
        self.tabbedPane = JTabbedPane()
        self.tabbedPane.addTab(self.app.strings.getString("Download"), None,
                               panel1,
                               self.app.strings.getString("download_tab"))
        mainPnl.add(self.tabbedPane, BorderLayout.CENTER)
        self.createLayout(mainPnl, False, None)

    def add_data_to_models(self, tool):
        """Add data of a tool to the models of the dialog components
        """
        #tools combobox model
        if tool == self.app.favouritesTool:
            self.toolsComboModel.addElement(JSeparator())
        self.toolsComboModel.addElement(tool)

        #views combobox model
        tool.viewsComboModel = DefaultComboBoxModel()
        for view in tool.views:
            tool.viewsComboModel.addElement(view.title)

        #checks table, one TableModel for each view, of each tool
        columns = [
            "",
            self.app.strings.getString("Check"),
            self.app.strings.getString("Errors")
        ]
        for view in tool.views:
            tableRows = []
            for check in view.checks:
                if check.icon is not None:
                    icon = check.icon
                else:
                    icon = ""
                errorsNumber = ""
                tableRows.append([icon, check.title, errorsNumber])
            view.tableModel = MyTableModel(tableRows, columns)

    def update_favourite_zone_indicator(self):
        #icon
        if self.app.favZone is not None:
            self.favAreaIndicator.setIcon(self.app.favZone.icon)
            #tooltip
            messageArguments = array([self.app.favZone.name], String)
            formatter = MessageFormat("")
            formatter.applyPattern(
                self.app.strings.getString("favAreaIndicator_tooltip"))
            msg = formatter.format(messageArguments)
            self.favAreaIndicator.setToolTipText(msg)
            #status
            self.favAreaIndicator.setVisible(self.app.favouriteZoneStatus)

    def set_checksTextFld_color(self, color):
        """Change color of textField under checksTable
        """
        colors = {
            "white": (255, 255, 255),
            "black": (0, 0, 0),
            "green": (100, 200, 0),
            "red": (200, 0, 0)
        }
        if color == "default":
            self.statsPanel.background = self.statsPanel_def_color
            self.checksTextFld.foreground = colors["black"]
        else:
            self.statsPanel.background = colors[color]
            self.checksTextFld.foreground = colors["white"]

    def change_selection(self, source):
        """Change comboboxes and checks table selections after a
           selection has been made by the user
        """
        if source in ("menu", "layer", "add favourite"):
            self.app.selectionChangedFromMenuOrLayer = True
            self.toolsCombo.setSelectedItem(self.app.selectedTool)
            self.viewsCombo.setModel(self.app.selectedTool.viewsComboModel)
            self.viewsCombo.setSelectedItem(self.app.selectedView.title)

            self.checksTable.setModel(self.app.selectedTableModel)
            self.refresh_checksTable_columns_geometries()
            for i, c in enumerate(self.app.selectedView.checks):
                if c == self.app.selectedChecks[0]:
                    break
            self.checksTable.setRowSelectionInterval(i, i)
            self.app.selectionChangedFromMenuOrLayer = False
        else:
            self.app.selectionChangedFromMenuOrLayer = False
            if source == "toolsCombo":
                self.viewsCombo.setModel(self.app.selectedTool.viewsComboModel)
                self.viewsCombo.setSelectedIndex(0)
            elif source == "viewsCombo":
                self.checksTable.setModel(self.app.selectedTableModel)
                self.refresh_checksTable_columns_geometries()
                if self.app.selectedView.checks != []:  # favourite checks may be none
                    self.checksTable.setRowSelectionInterval(0, 0)

    def refresh_checksTable_columns_geometries(self):
        self.checksTable.getColumnModel().getColumn(0).setCellRenderer(
            self.iconrenderer)
        self.checksTable.getColumnModel().getColumn(0).setMaxWidth(25)
        self.checksTable.getColumnModel().getColumn(2).setMaxWidth(60)

    def activate_error_tab(self, status):
        if status:
            if self.tabbedPane.getTabCount() == 1:
                self.tabbedPane.addTab(self.app.strings.getString("Fix"), None,
                                       self.panel2,
                                       self.app.strings.getString("fix_tab"))
        else:
            if self.tabbedPane.getTabCount() == 2:
                self.tabbedPane.remove(1)

    def update_checks_buttons(self):
        """This method sets the status of downloadBtn and startBtn
        """
        #none check selected
        if len(self.app.selectedChecks) == 0:
            self.downloadBtn.setEnabled(False)
            self.startBtn.setEnabled(False)
        else:
            #some check selected
            self.downloadBtn.setEnabled(True)
            if len(self.app.selectedChecks) > 1:
                self.startBtn.setEnabled(False)
            else:
                #only one check is selected
                self.app.errors = self.app.selectedChecks[0].errors
                if self.app.errors is None or len(self.app.errors) == 0:
                    #errors file has not been downloaded and parsed yet
                    self.startBtn.setEnabled(False)
                else:
                    #errors file has been downloaded and parsed
                    if self.app.selectedChecks[0].toDo == 0:
                        #all errors have been corrected
                        self.startBtn.setEnabled(False)
                    else:
                        self.startBtn.setEnabled(True)
                        #self.nextBtn.setEnabled(True)

    def update_error_buttons(self, mode):
        """This method sets the status of:
           ignoreBtn, falsePositiveBtn, correctedBtn, nextBtn
        """
        if mode == "new error":
            status = True
        else:
            status = False
        if self.app.selectedChecks[0].tool.fixedFeedbackMode is None:
            self.correctedBtn.setEnabled(False)
        else:
            self.correctedBtn.setEnabled(status)
        if self.app.selectedChecks[0].tool.falseFeedbackMode is None:
            self.notErrorBtn.setEnabled(False)
        else:
            self.notErrorBtn.setEnabled(status)
        self.errorInfoBtn.setEnabled(status)
        self.ignoreBtn.setEnabled(status)

        if mode in ("reset", "review end"):
            self.nextBtn.setEnabled(False)
        elif mode in ("errors downloaded", "show stats", "new error"):
            self.nextBtn.setEnabled(True)

    def update_text_fields(self, mode, errorInfo=""):
        """This method updates the text in:
           checksTextFld, errorDesc, errorTextFld
        """
        self.errorDesc.text = ""
        if mode == "review end":
            cheksTextColor = "green"
            checksText = self.app.strings.getString("All_errors_reviewed.")
            errorText = self.app.strings.getString("All_errors_reviewed.")
        elif mode == "reset":
            cheksTextColor = "default"
            checksText = ""
            errorText = ""
        elif mode == "show stats":
            cheksTextColor = "default"
            checksText = "%s %d / %s" % (
                self.app.strings.getString("to_do"),
                self.app.selectedChecks[0].toDo,
                len(self.app.selectedChecks[0].errors))
            #print "checks text", checksText
            errorText = "%s%s %d / %s" % (
                errorInfo, self.app.strings.getString("to_do"),
                self.app.selectedChecks[0].toDo,
                len(self.app.selectedChecks[0].errors))
            #print "error text", errorText
            if self.app.selectedError is not None and self.app.selectedError.desc != "":
                self.errorDesc.text = "<html>%s</html>" % self.app.selectedError.desc

        self.set_checksTextFld_color(cheksTextColor)
        self.checksTextFld.text = checksText
        self.errorTextFld.text = errorText
        self.update_statsPanel_status()

    def update_statsPanel_status(self):
        if self.checksTextFld.text == "" and not self.app.favouriteZoneStatus:
            self.statsPanel.setVisible(False)
        else:
            self.statsPanel.setVisible(True)