from burp import (IBurpExtender, ITab, IContextMenuFactory, IContextMenuInvocation, 
IHttpService, IParameter, IMessageEditorController, IHttpRequestResponse, IProxyListener,
IMessageEditorTabFactory, IMessageEditorTab, IExtensionStateListener )

from java.awt import (BorderLayout, FlowLayout , Dimension, Font, Color, Cursor)

from javax.swing import (JMenuItem, JTable, JButton, JTextField, GroupLayout, JTabbedPane, JTextPane, RowFilter
,JScrollPane, JSplitPane, JLabel, JPopupMenu, JComboBox, DefaultCellEditor, JToggleButton, JTextArea, DefaultComboBoxModel
,JPanel, JFileChooser, JSeparator, Box )

from javax.swing.event import ListSelectionListener

from javax.swing.table import ( DefaultTableModel, AbstractTableModel, TableRowSorter ,TableCellEditor)
from javax.swing.SwingConstants import VERTICAL
from java.lang import Short
import javax.swing.Box
from javax.swing.filechooser import FileNameExtensionFilter
from urlparse import urlparse
import time, csv, sys, os, base64, zlib
from threading import Lock


from pentestmapper.autolog import Autologclas  
from pentestmapper.APIMapper import LogEntry, Table, CustomTableModel
from pentestmapper.autosave import Autosaveclas 

sys.path.append("./lib/swingx-all-1.6.4.jar")
from org.jdesktop.swingx.autocomplete import AutoCompleteDecorator



csv.field_size_limit(sys.maxsize)




# Creating Burp Extend Class
class BurpExtender(IBurpExtender, ITab, IContextMenuFactory, AbstractTableModel, IMessageEditorController, IExtensionStateListener):
    

    def registerExtenderCallbacks(self, callbacks):
        self.callbacks = callbacks
        self.helpers = callbacks.getHelpers()

        # Allowing debugging
        sys.stdout = callbacks.getStdout()
        sys.stderr = callbacks.getStderr()

        # Informing Burp suite the name of the extension
        callbacks.setExtensionName("Pentest Mapper")

        #adding extension state listner if extenion loaded on unloaded 
        callbacks.registerExtensionStateListener(self)
        

        # Creating a output after loading
        callbacks.printOutput("Author: Sourav Kalal Aka AnoF")
        callbacks.printOutput("Version: 1.7.3")
        callbacks.printOutput("https://github.com/Anof-cyber/Pentest-Mapper")

        callbacks.registerContextMenuFactory(self)

        self.tab = JPanel(BorderLayout())
        self.tabbedPane = JTabbedPane()
        self.tab.add("Center", self.tabbedPane)

        self._log = list()
        self._vuln = list()
        self._lock = Lock()

        # Creating Another Tab in the extension tab
        # Creating the First tab named as CheckList
        self.firstTab = JPanel()
        self.firstTab.layout = BorderLayout()
        self.tabbedPane.addTab("CheckList", self.firstTab)
        callbacks.addSuiteTab(self)

        # Creating a Import button in CheckList Tab
        self.ChecklistbuttonPanel = JPanel()
        self.searchchecklist = JTextField('', 15)
        self.ChecklistbuttonPanel.add(self.searchchecklist)
        self.ChecklistbuttonPanel.add(JButton("Search", actionPerformed=self.searchinchecklist))

        
        # adding the import button with onclick action which refers to the function below
        self.ChecklistbuttonPanel.add(JButton(
            "Import CheckList", actionPerformed=self.importchecklist))
        self.createchecklistbutton = JButton("Create CheckList", actionPerformed=self.createtestcases)
        #self.ChecklistbuttonPanel.add(JButton("Create CheckList", actionPerformed=self.createtestcases))
        self.ChecklistbuttonPanel.add(self.createchecklistbutton)
        self.firstTab.add(self.ChecklistbuttonPanel, BorderLayout.PAGE_START)


        # Creating a tab in CheckList tab which will show the data from the import checlist
        self.tablePanel = JPanel()
        self.colNames = ('Sr', 'Test-Cases')
        self.dataModel = CustomDefaultTableModelHosts(None, self.colNames)
        self.table = JTable(self.dataModel)
        self.table.getTableHeader().setReorderingAllowed(False)
        self.table.setAutoCreateRowSorter(True)
        self.scrollPane = JScrollPane(self.table)
        self.sorter = TableRowSorter(self.dataModel);
      
        self.table.setRowSorter(self.sorter)
        X_BASE2 = 200  # send to leff
        # 3rd one send to right
    
        self.scrollPane.getViewport().setView((self.table))
        self.firstTab.add(self.scrollPane, BorderLayout.CENTER)

        # Creating Second Tab
        self.secondTab = JPanel()
        self.secondTab.layout = BorderLayout()
        self.tabbedPane.addTab("API Mapper", self.secondTab)


        # creating UI for button and button in api mapper tab
        self.APIMapperButtonPanel = JPanel()
        self.searchapimapper = JTextField('', 15)
        self.APIMapperButtonPanel.add(self.searchapimapper)
        self.APIMapperButtonPanel.add(JButton("Search", actionPerformed=self.searchinapimapper))

        # adding the import button with onclick action which refers to the function below
        self.APIMapperButtonPanel.add(JButton(
            "Save Project", actionPerformed=self.savelogger))
        self.APIMapperButtonPanel.add(JButton(
            "Load Project", actionPerformed=self.importlogger))
        self.secondTab.add(self.APIMapperButtonPanel, BorderLayout.PAGE_START)


        # Creating a UI for table in api mapper tab
        self.tablePanel2 = JPanel()
    
        
        '''
        creating a menu which will be added with the table in api mapper for right click 
        also assigning a fumction to handle the event when click
        '''
        popupMenu = JPopupMenu()
        sendVulneraility = JMenuItem("Add to Vulnerabilities", actionPerformed=self.sendVulnItem)
        sendRepeaterItem = JMenuItem("Send request to Repeater", actionPerformed=self.sendRepeaterItem)
        deleterow = JMenuItem("Delete Row", actionPerformed=self.deleterow)
        popupMenu.add(sendVulneraility)
        popupMenu.add(sendRepeaterItem)
        popupMenu.add(deleterow)
        
        self.comboBox1 = JComboBox()
        self.comboBox1.addItem(None)
        self.comboBox1.addItem("Pending")
        self.comboBox1.addItem("In Progress")
        self.comboBox1.addItem("Completed")


        # creating a message editor from burp to show request 
        self.requestViewer = callbacks.createMessageEditor(None, True)
        self.responseViewer = callbacks.createMessageEditor(None, True)

        # creating a table with custom model for api mapper


        self.apimappertable = CustomTableModel(self)

        self.logTable = Table(self, self.apimappertable)
        

        # allowed colum size for api mapper tab/table
        self.logTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF)
        self.logTable.getTableHeader().setReorderingAllowed(False)
        self.logTable.getColumnModel().getColumn(0).setPreferredWidth(25)
        self.logTable.getColumnModel().getColumn(1).setPreferredWidth(400)
        self.logTable.getColumnModel().getColumn(2).setPreferredWidth(50)
        self.logTable.getColumnModel().getColumn(3).setPreferredWidth(750)
        self.logTable.getColumnModel().getColumn(4).setPreferredWidth(142)
        self.logTable.setRowSelectionAllowed(True)

        comboColumn1 = self.logTable.getColumnModel().getColumn(5)
        comboColumn1.setCellEditor(DefaultCellEditor(self.comboBox1))

        #adding a right click menu in the table in api mapper
        self.logTable.setComponentPopupMenu(popupMenu)



        # Creating a scroller for table in api mapper and also width hight for table
        self.scrollPane2 = JScrollPane(self.logTable)
        
        self.scrollPane2.getViewport().setView((self.logTable))
        self.sorter2 = TableRowSorter(self.apimappertable);
        self.logTable.setRowSorter(self.sorter2)

       
        # creating a save test case button and UI and a split pane
        self.CommentsSplitPane = JSplitPane(JSplitPane.VERTICAL_SPLIT);
        self.bottomviewpanel = JPanel()
        self.SaveTestCasePanel = JPanel(FlowLayout(FlowLayout.LEADING, 10, 10))
        self.SaveTestCasePanel.add(JButton(
            "Save TestCases", actionPerformed=self.SaveTestCases))
        

        #crearting a text box for test cases
        self.testcases = JTextPane()
        self.testcases.setContentType("text/plain");
        self.testcases.setEditable(True)
        penTesterCommentBoxScrollPane = JScrollPane(self.testcases)

        # creating a split in test cases to add button and text box
        self.CommentsSplitPane.setTopComponent(self.SaveTestCasePanel)
        self.CommentsSplitPane.setBottomComponent(penTesterCommentBoxScrollPane);
   
       

        
        
       
       #adding the tapped pane to create request and test cases 
        self.editor_view = JTabbedPane()
        self.editor_view.addTab("Request", self.requestViewer.getComponent())
        self.editor_view.addTab("Response", self.responseViewer.getComponent())
        self.editor_view.addTab('Test Cases', self.CommentsSplitPane)

        

        # creating a split in api mapper with split size
        spl = JSplitPane(JSplitPane.VERTICAL_SPLIT)


        # adding the UI for split pane in api mapper tab

       
        spl.setLeftComponent(self.scrollPane2)
        spl.setRightComponent(self.editor_view)

        # adding the spilt part to api mapper tab
        self.secondTab.add(spl)

        # addinG the burp Defalut UI customization for the api mapper tab
        self.callbacks.customizeUiComponent(spl)
        self.callbacks.customizeUiComponent(self.logTable)
        self.callbacks.customizeUiComponent(self.scrollPane2)
        self.callbacks.customizeUiComponent(self.editor_view)


        # creating a new tab 
        self.ThirdTab = JPanel()
        self.ThirdTab.layout = BorderLayout()
        self.tabbedPane.addTab("Vulnerabilities", self.ThirdTab)    


        # creating the button and button location and width in vulnerability tab
        self.VulnerabilityButtonPanel = JPanel()

        # Search For Vulnerability UI
        self.searchvulnerability = JTextField('', 15)
        self.VulnerabilityButtonPanel.add(self.searchvulnerability)
        self.VulnerabilityButtonPanel.add(JButton("Search", actionPerformed=self.searchinvulnerability))

        # adding the import button with onclick action which refers to the function below
        
        self.VulnerabilityButtonPanel.add(JButton(
            "Export Vulnerabilities", actionPerformed=self.exportvulnerability))
        self.VulnerabilityButtonPanel.add(JButton(
            "Import Vulnerabilities", actionPerformed=self.importvulnerability))

        # adding the button in vulnerability tab
        self.ThirdTab.add(self.VulnerabilityButtonPanel, BorderLayout.PAGE_START)



        # creating the UI pannel for vulnerability tab --> table
        self.tablePanel3 = JPanel()
       
        # Creating a jcombobox that will show the selection option, and adding and none or empty item for selection
        self.comboBox = JComboBox()
        self.comboBox.addItem(None)
        self.comboBox.setEditable(True)
        self.combolist = []
        #self.comboBox.addActionListener(self.seachincombobox)

        AutoCompleteDecorator.decorate(self.comboBox)


        # Creating a seelction list for Severity on vulnerability table
        self.comboBox2 = JComboBox()
        self.comboBox2.addItem(None)
        self.comboBox2.addItem('Critical')
        self.comboBox2.addItem('High')
        self.comboBox2.addItem('Medium')
        self.comboBox2.addItem('Low')
        self.comboBox2.addItem('Informational')




        # creating the table to vulnerability tab
        #self.colNames3 = ['URL', 'Parameters','Vulnerability','Severity','Request','Response']
        #self.dataModel2 = CustomDefaultTableModelHosts2(None,self.colNames3)
        self.dataModel2 = CustomTableModelVuln(self)
        


        self.table3 = JTable(self.dataModel2)
        self.table3.setAutoCreateRowSorter(True)
        self.table3.getColumnModel().getColumn(2).setPreferredWidth(0)
        self.table3.getColumnModel().getColumn(1).setPreferredWidth(0)
        self.table3.getTableHeader().setReorderingAllowed(False)



        #comboColumn = self.table3.getColumnModel().getColumn(2)
        #comboColumn.setCellEditor(DefaultCellEditor(self.comboBox))
       

        self.editor = AutocompleteTableCellEditor(self.combolist,self.table3)
        comboColumn = self.table3.getColumnModel().getColumn(2)
        comboColumn.setCellEditor(self.editor)





        comboColumn2 = self.table3.getColumnModel().getColumn(3)
        comboColumn2.setCellEditor(DefaultCellEditor(self.comboBox2))

        #self.table3.removeColumn(self.table3.getColumnModel().getColumn(5));
        #self.table3.removeColumn(self.table3.getColumnModel().getColumn(4));
        self.table3.getColumnModel().getColumn(4).setMinWidth(0);
        self.table3.getColumnModel().getColumn(4).setMaxWidth(0);
        self.table3.getColumnModel().getColumn(4).setWidth(0);
        self.table3.getColumnModel().getColumn(5).setMinWidth(0);
        self.table3.getColumnModel().getColumn(5).setMaxWidth(0);
        self.table3.getColumnModel().getColumn(5).setWidth(0);
        



        # Adding a right click menu for Vulnerability
        popupMenu2 = JPopupMenu()
        deletevulnerability = JMenuItem("Delete Vulnerability", actionPerformed=self.deletevuln)
        popupMenu2.add(deletevulnerability)
        self.table3.setComponentPopupMenu(popupMenu2)
        
        

        # adding the table size, width, location and will add the scroller to the table
        self.scrollPane3 = JScrollPane(self.table3)
        X_BASE3 = 1  # send to leff
        # 3rd one send to right
        self.scrollPane3.setBounds(X_BASE3 + 10, 20, 1900, 850)
        self.scrollPane3.setPreferredSize(Dimension(1500, 700))
        self.scrollPane3.getViewport().setView((self.table3))
        self.tablePanel3.add(self.scrollPane3)


        self.requestViewer1 = callbacks.createMessageEditor(None, True)
        self.responseViewer1 = callbacks.createMessageEditor(None, True)

        self.editor_view1 = JTabbedPane()
        self.editor_view1.addTab("Request", self.requestViewer1.getComponent())
        self.editor_view1.addTab("Response", self.responseViewer1.getComponent())
        spl1 = JSplitPane(JSplitPane.VERTICAL_SPLIT)

        spl1.setLeftComponent(self.scrollPane3)
        spl1.setRightComponent(self.editor_view1)

        #listener = CustomSelectionListener(self.dataModel2, self.requestViewer1, self.responseViewer1)
        #self.table3.getSelectionModel().addListSelectionListener(listener)

        listener = CustomSelectionListener(self.table3, self.requestViewer1, self.responseViewer1)
        self.table3.getSelectionModel().addListSelectionListener(listener)

        



        # adding the table UI to vulnerability tab
        self.ThirdTab.add(spl1, BorderLayout.CENTER)
        #self.ThirdTab.add(self.scrollPane3, BorderLayout.CENTER)
        

        # Config Tab
        self.FourthTab = JPanel()
        self.FourthTab.layout = BorderLayout()
        self.tabbedPane.addTab("Config", self.FourthTab) 
        self.buttonPanel5 = JPanel()

        layout = GroupLayout(self.buttonPanel5)
        self.buttonPanel5.setLayout(layout)




        jButton1 = JButton("Choose Directory", actionPerformed=self.Autosavepath)
        jLabel1 = JLabel()
        self.autosavepath = JLabel();
        self.autosavepath.setForeground(Color(255, 102, 51))
        self.timeperid = JLabel();
        self.timerbox = JTextField(5);
        jLabel4 = JLabel();
        button2 = JButton("Choose File", actionPerformed=self.Autosavepath2)
        self.Checklistfilepath = JLabel()
        self.Checklistfilepath.setForeground(Color(255, 102, 51))
        Savechecklistfileconfig = JButton("Save Path", actionPerformed=self.saveautoconfigdata2)
        Savechecklistfileconfig.setBackground(Color(255, 102, 51))
        Savechecklistfileconfig.setFont(Font("Segoe UI", 1, 12))
        Savechecklistfileconfig.setForeground(Color(255, 255, 255))

        self.saveconfigbutton = JButton("Save Config", actionPerformed=self.saveautoconfigdata)
        self.saveconfigbutton.setBackground(Color(255, 102, 51));
        self.saveconfigbutton.setFont(Font("Segoe UI", 1, 12))
        self.saveconfigbutton.setForeground(Color(255, 255, 255))
        jLabel1.setText("Select the Auto Save Output Directory :")

        self.timeperid.setText("Set Time for Auto Save :")

        self.timerbox.setText("self.timerbox");

        self.timeerror = JLabel();
        self.timeerror.setForeground(Color(204, 0, 0))
        importall = JButton("Import All", actionPerformed=self.autoimportall)
        jSeparator1 = JSeparator()
        jSeparator2 = JSeparator()
        jSeparator1.setPreferredSize(Dimension(50, 100))


        jSeparator2.setPreferredSize(Dimension(50, 100))

        AutoSaveConfigHeading = JLabel()
        AutoSaveConfigHeading.setFont(Font("Segoe UI", 1, 14))
        AutoSaveConfigHeading.setToolTipText("")
        AutoloadChecklistHeading = JLabel();
        AutoloadChecklistHeading.setFont(Font("Segoe UI", 1, 14))
        AutoloadChecklistHeading.setToolTipText("")
        Exportall = JButton("Export All", actionPerformed=self.autoexportall);
        AutoSaveConfigHeading.setFont(Font("Segoe UI", 1, 14));
        AutoSaveConfigHeading.setText("Auto Save Config");
        AutoSaveConfigHeading.setToolTipText("");

        AutoloadChecklistHeading.setFont(Font("Segoe UI", 1, 14))
        AutoloadChecklistHeading.setText("Auto Load Checklist");
        AutoloadChecklistHeading.setToolTipText("")


        jLabel4.setText("Select Auto Load Checklist File :")
        OneclickImportExportLabel = JLabel()
        OneclickImportExportLabel.setText("Import and Export API Mapper and Vulnerabilities from Above Selected Directory")
        Singleclickfilename = JLabel()
        Singleclickfilename.setForeground(Color(204, 0, 0))
        Singleclickfilename.setText("Note: File Name should be APIMapper.csv & Vulnerability.csv")
        jSeparator3 = JSeparator()
        jSeparator3.setPreferredSize(Dimension(50, 100))
        AutologLabel = JLabel()
        AutologLabel.setText("Auto Log from Proxy to API Mapper :")
        AutologHeading1 = JLabel()
        AutologHeading1.setFont(Font("Segoe UI", 1, 14))
        AutologHeading1.setText("Auto Logging");
        AutologHeading1.setToolTipText("")
        self.AutoLoggingtoggle = JToggleButton()
        self.AutoLoggingtoggle.addItemListener(self.AutoLogtogglelistener)
        self.AutoLoggingtoggle.setBackground(Color(128, 128, 128));
        self.AutoLoggingtoggle.setFont(Font("Segoe UI", 1, 14))
        self.AutoLoggingtoggle.setText("ON");
        self.AutoLoggingtoggle.setCursor(Cursor(Cursor.DEFAULT_CURSOR))
        self.ToggleStatus = JLabel()
        self.ToggleStatus.setForeground(Color(255, 102, 51))
        self.ToggleStatus.setText("Current Status: OFF")
        oneclickimportexportHeading = JLabel()
        oneclickimportexportHeading.setFont(Font("Segoe UI", 1, 14))
        oneclickimportexportHeading.setText("One Click Import Export")
        oneclickimportexportHeading.setToolTipText("")
        self.SingleclickimportMapper = JLabel()
        self.SingleclickimportMapper.setForeground(Color(255, 102, 51));
        
        self.SingleclickimportVulnerabilities = JLabel()
        self.SingleclickimportVulnerabilities.setForeground(Color(255, 102, 51));
        
        self.SingleclickexportMapper = JLabel()
        self.SingleclickexportMapper.setForeground(Color(255, 102, 51))
        
        self.SingleclickexportVulnerabilities = JLabel()
        self.SingleclickexportVulnerabilities.setForeground(Color(255, 102, 51))
        
        Excludefilelabel = JLabel()
        Excludefilelabel.setText("Exclude Files :")
        Excludefilebutton = JButton("Save", actionPerformed=self.excludefilebuttonclick)
        Excludefilebutton.setBackground(Color(255, 102, 51))
        Excludefilebutton.setFont(Font("Segoe UI", 1, 12))
        Excludefilebutton.setForeground(Color(255, 255, 255))
        AutosaveHeading3 = JLabel()
        AutosaveHeading3.setFont(Font("Segoe UI", 1, 14))
        AutosaveHeading3.setText("Auto Save")
        AutosaveHeading3.setToolTipText("")
        self.AutoSavetoggle = JToggleButton()
        self.AutoSavetoggle.setBackground(Color(128, 128, 128))
        self.AutoSavetoggle.setFont(Font("Segoe UI", 1, 14))
        self.AutoSavetoggle.setText("ON")#, itemStateChanged = self.AutoSavetogglelistener)
        self.AutoSavetoggle.addItemListener(self.AutoSavetogglelistener)
        self.AutoSavetoggle.setCursor(Cursor(Cursor.DEFAULT_CURSOR))
        self.Autosavechecker = False
        AutoSaveLabel = JLabel()
        AutoSaveLabel.setText("Auto Save API Mapper and Vulnerability :")
        self.AutoSaveToggleStatus = JLabel()
        self.AutoSaveToggleStatus.setForeground(Color(255, 102, 51))
        self.AutoSaveToggleStatus.setText("Current Status: OFF")
        self.AutoSaveErrorlabel = JLabel()
        self.AutoSaveErrorlabel.setBackground(Color(0, 0, 0))
        self.AutoSaveErrorlabel.setForeground(Color(204, 0, 0))
        #AutoSaveErrorlabel.setText("Auto Save Requires Auto Save Config with Valid Directory Selected")
        jScrollPane1 = JScrollPane()
        self.Excludefiletextfield = JTextArea()
        self.Excludefiletextfield.setColumns(20)
        self.Excludefiletextfield.setRows(1)
        self.Excludefiletextfield.setTabSize(6)
        self.Excludefiletextfield.setText("SCRIPT,JPEG,CSS,PNG,IMAGE,APP")
        jScrollPane1.setViewportView(self.Excludefiletextfield)
        jSeparator5 = JSeparator()
        jSeparator5.setOrientation(VERTICAL)


        
        layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                            .addGap(26, 26, 26)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addGroup(layout.createSequentialGroup()
                                    .addComponent(AutologHeading1)
                                    .addGap(125, 125, 125)
                                    .addComponent(jSeparator3, javax.swing.GroupLayout.PREFERRED_SIZE, 180, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addComponent(oneclickimportexportHeading)
                                .addComponent(Singleclickfilename)
                                .addComponent(OneclickImportExportLabel)
                                .addGroup(layout.createSequentialGroup()
                                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addComponent(jLabel1)
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                            .addComponent(AutoloadChecklistHeading)
                                            .addComponent(self.timeperid))
                                        .addComponent(jLabel4))
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addGroup(layout.createSequentialGroup()
                                            .addComponent(button2)
                                            .addGap(37, 37, 37)
                                            .addComponent(self.Checklistfilepath))
                                        .addGroup(layout.createSequentialGroup()
                                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                                .addComponent(jButton1)
                                                .addComponent(self.timerbox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                                .addComponent(self.saveconfigbutton))
                                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                                .addComponent(self.timeerror)
                                                .addComponent(self.autosavepath)))
                                        .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 180, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addComponent(Savechecklistfileconfig)
                                        .addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 180, javax.swing.GroupLayout.PREFERRED_SIZE)))
                                .addGroup(layout.createSequentialGroup()
                                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, False)
                                            .addGroup(layout.createSequentialGroup()
                                                .addComponent(Exportall)
                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                                .addComponent(self.SingleclickexportMapper))
                                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                                .addComponent(importall)
                                                .addGap(18, 18, 18)
                                                .addComponent(self.SingleclickimportMapper)))
                                        .addGroup(layout.createSequentialGroup()
                                            .addComponent(AutologLabel)
                                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                            .addComponent(self.AutoLoggingtoggle, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE)))
                                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addGroup(layout.createSequentialGroup()
                                            .addGap(24, 24, 24)
                                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                                .addComponent(self.SingleclickimportVulnerabilities)
                                                .addComponent(self.SingleclickexportVulnerabilities)))
                                        .addGroup(layout.createSequentialGroup()
                                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                                .addGroup(layout.createSequentialGroup()
                                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                    .addComponent(self.ToggleStatus))
                                                .addGroup(layout.createSequentialGroup()
                                                    .addGap(52, 52, 52)
                                                    .addComponent(Excludefilebutton)))
                                            .addGap(45, 45, 45)
                                            .addComponent(jSeparator5, javax.swing.GroupLayout.PREFERRED_SIZE, 12, javax.swing.GroupLayout.PREFERRED_SIZE)
                                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                                .addComponent(self.AutoSaveErrorlabel)
                                                .addComponent(AutoSaveLabel)
                                                .addGroup(layout.createSequentialGroup()
                                                    .addComponent(self.AutoSavetoggle, javax.swing.GroupLayout.PREFERRED_SIZE, 73, javax.swing.GroupLayout.PREFERRED_SIZE)
                                                    .addGap(18, 18, 18)
                                                    .addComponent(self.AutoSaveToggleStatus))
                                                .addComponent(AutosaveHeading3)))))
                                .addGroup(layout.createSequentialGroup()
                                    .addComponent(Excludefilelabel)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
                        .addGroup(layout.createSequentialGroup()
                            .addGap(35, 35, 35)
                            .addComponent(AutoSaveConfigHeading)))
                    .addContainerGap(133, Short.MAX_VALUE))
            );
        layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(AutoSaveConfigHeading)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel1)
                        .addComponent(jButton1)
                        .addComponent(self.autosavepath))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(self.timeperid)
                        .addComponent(self.timerbox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(self.timeerror))
                    .addGap(18, 18, 18)
                    .addComponent(self.saveconfigbutton)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(2, 2, 2)
                    .addComponent(AutoloadChecklistHeading)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel4)
                        .addComponent(button2)
                        .addComponent(self.Checklistfilepath))
                    .addGap(18, 18, 18)
                    .addComponent(Savechecklistfileconfig)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(1, 1, 1)
                    .addComponent(oneclickimportexportHeading)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                    .addComponent(OneclickImportExportLabel)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                    .addComponent(Singleclickfilename)
                    .addGap(18, 18, 18)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(importall)
                        .addComponent(self.SingleclickimportMapper)
                        .addComponent(self.SingleclickimportVulnerabilities))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(Exportall)
                        .addComponent(self.SingleclickexportMapper)
                        .addComponent(self.SingleclickexportVulnerabilities))
                    .addGap(18, 18, 18)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                    .addComponent(AutologHeading1)
                                    .addComponent(AutosaveHeading3))
                                .addComponent(jSeparator3, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(AutologLabel)
                                .addComponent(self.AutoLoggingtoggle, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(self.ToggleStatus))
                            .addGap(18, 18, 18)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(Excludefilelabel)
                                .addComponent(Excludefilebutton))
                            .addGap(0, 0, Short.MAX_VALUE))
                        .addGroup(layout.createSequentialGroup()
                            .addGap(22, 22, 22)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addGroup(layout.createSequentialGroup()
                                    .addComponent(AutoSaveLabel)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                        .addComponent(self.AutoSavetoggle, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addComponent(self.AutoSaveToggleStatus))
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addComponent(self.AutoSaveErrorlabel))
                                .addComponent(jSeparator5, javax.swing.GroupLayout.PREFERRED_SIZE, 134, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addContainerGap(187, Short.MAX_VALUE))))
            )
        


        self.FourthTab.add(self.buttonPanel5)#,BorderLayout.NORTH)


        # Loading auto save time,path and auto load checklist and auto log exclude files from burp config
        self.path = callbacks.loadExtensionSetting('path')
        self.time = callbacks.loadExtensionSetting('time')
        self.loadexcludefiles = callbacks.loadExtensionSetting('excludefilestolog')
        self.checklistpath = callbacks.loadExtensionSetting('checklistpath')
        self.timerbox.setText(self.time)
        self.autosavepath.setText(self.path)

        
        
        self.autoloadchecklist = 0
        self.autosavelocation = 0
        self.extensionload = True


        # Validing the content og extension loaded config
        if self.loadexcludefiles == None:
            self.loadexcludefiles = "SCRIPT,JPEG,CSS,PNG,IMAGE,APP".upper()
        else:
            self.Excludefiletextfield.setText(self.loadexcludefiles)

        if self.time == None:
            self.time = 10
            self.timerbox.setText(str(self.time))
        else:
            pass

        if self.path == None:
            self.path = "Please select the Directory"
            self.autosavepath.setText(self.path)
        else:
            pass

        self.callbacks.printOutput("\nAuto Save Time = " + str(self.time))
        self.callbacks.printOutput("Auto Save Path = " + self.path +"\n")

        
        # Loading the checkling if auto load checklist configured
        if self.checklistpath == None:
            self.callbacks.printOutput(str(self.checklistpath))
            self.Checklistfilepath.setText("Select the Checklist file")
        else:
            self.comboBox.removeAllItems()
            self.comboBox.addItem(None)
            self.dataModel.setRowCount(0)
            with open(self.checklistpath, 'rb') as f:
                reader2 = csv.reader(f,  delimiter=',')
                for rows in reader2:
                    SR = rows[0]
                    title = rows[1]
                    obj = [SR,title]
                    self.dataModel.addRow(obj)
                    #self.comboBox.addItem(str(title))
                    self.combolist.append(str(title))
                    combo_model = DefaultComboBoxModel(self.combolist)
                    self.editor.comboBox.setModel(combo_model)
                f.close()
            self.Checklistfilepath.setText(self.checklistpath)
        
        

  
      
    # Validating if extension is unloaded to stop all running process ( Auto Save and Auto Log)
    def extensionUnloaded(self):
        self.extensionload = False
        self.Autosavechecker = False
        self.Autologcheck = False


    # Listner to validate if auto Log is on or off
    def AutoLogtogglelistener(self,e):
        self.AutoLoggingtoggle = e.getItem()
        if self.AutoLoggingtoggle.isSelected():
            self.AutoLoggingtoggle.setText("OFF")
            self.AutoLoggingtoggle.setBackground(Color(255, 255, 255))
            self.ToggleStatus.setText("Current Status: ON")
            self.Autologcheck = True
            self.callbacks.registerProxyListener(Autologclas(self))
            #Autologclas(self)
            

        else:
            self.AutoLoggingtoggle.setText("ON")
            self.AutoLoggingtoggle.setBackground(Color(128, 128, 128))
            self.ToggleStatus.setText("Current Status: OFF")
            self.Autologcheck = False
            self.callbacks.removeProxyListener(Autologclas(self))



    # Listner to validate if auto Save is on or off
    def AutoSavetogglelistener(self, e):
            self.AutoSavetoggle = e.getItem()
            t = Autosaveclas(self)
            #p = multiprocessing.Process(target=t.run)

            if self.AutoSavetoggle.isSelected():
                if not os.path.isdir(str(self.path)):
                    self.AutoSavetoggle.setBackground(Color(128, 128, 128))
                    self.AutoSaveErrorlabel.setText("Auto Save Requires Auto Save Config with Valid Directory Selected")
                    self.Autosavechecker = False
                else:
                
                    self.AutoSavetoggle.setText("OFF")
                    self.AutoSavetoggle.setBackground(Color(255, 255, 255))
                    self.AutoSaveToggleStatus.setText("Current Status: ON")
                    self.AutoSaveErrorlabel.setText("")

                    self.Autosavechecker = True
                    t.start() 

            else:
                self.AutoSavetoggle.setText("ON")
                self.AutoSaveToggleStatus.setText("Current Status: OFF")
                self.AutoSavetoggle.setBackground(Color(128, 128, 128))
                self.AutoSaveErrorlabel.setText("")
                self.Autosavechecker = False
                t.stop()
                    

    # Import All data if Import button clicked from config Tab
    def autoimportall(self,e):
        if os.path.isdir(str(self.path)):
            fname = "APIMapper"+"."+"csv"
            fnameWithPath = os.path.join(self.path,fname)
            if os.path.exists(fnameWithPath):
                with open(fnameWithPath, 'rb') as f:
                    reader2 = csv.reader(f,  delimiter=',')
                    for rows in reader2:
                        SR = rows[0]
                        url = rows[1]
                        method = rows[2]
                        body =  zlib.decompress(base64.b64decode(rows[3]))
                        functionname = rows[4]
                        request =  zlib.decompress(base64.b64decode(rows[5]))
                        testcases = rows[6]
                        try:
                            response =  zlib.decompress(base64.b64decode(rows[7]))
                            status = rows[8]
                        except IndexError:
                            response = None
                            status = None
                        self._log.append(LogEntry(SR,url, method,body,request,functionname,testcases,response,status))
                        
                    f.close()
                    self.fireTableDataChanged()
                    self.SingleclickimportMapper.setText("API Mapper Import Completed")
            fname2 = "Vulnerability"+"."+"csv"
            fnameWithPath2 = os.path.join(self.path,fname2)
            if os.path.exists(fnameWithPath2):
                with open(fnameWithPath2, 'rb') as f:
                    reader2 = csv.reader(f,  delimiter=',')
                    for rows in reader2:
                        URL = rows[0]
                        Parameter = rows[1]
                        Vulnerability = rows[2]
                        try:
                            Severity = rows[3]
                            Request = zlib.decompress(base64.b64decode(rows[4]))
                            Response = zlib.decompress(base64.b64decode(rows[5]))
                        except IndexError:
                            Severity = None
                            Request = None
                            Response = None
                        obj = [URL,Parameter,Vulnerability,Severity,Request,Response]
                        self.dataModel2.addRow(obj)  
                    f.close()
                    self.SingleclickimportVulnerabilities.setText("Vulnerabilities Import Completed")
        else:
            self.autosavepath.setText("Output Directory doesn't exist")
            self.SingleclickimportVulnerabilities.setText("Vulnerabilities Import Failed")
            self.SingleclickimportMapper.setText("API Mapper Import Failed")





    # Export All data if Export button clicked from config Tab
    def autoexportall(self,e):
        if os.path.isdir(str(self.path)):
                if self.logTable.getRowCount() > 0:
                    fname = "APIMapper"+"."+"csv"
                    fnameWithPath = os.path.join(self.path,fname)
                    if os.path.exists(fnameWithPath):
                        os.remove(fnameWithPath)
                    self.callbacks.printOutput("Saving the API Mapper output")
                    with open(fnameWithPath, 'wb') as loggerdata:
                        writer = csv.writer(loggerdata)
                        for logEntry in self._log:
                            writer.writerow([str(logEntry._sr), str(logEntry._url) ,str(logEntry._method) , base64.b64encode(zlib.compress(logEntry._postbody.encode('utf-8'))) ,str(logEntry._FunctionalityName) , base64.b64encode(zlib.compress(logEntry._requestResponse.encode('utf-8'))) ,str(logEntry._TestCases), base64.b64encode(zlib.compress(logEntry._response.encode('utf-8'))) ,str(logEntry._status)])
                        loggerdata.close()
                        self.SingleclickexportMapper.setText("API Mapper Export Completed")
                else:
                    self.callbacks.printOutput("Skipping the API Mapper, Table is empty")
                
                    self.SingleclickexportMapper.setText("API Mapper Export Failed. Empty Table")
                if self.dataModel2.getRowCount() > 0:

                    fname2 = "Vulnerability"+"."+"csv"
                    fnameWithPath2 = os.path.join(self.path,fname2)
                    if os.path.exists(fnameWithPath2):
                        os.remove(fnameWithPath2)
                    self.callbacks.printOutput("Saving the Vulnerability output")
                    totalrow = self.dataModel2.getRowCount()   
                    with open(fnameWithPath2, 'wb') as vulnerabilitydata:
                        writer = csv.writer(vulnerabilitydata)
                        for row in range (0, totalrow):
                            url = self.dataModel2.getValueAt(row,0)
                            paramter = self.dataModel2.getValueAt(int(row),1)
                            Vulnerability = self.dataModel2.getValueAt(int(row),2)
                            Severity  = self.dataModel2.getValueAt(int(row),3)
                            Request = self.dataModel2.getValueAt(int(row),4)
                            Response = self.dataModel2.getValueAt(int(row),5)

                            
                            writer.writerow([str(url), str(paramter) ,str(Vulnerability),str(Severity),base64.b64encode(zlib.compress(Request.encode('utf-8'))),base64.b64encode(zlib.compress(Response.encode('utf-8')))])
                        vulnerabilitydata.close()
                        self.SingleclickexportVulnerabilities.setText("Vulnerabilities Export Completed")
                else:
                    self.callbacks.printOutput("Skipping the  Vulnerability, Table is empty")
                    self.SingleclickexportVulnerabilities.setText("Vulnerabilities Export Failed. Empty Table")
        else:
            self.autosavepath.setText("Output Directory doesn't exist")
            self.SingleclickexportVulnerabilities.setText("Vulnerabilities Export Failed")
            self.SingleclickexportMapper.setText("API Mapper Export Failed")
        
           
    # Listner if Save button clicked from config tab to modify the auto log excluded files
    def excludefilebuttonclick(self,e):
        #Excludefiletextfield.getText()
        self.callbacks.saveExtensionSetting("excludefilestolog", self.Excludefiletextfield.getText().upper())
        self.Excludefiletextfield.setText(self.Excludefiletextfield.getText().upper())



    #Allowing users to select the auto save DIRECTORIES  
    def Autosavepath(self,e):
        chooseFile = JFileChooser()
        chooseFile.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY)
        returnedFile = chooseFile.showDialog(self.VulnerabilityButtonPanel, "Output Path")
        if returnedFile == JFileChooser.APPROVE_OPTION:
            fileLoad1 = chooseFile.getSelectedFile()
            self.autosavelocation = fileLoad1.getPath()
        return str(self.autosavelocation)


    # Allowing users to select the checklist CSV file to auto load it everytime extension is reloaded
    def Autosavepath2(self,e):
        chooseFile = JFileChooser()
        filter = FileNameExtensionFilter("csv files", ["csv"])
        chooseFile.addChoosableFileFilter(filter)

        ret = chooseFile.showDialog(self.tab, "Choose file")
        if ret == JFileChooser.APPROVE_OPTION:
            fileLoad = chooseFile.getSelectedFile()
            self.autoloadchecklist = fileLoad.getAbsolutePath()
        return str(self.autoloadchecklist)


    # Allowing users to set auto save time
    def saveautoconfigdata(self,e):
        if self.autoloadchecklist == 0:
            self.autoloadchecklist = None
        if self.autosavelocation == 0:
            if str(self.timerbox.getText()) == "0":
                self.timeerror.setText("Invalid time")
            else:
                self.path = self.callbacks.loadExtensionSetting('path')
                if os.path.isdir(str(self.path)):
                    self.autosavepath.setText(self.path)
                    self.callbacks.saveExtensionSetting("time", self.timerbox.getText())
                    self.time = self.callbacks.loadExtensionSetting('time')
                else:
                    self.callbacks.printOutput(str(self.autosavelocation))
                    self.autosavepath.setText("Please select the valid path!")
        else:
            if str(self.timerbox.getText()) == "0":
                
                self.timeerror.setText("Invalid time")

            
            else:
                self.callbacks.saveExtensionSetting("path", str(self.autosavelocation))
                self.callbacks.saveExtensionSetting("time", self.timerbox.getText())
                self.autosavepath.setText(str(self.autosavelocation))
                self.path = self.callbacks.loadExtensionSetting('path')
                self.time = self.callbacks.loadExtensionSetting('time')
           

    # Allow users to save the auto load checklist path       
    def saveautoconfigdata2(self,e):
        if self.autoloadchecklist == 0:
            self.Checklistfilepath.setText("Select the checklist file")    
        else:
            self.callbacks.saveExtensionSetting("checklistpath", str(self.autoloadchecklist))
            self.Checklistfilepath.setText(self.autoloadchecklist)
            self.Checklistfilepath.setText(str(self.autoloadchecklist))
    
        
    # this will send the selected row in api mapper to vulnerability tab
    def sendVulnItem(self,event):
        row = self.logTable.getSelectedRows()
        for rows in row:
            modelRowIndex = self.logTable.convertRowIndexToModel(rows)
            logEntry = self._log[modelRowIndex]
            self.url = logEntry._url
            self.requestinst = logEntry._requestResponse
            self.responseinst = logEntry._response
            obj = [str(self.url), None,'','',self.requestinst,self.responseinst]
            self.dataModel2.addRow(obj)
            
     # function will handle to send the selected row to repeater       
    def sendRepeaterItem(self,event):
        row = self.logTable.getSelectedRows()    
        for rows in row:
            modelRowIndex = self.logTable.convertRowIndexToModel(rows)
            logEntry = self._log[modelRowIndex]
            fullurl = logEntry._url
            url = urlparse(str(fullurl))
            hostname = url.hostname
            #port = url.port
            port = url.port if url.port is not None else 443
            protocol = url.scheme
            request = self.helpers.stringToBytes(logEntry._requestResponse)
            func = logEntry._FunctionalityName
            if protocol == "https":
                self.callbacks.sendToRepeater(hostname,port, True, request, func)
            else:
                self.callbacks.sendToRepeater(hostname,port, False, request, func)


    # function will handle, delete the row from api mapper
    def deleterow(self,event):  
        row = self.logTable.getSelectedRows()
        
        
        for rows in sorted(row, reverse=True):
            modelRowIndex = self.logTable.convertRowIndexToModel(rows)
            self._log.pop(modelRowIndex)
            self.fireTableDataChanged()

    # delete row from the vulnerability table 
    def deletevuln(self,e):
        totalvulnrows = self.table3.getSelectedRows()
        for rows in sorted(totalvulnrows, reverse=True):
            modelRowIndex = self.table3.convertRowIndexToModel(rows)
            self.dataModel2.removeRow(modelRowIndex)
            

    # allow users to search vulnerablity from select vulnerablity list in vulnerability table
    '''
    def seachincombobox(self,event):
        Combo = event.getSource()
        searchedvalue = Combo.getSelectedItem()
        self.comboBox.removeAllItems()
        self.comboBox.addItem(None)
        for items in self.combolist:
            if searchedvalue in items:
                self.comboBox.addItem(items)

    

    def seachincombobox(self, event):
        Combo = event.getSource()
        searchedValue = Combo.getEditor().getItem()
        model = Combo.getModel()
        model.removeAllElements()
        model.addElement(None)
        for item in self.combolist:
            if not searchedValue or searchedValue.lower() in item.lower():
                model.addElement(item)
    '''


    #function that will show a option to send request to extension in proxy/repeater etc
    def createMenuItems(self, invocation):
        ctx = invocation.getInvocationContext()
        menu = []
        menu.append(JMenuItem("Send To API Mapper", None,actionPerformed=lambda x, inv=invocation: self.getTabledataa(inv)))
        menu.append(JMenuItem("Send To Vulnerability", None,actionPerformed=lambda x, inv=invocation: self.getVulnerabilitydataa(inv)))

        if menu == []:
            return
        else:
            return menu


    # function will be called when user send any request to vulnerabilites tab, it will give the selected message
    def getVulnerabilitydataa(self,invocation):
        reqRes = invocation.getSelectedMessages()
        for items in reqRes:
            self.url = items.getUrl()
            req = self.helpers.analyzeRequest(items)
            gettingrequest = items.getRequest()
            self.requestinst = self.helpers.bytesToString(gettingrequest)
            self.responseinbytes = items.getResponse()
            self.responseinst = self.helpers.bytesToString(self.responseinbytes)
            obj = [str(self.url), None,'','',self.requestinst,self.responseinst]
            
            self.dataModel2.addRow(obj)



    # function will be called when user send any request to the extension, function will get the required data from the request that is send and will add it to the list
    def getTabledataa(self, invocation):
        reqRes = invocation.getSelectedMessages()
        for items in reqRes:
            req = self.helpers.analyzeRequest(items)
            self.method = req.getMethod()
            paramter = req.getParameters()
            self.url = items.getUrl()
            gettingrequest = items.getRequest()
            self.requestinst = self.helpers.bytesToString(gettingrequest)
            self.responseinbytes = items.getResponse()
            self.responseinst = self.helpers.bytesToString(self.responseinbytes)
            getody = req.getBodyOffset()
            self.body = self.requestinst[getody:len(self.requestinst)]
            rowss = self.logTable.getRowCount()
            self.sr2 = str((rowss + 1))
            self._lock.acquire()
            row = len(self._log)
            column = self.logTable.getColumnCount()
            self._log.append(LogEntry(self.sr2, self.url, self.method, self.body, self.requestinst, '', '', self.responseinst, ''))
            self.logTable.getModel().fireTableRowsInserted(row, row)
            self._lock.release()


     # Returning the tab name to Burp Suite
    def getTabCaption(self):
        return "Pentest Mapper"


    # Returning the UI to the extension tab - Returning the new taB insite the extension tab
    def getUiComponent(self):
        return self.tabbedPane

    # function will export the table data when clicked on save button in api mapper tab
    def savelogger(self,e):
        currenttime = str(time.strftime('%Y-%m-%d,%H:%M:%S', time.localtime(time.time())))
        chooseFile = JFileChooser()
        chooseFile.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY)
        returnedFile = chooseFile.showDialog(self.APIMapperButtonPanel, "Output Path")
        if returnedFile == JFileChooser.APPROVE_OPTION:
            fileLoad = chooseFile.getSelectedFile()
            self.filepath = fileLoad.getPath()
            fname = "APIMapper"+str(time.time())+"."+"csv"
            fnameWithPath = os.path.join(self.filepath,fname)
            with open(fnameWithPath, 'wb') as loggerdata:
                writer = csv.writer(loggerdata)
                for logEntry in self._log:
                    writer.writerow([str(logEntry._sr), str(logEntry._url) ,str(logEntry._method) , base64.b64encode(zlib.compress(logEntry._postbody.encode('utf-8'))) ,str(logEntry._FunctionalityName) , base64.b64encode(zlib.compress(logEntry._requestResponse.encode('utf-8'))) ,str(logEntry._TestCases), base64.b64encode(zlib.compress(logEntry._response.encode('utf-8'))) ,str(logEntry._status)])
            loggerdata.close()


    # function to handle event to import table data in api mapper tab
    def importlogger(self,e):
        chooseFile = JFileChooser()
        filter = FileNameExtensionFilter("csv files", ["csv"])
        chooseFile.addChoosableFileFilter(filter)
        ret = chooseFile.showDialog(self.tab, "Choose file")
        if ret == JFileChooser.APPROVE_OPTION:
            fileLoad = chooseFile.getSelectedFile()
            self.filepath = fileLoad.getAbsolutePath()
            with open(self.filepath, 'rb') as f:
                reader2 = csv.reader(f,  delimiter=',')
                for rows in reader2:
                    SR = rows[0]
                    url = rows[1]
                    method = rows[2]
                    body = zlib.decompress(base64.b64decode(rows[3]))
                    functionname = rows[4]
                    request = zlib.decompress(base64.b64decode(rows[5]))
                    testcases = rows[6]
                    try:
                        response = zlib.decompress(base64.b64decode(rows[7]))
                        status = rows[8]
                    except IndexError:
                        response = None
                        status = None
                    self._log.append(LogEntry(SR,url, method,body,request,functionname,testcases,response,status))  
                f.close()
                self.fireTableDataChanged()


    ## Search text in checklist tab            
    def searchinchecklist(self,e):
        checklistsearchstring = self.searchchecklist.getText()
        if checklistsearchstring == "":
            self.sorter.setRowFilter(None)
        else: 
            self.sorter.setRowFilter(RowFilter.regexFilter("(?i)" + checklistsearchstring));


    ## Search text in APIMapper tab            
    def searchinapimapper(self,e):
        apimappersearchstring = self.searchapimapper.getText()
        if apimappersearchstring == "":
            self.sorter2.setRowFilter(None)
        else:
            self.sorter2.setRowFilter(RowFilter.regexFilter("(?i)" + apimappersearchstring));

    ## Search text in APIMapper tab            
    def searchinvulnerability(self,e):
        vulnerabilitysearchstring = self.searchvulnerability.getText()
        if vulnerabilitysearchstring == "":
            self.sorter3.setRowFilter(None)
        else:
            self.sorter3.setRowFilter(RowFilter.regexFilter("(?i)" + vulnerabilitysearchstring));


    #Function that will be called when user click on import in checklist tab
    def importchecklist(self, e): 
        chooseFile = JFileChooser()
        filter = FileNameExtensionFilter("csv files", ["csv"])
        chooseFile.addChoosableFileFilter(filter) 
        ret = chooseFile.showDialog(self.tab, "Choose file")
        if ret == JFileChooser.APPROVE_OPTION:
            fileLoad = chooseFile.getSelectedFile()
            self.filepath = fileLoad.getAbsolutePath()
            self.comboBox.removeAllItems()
            self.comboBox.addItem(None)
            self.dataModel.setRowCount(0)
            with open(self.filepath, 'rb') as f:
                reader2 = csv.reader(f,  delimiter=',')
                for rows in reader2:
                    SR = rows[0]
                    title = rows[1]
                    obj = [SR,title]
                    self.dataModel.addRow(obj)
                    self.comboBox.addItem(str(title))
                    self.combolist.append(str(title))
                    combo_model = DefaultComboBoxModel(self.combolist)
                    self.editor.comboBox.setModel(combo_model)
                f.close()
            

    # creating a function that will be called when user clicks on the create button this function will show the input field in UI for checklist taB
    def createtestcases(self, e):
        self.createchecklistbutton.setEnabled(False)
        self.textfield1 = JTextField('', 15)
        self.ChecklistbuttonPanel.add(self.textfield1)
        self.ChecklistbuttonPanel.add(JButton(
            "Submit", actionPerformed=self.addrow))
        self.ChecklistbuttonPanel.add(Box.createVerticalGlue())

    # this function will be called as soon as user click on suBmit Button of add row UI input 
    def addrow(self, e):
        rowsss = self.dataModel.getRowCount()
        sr = (rowsss + 1)
        title = self.value = self.textfield1.getText()
        obj = [sr, title] 
        self.comboBox.addItem(str(title))
        self.combolist.append(str(title))
        combo_model = DefaultComboBoxModel(self.combolist)
        self.editor.comboBox.setModel(combo_model)
        self.dataModel.addRow(obj)
        if not self.checklistpath == None:
        # Writing the new entry in file   
            with open(self.checklistpath, 'a') as writechecklist:
                writer = csv.writer(writechecklist)
                writer.writerow([str(sr), str(title)])
            writechecklist.close()
        else:
            self.callbacks.printOutput("Auto add to csv file only work if auto checklist load is configured") 


    # function to handel event when save button clicked on test cases 
    def SaveTestCases(self,e):
        selectedrow = self.logTable.getSelectedRow()
        modelRowIndex = self.logTable.convertRowIndexToModel(selectedrow) 
        if modelRowIndex >= 0:
            logEntry = self._log[modelRowIndex]
            Value = self.testcases.getText()
            logEntry._TestCases = Value


    # function will handle to event once the export button clicked on vulnerablity tab
    def exportvulnerability(self,e):
        totalrow = self.dataModel2.getRowCount()
        self.callbacks.printOutput(str(totalrow))
        chooseFile = JFileChooser()
        chooseFile.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY)
        returnedFile = chooseFile.showDialog(self.VulnerabilityButtonPanel, "Output Path")
        if returnedFile == JFileChooser.APPROVE_OPTION:
            fileLoad1 = chooseFile.getSelectedFile()
            self.filepath2 = fileLoad1.getPath()
            fname2 = "Vulnerability"+str(time.time())+"."+"csv"
            fnameWithPath = os.path.join(self.filepath2,fname2)

            #self.filepath2 = fileLoad1.getAbsolutePath()
            with open(fnameWithPath, 'wb') as vulnerabilitydata:
                writer = csv.writer(vulnerabilitydata)
                for row in range (0, totalrow):
                    url = self.dataModel2.getValueAt(row,0)
                    paramter = self.dataModel2.getValueAt(int(row),1)
                    Vulnerability = self.dataModel2.getValueAt(int(row),2)
                    Severity = self.dataModel2.getValueAt(int(row),3)
                    Request = self.dataModel2.getValueAt(int(row),4)
                    Response = self.dataModel2.getValueAt(int(row),5)
                    writer.writerow([str(url), str(paramter) ,str(Vulnerability),str(Severity),base64.b64encode(zlib.compress(Request.encode('utf-8'))),base64.b64encode(zlib.compress(Response.encode('utf-8')))])
            vulnerabilitydata.close()



    # function will handle to event once the import button clicked on vulnerablity tab
    def importvulnerability(self,e):
        chooseFile = JFileChooser()
        filter = FileNameExtensionFilter("csv files", ["csv"])
        chooseFile.addChoosableFileFilter(filter)
        ret = chooseFile.showDialog(self.tab, "Choose file")
        if ret == JFileChooser.APPROVE_OPTION:
            fileLoad = chooseFile.getSelectedFile()
            self.filepath = fileLoad.getAbsolutePath()
            
            with open(self.filepath, 'rb') as f:
                reader2 = csv.reader(f,  delimiter=',')
                #self.data1 = list(reader)
                for rows in reader2:
                    URL = rows[0]
                    Parameter = rows[1]
                    Vulnerability = rows[2]
                    try:
                        Severity = rows[3]
                        Request = rows[4]
                        Response = rows[5]
                    except IndexError:
                        Severity = None
                        Request = None
                        Response = None
                    obj = [URL,Parameter,Vulnerability,Severity,zlib.decompress(base64.b64decode(Request)),zlib.decompress(base64.b64decode(Response))]
                    self.dataModel2.addRow(obj)
                f.close()


# extending the default table model to remove the editable column from the checklist taB table
class CustomDefaultTableModelHosts(DefaultTableModel):

    # override isCellEditable method
    def isCellEditable(self, row, column):
        return 0




class CustomSelectionListener(ListSelectionListener):
    def __init__(self, table, request_viewer, response_viewer):
        self.table = table
        self.request_viewer = request_viewer
        self.response_viewer = response_viewer

    def valueChanged(self, event):
        if not event.getValueIsAdjusting():
            selected_row = self.table.getSelectedRow()
            if selected_row != -1:
                request_data = self.table.getValueAt(selected_row, 4)  
                response_data = self.table.getValueAt(selected_row, 5)  
                self.request_viewer.setMessage(request_data, True)
                self.response_viewer.setMessage(response_data, True)





# Vulnerability Table vulnerability selection autocompletion
class AutocompleteTableCellEditor(TableCellEditor):
    def __init__(self, items,table3):
        self.items = items
        self.comboBox = JComboBox(items)
        self.comboBox.setEditable(True)
        AutoCompleteDecorator.decorate(self.comboBox)
        self.listeners = []
        self.table3 = table3


    def getCellEditorValue(self):
        return self.comboBox.getSelectedItem()

    def getTableCellEditorComponent(self, table, value, isSelected, row, column):
        self.comboBox = JComboBox(self.items)
        self.comboBox.setEditable(True)
        AutoCompleteDecorator.decorate(self.comboBox)
        self.comboBox.setSelectedItem(value)
        return self.comboBox

    def isCellEditable(self, event):
        return True

    def addCellEditorListener(self, listener):
        self.listeners.append(listener)

    def removeCellEditorListener(self, listener):
        self.listeners.remove(listener)

    def shouldSelectCell(self, event):
        return True

    def stopCellEditing(self):
        selected_value = self.comboBox.getSelectedItem()
        selected_row = self.table3.convertRowIndexToModel(self.table3.getEditingRow())
        selected_column = self.table3.convertColumnIndexToModel(self.table3.getEditingColumn())
        self.table3.getModel().setValueAt(selected_value, selected_row, selected_column)

        return True
    
    def cancelCellEditing(self):
        return True
    


class RowData:
    def __init__(self, url="", parameters="", vulnerability="", severity="", request="", response=""):
        self.url = url
        self.parameters = parameters
        self.vulnerability = vulnerability
        self.severity = severity
        self.request = request
        self.response = response



class CustomTableModelVuln(AbstractTableModel):
    def __init__(self, extender):
        self.vulndata = extender._vuln
        self.callbacks = extender.callbacks
        

    def getRowCount(self):
        try:
            return len(self.vulndata)
        except:
            return 0
    

    def getColumnCount(self):
        return 6

    def getColumnName(self, columnIndex):
        if columnIndex == 0:
            return "URL"
        if columnIndex == 1:
            return "Parameters"
        if columnIndex == 2:
            return "Vulnerability"
        if columnIndex == 3:
            return "Severity"
        if columnIndex == 4:
            return "Request"
        if columnIndex == 5:
            return "Response"
        return ""


    def getValueAt(self, rowIndex, columnIndex):
        if rowIndex < self.getRowCount() and columnIndex < self.getColumnCount():
            vulnEntry = self.vulndata[rowIndex]
       
            if columnIndex == 0:
                return vulnEntry.url
            elif columnIndex == 1:
                return vulnEntry.parameters
            elif columnIndex == 2:
                return vulnEntry.vulnerability
            elif columnIndex == 3:
                return vulnEntry.severity
            elif columnIndex == 4:
                return vulnEntry.request
            elif columnIndex == 5:
                return vulnEntry.response


    def getColumnClass(self, col):
        return str

    def isCellEditable(self, row, col):
        return True

    def setValueAt(self, value, row, col):
        rowData = self.vulndata[row]
        if col == 0:
            rowData.url = value
        elif col == 1:
            rowData.parameters = value
        elif col == 2:
            rowData.vulnerability = value
        elif col == 3:
            rowData.severity = value
        elif col == 4:
            rowData.request = value
        elif col == 5:
            rowData.response = value
        self.fireTableCellUpdated(row, col)


 
    def setValueAt(self, value, rowIndex, columnIndex):
        
        if rowIndex < self.getRowCount() and columnIndex == 1:
                vulEntry = self.vulndata[rowIndex]
                vulEntry.parameters = value

        if rowIndex < self.getRowCount() and columnIndex == 2:
                vulEntry = self.vulndata[rowIndex]
                vulEntry.vulnerability = value

        if rowIndex < self.getRowCount() and columnIndex == 3:
                vulEntry = self.vulndata[rowIndex]
                vulEntry.severity = value
        else:
            self.callbacks.printError("Table is empty")

    def addRow(self, obj):
        row_data = RowData(*obj)
        self.vulndata.append(row_data)
        self.fireTableRowsInserted(len(self.vulndata) - 1, len(self.vulndata) - 1)
                                   



