示例#1
0
文件: ModelView.py 项目: oracc/nammu
    def addLine(self, objectID, category, text):
        """
        Add a new panel containing the text corresponding to one line in the
        ATF file.
        This panel will show the line type (ruling, comment, text,
        translation...), followed by the line content and a group of icons to
        add, edit or remove the line.
        """
        linePanel = JPanel()
        linePanel.setLayout(BorderLayout())

        label = JLabel(category)

        combo = JComboBox(text)
        combo.setEditable(True)
        combo.setPreferredSize(Dimension(500, 20))
        combo.setSize(combo.getPreferredSize())
        combo.setMinimumSize(combo.getPreferredSize())
        combo.setMaximumSize(combo.getPreferredSize())

        buttonsPanel = JPanel()
        addButton = JButton("Add")
        editButton = JButton("Edit")
        deleteButton = JButton("Delete")
        buttonsPanel.add(addButton)
        buttonsPanel.add(editButton)
        buttonsPanel.add(deleteButton)

        linePanel.add(label, BorderLayout.WEST)
        linePanel.add(combo, BorderLayout.CENTER)
        linePanel.add(buttonsPanel, BorderLayout.EAST)

        # Add metadataPanel to object tab in main panel
        self.objectTabs[objectID].add(linePanel)
示例#2
0
    def addLine(self, objectID, category, text):
        """
        Add a new panel containing the text corresponding to one line in the
        ATF file.
        This panel will show the line type (ruling, comment, text,
        translation...), followed by the line content and a group of icons to
        add, edit or remove the line.
        """
        linePanel = JPanel()
        linePanel.setLayout(BorderLayout())

        label = JLabel(category)

        combo = JComboBox(text)
        combo.setEditable(True)
        combo.setPreferredSize(Dimension(500, 20))
        combo.setSize(combo.getPreferredSize())
        combo.setMinimumSize(combo.getPreferredSize())
        combo.setMaximumSize(combo.getPreferredSize())

        buttonsPanel = JPanel()
        addButton = JButton("Add")
        editButton = JButton("Edit")
        deleteButton = JButton("Delete")
        buttonsPanel.add(addButton)
        buttonsPanel.add(editButton)
        buttonsPanel.add(deleteButton)

        linePanel.add(label, BorderLayout.WEST)
        linePanel.add(combo, BorderLayout.CENTER)
        linePanel.add(buttonsPanel, BorderLayout.EAST)

        # Add metadataPanel to object tab in main panel
        self.objectTabs[objectID].add(linePanel)
示例#3
0
def get_time_combo():
    combo_box = JComboBox()
    combo_model = DefaultComboBoxModel()
    combo_model.addElement("seconds")
    combo_model.addElement("milliseconds")
    combo_model.addElement("microseconds")
    combo_box.setModel(combo_model)
    combo_box.setMaximumSize(Dimension(100, 20))
    return combo_box
示例#4
0
def get_delay_correlation_combo():
    combo_box = JComboBox()
    combo_model = DefaultComboBoxModel()
    combo_model.addElement("normal")
    combo_model.addElement("uniform")
    combo_model.addElement("pareto")
    combo_model.addElement("paretonormal")
    combo_box.setModel(combo_model)
    combo_box.setMaximumSize(Dimension(120, 20))
    return combo_box
示例#5
0
def get_rate_combo():
    combo_box = JComboBox()
    combo_model = DefaultComboBoxModel()
    combo_model.addElement("MB/sec")
    combo_model.addElement("KB/sec")
    combo_model.addElement("bytes/sec")
    combo_model.addElement("mbit/sec")
    combo_model.addElement("kbit/sec")
    combo_box.setModel(combo_model)
    combo_box.setMaximumSize(Dimension(100, 20))
    return combo_box
示例#6
0
    def get_loss_type_combo(self):
        combo_box = JComboBox()
        combo_model = DefaultComboBoxModel()
        combo_model.addElement("random")
        combo_model.addElement("state")
        combo_model.addElement("gemodel")
        combo_box.setModel(combo_model)
        combo_box.setMaximumSize(Dimension(120, 20))

        combo_box.addActionListener(
            self.ComboListener(self.loss_random_items, self.loss_state_items,
                               self.loss_gemodel_items))
        return combo_box
示例#7
0
 def __init__(self, chartFun, isTemporal = False):
     self.isTemporal = isTemporal
     JPanel()
     #self.setBackground(Color.LIGHT_GRAY)
     self.chartFun = chartFun
     self.enableChartFun = False
     self.setLayout(GridLayout(6,2))
     self.add(JLabel('CPU Cores'))
     nprocs = ManagementFactory.getOperatingSystemMXBean().getAvailableProcessors()
     procvals = sorted(set([nprocs, 1, 2, 4, 8, 16, 32, 64, 128]))
     cores = JComboBox(procvals)
     cores.setSelectedIndex(procvals.index(nprocs))
     cores.setMaximumSize(cores.getPreferredSize())
     self.cores = cores
     self.add(self.cores)
     self.add(JLabel('# of sims (x1000)  '))
     numSims = JComboBox(
         map(lambda x: str((10+x)*5), range(10)) +
         map(lambda x: str(x*100), range(1,11))
     )
     numSims.setMaximumSize(numSims.getPreferredSize())
     self.numSims = numSims
     self.add(self.numSims)
     if isTemporal:
         self.add(JLabel('"Neutral" Ne'))
         self.neutral = JCheckBox()
         self.neutral.addActionListener(self)
         self.add(self.neutral)
     else:
         self.add(JLabel('"Neutral" mean Fst'))
         self.neutral = JCheckBox()
         self.neutral.addActionListener(self)
         self.add(self.neutral)
         self.add(JLabel('Force mean Fst'))
         self.force = JCheckBox()
         self.force.addActionListener(self)
         self.add(self.force)
     self.add(JLabel('Confidence interval '))
     ci = JComboBox(['0.95', '0.99', '0.995'])
     ci.addItemListener(self)
     ci.setMaximumSize(cores.getPreferredSize())
     self.ci = ci
     self.add(self.ci)
     self.add(JLabel('False Disc. Rate'))
     fdr = JFormattedTextField(
         NumberFormat.getNumberInstance(Locale.US))
     fdr.setValue(0.1)
     fdr.addPropertyChangeListener(self)
     self.add(fdr)
     self.fdr = fdr
示例#8
0
 def __init__(self, chartFun, isTemporal = False):
     self.isTemporal = isTemporal
     JPanel()
     #self.setBackground(Color.LIGHT_GRAY)
     self.chartFun = chartFun
     self.enableChartFun = False
     self.setLayout(GridLayout(6,2))
     self.add(JLabel('CPU Cores'))
     cores = JComboBox(['1', '2', '4', '8', '16', '32', '64', '128'])
     nprocs = ManagementFactory.getOperatingSystemMXBean().getAvailableProcessors()
     pos = min([7, log(ceil(nprocs)) / log(2)])
     cores.setSelectedIndex(int(pos))
     cores.setMaximumSize(cores.getPreferredSize())
     self.cores = cores
     self.add(self.cores)
     self.add(JLabel('# of sims (x1000)  '))
     numSims = JComboBox(
         map(lambda x: str((10+x)*5), range(10)) +
         map(lambda x: str(x*100), range(1,11))
     )
     numSims.setMaximumSize(numSims.getPreferredSize())
     self.numSims = numSims
     self.add(self.numSims)
     if isTemporal:
         self.add(JLabel('"Neutral" Ne'))
         self.neutral = JCheckBox()
         self.neutral.addActionListener(self)
         self.add(self.neutral)
     else:
         self.add(JLabel('"Neutral" mean Fst'))
         self.neutral = JCheckBox()
         self.neutral.addActionListener(self)
         self.add(self.neutral)
         self.add(JLabel('Force mean Fst'))
         self.force = JCheckBox()
         self.force.addActionListener(self)
         self.add(self.force)
     self.add(JLabel('Confidence interval '))
     ci = JComboBox(['0.95', '0.99', '0.995'])
     ci.addItemListener(self)
     ci.setMaximumSize(cores.getPreferredSize())
     self.ci = ci
     self.add(self.ci)
     self.add(JLabel('False Disc. Rate'))
     fdr = JFormattedTextField(
         NumberFormat.getNumberInstance(Locale.US))
     fdr.setValue(0.1)
     fdr.addPropertyChangeListener(self)
     self.add(fdr)
     self.fdr = fdr
示例#9
0
class NewAtfView(JDialog):
    '''
    Prompt user to choose some options to create a template for a new ATF
    file.
    '''
    def __init__(self, controller, projects, languages, protocols):
        self.modalityType = Dialog.ModalityType.APPLICATION_MODAL
        self.controller = controller
        self.projects = projects
        self.languages = languages
        self.protocols = protocols
        self.cancelled = False
        self.springLayout = SpringLayout()
        self.pane = self.getContentPane()

    def display(self):
        '''
        Displays window.
        '''
        self.build()
        self.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE)
        self.setResizable(False)
        self.setTitle("New ATF template")
        self.pack()
        self.setLocationRelativeTo(None)
        self.visible = 1

    def build(self):
        '''
        Puts all the window components together in the JFrame
        '''
        layout = BoxLayout(self.getContentPane(), BoxLayout.Y_AXIS)
        self.setLayout(layout)

        # Create all necessary panels
        ampersand_panel = self.build_ampersand_row()
        project_panel = self.build_projects_row()
        language_panel = self.build_language_row()
        buttons_panel = self.build_buttons_row()

        # Add panels to main JFrame
        self.add(ampersand_panel)
        self.add(project_panel)
        self.add(language_panel)
        self.add(buttons_panel)

    def build_ampersand_row(self):
        '''
        Builds the &-line row.
        '''
        # Build own panel with SpringLayout.
        panel = JPanel()
        layout = SpringLayout()
        panel.setLayout(layout)
        # Create necessary components and add them to panel.
        ampersand_label = JLabel("CDLI's ID: ")
        self.left_field = JTextField('&')
        equals_label = JLabel('=')
        self.right_field = JTextField()
        tooltip_text = ("<html><body>This is the ID and text's designation "
                        "according to<br/>the CDLI catalog. If your text is "
                        "not yet in the<br/>catalog, please email "
                        "[email protected] to get<br/>an ID and designation.")
        help_label = self.build_help_label(tooltip_text)
        panel.add(ampersand_label)
        panel.add(self.left_field)
        panel.add(equals_label)
        panel.add(self.right_field)
        panel.add(help_label)
        # Set up constraints to tell panel how to position components.
        layout.putConstraint(SpringLayout.WEST, ampersand_label, 20,
                             SpringLayout.WEST, panel)
        layout.putConstraint(SpringLayout.NORTH, ampersand_label, 23,
                             SpringLayout.NORTH, panel)
        layout.putConstraint(SpringLayout.WEST, self.left_field, 90,
                             SpringLayout.WEST, panel)
        layout.putConstraint(SpringLayout.NORTH, self.left_field, 20,
                             SpringLayout.NORTH, panel)
        layout.putConstraint(SpringLayout.WEST, equals_label, 5,
                             SpringLayout.EAST, self.left_field)
        layout.putConstraint(SpringLayout.NORTH, equals_label, 23,
                             SpringLayout.NORTH, panel)
        layout.putConstraint(SpringLayout.WEST, self.right_field, 5,
                             SpringLayout.EAST, equals_label)
        layout.putConstraint(SpringLayout.NORTH, self.right_field, 20,
                             SpringLayout.NORTH, panel)
        layout.putConstraint(SpringLayout.WEST, help_label, 5,
                             SpringLayout.EAST, self.right_field)
        layout.putConstraint(SpringLayout.NORTH, help_label, 23,
                             SpringLayout.NORTH, panel)
        layout.putConstraint(SpringLayout.EAST, panel, 15, SpringLayout.EAST,
                             help_label)
        layout.putConstraint(SpringLayout.SOUTH, panel, 10, SpringLayout.SOUTH,
                             help_label)
        # Add this to NewAtf JFrame
        return panel

    def build_projects_row(self):
        '''
        Builds the projects row.
        '''
        # Build own panel with SpringLayout.
        panel = JPanel()
        layout = SpringLayout()
        panel.setLayout(layout)
        # Create necessary components and add them to panel.
        project_label = JLabel('Project: ')
        self.right_combo = JComboBox()
        self.right_combo.setEditable(True)

        def create_project_list():
            '''
            Prepares list of projects and subprojects ordered with the default
            one first.
            '''
            default_project = self.projects['default'][0].split('/')[0]
            if '/' in self.projects['default']:
                default_subproject = self.projects['default'].split('/')[1]
            else:
                default_subproject = ''
            projects = [default_project]
            subprojects = [default_subproject]
            # User created projects might not be in default dictionary
            for project in self.projects.keys():
                if (project != default_project and project != 'default'):
                    projects.append(project)
                # Default project might not have subproject
            if default_project in self.projects.keys():
                if default_subproject:
                    for subproject in self.projects[default_project]:
                        if (subproject != default_subproject):
                            subprojects.append(subproject)
            return projects, subprojects

        self.left_combo = JComboBox(create_project_list()[0])
        # Make left combo keep size no matter how long project names are
        self.left_combo.setPreferredSize(Dimension(125, 30))
        self.left_combo.setMinimumSize(self.left_combo.getPreferredSize())
        self.left_combo.setMaximumSize(self.left_combo.getPreferredSize())
        self.left_combo.setSize(self.left_combo.getPreferredSize())

        self.right_combo = JComboBox(create_project_list()[1])
        # Prevent right combo to change sizes dynamically
        self.right_combo.setPreferredSize(Dimension(100, 30))
        self.right_combo.setMinimumSize(self.left_combo.getPreferredSize())
        self.right_combo.setMaximumSize(self.left_combo.getPreferredSize())
        self.right_combo.setSize(self.left_combo.getPreferredSize())

        action_listener = ComboActionListener(self.right_combo, self.projects)
        self.left_combo.addActionListener(action_listener)
        self.left_combo.setEditable(True)
        self.right_combo.setEditable(True)

        slash_label = JLabel('/')

        tooltip_text = ("<html><body>Choose project from list or insert a new "
                        "one.<br/>You can leave the right-hand field blank."
                        "</body><html>")
        help_label = self.build_help_label(tooltip_text)
        panel.add(project_label)
        panel.add(self.left_combo)
        panel.add(slash_label)
        panel.add(self.right_combo)
        panel.add(help_label)
        # Set up constraints to tell panel how to position components.
        layout.putConstraint(SpringLayout.WEST, project_label, 15,
                             SpringLayout.WEST, panel)
        layout.putConstraint(SpringLayout.NORTH, project_label, 18,
                             SpringLayout.NORTH, panel)
        layout.putConstraint(SpringLayout.WEST, self.left_combo, 90,
                             SpringLayout.WEST, panel)
        layout.putConstraint(SpringLayout.NORTH, self.left_combo, 15,
                             SpringLayout.NORTH, panel)
        layout.putConstraint(SpringLayout.WEST, slash_label, 5,
                             SpringLayout.EAST, self.left_combo)
        layout.putConstraint(SpringLayout.NORTH, slash_label, 18,
                             SpringLayout.NORTH, panel)
        layout.putConstraint(SpringLayout.WEST, self.right_combo, 5,
                             SpringLayout.EAST, slash_label)
        layout.putConstraint(SpringLayout.NORTH, self.right_combo, 15,
                             SpringLayout.NORTH, panel)
        layout.putConstraint(SpringLayout.WEST, help_label, 5,
                             SpringLayout.EAST, self.right_combo)
        layout.putConstraint(SpringLayout.NORTH, help_label, 18,
                             SpringLayout.NORTH, panel)
        layout.putConstraint(SpringLayout.EAST, panel, 15, SpringLayout.EAST,
                             help_label)
        layout.putConstraint(SpringLayout.SOUTH, panel, 10, SpringLayout.SOUTH,
                             help_label)
        # Add this to NewAtf JFrame
        return panel

    def build_language_row(self):
        '''
        Builds the language row.
        '''
        # Build own panel with SpringLayout.
        panel = JPanel()
        layout = SpringLayout()
        panel.setLayout(layout)
        # Get language list from settings.yaml, removing the default one from
        # the list
        languages = self.languages.keys()
        languages.remove('default')
        # Create necessary components and add them to panel.
        language_label = JLabel('Language: ')
        self.language_combo = JComboBox(languages)
        # Set selected language to default
        self.language_combo.setSelectedItem(self.languages['default'])
        tooltip_text = "Choose a language from the dropdown menu."
        help_label = self.build_help_label(tooltip_text)
        panel.add(language_label)
        panel.add(self.language_combo)
        panel.add(help_label)
        # Set up constraints to tell panel how to position components.
        layout.putConstraint(SpringLayout.WEST, language_label, 15,
                             SpringLayout.WEST, panel)
        layout.putConstraint(SpringLayout.NORTH, language_label, 18,
                             SpringLayout.NORTH, panel)
        layout.putConstraint(SpringLayout.WEST, self.language_combo, 90,
                             SpringLayout.WEST, panel)
        layout.putConstraint(SpringLayout.NORTH, self.language_combo, 15,
                             SpringLayout.NORTH, panel)
        layout.putConstraint(SpringLayout.WEST, help_label, 5,
                             SpringLayout.EAST, self.language_combo)
        layout.putConstraint(SpringLayout.NORTH, help_label, 18,
                             SpringLayout.NORTH, panel)
        layout.putConstraint(SpringLayout.EAST, panel, 15, SpringLayout.EAST,
                             help_label)
        layout.putConstraint(SpringLayout.SOUTH, panel, 10, SpringLayout.SOUTH,
                             help_label)
        # Add this to NewAtf JFrame
        return panel

    def build_buttons_row(self):
        '''
        Add OK/Cancel/Blank buttons.
        '''
        # Build own panel with SpringLayout.
        panel = JPanel()
        layout = SpringLayout()
        panel.setLayout(layout)
        # Create necessary components and add them to panel.
        create_button = JButton('Create template',
                                actionPerformed=self.create_template)
        leave_button = JButton('Leave blank', actionPerformed=self.blank)
        cancel_button = JButton('Cancel', actionPerformed=self.cancel)
        panel.add(create_button)
        panel.add(leave_button)
        panel.add(cancel_button)

        # Set up constraints to tell panel how to position components.
        layout.putConstraint(SpringLayout.WEST, create_button, 15,
                             SpringLayout.WEST, panel)
        layout.putConstraint(SpringLayout.NORTH, create_button, 15,
                             SpringLayout.NORTH, panel)
        layout.putConstraint(SpringLayout.WEST, leave_button, 5,
                             SpringLayout.EAST, create_button)
        layout.putConstraint(SpringLayout.NORTH, leave_button, 15,
                             SpringLayout.NORTH, panel)
        layout.putConstraint(SpringLayout.WEST, cancel_button, 5,
                             SpringLayout.EAST, leave_button)
        layout.putConstraint(SpringLayout.NORTH, cancel_button, 15,
                             SpringLayout.NORTH, panel)
        layout.putConstraint(SpringLayout.EAST, panel, 15, SpringLayout.EAST,
                             cancel_button)
        layout.putConstraint(SpringLayout.SOUTH, panel, 10, SpringLayout.SOUTH,
                             cancel_button)
        # Add this to NewAtf JFrame
        return panel

    def build_help_label(self, tooltip_text):
        icon = ImageIcon(find_image_resource('smallhelp'))
        label = JLabel()
        label.setIcon(icon)
        label.setToolTipText(tooltip_text)
        return label

    def cancel(self, event):
        self.cancelled = True
        self.dispose()

    def blank(self, event):
        self.controller.show_template()
        self.dispose()

    def create_template(self, event):
        '''
        Put together user selected elements of the template following ATF
        file format.
        '''
        # &-line
        # E.g. &X001001 = JCS 48, 089
        and_line = "{} = {}".format(self.left_field.getText().encode('utf-8'),
                                    self.right_field.getText().encode('utf-8'))

        # Project line
        # E.g. #project: cams/gkab
        # E.g. #project: rimanum
        project_line = "#project: {}".format(
            self.left_combo.getSelectedItem().encode('utf-8'))
        if self.right_combo.getSelectedItem():
            project_line = "{}/{}".format(
                project_line,
                self.right_combo.getSelectedItem().encode('utf-8'))

        # Language line
        # E.g. #atf: lang akk-x-stdbab
        language = self.language_combo.getSelectedItem()
        language_code = self.languages[language]

        # Protocol line/s
        # E.g. #atf: use unicode
        protocols = ''
        for protocol in self.protocols:
            protocols += '#atf: use {}\n'.format(protocol)

        # Put together all lines to create the template and show in ATF area
        self.controller.template = ('{}\n'
                                    '{}\n'
                                    '#atf: lang {}\n'
                                    '{}\n'.format(and_line, project_line,
                                                  language_code, protocols))
        self.controller.show_template()
        self.dispose()
示例#10
0
文件: NewAtfView.py 项目: oracc/nammu
class NewAtfView(JDialog):
    '''
    Prompt user to choose some options to create a template for a new ATF
    file.
    '''
    def __init__(self, controller, projects, languages, protocols):
        self.modalityType = Dialog.ModalityType.APPLICATION_MODAL
        self.controller = controller
        self.projects = projects
        self.languages = languages
        self.protocols = protocols
        self.cancelled = False
        self.springLayout = SpringLayout()
        self.pane = self.getContentPane()

    def display(self):
        '''
        Displays window.
        '''
        self.build()
        self.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE)
        self.setResizable(False)
        self.setTitle("New ATF template")
        self.pack()
        self.setLocationRelativeTo(None)
        self.visible = 1

    def build(self):
        '''
        Puts all the window components together in the JFrame
        '''
        layout = BoxLayout(self.getContentPane(), BoxLayout.Y_AXIS)
        self.setLayout(layout)

        # Create all necessary panels
        ampersand_panel = self.build_ampersand_row()
        project_panel = self.build_projects_row()
        language_panel = self.build_language_row()
        buttons_panel = self.build_buttons_row()

        # Add panels to main JFrame
        self.add(ampersand_panel)
        self.add(project_panel)
        self.add(language_panel)
        self.add(buttons_panel)

    def build_ampersand_row(self):
        '''
        Builds the &-line row.
        '''
        # Build own panel with SpringLayout.
        panel = JPanel()
        layout = SpringLayout()
        panel.setLayout(layout)
        # Create necessary components and add them to panel.
        ampersand_label = JLabel("CDLI's ID: ")
        self.left_field = JTextField('&')
        equals_label = JLabel('=')
        self.right_field = JTextField()
        tooltip_text = ("<html><body>This is the ID and text's designation "
                        "according to<br/>the CDLI catalog. If your text is "
                        "not yet in the<br/>catalog, please email "
                        "[email protected] to get<br/>an ID and designation."
                        )
        help_label = self.build_help_label(tooltip_text)
        panel.add(ampersand_label)
        panel.add(self.left_field)
        panel.add(equals_label)
        panel.add(self.right_field)
        panel.add(help_label)
        # Set up constraints to tell panel how to position components.
        layout.putConstraint(SpringLayout.WEST,
                             ampersand_label,
                             20,
                             SpringLayout.WEST,
                             panel)
        layout.putConstraint(SpringLayout.NORTH,
                             ampersand_label,
                             23,
                             SpringLayout.NORTH,
                             panel)
        layout.putConstraint(SpringLayout.WEST,
                             self.left_field,
                             90,
                             SpringLayout.WEST,
                             panel)
        layout.putConstraint(SpringLayout.NORTH,
                             self.left_field,
                             20,
                             SpringLayout.NORTH,
                             panel)
        layout.putConstraint(SpringLayout.WEST,
                             equals_label,
                             5,
                             SpringLayout.EAST,
                             self.left_field)
        layout.putConstraint(SpringLayout.NORTH,
                             equals_label,
                             23,
                             SpringLayout.NORTH,
                             panel)
        layout.putConstraint(SpringLayout.WEST,
                             self.right_field,
                             5,
                             SpringLayout.EAST,
                             equals_label)
        layout.putConstraint(SpringLayout.NORTH,
                             self.right_field,
                             20,
                             SpringLayout.NORTH,
                             panel)
        layout.putConstraint(SpringLayout.WEST,
                             help_label,
                             5,
                             SpringLayout.EAST,
                             self.right_field)
        layout.putConstraint(SpringLayout.NORTH,
                             help_label,
                             23,
                             SpringLayout.NORTH,
                             panel)
        layout.putConstraint(SpringLayout.EAST,
                             panel,
                             15,
                             SpringLayout.EAST,
                             help_label)
        layout.putConstraint(SpringLayout.SOUTH,
                             panel,
                             10,
                             SpringLayout.SOUTH,
                             help_label)
        # Add this to NewAtf JFrame
        return panel

    def build_projects_row(self):
        '''
        Builds the projects row.
        '''
        # Build own panel with SpringLayout.
        panel = JPanel()
        layout = SpringLayout()
        panel.setLayout(layout)
        # Create necessary components and add them to panel.
        project_label = JLabel('Project: ')
        self.right_combo = JComboBox()
        self.right_combo.setEditable(True)

        def create_project_list():
            '''
            Prepares list of projects and subprojects ordered with the default
            one first.
            '''
            default_project = self.projects['default'][0].split('/')[0]
            if '/' in self.projects['default']:
                default_subproject = self.projects['default'].split('/')[1]
            else:
                default_subproject = ''
            projects = [default_project]
            subprojects = [default_subproject]
            # User created projects might not be in default dictionary
            for project in self.projects.keys():
                if (project != default_project and project != 'default'):
                    projects.append(project)
                # Default project might not have subproject
            if default_project in self.projects.keys():
                if default_subproject:
                    for subproject in self.projects[default_project]:
                        if (subproject != default_subproject):
                            subprojects.append(subproject)
            return projects, subprojects

        self.left_combo = JComboBox(create_project_list()[0])
        # Make left combo keep size no matter how long project names are
        self.left_combo.setPreferredSize(Dimension(125, 30))
        self.left_combo.setMinimumSize(self.left_combo.getPreferredSize())
        self.left_combo.setMaximumSize(self.left_combo.getPreferredSize())
        self.left_combo.setSize(self.left_combo.getPreferredSize())

        self.right_combo = JComboBox(create_project_list()[1])
        # Prevent right combo to change sizes dynamically
        self.right_combo.setPreferredSize(Dimension(100, 30))
        self.right_combo.setMinimumSize(self.left_combo.getPreferredSize())
        self.right_combo.setMaximumSize(self.left_combo.getPreferredSize())
        self.right_combo.setSize(self.left_combo.getPreferredSize())

        action_listener = ComboActionListener(self.right_combo,
                                              self.projects)
        self.left_combo.addActionListener(action_listener)
        self.left_combo.setEditable(True)
        self.right_combo.setEditable(True)

        slash_label = JLabel('/')

        tooltip_text = ("<html><body>Choose project from list or insert a new "
                        "one.<br/>You can leave the right-hand field blank."
                        "</body><html>")
        help_label = self.build_help_label(tooltip_text)
        panel.add(project_label)
        panel.add(self.left_combo)
        panel.add(slash_label)
        panel.add(self.right_combo)
        panel.add(help_label)
        # Set up constraints to tell panel how to position components.
        layout.putConstraint(SpringLayout.WEST,
                             project_label,
                             15,
                             SpringLayout.WEST,
                             panel)
        layout.putConstraint(SpringLayout.NORTH,
                             project_label,
                             18,
                             SpringLayout.NORTH,
                             panel)
        layout.putConstraint(SpringLayout.WEST,
                             self.left_combo,
                             90,
                             SpringLayout.WEST,
                             panel)
        layout.putConstraint(SpringLayout.NORTH,
                             self.left_combo,
                             15,
                             SpringLayout.NORTH,
                             panel)
        layout.putConstraint(SpringLayout.WEST,
                             slash_label,
                             5,
                             SpringLayout.EAST,
                             self.left_combo)
        layout.putConstraint(SpringLayout.NORTH,
                             slash_label,
                             18,
                             SpringLayout.NORTH,
                             panel)
        layout.putConstraint(SpringLayout.WEST,
                             self.right_combo,
                             5,
                             SpringLayout.EAST,
                             slash_label)
        layout.putConstraint(SpringLayout.NORTH,
                             self.right_combo,
                             15,
                             SpringLayout.NORTH,
                             panel)
        layout.putConstraint(SpringLayout.WEST,
                             help_label,
                             5,
                             SpringLayout.EAST,
                             self.right_combo)
        layout.putConstraint(SpringLayout.NORTH,
                             help_label,
                             18,
                             SpringLayout.NORTH,
                             panel)
        layout.putConstraint(SpringLayout.EAST,
                             panel,
                             15,
                             SpringLayout.EAST,
                             help_label)
        layout.putConstraint(SpringLayout.SOUTH,
                             panel,
                             10,
                             SpringLayout.SOUTH,
                             help_label)
        # Add this to NewAtf JFrame
        return panel

    def build_language_row(self):
        '''
        Builds the language row.
        '''
        # Build own panel with SpringLayout.
        panel = JPanel()
        layout = SpringLayout()
        panel.setLayout(layout)
        # Get language list from settings.yaml, removing the default one from
        # the list
        languages = self.languages.keys()
        languages.remove('default')
        # Create necessary components and add them to panel.
        language_label = JLabel('Language: ')
        self.language_combo = JComboBox(languages)
        # Set selected language to default
        self.language_combo.setSelectedItem(self.languages['default'])
        tooltip_text = "Choose a language from the dropdown menu."
        help_label = self.build_help_label(tooltip_text)
        panel.add(language_label)
        panel.add(self.language_combo)
        panel.add(help_label)
        # Set up constraints to tell panel how to position components.
        layout.putConstraint(SpringLayout.WEST,
                             language_label,
                             15,
                             SpringLayout.WEST,
                             panel)
        layout.putConstraint(SpringLayout.NORTH,
                             language_label,
                             18,
                             SpringLayout.NORTH,
                             panel)
        layout.putConstraint(SpringLayout.WEST,
                             self.language_combo,
                             90,
                             SpringLayout.WEST,
                             panel)
        layout.putConstraint(SpringLayout.NORTH,
                             self.language_combo,
                             15,
                             SpringLayout.NORTH,
                             panel)
        layout.putConstraint(SpringLayout.WEST,
                             help_label,
                             5,
                             SpringLayout.EAST,
                             self.language_combo)
        layout.putConstraint(SpringLayout.NORTH,
                             help_label,
                             18,
                             SpringLayout.NORTH,
                             panel)
        layout.putConstraint(SpringLayout.EAST,
                             panel,
                             15,
                             SpringLayout.EAST,
                             help_label)
        layout.putConstraint(SpringLayout.SOUTH,
                             panel,
                             10,
                             SpringLayout.SOUTH,
                             help_label)
        # Add this to NewAtf JFrame
        return panel

    def build_buttons_row(self):
        '''
        Add OK/Cancel/Blank buttons.
        '''
        # Build own panel with SpringLayout.
        panel = JPanel()
        layout = SpringLayout()
        panel.setLayout(layout)
        # Create necessary components and add them to panel.
        create_button = JButton('Create template',
                                actionPerformed=self.create_template)
        leave_button = JButton('Leave blank', actionPerformed=self.blank)
        cancel_button = JButton('Cancel', actionPerformed=self.cancel)
        panel.add(create_button)
        panel.add(leave_button)
        panel.add(cancel_button)

        # Set up constraints to tell panel how to position components.
        layout.putConstraint(SpringLayout.WEST,
                             create_button,
                             15,
                             SpringLayout.WEST,
                             panel)
        layout.putConstraint(SpringLayout.NORTH,
                             create_button,
                             15,
                             SpringLayout.NORTH,
                             panel)
        layout.putConstraint(SpringLayout.WEST,
                             leave_button,
                             5,
                             SpringLayout.EAST,
                             create_button)
        layout.putConstraint(SpringLayout.NORTH,
                             leave_button,
                             15,
                             SpringLayout.NORTH,
                             panel)
        layout.putConstraint(SpringLayout.WEST,
                             cancel_button,
                             5,
                             SpringLayout.EAST,
                             leave_button)
        layout.putConstraint(SpringLayout.NORTH,
                             cancel_button,
                             15,
                             SpringLayout.NORTH,
                             panel)
        layout.putConstraint(SpringLayout.EAST,
                             panel,
                             15,
                             SpringLayout.EAST,
                             cancel_button)
        layout.putConstraint(SpringLayout.SOUTH,
                             panel,
                             10,
                             SpringLayout.SOUTH,
                             cancel_button)
        # Add this to NewAtf JFrame
        return panel

    def build_help_label(self, tooltip_text):
        icon = ImageIcon(find_image_resource('smallhelp'))
        label = JLabel()
        label.setIcon(icon)
        label.setToolTipText(tooltip_text)
        return label

    def cancel(self, event):
        self.cancelled = True
        self.dispose()

    def blank(self, event):
        self.controller.show_template()
        self.dispose()

    def create_template(self, event):
        '''
        Put together user selected elements of the template following ATF
        file format.
        '''
        # &-line
        # E.g. &X001001 = JCS 48, 089
        and_line = "{} = {}".format(self.left_field.getText().encode('utf-8'),
                                    self.right_field.getText().encode('utf-8'))

        # Project line
        # E.g. #project: cams/gkab
        # E.g. #project: rimanum
        project_line = "#project: {}".format(
                            self.left_combo.getSelectedItem().encode('utf-8'))
        if self.right_combo.getSelectedItem():
            project_line = "{}/{}".format(
                            project_line,
                            self.right_combo.getSelectedItem().encode('utf-8'))

        # Language line
        # E.g. #atf: lang akk-x-stdbab
        language = self.language_combo.getSelectedItem()
        language_code = self.languages[language]

        # Protocol line/s
        # E.g. #atf: use unicode
        protocols = ''
        for protocol in self.protocols:
            protocols += '#atf: use {}\n'.format(protocol)

        # Put together all lines to create the template and show in ATF area
        self.controller.template = ('{}\n'
                                    '{}\n'
                                    '#atf: lang {}\n'
                                    '{}\n'.format(and_line, project_line,
                                                  language_code, protocols)
                                    )
        self.controller.show_template()
        self.dispose()
示例#11
0
class ConfigTab(ITab, JPanel):
    def __init__(self, callbacks):
        self._callbacks = callbacks
        self._helpers = callbacks.getHelpers()
        self.__initLayout__()

    def __initLayout__(self):
        self._levelComboBox = JComboBox()
        levelComboBoxSize = Dimension(300, 30)
        self._levelComboBox.setPreferredSize(levelComboBoxSize)
        self._levelComboBox.setMaximumSize(levelComboBoxSize)
        for level in range(0, 6):
            self._levelComboBox.addItem(str(level))

        self._techRenderedCheckBox = JCheckBox('Rendered', True)
        self._techTimebasedCheckBox = JCheckBox('Time-based', True)

        self._plugin_groups = {}
        for plugin in plugins:
            parent = plugin.__base__.__name__
            if not self._plugin_groups.has_key(parent):
                self._plugin_groups[parent] = []
            self._plugin_groups[parent].append(plugin)
        self._pluginCheckBoxes = []
        for pluginGroup in self._plugin_groups.values():
            for plugin in pluginGroup:
                self._pluginCheckBoxes.append(PluginCheckBox(plugin))

        self._positionReplaceCheckBox = JCheckBox('Replace', True)
        self._positionAppendCheckBox = JCheckBox('Append', False)

        displayItems = ({
            'label':
            'Level',
            'components': (self._levelComboBox, ),
            'description':
            'Level of code context escape to perform (1-5, Default:0).'
        }, {
            'label':
            'Techniques',
            'components': (
                self._techRenderedCheckBox,
                self._techTimebasedCheckBox,
            ),
            'description':
            'Techniques R(endered) T(ime-based blind). Default: RT.'
        }, {
            'label':
            'Template Engines',
            'components':
            self._pluginCheckBoxes,
            'description':
            'Force back-end template engine to this value(s).'
        }, {
            'label':
            'Payload position',
            'components': (
                self._positionReplaceCheckBox,
                self._positionAppendCheckBox,
            ),
            'description':
            'Scan payload position. This feature only appears in BurpExtension.'
        })

        layout = GroupLayout(self)
        self.setLayout(layout)
        layout.setAutoCreateGaps(True)
        layout.setAutoCreateContainerGaps(True)

        labelWidth = 200
        hgroup = layout.createParallelGroup(GroupLayout.Alignment.LEADING)
        vgroup = layout.createSequentialGroup()
        for displayItem in displayItems:
            label = JLabel(displayItem.get('label'))
            label.setToolTipText(displayItem.get('description'))
            _hgroup = layout.createSequentialGroup().addComponent(
                label, labelWidth, labelWidth, labelWidth)
            _vgroup = layout.createParallelGroup(
                GroupLayout.Alignment.BASELINE).addComponent(label)
            for component in displayItem.get('components'):
                _hgroup.addComponent(component)
                _vgroup.addComponent(component)
            hgroup.addGroup(_hgroup)
            vgroup.addGroup(_vgroup)

        layout.setHorizontalGroup(hgroup)
        layout.setVerticalGroup(vgroup)

    def getTabCaption(self):
        return 'Tplmap'

    def getUiComponent(self):
        return self

    def getLevel(self):
        return self._levelComboBox.getSelectedIndex()

    def getTechniques(self):
        return '%s%s' % ('R' if self._techRenderedCheckBox.isSelected(
        ) else '', 'T' if self._techTimebasedCheckBox.isSelected() else '')

    def getEngines(self):
        return [
            checkbox.getPlugin() for checkbox in self._pluginCheckBoxes
            if checkbox.isSelected()
        ]

    def getPayloadPosition(self):
        return {
            'replace': self._positionReplaceCheckBox.isSelected(),
            'append': self._positionAppendCheckBox.isSelected()
        }
示例#12
0
class ConfigTab( ITab, JPanel ):

    def __init__( self, callbacks ):
        self._callbacks = callbacks
        self._helpers = callbacks.getHelpers()
        self.__initLayout__()

    def __initLayout__( self ):
        self._levelComboBox = JComboBox()
        levelComboBoxSize = Dimension( 300, 30 )
        self._levelComboBox.setPreferredSize( levelComboBoxSize )
        self._levelComboBox.setMaximumSize( levelComboBoxSize )
        for level in range( 0, 6 ):
            self._levelComboBox.addItem( str( level ) )

        self._techRenderedCheckBox = JCheckBox( 'Rendered', True )
        self._techTimebasedCheckBox = JCheckBox( 'Time-based', True )

        self._plugin_groups = {}
        for plugin in plugins:
            parent = plugin.__base__.__name__
            if not self._plugin_groups.has_key( parent ):
                self._plugin_groups[ parent ] = []
            self._plugin_groups[ parent ].append( plugin )
        self._pluginCheckBoxes = []
        for pluginGroup in self._plugin_groups.values():
            for plugin in pluginGroup:
                self._pluginCheckBoxes.append( PluginCheckBox( plugin ) )

        self._positionReplaceCheckBox = JCheckBox( 'Replace', True )
        self._positionAppendCheckBox = JCheckBox( 'Append', False )

        displayItems = (
            {
                'label': 'Level',
                'components': ( self._levelComboBox, ),
                'description': 'Level of code context escape to perform (1-5, Default:0).'
            },
            {
                'label': 'Techniques',
                'components': ( self._techRenderedCheckBox, self._techTimebasedCheckBox, ),
                'description': 'Techniques R(endered) T(ime-based blind). Default: RT.'
            },
            {
                'label': 'Template Engines',
                'components': self._pluginCheckBoxes,
                'description': 'Force back-end template engine to this value(s).'
            },
            {
                'label': 'Payload position',
                'components': ( self._positionReplaceCheckBox, self._positionAppendCheckBox, ),
                'description': 'Scan payload position. This feature only appears in BurpExtension.'
            }
        )

        layout = GroupLayout( self )
        self.setLayout( layout )
        layout.setAutoCreateGaps( True )
        layout.setAutoCreateContainerGaps( True )

        labelWidth = 200
        hgroup =  layout.createParallelGroup( GroupLayout.Alignment.LEADING )
        vgroup = layout.createSequentialGroup()
        for displayItem in displayItems:
            label = JLabel( displayItem.get( 'label' ) )
            label.setToolTipText( displayItem.get( 'description' ) )
            _hgroup = layout.createSequentialGroup().addComponent( label, labelWidth, labelWidth, labelWidth )
            _vgroup = layout.createParallelGroup( GroupLayout.Alignment.BASELINE ).addComponent( label )
            for component in displayItem.get( 'components' ):
                _hgroup.addComponent( component )
                _vgroup.addComponent( component )
            hgroup.addGroup( _hgroup )
            vgroup.addGroup( _vgroup )

        layout.setHorizontalGroup( hgroup )
        layout.setVerticalGroup( vgroup )

    def getTabCaption( self ):
        return 'Tplmap'

    def getUiComponent( self ):
        return self

    def getLevel( self ):
        return self._levelComboBox.getSelectedIndex()

    def getTechniques( self ):
        return '%s%s' % ( 'R' if self._techRenderedCheckBox.isSelected() else '', 'T' if self._techTimebasedCheckBox.isSelected() else '' )

    def getEngines( self ):
        return [ checkbox.getPlugin() for checkbox in self._pluginCheckBoxes if checkbox.isSelected() ]

    def getPayloadPosition( self ):
        return { 'replace': self._positionReplaceCheckBox.isSelected(), 'append': self._positionAppendCheckBox.isSelected() }
示例#13
0
class Panel_Extension(JPanel):

    def get_combo_items(self, combo):

        itemcount = combo.getItemCount()
        items = []
        for i in range(itemcount):
            items.append(combo.getItemAt(i))

        return items

    def load_profiles(self):
        loaded_profiles = cb.callbacks.loadExtensionSetting("Profiles")
        if loaded_profiles is not None:
            self.profiles = loaded_profiles.splitlines()

            items = self.get_combo_items(self._profiles_combo)

            for profile in self.profiles:
                if profile not in items:
                    self._profiles_combo.addItem(profile)
        if len(self.profiles) > 0:
            self.load_fields(
                            "bao7uo WAF bypass" if "bao7uo WAF bypass" in self.profiles
                            else self.profiles[0]
                            )
        else:
            self.save_fields("bao7uo WAF bypass")

    def save_profiles(self):
        cb.callbacks.saveExtensionSetting(
                                            "Profiles",
                                            "\n".join(self.profiles)
                                            if len(self.profiles) > 0
                                            else None
                                           )

    def load_fields(self, profile):
        self.parent.panel_update_cookies._update_values()
        values = self.parent.panel_update_cookies.values
        for key in values.keys():
            if key is None:
                break
            loaded = cb.callbacks.loadExtensionSetting(profile + "_" + key)
            if loaded is None:
                break
            self.parent.panel_update_cookies.values[key] = loaded
            self.parent.panel_extension._profile_textfield.setText(profile)
        self.parent.panel_update_cookies._load_values()

        Update_cookies = cb.callbacks.loadExtensionSetting(
                                        profile + "_" + "Update_cookies"
                                        )

        if Update_cookies is not None:
            self.parent.panel_update_cookies._rowpanel2.removeAllElements()
            if len(Update_cookies) > 0:
                self.parent.panel_update_cookies._rowpanel2.addelements(
                                                           Update_cookies, True
                                                        )

        Remove_cookies = cb.callbacks.loadExtensionSetting(
                                        profile + "_" + "Remove_cookies"
                                        )

        if Remove_cookies is not None:
            self.parent.panel_remove_cookies._rowpanel1.removeAllElements()
            if len(Remove_cookies) > 0:
                self.parent.panel_remove_cookies._rowpanel1.addelements(
                                                        Remove_cookies, True
                                                        )

    def save_fields(self, profile, delete=False):

        items = self.get_combo_items(self._profiles_combo)

        if delete:
            if len(items) == 0:
                return
            items_profile_index = items.index(profile)
            if profile in self.profiles:
                self.profiles.remove(profile)
                self.save_profiles()
            if profile in items:
                self._profiles_combo.removeItem(profile)
        else:
            if profile not in self.profiles:
                self.profiles.append(profile)
                self.save_profiles()
            if profile not in items:
                self._profiles_combo.addItem(profile)
                items = self.get_combo_items(self._profiles_combo)
            items_profile_index = items.index(profile)

        self.parent.panel_update_cookies._update_values()

        values = self.parent.panel_update_cookies.values

        if delete:
            values = dict.fromkeys(values.iterkeys(), None)

        for key in values.keys():
            cb.callbacks.saveExtensionSetting(
                            profile + "_" + key, values[key]
                            )

        if delete:
            Update_cookies = None
            Remove_cookies = None
        else:
            Update_cookies = \
                self.parent.panel_update_cookies._rowpanel2.getAllElements(
                                                                    True
                                                                    )
            Remove_cookies = \
                self.parent.panel_remove_cookies._rowpanel1.getAllElements(
                                                                    True
                                                                    )

        cb.callbacks.saveExtensionSetting(
                                            profile + "_" + "Update_cookies",
                                            Update_cookies
                                          )
        cb.callbacks.saveExtensionSetting(
                                            profile + "_" + "Remove_cookies",
                                            Remove_cookies
                                        )

        if self._profiles_combo.getItemCount() > 0:
            if delete:
                select_index = items_profile_index - 1 \
                                if items_profile_index > 0 else 0
            else:
                select_index = items_profile_index

            self._profiles_combo.setSelectedIndex(select_index)

    def _button_delete_profile_pressed(self, msg):
        self.save_fields(self._profiles_combo.getSelectedItem(), True)

    def _button_save_fields_pressed(self, msg):
        self.save_fields(self._profile_textfield.getText())

    def _button_demo_pressed(self, msg):
        if JOptionPane.showConfirmDialog(
            msg.getSource().getParent().getParent(),
            "This will clear all session handling rules in Burp's \n" +
            "\"Project options -> Sessions\"\n" +
            "tab, even rules not produced by this extension. They\n" +
            "will be replaced with a sample/demo rule containing an\n" +
            "invoke extension session handler action.\n\n" +
            "A request which can be used for the demo will be sent\n" +
            "to the Repeater tab.\n\n" +
            "The demo URL will be placed in the settings, and the\n" +
            "contents of the \"Cookies to obtain\" list will be\n"+
            "replaced with a single demo cookie named\n" +
            "\"ClientSideCookie\"\n\n" +
            "Please check the PhantomJS settings, then click on\n" +
            "\'Add a new \"Get Cookies\" session handler\'.\n\n" +
            "Are you sure you want to remove any existing session\n" +
            "handling rules?",
            "Burp Suite / WAF Cookie Fetcher",
            JOptionPane.YES_NO_OPTION
        ) == JOptionPane.YES_OPTION:
            panel_update_cookies = self.getParent().panel_update_cookies
            for field in \
                    panel_update_cookies.fields:
                if "getText" in dir(field) and "getName" in dir(field):
                    field_name = field.getName()
                    if field_name == "url":
                        field.setText(cb.demo_url)
                    if field_name == "domain":
                        field.setText(cb.demo_domain)
            panel_update_cookies._rowpanel2.removeAllElements()
            panel_update_cookies._rowpanel2.addelement(cb.demo_cookie)

            cb.callbacks.loadConfigFromJson(cb.demo_json)
            cb.send_url_to_repeater(cb.demo_url)

    def _button_quit_pressed(self, msg):
        cb.callbacks.unloadExtension()

    def __init__(self):

        self.profiles = []

        self.setBorder(
            BorderFactory.createTitledBorder("Profiles")
            )
        self.setLayout(BoxLayout(self, BoxLayout.Y_AXIS))
        self._rowpanel1 = JPanel()
        self._rowpanel1.setLayout(BoxLayout(self._rowpanel1, BoxLayout.X_AXIS))

        self._profiles_combo = \
            JComboBox(
                      self.profiles
                      )
        self._profiles_combo.addItem("0"*40)
        self._profiles_combo.setMaximumSize(
                                self._profiles_combo.getPreferredSize()
                                )
        self._profiles_combo.removeItem("0" * 40)

        self._profiles_combo_panel = border_X_panel()

        self._demo_panel = button_panel(
                            "Demo",
                            self._button_demo_pressed
                            )
        self._quit_panel = button_panel(
                            "Unload WAF Cookie Fetcher",
                            self._button_quit_pressed
                            )

        self._profile_textfield = \
            PTTextField(
                        "profile",
                        "Profile name: ",
                        "bao7uo WAF bypass", None,
                        JButton(
                               "Save profile",
                               actionPerformed=self._button_save_fields_pressed
                            )
                    )

        self._profiles_combo_panel.add(self._profiles_combo)

        self._button_delete_profile = \
            JButton(
                    "Delete profile",
                    actionPerformed=self._button_delete_profile_pressed
                    )

        self._profiles_combo_panel.add(self._button_delete_profile)

        self._profiles_combo.addActionListener(actionlistener(self))

        self._rowpanel1.add(self._profiles_combo_panel)
        self._rowpanel1.add(Box.createHorizontalGlue())
        self._rowpanel1.add(self._profile_textfield)

        self._rowpanel1.add(Box.createHorizontalGlue())

        self._rowpanel1.add(self._demo_panel)
        self._rowpanel1.add(self._quit_panel)

        self.add(self._rowpanel1)
示例#14
0
class BurpExtender(IBurpExtender, IContextMenuFactory, IHttpListener,
                   ISessionHandlingAction, ITab):
    def registerExtenderCallbacks(self, callbacks):
        self._callbacks = callbacks
        self._helpers = callbacks.getHelpers()
        callbacks.setExtensionName("JC-AntiToken")
        callbacks.registerContextMenuFactory(self)
        # callbacks.registerHttpListener(self)
        callbacks.registerSessionHandlingAction(self)
        self.drawUI()

    def printcn(self, msg):
        print(msg.decode('utf-8').encode(sys_encoding))

    def drawUI(self):
        # 最外层:垂直盒子,内放一个水平盒子+一个胶水
        out_vBox_main = Box.createVerticalBox()
        # 次外层:水平盒子,使用说明
        usage = u'''
                             JC-AntiToken(简单防重放绕过)
        适用场景:防重放的方式为,提前向一个页面发送请求取得token,替换到下一个页面中。
        适用说明:
            1. 请求头中Headers和Data的值必须是JSON字符串,如:{"var":"value"}
            2. 左边tokenRegex的格式为:
                a. .*开头,.*结尾,用()括住要取出的token
                b. 如:.*,"token":"(.*?)".*
            3. 右边tokenRegex的格式为:
                a. 需要三个(),第二个()括住要替换的token
                b. 如:(.*,"token":")(.*?)(".*)
        详见:https://github.com/chroblert/JC-AntiToken
        '''
        hBox_usage = Box.createHorizontalBox()
        jpanel_test = JPanel()
        jTextarea_usage = JTextArea()
        jTextarea_usage.setText(usage)
        jTextarea_usage.setRows(13)
        jTextarea_usage.setEditable(False)
        # jpanel_test.add(jTextarea_usage)
        hBox_usage.add(JScrollPane(jTextarea_usage))

        # 次外层:水平盒子,内放两个垂直盒子
        hBox_main = Box.createHorizontalBox()
        # 左垂直盒子
        vBox_left = Box.createVerticalBox()
        # 右垂直盒子
        vBox_right = Box.createVerticalBox()

        # 左垂直盒子内部:发送请求包拿token
        # URL标签
        jlabel_url = JLabel("       URL: ")
        self.jtext_url = JTextField(generWidth)
        self.jtext_url.setMaximumSize(self.jtext_url.getPreferredSize())
        hbox_url = Box.createHorizontalBox()
        hbox_url.add(jlabel_url)
        hbox_url.add(self.jtext_url)
        hglue_url = Box.createHorizontalGlue()
        hbox_url.add(hglue_url)
        # 请求方法标签
        jlabel_reqMeth = JLabel("ReqMeth: ")
        self.jcombobox_reqMeth = JComboBox()
        self.jcombobox_reqMeth.addItem("GET")
        self.jcombobox_reqMeth.addItem("POST")
        hbox_reqMeth = Box.createHorizontalBox()
        hbox_reqMeth.add(jlabel_reqMeth)
        hbox_reqMeth.add(self.jcombobox_reqMeth)
        self.jcombobox_reqMeth.setMaximumSize(
            self.jcombobox_reqMeth.getPreferredSize())
        hglue_reqMeth = Box.createHorizontalGlue()
        hbox_reqMeth.add(hglue_reqMeth)
        # ContentType标签
        jlabel_contentType = JLabel("ConType: ")
        self.jcombobox_contentType = JComboBox()
        self.jcombobox_contentType.addItem("application/json")
        self.jcombobox_contentType.addItem("application/x-www-form-urlencoded")
        hbox_contentType = Box.createHorizontalBox()
        hbox_contentType.add(jlabel_contentType)
        hbox_contentType.add(self.jcombobox_contentType)
        self.jcombobox_contentType.setMaximumSize(
            self.jcombobox_contentType.getPreferredSize())
        hglue_contentType = Box.createHorizontalGlue()
        hbox_contentType.add(hglue_contentType)
        # Charset标签
        jlabel_charset = JLabel("CharSet: ")
        self.jcombobox_charset = JComboBox()
        self.jcombobox_charset.addItem("UTF-8")
        self.jcombobox_charset.addItem("GBK")
        hbox_charset = Box.createHorizontalBox()
        hbox_charset.add(jlabel_charset)
        hbox_charset.add(self.jcombobox_charset)
        self.jcombobox_charset.setMaximumSize(
            self.jcombobox_charset.getPreferredSize())
        hglue_charset = Box.createHorizontalGlue()
        hbox_charset.add(hglue_charset)
        # 请求头标签
        jlabel_headers = JLabel("Headers: ")
        self.jtext_headers = JTextField(generWidth)
        self.jtext_headers.setMaximumSize(
            self.jtext_headers.getPreferredSize())
        hbox_headers = Box.createHorizontalBox()
        hbox_headers.add(jlabel_headers)
        hbox_headers.add(self.jtext_headers)
        hglue_headers = Box.createHorizontalGlue()
        hbox_headers.add(hglue_headers)
        # 请求参数标签
        jlabel_data = JLabel("     Data: ")
        self.jtext_data = JTextField(generWidth)
        self.jtext_data.setPreferredSize(Dimension(20, 40))
        self.jtext_data.setMaximumSize(self.jtext_data.getPreferredSize())
        hbox_data = Box.createHorizontalBox()
        hbox_data.add(jlabel_data)
        hbox_data.add(self.jtext_data)
        hglue_data = Box.createHorizontalGlue()
        hbox_data.add(hglue_data)
        # token标志位置标签
        hbox_radiobtn = Box.createHorizontalBox()
        jlabel_tokenPosition = JLabel("Token Position: ")
        self.radioBtn01 = JRadioButton("Header")
        self.radioBtn02 = JRadioButton("Body")
        btnGroup = ButtonGroup()
        btnGroup.add(self.radioBtn01)
        btnGroup.add(self.radioBtn02)
        self.radioBtn01.setSelected(True)
        hbox_radiobtn.add(jlabel_tokenPosition)
        hbox_radiobtn.add(self.radioBtn01)
        hbox_radiobtn.add(self.radioBtn02)
        # token正则表达式标签
        hbox_token = Box.createHorizontalBox()
        hbox_token_header = Box.createHorizontalBox()
        hbox_token_body = Box.createHorizontalBox()
        # token正则表达式标签:header中
        jlabel_tokenName = JLabel("tokenName: ")
        self.jtext_tokenName = JTextField(tokenWidth)
        self.jtext_tokenName.setMaximumSize(
            self.jtext_tokenName.getPreferredSize())
        hbox_token_header.add(jlabel_tokenName)
        hbox_token_header.add(self.jtext_tokenName)
        hglue_token_header = Box.createHorizontalGlue()
        hbox_token_header.add(hglue_token_header)
        # token正则表达式标签:body中
        jlabel_tokenRegex = JLabel("tokenRegex: ")
        self.jtext_tokenRegex = JTextField(tokenWidth)
        self.jtext_tokenRegex.setMaximumSize(
            self.jtext_tokenRegex.getPreferredSize())
        hbox_token_body.add(jlabel_tokenRegex)
        hbox_token_body.add(self.jtext_tokenRegex)
        hglue_token_body = Box.createHorizontalGlue()
        hbox_token_body.add(hglue_token_body)
        # token正则表达式标签
        hbox_token.add(hbox_token_header)
        hbox_token.add(hbox_token_body)
        # test测试按钮
        hbox_test = Box.createHorizontalBox()
        jbtn_test = JButton("TEST", actionPerformed=self.btnTest)
        self.jlabel_test = JLabel("Result: ")
        hbox_test.add(jbtn_test)
        hbox_test.add(self.jlabel_test)
        # 水平胶水填充
        hGlue_test = Box.createHorizontalGlue()
        hbox_test.add(hGlue_test)
        hbox_test.setBorder(BorderFactory.createLineBorder(Color.green, 2))
        # 响应数据输出
        hbox_resp = Box.createHorizontalBox()
        self.jtextarea_resp = JTextArea()
        jsp = JScrollPane(self.jtextarea_resp)
        hbox_resp.add(self.jtextarea_resp)
        # 左垂直盒子:添加各种水平盒子
        vBox_left.add(hbox_url)
        vBox_left.add(hbox_reqMeth)
        vBox_left.add(hbox_contentType)
        vBox_left.add(hbox_charset)
        vBox_left.add(hbox_headers)
        vBox_left.add(hbox_data)
        vBox_left.add(hbox_radiobtn)
        vBox_left.add(hbox_token)
        vBox_left.add(hbox_test)
        vBox_left.add(hbox_resp)
        # 左垂直盒子:垂直胶水填充
        vGlue_test = Box.createGlue()
        vBox_left.add(vGlue_test)

        # 右垂直盒子内部:指定token在请求包中的位置
        # token标志位置单选按钮
        hbox_radiobtn_r = Box.createHorizontalBox()
        jlabel_tokenPosition_r = JLabel("Token Position: ")
        self.radioBtn01_r = JRadioButton("Header")
        self.radioBtn02_r = JRadioButton("Body")
        btnGroup_r = ButtonGroup()
        btnGroup_r.add(self.radioBtn01_r)
        btnGroup_r.add(self.radioBtn02_r)
        self.radioBtn01_r.setSelected(True)
        hbox_radiobtn_r.add(jlabel_tokenPosition_r)
        hbox_radiobtn_r.add(self.radioBtn01_r)
        hbox_radiobtn_r.add(self.radioBtn02_r)

        # token正则表达式
        hbox_token_r = Box.createHorizontalBox()
        hbox_token_header_r = Box.createHorizontalBox()
        hbox_token_body_r = Box.createHorizontalBox()
        # token正则表达式:在header中
        jlabel_tokenName_r = JLabel("tokenName: ")
        self.jtext_tokenName_r = JTextField(tokenWidth)
        self.jtext_tokenName_r.setMaximumSize(
            self.jtext_tokenName_r.getPreferredSize())
        hbox_token_header_r.add(jlabel_tokenName_r)
        hbox_token_header_r.add(self.jtext_tokenName_r)
        hglue_token_header_r = Box.createHorizontalGlue()
        hbox_token_header_r.add(hglue_token_header_r)
        # token正则表达式:在Body中
        jlabel_tokenRegex_r = JLabel("tokenRegex: ")
        self.jtext_tokenRegex_r = JTextField(tokenWidth)
        self.jtext_tokenRegex_r.setMaximumSize(
            self.jtext_tokenRegex_r.getPreferredSize())
        hbox_token_body_r.add(jlabel_tokenRegex_r)
        hbox_token_body_r.add(self.jtext_tokenRegex_r)
        hglue_token_body_r = Box.createHorizontalGlue()
        hbox_token_body_r.add(hglue_token_body_r)
        # token正则表达式
        hbox_token_r.add(hbox_token_header_r)
        hbox_token_r.add(hbox_token_body_r)
        # 测试按钮
        hbox_test_r = Box.createHorizontalBox()
        jbtn_test_r = JButton("SET", actionPerformed=self.btnTest_r)
        self.jlabel_test_r = JLabel("Result: ")
        hbox_test_r.add(jbtn_test_r)
        hbox_test_r.add(self.jlabel_test_r)
        # 水平胶水填充
        hGlue02 = Box.createHorizontalGlue()
        hbox_test_r.add(hGlue02)
        hbox_test_r.setBorder(BorderFactory.createLineBorder(Color.green, 2))

        # 右垂直盒子:添加各种水平盒子
        vBox_right.add(hbox_radiobtn_r)
        vBox_right.add(hbox_token_r)
        vBox_right.add(hbox_test_r)
        vGlue = Box.createVerticalGlue()
        vBox_right.add(vGlue)

        vBox_left.setBorder(BorderFactory.createLineBorder(Color.black, 3))
        vBox_right.setBorder(BorderFactory.createLineBorder(Color.black, 3))

        # 次外层水平盒子:添加左右两个垂直盒子
        hBox_main.add(vBox_left)
        hBox_main.add(vBox_right)
        # 最外层垂直盒子:添加次外层水平盒子,垂直胶水
        out_vBox_main.add(hBox_usage)
        out_vBox_main.add(hBox_main)

        self.mainPanel = out_vBox_main
        self._callbacks.customizeUiComponent(self.mainPanel)
        self._callbacks.addSuiteTab(self)

    def getTabCaption(self):
        return "JC-AntiToken"

    def getUiComponent(self):
        return self.mainPanel

    def testBtn_onClick(self, event):
        print("click button")

    def createMenuItems(self, invocation):
        menu = []
        if invocation.getToolFlag() == IBurpExtenderCallbacks.TOOL_REPEATER:
            menu.append(
                JMenuItem("Test menu", None, actionPerformed=self.testmenu))
        return menu

    def testmenu(self, event):
        print(event)
        print("JCTest test menu")

    def processHttpMessage(self, toolflag, messageIsRequest, messageInfo):
        service = messageInfo.getHttpService()
        if messageIsRequest:
            pass
            print("Host: " + str(service.getHost()))
            print("Port: " + str(service.getPort()))
            print("Protocol: " + str(service.getProtocol()))
            print("-----------------------------------")

    def getActionName(self):
        return "JC-AntiToken"

    def performAction(self, currentRequest, macroItems):
        # url
        url = self._helpers.analyzeRequest(currentRequest).getUrl()
        print(url)
        reqInfo = self._helpers.analyzeRequest(currentRequest)
        # request headers
        headers = reqInfo.getHeaders()
        print("ReqHeaders: " + headers)
        # get cookie from request header
        cookie = self.getCookieFromReq(headers)
        print(cookie)
        print(type(cookie))
        # offset to req body
        reqBodyOffset = reqInfo.getBodyOffset()
        reqBody = str(bytearray(currentRequest.getRequest()[reqBodyOffset:]))
        print("ReqBody: " + reqBody)
        # modify Request Body
        newToken = self.getNewToken(cookie)
        if newToken != None:
            # tokenInReqHeader
            res = False
            if self.tokenInHeader_r:
                # pass
                # 普通header中
                for header in headers:
                    if ":" in header:
                        if header.split(":")[0] == self.tokenName_r:
                            headers = [
                                self.tokenName_r + ": " + newToken
                                if i.split(":")[0] == self.tokenName_r else i
                                for i in headers
                            ]
                            res = True
                            break
                # cookie中
                if not res and cookie != None and self.tokenName_r + "=" in cookie:
                    # pass
                    for i in range(len(headers)):
                        if headers[i].startwith("Cookie:"):
                            cookies2 = headers[i]
                            cookies3 = cookies2.split(":")[1]
                            if ";" not in cookies3:
                                headers[
                                    i] = "Cookie: " + self.tokenName_r + "=" + newToken
                                res = True
                                break
                            else:
                                cookies4 = cookies3.split(";")
                                for cookie_idx in range(len(cookies4)):
                                    if self.tokenName_r + "+" in cookies4[
                                            cookie_idx]:
                                        cookies4[
                                            cookie_idx] = self.tokenName_r + "=" + newToken
                                        res = True
                                        break
                                headers[i] = "Cookie: " + ";".join(cookies4)
                                break
                # query string中
                if not res:
                    meth = headers[0].split(" ")[0]
                    url = headers[0].split(" ")[1]
                    ver = headers[0].split(" ")[2]
                    if self.tokenName_r + "=" not in url:
                        pass
                    else:
                        if "&" not in url:
                            url = url.split("?")[
                                0] + "?" + self.tokenName_r + "=" + newToken
                            headers[0] = meth + " " + url + " " + ver
                        else:
                            params = url.split("?")[1].split("&")
                            for i in range(len(params)):
                                if self.tokenName_r + "=" in params[i]:
                                    params[
                                        i] = self.tokenName_r + "=" + newToken
                                    break
                            url = url.split("?")[0] + "?" + "&".join(params)
                            headers[0] = meth + " " + url + " " + ver
            # tokenInReqBody
            else:
                if re.match(self.tokenRegex_r, reqBody):
                    try:
                        reqBody = re.sub(self.tokenRegex_r,
                                         r'\g<1>' + newToken + r'\g<3>',
                                         reqBody, 0, re.M | re.I)
                    except Exception as e:
                        print(e)
                        # print(reqBody)
                        # reqBody = re.sub(self.tokenRegex_r,r'\g<1>'+newToken+r'\g<3>',reqBody,0,re.M|re.I)

            # if re.match(r'(.*?"_tokenName":")([a-zA-Z0-9]{6,})(")',reqBody):
            #     reqBody = re.sub(r'(.*?"_tokenName":")([a-zA-Z0-9]{6,})(")',r'\1'+newToken+r'\3',reqBody,0,re.M|re.I)
        # rebuild request
        reqMessage = self._helpers.buildHttpMessage(headers, bytes(reqBody))
        # forward
        currentRequest.setRequest(reqMessage)
        print("++++++++++++++++++++++++")

    def getCookieFromReq(self, headers):
        for header in headers:
            if re.match(r'^Cookie:', header, re.I):
                return re.match(r'^Cookie: (.*)', header, re.I).group(1)

    # get new token
    def getNewToken(self, cookie):
        print(cookie)
        print("getNewToken")
        # url = "http://myip.ipip.net"
        headers_cookie = {
            'Cookie': cookie,
        }
        if cookie != '':
            self.headers.update(**headers_cookie)
        if self.reqMeth == "GET":
            resp = self.sendGetHttp(self.url, self.headers, self.data,
                                    self.contentType)
        else:
            resp = self.sendPostHttp(self.url, self.headers, self.data,
                                     self.contentType)
        respBody = resp.read()
        respInfo = resp.info()
        if self.tokenInHeader:
            if respInfo.getheader(self.tokenName) != None:
                newToken = respInfo.getheader(self.tokenName)
                print(newToken)
                return newToken
            else:
                regexPattern = '.*' + self.tokenName + '=(.*?);'
                if respInfo.getheader("set-cookie") != None:
                    cookies = respInfo.getheader("set-cookie")
                    if re.match(regexPattern, cookies, re.M | re.I):
                        newToken = re.match(regexPattern, cookies,
                                            re.M | re.I).group(1)
                        print("newToken: ", newToken)
                        return newToken
                    else:
                        return None
                else:
                    return None
        else:
            regexPattern = self.tokenRegex
            if re.match(regexPattern, respBody, re.M | re.I):
                newToken = re.match(regexPattern, respBody,
                                    re.M | re.I).group(1)
                print("newToken: ", newToken)
                return newToken
            else:
                return None

    def sendGetHttp(self, url, headers, data, contentType):
        context = ssl._create_unverified_context()
        headers_contentType = {'Content-Type': contentType}
        if not headers.has_key("Content-Type"):
            headers.update(**headers_contentType)
        headers_userAgent = {
            'User-Agent':
            'Mozilla/6.0 (iPhone; CPU iPhone OS 8_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/8.0 Mobile/10A5376e Safari/8536.25'
        }
        if not headers.has_key("User-Agent"):
            headers.update(**headers_userAgent)
        try:
            if data != None:
                # if "urlencode" in contentType:
                data = urllib.urlencode(data)
                url = url + "?" + data
                req = urllib2.Request(url, headers=headers)
            else:
                req = urllib2.Request(url, headers=headers)
            resp = urllib2.urlopen(req, context=context)
            return resp
        except urllib2.HTTPError as error:
            print("ERROR: ", error)
            return None

    def sendPostHttp(self, url, headers, data, contentType):
        context = ssl._create_unverified_context()
        headers_contentType = {'Content-Type': contentType}
        if not headers.has_key("Content-Type"):
            headers.update(**headers_contentType)
        headers_userAgent = {
            'User-Agent':
            'Mozilla/6.0 (iPhone; CPU iPhone OS 8_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/8.0 Mobile/10A5376e Safari/8536.25'
        }
        if not headers.has_key("User-Agent"):
            headers.update(**headers_userAgent)
        print(headers)
        resp = ""
        print("data: ", data)
        if data != None:
            if "urlencode" in contentType:
                data = urllib.urlencode(data)
                req = urllib2.Request(url, headers=headers, data=data)
            else:
                data = json.dumps(data)
                req = urllib2.Request(url, headers=headers, data=data)
        else:
            if "urlencode" in contentType:
                req = urllib2.Request(url, headers=headers)
            else:
                data = json.dumps(data)
                req = urllib2.Request(url, headers=headers)
        try:
            resp = urllib2.urlopen(req, context=context)
            return resp
        except urllib2.HTTPError as error:
            print("ERROR: ", error)
            return None

    def btnTest(self, e):
        self.printcn("中文测试")
        self.url = self.jtext_url.getText()
        if self.url == "":
            self.jlabel_test.setText("please input url")
            return
        self.reqMeth = self.jcombobox_reqMeth.getSelectedItem()
        # 用户设置content-type
        self.contentType = self.jcombobox_contentType.getSelectedItem(
        ) + ";charset=" + self.jcombobox_charset.getSelectedItem()
        # 用户有没有自定义请求头
        if self.jtext_headers.getText() != "":
            self.headers = json.loads(self.jtext_headers.getText())
        else:
            self.headers = {}
        # 用户有没有自定义请求体
        if self.jtext_data.getText() != "":
            self.data = json.loads(self.jtext_data.getText())
        else:
            self.data = None
        self.tokenName = self.jtext_tokenName.getText()
        self.tokenRegex = self.jtext_tokenRegex.getText()
        resp = ''
        if self.reqMeth == "GET":
            resp = self.sendGetHttp(self.url, self.headers, self.data,
                                    self.contentType)
        else:
            resp = self.sendPostHttp(self.url, self.headers, self.data,
                                     self.contentType)
        if resp == None:
            self.jlabel_test.setText("error,detail in extender output")
            return
        respHeader = resp.info().headers
        print("resp-headers: ", respHeader)
        # print(resp.info().getheader("content-type"))
        self.printcn(resp.info().getheader("set-cookie"))
        # print(resp.info().getheader("xxx"))
        respBody = resp.read()
        print("respBody: ", respBody)
        self.jtextarea_resp.setText("".join(respHeader) + "\n" +
                                    "".join(respBody))
        if (self.radioBtn01.isSelected()):
            self.tokenInHeader = True
            if self.tokenName == "":
                self.jlabel_test.setText("please input tokenName")
                return
        else:
            self.tokenInHeader = False
            if self.tokenRegex == "":
                self.jlabel_test.setText("please input tokenRegex")
                return
        print(self.reqMeth)
        newToken = self.getNewToken("")
        if newToken != None:
            self.jlabel_test.setText("Result: " + str(newToken))
            self.jlabel_test.setBackground(Color.cyan)
        else:
            self.jlabel_test.setText("Result: None")

    def btnTest_r(self, e):
        self.tokenName_r = self.jtext_tokenName_r.getText()
        self.tokenRegex_r = self.jtext_tokenRegex_r.getText()
        if (self.radioBtn01_r.isSelected()):
            self.tokenInHeader_r = True
            if self.tokenName_r == "":
                self.jlabel_test_r.setText("please input tokenName")
                return
        else:
            self.tokenInHeader_r = False
            if self.tokenRegex_r == "":
                self.jlabel_test_r.setText("please input tokenRegex")
                return
        self.jlabel_test_r.setText("SUCCESS")
示例#15
0
class Process_EVTX1WithUISettingsPanel(IngestModuleIngestJobSettingsPanel):
    # Note, we can't use a self.settings instance variable.
    # Rather, self.local_settings is used.
    # https://wiki.python.org/jython/UserGuide#javabean-properties
    # Jython Introspector generates a property - 'settings' on the basis
    # of getSettings() defined in this class. Since only getter function
    # is present, it creates a read-only 'settings' property. This auto-
    # generated read-only property overshadows the instance-variable -
    # 'settings'

    # We get passed in a previous version of the settings so that we can
    # prepopulate the UI
    # TODO: Update this for your UI
    def __init__(self, settings):
        self.local_settings = settings
        self.initComponents()
        self.customizeComponents()

    # TODO: Update this for your UI
    def checkBoxEvent(self, event):
        if self.checkbox.isSelected():
            self.local_settings.setSetting('All', 'true')
        else:
            self.local_settings.setSetting('All', 'false')
        if self.checkbox1.isSelected():
            self.local_settings.setSetting('Application', 'true')
        else:
            self.local_settings.setSetting('Application', 'false')
        if self.checkbox2.isSelected():
            self.local_settings.setSetting('Security', 'true')
        else:
            self.local_settings.setSetting('Security', 'false')
        if self.checkbox3.isSelected():
            self.local_settings.setSetting('System', 'true')
        else:
            self.local_settings.setSetting('System', 'false')
        if self.checkbox4.isSelected():
            self.local_settings.setSetting('Other', 'true')
            self.area.setEnabled(True)
        else:
            self.local_settings.setSetting('Other', 'false')
            self.area.setEnabled(False)
        if self.filterCheckbox.isSelected():
            self.local_settings.setSetting('Filter', 'true')
            self.filterField.setEnabled(True)
            self.filterSelector.setEnabled(True)
            self.filterInput.setEnabled(True)
        else:
            self.local_settings.setSetting('Filter', 'false')
            self.filterField.setEnabled(False)
            self.filterSelector.setEnabled(False)
            self.filterInput.setEnabled(False)
        if self.sortCheckbox.isSelected():
            self.local_settings.setSetting('SortDesc', 'true')
        else:
            self.local_settings.setSetting('SortDesc', 'false')

    def keyPressed(self, event):
        self.local_settings.setSetting('EventLogs', self.area.getText())

    # TODO: Update this for your UI
    def initComponents(self):
        self.setLayout(BoxLayout(self, BoxLayout.Y_AXIS))
        self.setAlignmentX(JComponent.LEFT_ALIGNMENT)

        self.checkbox = JCheckBox("All Logs",
                                  actionPerformed=self.checkBoxEvent)
        self.checkbox1 = JCheckBox("Application.Evtx",
                                   actionPerformed=self.checkBoxEvent)
        self.checkbox2 = JCheckBox("Security.EVTX",
                                   actionPerformed=self.checkBoxEvent)
        self.checkbox3 = JCheckBox("System.EVTX",
                                   actionPerformed=self.checkBoxEvent)
        self.checkbox4 = JCheckBox(
            "Other - Input in text area below then check this box",
            actionPerformed=self.checkBoxEvent)

        # Scrollable text area for additional log names
        self.area = JTextArea(3, 10)
        self.area.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0))
        self.area.setEnabled(False)
        self.pane = JScrollPane()
        self.pane.getViewport().add(self.area)

        self.add(self.checkbox)
        self.add(self.checkbox1)
        self.add(self.checkbox2)
        self.add(self.checkbox3)
        self.add(self.checkbox4)
        self.add(self.pane)

        self.add(JSeparator())
        self.add(JSeparator())

        self.filterCheckbox = JCheckBox("Filter",
                                        actionPerformed=self.checkBoxEvent)
        self.filterCheckbox.setLayout(
            BoxLayout(self.filterCheckbox, BoxLayout.X_AXIS))
        self.add(self.filterCheckbox)

        self.filterPanel = JPanel()
        self.filterPanel.setLayout(
            BoxLayout(self.filterPanel, BoxLayout.X_AXIS))
        self.filterField = JComboBox([
            "Computer Name", "Event Identifier", "Event Level", "Source Name",
            "Event Detail"
        ])
        self.filterField.setEnabled(False)
        self.filterField.setMaximumSize(self.filterField.getPreferredSize())
        self.filterSelector = JComboBox(
            ["equals", "not equals", "contains", "starts with", "ends with"])
        self.filterSelector.setEnabled(False)
        self.filterSelector.setMaximumSize(
            self.filterSelector.getPreferredSize())
        self.filterInput = JTextField()
        self.filterInput.setEnabled(False)
        self.filterInput.setMaximumSize(
            Dimension(512,
                      self.filterInput.getPreferredSize().height))
        self.filterPanel.add(self.filterField)
        self.filterPanel.add(self.filterSelector)
        self.filterPanel.add(self.filterInput)

        self.add(self.filterPanel)

        self.sortCheckbox = JCheckBox("Sort Event Counts Descending",
                                      actionPerformed=self.checkBoxEvent)
        self.add(self.sortCheckbox)

    # TODO: Update this for your UI
    def customizeComponents(self):
        self.checkbox.setSelected(
            self.local_settings.getSetting('All') == 'true')
        self.checkbox1.setSelected(
            self.local_settings.getSetting('Application') == 'true')
        self.checkbox2.setSelected(
            self.local_settings.getSetting('Security') == 'true')
        self.checkbox3.setSelected(
            self.local_settings.getSetting('System') == 'true')
        self.checkbox4.setSelected(
            self.local_settings.getSetting('Other') == 'true')
        self.area.setText(self.local_settings.getSetting('EventLogs'))

    # Return the settings used
    def getSettings(self):
        self.local_settings.setSetting('EventLogs', self.area.getText())
        self.local_settings.setSetting('FilterField',
                                       self.filterField.getSelectedItem())
        self.local_settings.setSetting('FilterMode',
                                       self.filterSelector.getSelectedItem())
        self.local_settings.setSetting('FilterInput',
                                       self.filterInput.getText())
        return self.local_settings