Beispiel #1
0
    def __init__(self, frame, what, entries, pingFun):
        JDialog(frame, what)
        self.frame   = frame
        self.entries = entries
        self.pingFun = pingFun
        pane = self.getRootPane().getContentPane()

        self.ent_pane, self.ent_list, self.ent = self.createList(entries)
        pane.add(self.ent_pane, BorderLayout.WEST)

        actionPanel = JPanel()
        actionPanel.setLayout(GridLayout(20, 1))
        self.text = JTextField(20)
        actionPanel.add(self.text)
        change = JButton('Change')
        change.setActionCommand('Change')
        change.addActionListener(self)
        actionPanel.add(change)
        actionPanel.add(JLabel(''))
        quit = JButton('Exit')
        quit.setActionCommand('Exit')
        quit.addActionListener(self)
        actionPanel.add(quit)
        actionPanel.add(JLabel(''))
        pane.add(actionPanel, BorderLayout.CENTER)

        self.pack()
Beispiel #2
0
    def __init__(self, frame, chart, pingFun):
        JDialog(frame)
        self.setTitle("Chart Settings")
        self.setModal(True)
        self.pingFun = pingFun
        pane = self.getRootPane().getContentPane()
        pane.setLayout(GridLayout(7, 2))
        pane.add(JLabel("Marker color"))
        self.markerPanel = self.createColorPanel(chart.markerColor, pane)
        pane.add(JLabel("Positive selection color"))
        self.posPanel = self.createColorPanel(chart.posColor, pane)
        pane.add(JLabel("Neutral color"))
        self.neuPanel = self.createColorPanel(chart.neuColor, pane)
        pane.add(JLabel("Balancing selection color "))
        self.balPanel = self.createColorPanel(chart.balColor, pane)

        self.add(JLabel("Label candidate selected loci"))
        self.selLabel = JCheckBox()
        self.selLabel.setSelected(chart.labelSelected)
        self.add(self.selLabel)
        self.add(JLabel("Label candidate neutral loci"))
        self.neuLabel = JCheckBox()
        self.neuLabel.setSelected(chart.labelNeutral)
        self.add(self.neuLabel)

        change = JButton("Change")
        change.setActionCommand("Change")
        change.addActionListener(self)
        pane.add(change)
        exit = JButton("Exit")
        exit.setActionCommand("Exit")
        exit.addActionListener(self)
        pane.add(exit)
        self.pack()
Beispiel #3
0
def tree():
  """
  tree(xmlfile="dsm2.xml")
    creates a tree view on a given xml file of dsm2 input data
  """
  tv = TreeViewer()
  mp2 = JPanel()
  mp2.setLayout(BorderLayout())
  tf = JTextField("dsm2.inp")
  pb = JButton("parse")
  mp2.add(tf,BorderLayout.CENTER)
  mp2.add(pb,BorderLayout.EAST)
  class ParseListener(ActionListener):
    def __init__(self,tf,tv,fr):
      self.tf = tf
      self.tv = tv
      self.fr = fr
    def actionPerformed(self,evt):
      dsm2file = self.tf.getText()
      parser = DSM2Parser(dsm2file)
      self.tv.xdoc = parser.dsm2_data.toXml()
      self.fr.getContentPane().add(self.tv.gui(),BorderLayout.CENTER)
      self.fr.pack()
      self.fr.setVisible(1)
  fr = JFrame()
  fr.setTitle("DSM2Tree")
  fr.setLocation(100,100)
  fr.setSize(600,60)
  fr.getContentPane().setLayout(BorderLayout())
  fr.getContentPane().add(mp2,BorderLayout.NORTH)
  al = ParseListener(tf,tv,fr)
  pb.addActionListener(al)
  fr.pack()
  fr.setVisible(1)
Beispiel #4
0
 def add_button(self, text, action):
     index = len(self.actions)
     name = "button%i" % index
     button = JButton(text)
     self.panel.add(button)
     button.setActionCommand(name)
     button.addActionListener(self)
     self.actions[name] = action
     return button
Beispiel #5
0
    def initGui(self):
        def make_game_selector():
            self.gameChanger = False
            def dbChange(evt):
                if evt.source.text: 
                    self.gamedb = GameDB(evt.source.text)
                    self.gameChanger = True
            def idChange(evt):
                if evt.source.text: 
                    self.gameid = evt.source.text
                    self.gameChanger = True
            def turnChange(evt):
                if evt.source.text: 
                    self.turnid = evt.source.text
                    self.gameChanger = True

            selector = JPanel()
            selector.add(JLabel("DB:"))
            selector.add(textfield(self.gamedb.dbfile, dbChange))
            selector.add(JLabel("Game ID:"))
            selector.add(textfield(self.gameid, idChange))
            selector.add(JLabel("Turn ID:"))
            selector.add(textfield(self.turnid, turnChange))
            return JScrollPane(selector)

        def make_content_panel():
            self.contentPanel = JPanel(GridLayout(1, 0, 5, 5))
            self.render()
            return JScrollPane(self.contentPanel)

        def save(self, txt, filename):
            pass
            
        def make_code_editor():
            import inspect
            panel = JPanel(BorderLayout(2,2))
            self.codeArea = JTextArea()
            self.codeArea.text = self.scoringModule and inspect.getsource(self.scoringModule) or ""
            panel.add(JScrollPane(self.codeArea), BorderLayout.CENTER)
            return panel

        self.frame.contentPane.add(make_game_selector(), BorderLayout.NORTH)
#        self.frame.contentPane.add(make_content_panel(), BorderLayout.WEST)
#        self.frame.contentPane.add(make_code_editor(),   BorderLayout.CENTER)
        pane = JSplitPane(JSplitPane.HORIZONTAL_SPLIT, make_content_panel(), make_code_editor())
        pane.setDividerLocation(self.frame.width/2)
        self.frame.contentPane.add(pane)
        reloadButton = JButton("Reload")
        def reload(evt):
            self.reload()
        reloadButton.addActionListener(reload)
        self.frame.contentPane.add(reloadButton, BorderLayout.SOUTH)
Beispiel #6
0
def makeScriptButton(button_name,script_name):
	from javax.swing import JButton
	from java.awt.event import ActionListener
	btn = JButton(button_name)
        #defin a class to invoke a script
	# creating a class called action which does not exist
	# this creates a python class deriving from ActionListener( a java class)
	class action(ActionListener):
		# defines a constructor
		def __init__(self,sname):
			self.sname = sname
		def actionPerformed(self, event):
			execfile(self.sname)
	# registers an instance of the action object with the button
	btn.addActionListener(action(script_name))
	return btn
def createSNTPanel():
  # Create out control panel
  panel = JPanel()
  button = JButton("Run SNT")
  panel.add(button)
  panel.add(JButton("Remove panel", actionPerformed=removeSNTPanel))
  op = OptionPanel()
  layers = []
  cal = front.getLayerSet().getCalibrationCopy()
  for i, layer in enumerate(front.getLayerSet().getLayers()):
    layers.append(str(i+1) + ": " + str(IJ.d2s(layer.getZ() * cal.pixelWidth, 2)))
  c1 = op.addChoice("First section:", layers, 0, None)
  c2 = op.addChoice("Last section:", layers, len(layers)-1)
  button.addActionListener(Listener(c1, c2))
  panel.add(op)
  
  return panel
Beispiel #8
0
    def __init__(self):
        super(BobGui, self).__init__('BobPy')
        # IJ.log('okay?')
        # print('okay??')
        self.setLayout(BorderLayout())
        self.main_panel = JPanel()
        # self.main_panel.setLayout(MigLayout('insets 1 10 1 1'))
        self.main_panel.setLayout(MigLayout())

        dir_panel = JPanel()
        dir_panel.setLayout(BoxLayout(dir_panel, BoxLayout.X_AXIS))

        dir_label = JLabel('Experiment Folder:')
        dir_panel.add(dir_label)

        self.dir_text_field = JTextField(10)
        self.dir_text_field.addActionListener(
            ActionListenerFactory(self, self.text_field_al))
        dir_panel.add(self.dir_text_field)

        dir_button = JButton('open')
        dir_button.addActionListener(
            ActionListenerFactory(self, self.choose_dir_al))
        dir_panel.add(dir_button)

        self.main_panel.add(dir_panel, 'wrap, growx, spanx, pushx')

        add_key_args(self.main_panel, 'close_w',
                     ActionListenerFactory(self, self.close_al), KeyEvent.VK_W,
                     Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())

        self.add(self.main_panel, BorderLayout.CENTER)

        self.setPreferredSize(Dimension(650, 600))

        self.pack()
        self.setLocationRelativeTo(None)
        self.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE)
        self.setVisible(True)
Beispiel #9
0
    def __init__(self, program):
        self.setLayout(GridBagLayout())
        self.setBorder(make_title_border("User-Agent", padding=5))
        btn = JButton("Add to settings")
        ua_text = JTextField(program.user_agent)
        self.add(
            ua_text,
            make_constraints(weightx=4, fill=GridBagConstraints.HORIZONTAL))
        self.add(btn, make_constraints(weightx=1))
        self.setMaximumSize(
            Dimension(9999999,
                      self.getPreferredSize().height + 10))

        def add_to_options(event):
            prefix = "Generated by YWH-addon"
            config = json.loads(
                context.callbacks.saveConfigAsJson(
                    "proxy.match_replace_rules"))

            # remove other YWH addon rules
            match_replace_rules = filter(
                lambda rule: not rule["comment"].startswith(prefix),
                config["proxy"]["match_replace_rules"],
            )
            new_rule = {
                "is_simple_match": False,
                "enabled": True,
                "rule_type": "request_header",
                "string_match": "^User-Agent: (.*)$",
                "string_replace":
                "User-Agent: $1 {}".format(program.user_agent),
                "comment": "{} for {}".format(prefix, program.slug),
            }
            match_replace_rules.append(new_rule)
            config["proxy"]["match_replace_rules"] = match_replace_rules
            context.callbacks.loadConfigFromJson(json.dumps(config))

        btn.addActionListener(CallbackActionListener(add_to_options))
Beispiel #10
0
    def actionPerformed(self, e):
        bugs_tab = self.tabbed_panes[self.key].getComponentAt(1)
        tab_count = str(bugs_tab.getTabCount())

        request_tab = self.view.set_request_tab_pane(self.request_response)
        response_tab = self.view.set_response_tab_pane(self.request_response)
        bugs_tabbed_pane = self.view.set_bugs_tabbed_pane(
            request_tab, response_tab)

        bugs_tab.add(tab_count, bugs_tabbed_pane)
        index = bugs_tab.indexOfTab(tab_count)
        panel_tab = JPanel(GridBagLayout())
        panel_tab.setOpaque(False)
        label_title = JLabel(tab_count)
        button_close = JButton("x")
        button_close.setBorder(None)

        panel_tab.add(label_title)
        panel_tab.add(button_close)

        bugs_tab.setTabComponentAt(index, panel_tab)

        button_close.addActionListener(CloseTab(bugs_tab))
Beispiel #11
0
    def __init__(self, scopes):
        ColumnPanel.__init__(self)

        scope_list = JList(tuple(entry.scope for entry in scopes))
        scope_list.setVisibleRowCount(10)
        btn_list = RowPanel()
        select_all = JButton("Select all")
        select_all.setMaximumSize(select_all.getPreferredSize())
        select_all.addActionListener(
            CallbackActionListener(
                partial(self.do_selection, scope_list, scopes)))
        btn_list.add(select_all)

        add_scope = JButton("Add to scope")
        add_scope.setMaximumSize(add_scope.getPreferredSize())
        add_scope.addActionListener(
            CallbackActionListener(partial(self.add_to_scope, scope_list)))
        btn_list.add(add_scope)

        self.add(JScrollPane(scope_list))
        self.add(btn_list)
        self.setBorder(make_title_border("Scopes"))
        self.setMaximumSize(Dimension(9999999, self.getPreferredSize().height))
Beispiel #12
0
    def set_settings(self):
        self.settings = JPanel()
        layout = GroupLayout(self.settings)
        self.settings.setLayout(layout)
        layout.setAutoCreateGaps(True)

        load_file_button = JButton("Load JSON File")
        load_file_button.setActionCommand("load")
        load_file_button.addActionListener(
            SettingsAction(self, load_file_button, None))
        save_file_button = JButton("Save JSON File")
        save_file_button.setActionCommand("save")
        save_file_button.addActionListener(
            SettingsAction(None, save_file_button, self.tabbed_panes))

        horizontal_group1 = layout.createParallelGroup(
            GroupLayout.Alignment.LEADING)
        horizontal_group1.addComponent(load_file_button)
        horizontal_group1.addComponent(save_file_button)

        horizontal_group = layout.createSequentialGroup()
        horizontal_group.addGroup(horizontal_group1)

        layout.setHorizontalGroup(horizontal_group)

        vertical_group1 = layout.createParallelGroup(
            GroupLayout.Alignment.BASELINE)
        vertical_group1.addComponent(load_file_button)
        vertical_group2 = layout.createParallelGroup(
            GroupLayout.Alignment.BASELINE)
        vertical_group2.addComponent(save_file_button)

        vertical_group = layout.createSequentialGroup()
        vertical_group.addGroup(vertical_group1)
        vertical_group.addGroup(vertical_group2)

        layout.setVerticalGroup(vertical_group)
Beispiel #13
0
class EmulatorComponentProvider(ComponentProviderAdapter):
    def __init__(self, plugin):
        super(EmulatorComponentProvider,
              self).__init__(plugin.getTool(), "Emulator", "emulate_function")
        self.plugin = plugin

        self.panel = JPanel(GridBagLayout())
        c = GridBagConstraints()
        c.fill = GridBagConstraints.HORIZONTAL
        c.gridy = 0

        c.gridx = 0
        c.weightx = 0.8
        self.panel_label = JLabel("")
        self.panel.add(self.panel_label, c)

        c.gridx = 1
        c.weightx = 0.2
        self.panel_btn = JButton("Start")
        self.panel_btn.addActionListener(EmulatorBtnAction(self))
        self.panel.add(self.panel_btn, c)

        c.gridy = 1
        c.gridx = 0
        c.gridwidth = 2
        self.panel_input = JTextField()
        self.panel_input.addActionListener(EmulatorInputAction(self))
        self.panel.add(self.panel_input, c)

        self.setStatus("Stopped")

    def getComponent(self):
        return self.panel

    def setStatus(self, status):
        self.panel_label.setText(status)
Beispiel #14
0
    def make_hseg_tree_panel(self):
        root = DefaultMutableTreeNode(self.exper.name)

        for hseg in self.exper.hsegs():
            hseg_node = DefaultMutableTreeNode(hseg.name)
            root.add(hseg_node)
            hseg_at_deviations = self.exper.hseg_files_cab(
            ).archetype_deviations
            if len(hseg_at_deviations[hseg.name]) > 0:
                for definer, file_names in hseg_at_deviations[
                        hseg.name].items():
                    for file_name in file_names:
                        node_str = definer + ': ' + file_name

                        temp = DefaultMutableTreeNode(node_str)
                        hseg_node.add(temp)

        hseg_tree = JTree(root)
        hseg_tree.setCellRenderer(BobPyTreeCellRenderer())

        hseg_scroll_pane = JScrollPane()
        hseg_scroll_pane.getViewport().setView((hseg_tree))

        hseg_panel = JPanel(MigLayout('insets 0'))
        hseg_panel.add(hseg_scroll_pane, 'grow, span, push, wrap')

        run_button = JButton('Run')
        run_button.addActionListener(ActionListenerFactory(self, self.run_al))
        rerun_button = JButton('Rerun')
        rerun_button.addActionListener(
            ActionListenerFactory(self, self.rerun_al))

        hseg_panel.add(run_button)
        hseg_panel.add(rerun_button)

        return hseg_panel
Beispiel #15
0
def makeScriptComboBox(list):
    from javax.swing import JComboBox, JButton, JPanel
    from java.awt.event import ActionListener

    jcb = JComboBox(list)
    jcb.setSelectedIndex(0)
    plot_btn = JButton("Plot station")
    # create a Python class
    class PlotButtonAction(ActionListener):
        # defines a constructor
        def __init__(self, combo_box):
            self.cb = combo_box

        def actionPerformed(self, event):
            plotStation(self.cb.getSelectedIndex(), None)

    # registers an instance of the action object with the button
    plot_btn.addActionListener(PlotButtonAction(jcb))
    #
    alltw_btn = JButton("All Data")

    class AllButtonAction(ActionListener):
        # defines a constructor
        def __init__(self, combo_box):
            self.cb = combo_box

        def actionPerformed(self, event):
            plotStation(self.cb.getSelectedIndex(), 1)

    alltw_btn.addActionListener(AllButtonAction(jcb))
    #
    quit_btn = JButton("Quit")

    class QuitButtonAction(ActionListener):
        # defines a constructor
        def __init__(self, combo_box):
            self.cb = combo_box

        def actionPerformed(self, event):
            fr.dispose()

    quit_btn.addActionListener(QuitButtonAction(jcb))
    # add both button and combo box to a panel
    panel = JPanel()
    panel.setLayout(GridLayout(2, 2))
    panel.add(alltw_btn)
    panel.add(jcb)
    panel.add(plot_btn)
    panel.add(quit_btn)
    return panel
Beispiel #16
0
def makeScriptComboBox(list):
    from javax.swing import JComboBox, JButton, JPanel
    from java.awt.event import ActionListener
    jcb = JComboBox(list)
    jcb.setSelectedIndex(0)
    plot_btn = JButton("Plot station")

    # create a Python class
    class PlotButtonAction(ActionListener):
        # defines a constructor
        def __init__(self, combo_box):
            self.cb = combo_box

        def actionPerformed(self, event):
            plotStation(self.cb.getSelectedIndex(), None)

    # registers an instance of the action object with the button
    plot_btn.addActionListener(PlotButtonAction(jcb))
    #
    alltw_btn = JButton("All Data")

    class AllButtonAction(ActionListener):
        # defines a constructor
        def __init__(self, combo_box):
            self.cb = combo_box

        def actionPerformed(self, event):
            plotStation(self.cb.getSelectedIndex(), 1)

    alltw_btn.addActionListener(AllButtonAction(jcb))
    #
    quit_btn = JButton("Quit")

    class QuitButtonAction(ActionListener):
        # defines a constructor
        def __init__(self, combo_box):
            self.cb = combo_box

        def actionPerformed(self, event):
            fr.dispose()

    quit_btn.addActionListener(QuitButtonAction(jcb))
    # add both button and combo box to a panel
    panel = JPanel()
    panel.setLayout(GridLayout(2, 2))
    panel.add(alltw_btn)
    panel.add(jcb)
    panel.add(plot_btn)
    panel.add(quit_btn)
    return panel
Beispiel #17
0
    def __init__(self, frame, what, all, removed, pingFun):
        JDialog.__init__(self, frame, what)
        self.frame = frame
        self.all = all
        self.removed = removed
        self.pingFun = pingFun
        pane = self.getRootPane().getContentPane()

        self.sel_pane, self.sel_list, self.sel = self.createList(all)
        pane.add(self.sel_pane, BorderLayout.WEST)

        button_panel = JPanel()
        button_panel.setLayout(GridLayout(8, 1))
        button_panel.add(JLabel('<-- Selected'))
        button_panel.add(JLabel('Removed -->'))
        select = JButton('Select')
        select.setActionCommand('Select')
        select.addActionListener(self)
        button_panel.add(select)
        button_panel.add(JLabel(''))
        restrict = JButton('Remove')
        restrict.setActionCommand('Remove')
        restrict.addActionListener(self)
        button_panel.add(restrict)
        button_panel.add(JLabel(''))
        quit = JButton('Exit')
        quit.setActionCommand('Exit')
        quit.addActionListener(self)
        button_panel.add(quit)
        button_panel.add(JLabel(''))
        pane.add(button_panel, BorderLayout.CENTER)

        self.rem_pane, self.rem_list, self.rem = self.createList(removed)
        pane.add(self.rem_pane, BorderLayout.EAST)

        warning_panel = JPanel()
        warning_panel.add(
            JLabel(
                "Warning: Removing/adding loci or pops might take some time!"))
        pane.add(warning_panel, BorderLayout.NORTH)

        self.pack()
Beispiel #18
0
    def __init__(self, frame, what, all, removed, pingFun):
        JDialog.__init__(self,frame, what)
        self.frame   = frame
        self.all     = all
        self.removed = removed 
        self.pingFun = pingFun
        pane = self.getRootPane().getContentPane()

        self.sel_pane, self.sel_list, self.sel = self.createList(all)
        pane.add(self.sel_pane, BorderLayout.WEST)

        button_panel = JPanel()
        button_panel.setLayout(GridLayout(8,1))
        button_panel.add(JLabel('<-- Selected'))
        button_panel.add(JLabel('Removed -->'))
        select = JButton('Select')
        select.setActionCommand('Select')
        select.addActionListener(self)
        button_panel.add(select)
        button_panel.add(JLabel(''))
        restrict = JButton('Remove')
        restrict.setActionCommand('Remove')
        restrict.addActionListener(self)
        button_panel.add(restrict)
        button_panel.add(JLabel(''))
        quit = JButton('Exit')
        quit.setActionCommand('Exit')
        quit.addActionListener(self)
        button_panel.add(quit)
        button_panel.add(JLabel(''))
        pane.add(button_panel, BorderLayout.CENTER)

        self.rem_pane, self.rem_list, self.rem = self.createList(removed)
        pane.add(self.rem_pane, BorderLayout.EAST)


        warning_panel = JPanel()
        warning_panel.add(JLabel("Warning: Removing/adding loci or pops might take some time!"))
        pane.add(warning_panel, BorderLayout.NORTH)

        self.pack()
Beispiel #19
0
    def __init__(self, frame, chart, lociNames, pv,
                 ci, confLines, locusFst, isDominant, fdr):
        JDialog(frame)
        self.chart = chart
        self.frame = frame
        self.confLines = confLines
        self.isDominant = isDominant
        self.fdr = fdr
        pane = self.getRootPane().getContentPane()

        pane.setLayout(BorderLayout())

        self.initTable(lociNames, pv, ci, locusFst)
        scrollPane = JScrollPane(self.table)
        osName = System.getProperty('os.name').lower()

        if not System.getProperty('java.specification.version')[-1] == '5':
            self.table.setFillsViewportHeight(True)
        pane.add(scrollPane, BorderLayout.CENTER)

        buttonPane = JPanel()
        sll = JButton('Save loci list')
        sll.addActionListener(self)
        sll.setActionCommand('SLL')
        buttonPane.add(sll)
        sci = JButton('Save confidence intervals')
        sci.addActionListener(self)
        sci.setActionCommand('SCI')
        buttonPane.add(sci)
        close = JButton('Close')
        close.addActionListener(self)
        close.setActionCommand('Close')
        buttonPane.add(close)
        pane.add(buttonPane, BorderLayout.PAGE_END)


        self.pack()
Beispiel #20
0
    def __init__(self, callbacks, log):
        self.callbacks = callbacks
        self.log = log
        self.log_table = None  # to be set by caller

        self.setLayout(BoxLayout(self, BoxLayout.PAGE_AXIS))

        label = JLabel("Reload from Git Repo:")
        button = JButton("Reload")
        button.addActionListener(CommandPanel.ReloadAction(log))
        self.add(label)
        self.add(button)

        label = JLabel("Send selected entries to respective Burp tools:")
        button = JButton("Send")
        button.addActionListener(CommandPanel.SendAction(self))
        self.add(label)
        self.add(button)

        label = JLabel("Remove selected entries from Git Repo:")
        button = JButton("Remove")
        button.addActionListener(CommandPanel.RemoveAction(self, log))
        self.add(label)
        self.add(button)
Beispiel #21
0
    def __init__(self, callbacks, log):
        self.callbacks = callbacks
        self.log = log
        self.log_table = None # to be set by caller

        self.setLayout(BoxLayout(self, BoxLayout.PAGE_AXIS))

        label = JLabel("Reload from Git Repo:")
        button = JButton("Reload")
        button.addActionListener(CommandPanel.ReloadAction(log))
        self.add(label)
        self.add(button)

        label = JLabel("Send selected entries to respective Burp tools:")
        button = JButton("Send")
        button.addActionListener(CommandPanel.SendAction(self))
        self.add(label)
        self.add(button)

        label = JLabel("Remove selected entries from Git Repo:")
        button = JButton("Remove")
        button.addActionListener(CommandPanel.RemoveAction(self, log))
        self.add(label)
        self.add(button)
Beispiel #22
0
    def __init__(self, frame, chart, lociNames, pv, ci, confLines, locusFst,
                 isDominant, fdr):
        JDialog(frame)
        self.chart = chart
        self.frame = frame
        self.confLines = confLines
        self.isDominant = isDominant
        self.fdr = fdr
        pane = self.getRootPane().getContentPane()

        pane.setLayout(BorderLayout())

        self.initTable(lociNames, pv, ci, locusFst)
        scrollPane = JScrollPane(self.table)
        osName = System.getProperty('os.name').lower()

        if not System.getProperty('java.specification.version')[-1] == '5':
            self.table.setFillsViewportHeight(True)
        pane.add(scrollPane, BorderLayout.CENTER)

        buttonPane = JPanel()
        sll = JButton('Save loci list')
        sll.addActionListener(self)
        sll.setActionCommand('SLL')
        buttonPane.add(sll)
        sci = JButton('Save confidence intervals')
        sci.addActionListener(self)
        sci.setActionCommand('SCI')
        buttonPane.add(sci)
        close = JButton('Close')
        close.addActionListener(self)
        close.setActionCommand('Close')
        buttonPane.add(close)
        pane.add(buttonPane, BorderLayout.PAGE_END)

        self.pack()
Beispiel #23
0
class BurpExtender(IBurpExtender, ITab, IHttpListener,
                   IMessageEditorController, AbstractTableModel,
                   IContextMenuFactory, IExtensionStateListener):

    #
    # implement IBurpExtender
    #

    def registerExtenderCallbacks(self, callbacks):
        # keep a reference to our callbacks object
        self._callbacks = callbacks

        # obtain an extension helpers object
        self._helpers = callbacks.getHelpers()

        # set our extension name
        callbacks.setExtensionName("Burp Scope Monitor Experimental")

        self.GLOBAL_HANDLER_ANALYZED = False
        self.GLOBAL_HANDLER = False
        self.STATUS = False
        self.AUTOSAVE_REQUESTS = 10
        self.AUTOSAVE_TIMEOUT = 600  # 10 minutes should be fine
        self.CONFIG_INSCOPE = True

        self.BAD_EXTENSIONS_DEFAULT = [
            '.gif', '.png', '.js', '.woff', '.woff2', '.jpeg', '.jpg', '.css',
            '.ico', '.m3u8', '.ts', '.svg'
        ]
        self.BAD_MIMES_DEFAULT = [
            'gif', 'script', 'jpeg', 'jpg', 'png', 'video', 'mp2t'
        ]

        self.BAD_EXTENSIONS = self.BAD_EXTENSIONS_DEFAULT
        self.BAD_MIMES = self.BAD_MIMES_DEFAULT

        # create the log and a lock on which to synchronize when adding log entries

        self._currentlyDisplayedItem = None

        self.SELECTED_MODEL_ROW = 0
        self.SELECTED_VIEW_ROW = 0

        self._log = ArrayList()
        self._fullLog = ArrayList()
        self._lock = Lock()
        self._lockFile = Lock()

        # main split pane
        self._parentPane = JTabbedPane()

        self._splitpane = JSplitPane(JSplitPane.VERTICAL_SPLIT)

        ##### config pane
        self._config = JTabbedPane()

        config = JPanel()
        iexport = JPanel()

        #config.setLayout(BorderLayout())
        config.setLayout(None)
        iexport.setLayout(None)

        # config radio button
        X_BASE = 40
        Y_OFFSET = 5
        Y_OPTION = 200
        Y_OPTION_SPACING = 20
        Y_CHECKMARK_SPACING = 20

        self.showAllButton = JRadioButton(SHOW_ALL_BUTTON_LABEL, True)
        self.showNewButton = JRadioButton(SHOW_NEW_BUTTON_LABEL, False)
        self.showTestedButton = JRadioButton(SHOW_TEST_BUTTON_LABEL, False)

        self.showAllButton.setBounds(40, 60 + Y_OFFSET, 400, 30)
        self.showNewButton.setBounds(40, 80 + Y_OFFSET, 400, 30)
        self.showTestedButton.setBounds(40, 100 + Y_OFFSET, 400, 30)
        #self.showNewButton = JRadioButton(SHOW_NEW_BUTTON_LABEL, False)
        #self.showTestedButton = JRadioButton(SHOW_TEST_BUTTON_LABEL, False)

        self.showAllButton.addActionListener(self.handleRadioConfig)
        self.showNewButton.addActionListener(self.handleRadioConfig)
        self.showTestedButton.addActionListener(self.handleRadioConfig)

        self.clearButton = JButton("Clear")
        self.clearButton.addActionListener(self.handleClearButton)
        self.clearButton.setBounds(40, 20, 100, 30)

        self.startButton = JButton(MONITOR_ON_LABEL)
        self.startButton.addActionListener(self.handleStartButton)
        self.startButton.setBounds(150, 20, 200, 30)

        self.badExtensionsLabel = JLabel("Ignore extensions:")
        self.badExtensionsLabel.setBounds(X_BASE, 150, 200, 30)

        self.badExtensionsText = JTextArea("")
        self.loadBadExtensions()
        self.badExtensionsText.setBounds(X_BASE, 175, 310, 30)

        self.badExtensionsButton = JButton("Save")
        self.badExtensionsButton.addActionListener(
            self.handleBadExtensionsButton)
        self.badExtensionsButton.setBounds(355, 175, 70, 30)

        self.badExtensionsDefaultButton = JButton("Load Defaults")
        self.badExtensionsDefaultButton.addActionListener(
            self.handleBadExtensionsDefaultButton)
        self.badExtensionsDefaultButton.setBounds(430, 175, 120, 30)

        self.badMimesLabel = JLabel("Ignore mime types:")
        self.badMimesLabel.setBounds(X_BASE, 220, 200, 30)

        self.badMimesText = JTextArea("")
        self.loadBadMimes()
        self.badMimesText.setBounds(X_BASE, 245, 310, 30)

        self.badMimesButton = JButton("Save")
        self.badMimesButton.addActionListener(self.handleBadMimesButton)
        self.badMimesButton.setBounds(355, 245, 70, 30)

        self.badMimesDefaultButton = JButton("Load Defaults")
        self.badMimesDefaultButton.addActionListener(
            self.handleBadMimesDefaultButton)
        self.badMimesDefaultButton.setBounds(430, 245, 120, 30)

        self.otherLabel = JLabel("Other:")
        self.otherLabel.setBounds(40, 300, 120, 30)

        self.otherLabel2 = JLabel("Other:")
        self.otherLabel2.setBounds(X_BASE, Y_OPTION, 120, 30)

        self.autoSaveOption = JCheckBox("Auto save periodically")
        self.autoSaveOption.setSelected(True)
        self.autoSaveOption.addActionListener(self.handleAutoSaveOption)
        self.autoSaveOption.setBounds(X_BASE, Y_OPTION + Y_CHECKMARK_SPACING,
                                      420, 30)

        self.repeaterOptionButton = JCheckBox(
            "Repeater request automatically marks as analyzed")
        self.repeaterOptionButton.setSelected(True)
        self.repeaterOptionButton.addActionListener(
            self.handleRepeaterOptionButton)
        self.repeaterOptionButton.setBounds(50, 330, 420, 30)

        self.scopeOptionButton = JCheckBox("Follow Burp Target In Scope rules")
        self.scopeOptionButton.setSelected(True)
        self.scopeOptionButton.addActionListener(self.handleScopeOptionButton)
        self.scopeOptionButton.setBounds(50, 350, 420, 30)

        self.startOptionButton = JCheckBox("Autostart Scope Monitor")
        self.startOptionButton.setSelected(True)
        self.startOptionButton.addActionListener(self.handleStartOption)
        self.startOptionButton.setBounds(50, 350 + Y_OPTION_SPACING, 420, 30)

        self.markTestedRequestsProxy = JCheckBox(
            "Color request in Proxy tab if analyzed")
        self.markTestedRequestsProxy.setSelected(True)
        self.markTestedRequestsProxy.addActionListener(
            self.handleTestedRequestsProxy)
        self.markTestedRequestsProxy.setBounds(50, 350 + Y_OPTION_SPACING * 2,
                                               420, 30)

        self.markNotTestedRequestsProxy = JCheckBox(
            "Color request in Proxy tab if NOT analyzed")
        self.markNotTestedRequestsProxy.setSelected(True)
        self.markNotTestedRequestsProxy.addActionListener(
            self.handleNotTestedRequestsProxy)
        self.markNotTestedRequestsProxy.setBounds(50,
                                                  350 + Y_OPTION_SPACING * 3,
                                                  420, 30)

        self.saveButton = JButton("Save now")
        self.saveButton.addActionListener(self.handleSaveButton)
        self.saveButton.setBounds(X_BASE + 320, 95, 90, 30)

        self.loadButton = JButton("Load now")
        self.loadButton.addActionListener(self.handleLoadButton)
        self.loadButton.setBounds(X_BASE + 420, 95, 90, 30)

        self.selectPath = JButton("Select path")
        self.selectPath.addActionListener(self.selectExportFile)
        self.selectPath.setBounds(X_BASE + 530, 60, 120, 30)

        self.selectPathText = JTextArea("")
        self.selectPathText.setBounds(X_BASE, 60, 510, 30)

        self.selectPathLabel = JLabel("State file:")
        self.selectPathLabel.setBounds(X_BASE, 30, 200, 30)

        bGroup = ButtonGroup()

        bGroup.add(self.showAllButton)
        bGroup.add(self.showNewButton)
        bGroup.add(self.showTestedButton)

        config.add(self.clearButton)
        config.add(self.startButton)
        config.add(self.startOptionButton)
        config.add(self.showAllButton)
        config.add(self.showNewButton)
        config.add(self.showTestedButton)

        config.add(self.badExtensionsButton)
        config.add(self.badExtensionsText)
        config.add(self.badExtensionsLabel)

        config.add(self.badMimesButton)
        config.add(self.badMimesText)
        config.add(self.badMimesLabel)

        config.add(self.badExtensionsDefaultButton)
        config.add(self.badMimesDefaultButton)

        config.add(self.otherLabel)
        config.add(self.repeaterOptionButton)
        config.add(self.scopeOptionButton)
        config.add(self.markTestedRequestsProxy)
        config.add(self.markNotTestedRequestsProxy)

        iexport.add(self.saveButton)
        iexport.add(self.loadButton)
        iexport.add(self.selectPath)
        iexport.add(self.selectPathText)
        iexport.add(self.selectPathLabel)
        iexport.add(self.otherLabel2)
        iexport.add(self.autoSaveOption)

        self._config.addTab("General", config)
        self._config.addTab("Import/Export", iexport)

        ##### end config pane

        self._parentPane.addTab("Monitor", self._splitpane)
        self._parentPane.addTab("Config", self._config)

        # table of log entries
        self.logTable = Table(self)

        #self.logTable.setDefaultRenderer(self.logTable.getColumnClass(0), ColoredTableCellRenderer(self))

        self.logTable.setAutoCreateRowSorter(True)
        self.logTable.setRowSelectionAllowed(True)

        renderer = ColoredTableCellRenderer(self)
        #column = TableColumn(0, 190, renderer, None)

        print 'Initiating... '

        # this could be improved by fetching initial dimensions
        self.logTable.getColumn("URL").setPreferredWidth(720)  # noscope
        self.logTable.getColumn("URL").setResizable(True)

        self.logTable.getColumn("Checked").setCellRenderer(renderer)
        self.logTable.getColumn("Checked").setPreferredWidth(80)
        self.logTable.getColumn("Checked").setMaxWidth(80)

        self.logTable.getColumn("Method").setPreferredWidth(120)
        #self.logTable.getColumn("Method").setMaxWidth(120)
        self.logTable.getColumn("Method").setResizable(True)

        self.logTable.getColumn("Time").setPreferredWidth(120)  # noscope
        self.logTable.getColumn("Time").setResizable(True)

        scrollPane = JScrollPane(self.logTable)
        self._splitpane.setLeftComponent(scrollPane)

        # tabs with request/response viewers
        tabs = JTabbedPane()
        self._requestViewer = callbacks.createMessageEditor(self, False)
        self._responseViewer = callbacks.createMessageEditor(self, False)
        tabs.addTab("Request", self._requestViewer.getComponent())
        tabs.addTab("Response", self._responseViewer.getComponent())
        self._splitpane.setRightComponent(tabs)

        ## Row sorter shit

        #self._tableRowSorterAutoProxyAutoAction = CustomTableRowSorter(self.logTable.getModel())
        #self.logTable.setRowSorter(self._tableRowSorterAutoProxyAutoAction)

        markAnalyzedButton = JMenuItem("Mark Requests as Analyzed")
        markAnalyzedButton.addActionListener(markRequestsHandler(self, True))

        markNotAnalyzedButton = JMenuItem("Mark Requests as NOT Analyzed")
        markNotAnalyzedButton.addActionListener(
            markRequestsHandler(self, False))

        sendRequestMenu = JMenuItem("Send Request to Repeater")
        sendRequestMenu.addActionListener(sendRequestRepeater(self))

        deleteRequestMenu = JMenuItem("Delete request")
        deleteRequestMenu.addActionListener(deleteRequestHandler(self))

        self.menu = JPopupMenu("Popup")
        self.menu.add(markAnalyzedButton)
        self.menu.add(markNotAnalyzedButton)
        self.menu.add(sendRequestMenu)
        self.menu.add(deleteRequestMenu)

        # customize our UI components
        callbacks.customizeUiComponent(self._parentPane)
        callbacks.customizeUiComponent(self._splitpane)
        callbacks.customizeUiComponent(self._config)
        callbacks.customizeUiComponent(config)
        callbacks.customizeUiComponent(self.logTable)
        callbacks.customizeUiComponent(scrollPane)
        callbacks.customizeUiComponent(tabs)

        callbacks.registerContextMenuFactory(self)
        callbacks.registerExtensionStateListener(self)
        callbacks.registerScannerCheck(passiveScanner(self))

        # add the custom tab to Burp's UI
        callbacks.addSuiteTab(self)

        # register ourselves as an HTTP listener
        callbacks.registerHttpListener(self)

        self.loadConfigs()

        print "Loaded!"

        print "Experimental import state.. "
        self.importState("")

        self.SC = sched.scheduler(time.time, time.sleep)
        self.SCC = self.SC.enter(10, 1, self.autoSave, (self.SC, ))
        self.SC.run()

        return

    ##### CUSTOM CODE #####
    def loadConfigs(self):

        if self._callbacks.loadExtensionSetting("CONFIG_AUTOSTART") == "False":
            self.startOptionButton.setSelected(False)
            self.startOrStop(None, False)
        else:
            self.startOptionButton.setSelected(True)
            self.startOrStop(None, True)

        if self._callbacks.loadExtensionSetting("exportFile") != "":
            self.selectPathText.setText(
                self._callbacks.loadExtensionSetting("exportFile"))

        if self._callbacks.loadExtensionSetting("CONFIG_REPEATER") == "True":
            self.repeaterOptionButton.setSelected(True)
        else:
            self.repeaterOptionButton.setSelected(False)

        if self._callbacks.loadExtensionSetting("CONFIG_INSCOPE") == "True":
            self.scopeOptionButton.setSelected(True)
        else:
            self.scopeOptionButton.setSelected(False)

        if self._callbacks.loadExtensionSetting("CONFIG_AUTOSAVE") == "True":
            self.autoSaveOption.setSelected(True)
        else:
            self.autoSaveOption.setSelected(False)

        if self._callbacks.loadExtensionSetting(
                "CONFIG_HIGHLIGHT_TESTED") == "True":
            self.markTestedRequestsProxy.setSelected(True)
        else:
            self.markTestedRequestsProxy.setSelected(False)

        if self._callbacks.loadExtensionSetting(
                "CONFIG_HIGHLIGHT_NOT_TESTED") == "True":
            self.markNotTestedRequestsProxy.setSelected(True)
        else:
            self.markNotTestedRequestsProxy.setSelected(False)

        return

    def selectExportFile(self, event):
        parentFrame = JFrame()
        fileChooser = JFileChooser()
        fileChooser.setDialogTitle("Specify file to save state")
        fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY)

        userSelection = fileChooser.showOpenDialog(parentFrame)

        if (userSelection == JFileChooser.APPROVE_OPTION):
            fileLoad = fileChooser.getSelectedFile()
            filename = fileLoad.getAbsolutePath()

            self.selectPathText.setText(filename)
            print 'Filename selected:' + filename
            self._callbacks.saveExtensionSetting("exportFile", filename)

        return

    def extensionUnloaded(self):
        print 'extension unloading.. '

        print 'canceling scheduler.. '
        map(self.SC.cancel, self.SC.queue)
        return

    def loadBadExtensions(self):
        bad = self._callbacks.loadExtensionSetting("badExtensions")
        if bad:
            self.badExtensionsText.setText(bad)
            # transform text to array
            bad = bad.replace(" ", "")
            self.BAD_EXTENSIONS = bad.split(",")
        else:
            print 'no bad extension saved, reverting'
            self.badExtensionsText.setText(", ".join(self.BAD_EXTENSIONS))

    def loadBadMimes(self):
        bad = self._callbacks.loadExtensionSetting("badMimes")
        if bad:
            self.badMimesText.setText(bad)

            bad = bad.replace(" ", "")
            self.BAD_MIMES = bad.split(",")
        else:
            print 'no bad mimes saved, reverting'
            self.badMimesText.setText(", ".join(self.BAD_MIMES))

    ## GLOBAL CONTEXT CODE ##

    def createMenuItems(self, invocation):
        responses = invocation.getSelectedMessages()
        if responses > 0:
            ret = LinkedList()
            analyzedMenuItem = JMenuItem("Mark as analyzed")
            notAnalyzedMenuItem = JMenuItem("Mark as NOT analyzed")

            for response in responses:
                analyzedMenuItem.addActionListener(
                    handleMenuItems(self, response, "analyzed"))
                notAnalyzedMenuItem.addActionListener(
                    handleMenuItems(self, response, "not"))
            ret.add(analyzedMenuItem)
            ret.add(notAnalyzedMenuItem)
            return ret

    def getEndpoint(self, requestResponse):
        url_ = str(self._helpers.analyzeRequest(requestResponse).getUrl())
        o = urlparse(url_)

        url = o.scheme + "://" + o.netloc + o.path
        #print "Url3: " + url
        return url

    def getMethod(self, requestResponse):
        return self._helpers.analyzeRequest(requestResponse).getMethod()

    ##### CUSTOM CODE #####
    def handleTestedRequestsProxy(self, event):
        self._callbacks.saveExtensionSetting(
            "CONFIG_HIGHLIGHT_TESTED",
            str(self.markTestedRequestsProxy.isSelected()))
        return

    def handleNotTestedRequestsProxy(self, event):
        self._callbacks.saveExtensionSetting(
            "CONFIG_HIGHLIGHT_NOT_TESTED",
            str(self.markNotTestedRequestsProxy.isSelected()))
        return

    def handleStartOption(self, event):
        self._callbacks.saveExtensionSetting(
            "CONFIG_AUTOSTART", str(self.startOptionButton.isSelected()))
        #print 'saving autostart: ' + str(self.startOptionButton.isSelected())
        return

    def startOrStop(self, event, autoStart):
        if (self.startButton.getText() == MONITOR_OFF_LABEL) or autoStart:
            self.startButton.setText(MONITOR_ON_LABEL)
            self.startButton.setBackground(GREEN_COLOR)
            self.STATUS = True
        else:
            self.startButton.setText(MONITOR_OFF_LABEL)
            self.startButton.setBackground(RED_COLOR)
            self.STATUS = False

    def handleStartButton(self, event):
        self.startOrStop(event, False)

    def handleAutoSaveOption(self, event):
        self._callbacks.saveExtensionSetting(
            "CONFIG_AUTOSAVE", str(self.autoSaveOption.isSelected()))
        return

    def handleSaveButton(self, event):
        self.exportState("")

    def handleLoadButton(self, event):
        self.importState("")

    def handleRepeaterOptionButton(self, event):
        self._callbacks.saveExtensionSetting(
            "CONFIG_REPEATER", str(self.repeaterOptionButton.isSelected()))
        return

    def handleScopeOptionButton(self, event):
        self.CONFIG_INSCOPE = self.scopeOptionButton.isSelected()
        self._callbacks.saveExtensionSetting("CONFIG_INSCOPE",
                                             str(self.CONFIG_INSCOPE))
        return

    def handleBadExtensionsButton(self, event):
        #print "before BAD array: "
        print self.BAD_EXTENSIONS

        extensions = self.badExtensionsText.getText()
        self._callbacks.saveExtensionSetting("badExtensions", extensions)
        print 'New extensions blocked: ' + extensions
        bad = extensions.replace(" ", "")
        self.BAD_EXTENSIONS = bad.split(",")
        #print "BAD array: "
        #print self.BAD_EXTENSIONS

    def handleBadExtensionsDefaultButton(self, event):
        self.BAD_EXTENSIONS = self.BAD_EXTENSIONS_DEFAULT
        self.badExtensionsText.setText(", ".join(self.BAD_EXTENSIONS))
        self._callbacks.saveExtensionSetting("badExtensions",
                                             ", ".join(self.BAD_EXTENSIONS))
        return

    def handleBadMimesDefaultButton(self, event):
        self.BAD_MIMES = self.BAD_MIMES_DEFAULT
        self.badMimesText.setText(", ".join(self.BAD_MIMES))
        self._callbacks.saveExtensionSetting("badExtensions",
                                             ", ".join(self.BAD_MIMES))
        return

    def handleBadMimesButton(self, event):
        mimes = self.badMimesText.getText()
        self._callbacks.saveExtensionSetting("badMimes", mimes)
        print 'New mimes blocked: ' + mimes
        bad = mimes.replace(" ", "")
        self.BAD_MIMES = bad.split(",")

    def handleClearButton(self, event):
        print 'Clearing table'
        self._lock.acquire()
        self._log = ArrayList()
        self._fullLog = ArrayList()
        self._lock.release()
        return

    def handleRadioConfig(self, event):
        #print ' radio button clicked '
        #print event.getActionCommand()
        self._lock.acquire()

        if event.getActionCommand() == SHOW_ALL_BUTTON_LABEL:
            print "Showing all"
            self._log = self._fullLog
        elif event.getActionCommand() == SHOW_NEW_BUTTON_LABEL:
            print "Showing new scope only"
            tmpLog = ArrayList()
            for item in self._fullLog:
                if not (item._analyzed):
                    tmpLog.add(item)
            self._log = tmpLog
        elif event.getActionCommand() == SHOW_TEST_BUTTON_LABEL:
            print "Showing tested scope only"
            tmpLog = ArrayList()
            for item in self._fullLog:
                if item._analyzed:
                    tmpLog.add(item)
            self._log = tmpLog
        else:
            print "unrecognized radio label"

        self.fireTableDataChanged()
        #self._tableRowSorterAutoProxyAutoAction.toggleSortOrder(1)
        #self.toggleSortOrder(2)

        #self.logTable.toggleSortOrder(2)

        # refresh table?

        self._lock.release()

    #
    # implement ITab
    #

    def getTabCaption(self):
        return "Scope Monitor"

    def getUiComponent(self):
        return self._parentPane

    #
    # implement IHttpListener
    #

    def markAnalyzed(self, messageIsRequest, state):
        #print "markAnalyzed..."
        self._lock.acquire()

        url = self.getEndpoint(messageIsRequest)
        for item in self._log:
            if url == item._url:
                item._analyzed = state
                self._lock.release()
                return
        self._lock.release()
        return

    def processHttpMessage(self, toolFlag, messageIsRequest, messageInfo):
        # only process requests

        #print "processing httpMessage.."
        #print messageIsRequest

        print "processHttpMessage toolFlag: " + str(toolFlag)
        #print " -- " + str(self._callbacks.getToolName(toolFlag)) + " -- "

        if not (self.STATUS):
            return

        #print "global handler status: (true): " + str(self.GLOBAL_HANDLER)
        #print "(processHTTP) messageIsRequest"
        #print messageIsRequest

        isFromPassiveScan = False
        if toolFlag == 1234:
            print "1 processHttpMessage: processing passiveScan item"
            isFromPassiveScan = True

        if toolFlag != 1234:
            if messageIsRequest and not (self.GLOBAL_HANDLER):
                print "1.5 processHttpMessage droping message"
                return

        if self.scopeOptionButton.isSelected():
            url = self._helpers.analyzeRequest(messageInfo).getUrl()
            if not self._callbacks.isInScope(url):
                #print 'Url not in scope, skipping.. '
                return

        #print "still processing httpMessage.., request came from: " + self._callbacks.getToolName(toolFlag)
        if toolFlag == 1234:
            print "2 processHttpMessage: processing passiveScan item; setting toolFlag to proxy (4)"
            toolFlag = 4

        #toolFlag = 4
        if ((self._callbacks.getToolName(toolFlag) != "Repeater")
                and (self._callbacks.getToolName(toolFlag) != "Proxy")
                and (self._callbacks.getToolName(toolFlag) != "Target")):
            #print 'Aborting processHTTP, request came from: ' + str(self._callbacks.getToolName(toolFlag))
            print "Droping request from " + str(
                self._callbacks.getToolName(toolFlag))
            return

        #print "---> still processing from tool: " + str(self._callbacks.getToolName(toolFlag))

        url = self.getEndpoint(messageInfo)
        method = self.getMethod(messageInfo)

        #print "(processHTTP) before extensions check: " + url

        for extension in self.BAD_EXTENSIONS:
            if url.endswith(extension):
                return

        if messageInfo.getResponse():
            mime = self._helpers.analyzeResponse(
                messageInfo.getResponse()).getStatedMimeType()
            #print 'Declared mime:' + mime
            mime = mime.lower()
            if mime in self.BAD_MIMES:
                #print 'Bad mime:' + mime
                return

        #print "[httpMessage] before lock"
        # create a new log entry with the message details
        self._lock.acquire()
        row = self._log.size()

        for item in self._log:
            if url == item._url:
                if method == self._helpers.analyzeRequest(
                        item._requestResponse).getMethod():
                    #print 'duplicate URL+method, skipping.. '
                    self._lock.release()

                    # has it been analyzed?
                    analyzed = False
                    if self._callbacks.getToolName(toolFlag) == "Repeater":
                        if self.repeaterOptionButton.isSelected():
                            analyzed = True
                            #print "[httpMessage] setting analyzed as true"
                    if self.GLOBAL_HANDLER_ANALYZED:
                        analyzed = True

                    item._analyzed = analyzed
                    self.paintItems(messageInfo, item)

                    return

        #print "[httpMessage] before setComment"
        if not (isFromPassiveScan):
            messageInfo.setComment(SCOPE_MONITOR_COMMENT)
        # reached here, must be new entry
        analyzed = False
        if self._callbacks.getToolName(toolFlag) == "Repeater":
            if self.repeaterOptionButton.isSelected():
                analyzed = True
                #print "[httpMessage] setting analyzed as true"
        if self.GLOBAL_HANDLER_ANALYZED:
            analyzed = True

        #print "[httpMessage] after comment"
        #print 'in httpmessage, response:'
        #print self._helpers.analyzeResponse(messageInfo.getResponse())

        date = datetime.datetime.fromtimestamp(
            time.time()).strftime('%H:%M:%S %d %b %Y')
        entry = LogEntry(toolFlag,
                         self._callbacks.saveBuffersToTempFiles(messageInfo),
                         url, analyzed, date, method)
        #print "toolFlag: " + str(toolFlag)

        #print "(processHTTP) Adding URL: " + url
        self._log.add(entry)
        self._fullLog.add(entry)
        self.fireTableRowsInserted(row, row)

        self.paintItems(messageInfo, entry)

        self._lock.release()

        #print "columnCoun:" + str(self.logTable.getColumnCount())

    #
    # extend AbstractTableModel
    #

    def paintItems(self, messageInfo, item):
        '''
        print "in paint Items"
        print "mark color is: (true)" + str(self.markTestedRequestsProxy.isSelected())
        print "global handler analyzed:           :" + str(self.GLOBAL_HANDLER_ANALYZED)
        print "item analyzed should be the same ^^:" + str(item._analyzed)
        '''
        if (self.markTestedRequestsProxy.isSelected()) and (
                item._analyzed and self.GLOBAL_HANDLER_ANALYZED):
            messageInfo.setHighlight("green")
            return

        if self.markNotTestedRequestsProxy.isSelected() and not (
                item._analyzed):
            messageInfo.setHighlight("red")

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

    def getColumnCount(self):
        return 4

    def getColumnName(self, columnIndex):
        if columnIndex == 0:
            return "Checked"
        if columnIndex == 1:
            return "URL"
        if columnIndex == 2:
            return "Method"
        if columnIndex == 3:
            return "Time"

    def getValueAt(self, rowIndex, columnIndex):
        logEntry = self._log.get(rowIndex)

        #self.setBackground(Color.GREEN)
        return self.returnEntry(rowIndex, columnIndex, logEntry)

        if self.showNewButton.isSelected() and not (logEntry._analyzed):
            return self.returnEntry(rowIndex, columnIndex, logEntry)
        elif self.showTestedButton.isSelected() and logEntry._analyzed:
            return self.returnEntry(rowIndex, columnIndex, logEntry)
        elif self.showAllButton.isSelected():
            return self.returnEntry(rowIndex, columnIndex, logEntry)

    def returnEntry(self, rowIndex, columnIndex, entry):
        logEntry = self._log.get(rowIndex)
        if columnIndex == 0:
            if logEntry._analyzed:
                return "True"
            else:
                return "False"
        if columnIndex == 1:
            return self._helpers.urlDecode(logEntry._url)
        if columnIndex == 2:
            return logEntry._method
        if columnIndex == 3:
            return logEntry._date
            # return date
        return ""

    #
    # implement IMessageEditorController
    # this allows our request/response viewers to obtain details about the messages being displayed
    #

    def getHttpService(self):
        return self._currentlyDisplayedItem.getHttpService()

    def getRequest(self):
        #print 'getRequest called'
        return self._currentlyDisplayedItem.getRequest()

    def getResponse(self):
        #print 'getResponse called: '
        print self._currentlyDisplayedItem.getResponse()
        return self._currentlyDisplayedItem.getResponse()

    def exportRequest(self, entity, filename):

        line = str(entity._analyzed) + ","
        line = line + self._helpers.urlEncode(entity._url).replace(
            ",", "%2c") + ","  # URL is encoded so we should be good
        line = line + entity._method + ","
        line = line + entity._date
        line = line + '\n'

        #print 'Exporting: "' + line + '"'
        return line

    def exportUrlEncode(self, url):
        return self._helpers.urlEncode(url).replace(",", "%2c")

    def exportState(self, filename):
        filename = self.selectPathText.getText()

        if filename == "":
            filename = self._callbacks.loadExtensionSetting("exportFile")
            print 'Empty filename, skipping export'
            return
        else:
            self._callbacks.saveExtensionSetting("exportFile", filename)

        print 'saving state to: ' + filename

        savedUrls = []

        self._lockFile.acquire()
        try:
            with open(filename, 'r') as fr:
                savedEntries = fr.read().splitlines()
                savedUrls = []
                for savedEntry in savedEntries:
                    savedUrls.append(savedEntry.split(",")[1])
                #print "savedUrls len: " + str(len(savedUrls))
                #print "savedUrls:"
                #print savedUrls
                fr.close()
        except IOError:
            print "Autosaving skipped as file doesn't exist yet"

        with open(filename, 'a+') as f:

            for item in self._log:
                if self.exportUrlEncode(item._url) not in savedUrls:
                    line = self.exportRequest(item, "xx")
                    f.write(line)
            f.close()
        self._lockFile.release()

        return

    def importState(self, filename):
        filename = self.selectPathText.getText()

        if filename == "":
            filename = self._callbacks.loadExtensionSetting("exportFile")
            print 'Empty filename, skipping import'
            return
        else:
            self._callbacks.saveExtensionSetting("exportFile", filename)

        print 'loading state from: ' + filename

        self.STATUS = False

        self._lockFile.acquire()
        with open(filename, 'r') as f:

            proxy = self._callbacks.getProxyHistory()

            proxyItems = []
            for item in proxy:
                if item.getComment():
                    if SCOPE_MONITOR_COMMENT in item.getComment():
                        proxyItems.append(item)

            print 'proxyItems has: ' + str(len(proxyItems))
            # TODO - if no proxy items, sraight to import

            lines = f.read().splitlines()
            for line in lines:
                data = line.split(",")
                url = data[1]
                url = self._helpers.urlDecode(url)

                #print 'Saving: ' + url
                if not self._callbacks.isInScope(URL(url)):
                    print '-- imported url not in scope, skipping.. '
                    continue

                analyzed = False
                if data[0] == "True":
                    analyzed = True

                #print '.. simulating url search.. '
                requestResponse = None
                for request in proxyItems:
                    if url == self.getEndpoint(request):
                        #print 'Match found when importing for url: ' + url
                        requestResponse = request
                        break

                self._log.add(
                    LogEntry("", requestResponse, url, analyzed, data[3],
                             data[2]))

            self._lockFile.release()
        print 'finished loading.. '
        #print 'size: ' + str(self._log.size())
        self.fireTableDataChanged()

        if self.startButton.getText() == MONITOR_ON_LABEL:
            self.STATUS = True

        return

    def autoSave(self, sc):
        #print 'autosaving.. lol what'
        if self.autoSaveOption.isSelected():
            print "[" + self.getTime(
            ) + "] autosaving to " + self._callbacks.loadExtensionSetting(
                "exportFile")
            self.exportState("")

        self.SC.enter(self.AUTOSAVE_TIMEOUT, 1, self.autoSave, (self.SC, ))
        return

    def getTime(self):
        date = datetime.datetime.fromtimestamp(
            time.time()).strftime('%H:%M:%S')
        return date
Beispiel #24
0
    def __init__(self, extender=None, *rows):
        self.extender = extender

        self.table = table = JTable(ParameterProcessingRulesTableModel(*rows))
        table.setPreferredScrollableViewportSize(Dimension(500, 70))
        table.setRowSorter(TableRowSorter(table.getModel()))
        table.setFillsViewportHeight(True)

        gridBagLayout = GridBagLayout()
        gridBagLayout.columnWidths = [0, 0, 25, 0 ]
        gridBagLayout.rowHeights = [0, 0, 0, 0]
        gridBagLayout.columnWeights = [0.0, 1.0, 1.0, Double.MIN_VALUE]
        gridBagLayout.rowWeights = [0.0, 0.0, 0.0, Double.MIN_VALUE]
        self.setLayout(gridBagLayout)

        addButton = JButton("Add")
        addButton.addActionListener(AddRemoveParameterListener(table))
        addButtonConstraints = GridBagConstraints()
        addButtonConstraints.fill = GridBagConstraints.HORIZONTAL
        addButtonConstraints.insets = Insets(0, 0, 5, 5) 
        addButtonConstraints.gridx = 0
        addButtonConstraints.gridy = 0
        self.add(addButton, addButtonConstraints)

        removeButton = JButton("Remove")
        removeButton.addActionListener(AddRemoveParameterListener(table))
        removeButtonConstraints = GridBagConstraints()
        removeButtonConstraints.fill = GridBagConstraints.HORIZONTAL
        removeButtonConstraints.insets = Insets(0, 0, 5, 5) 
        removeButtonConstraints.gridx = 0
        removeButtonConstraints.gridy = 1
        self.add(removeButton, removeButtonConstraints)

        upButton = JButton("Up")
        upButton.addActionListener(AddRemoveParameterListener(table))
        upButtonConstraints = GridBagConstraints()
        upButtonConstraints.fill = GridBagConstraints.HORIZONTAL
        upButtonConstraints.insets = Insets(0, 0, 5, 5) 
        upButtonConstraints.gridx = 0
        upButtonConstraints.gridy = 2
        self.add(upButton, upButtonConstraints)

        downButton = JButton("Down")
        downButton.addActionListener(AddRemoveParameterListener(table))
        downButtonConstraints = GridBagConstraints()
        downButtonConstraints.fill = GridBagConstraints.HORIZONTAL
        downButtonConstraints.anchor = GridBagConstraints.NORTH
        downButtonConstraints.insets = Insets(0, 0, 5, 5) 
        downButtonConstraints.gridx = 0
        downButtonConstraints.gridy = 3
        self.add(downButton, downButtonConstraints)

        scrollPane = JScrollPane(table)
        scrollPaneConstraints = GridBagConstraints()
        scrollPaneConstraints.gridwidth = 2
        scrollPaneConstraints.gridheight = 5
        scrollPaneConstraints.insets = Insets(0, 0, 5, 5)
        scrollPaneConstraints.anchor = GridBagConstraints.NORTHWEST 
        scrollPaneConstraints.gridx = 1
        scrollPaneConstraints.gridy = 0
        self.add(scrollPane, scrollPaneConstraints)

        self.initParameterColumn(table)
        self.initColumnSizes(table)
Beispiel #25
0
class BobGui(JFrame):
    def choose_dir_al(self, e):

        dc = DirectoryChooser('Choose a bob_py experiment folder')
        self.dir_path = dc.getDirectory()

        self.choose_dir_textField.setText(self.dir_path)

    def textField_al(self, e):
        self.dir_path = self.choose_dir_textField.getText()

    def run_button_al(self, e):
        print('run button al')
        self.exper = bob_py.Exper(self.dir_path)
        # self.exper.hsegs()[0].nuc_bin().show()
        self.make_tree()

    def make_tree(self):
        root = DefaultMutableTreeNode(self.exper.name)
        for hseg in self.exper.hsegs():
            hseg_node = DefaultMutableTreeNode(hseg.name)
            root.add(hseg_node)
            for file_suf in hseg.file_dict():
                hseg_node.add(DefaultMutableTreeNode(file_suf))
        self.tree = JTree(root)
        scrollPane = JScrollPane()
        scrollPane.getViewport().setView((self.tree))
        # scrollPane.setPreferredSize(Dimension(300,250))

        tree_panel = JPanel()
        tree_panel.add(scrollPane)
        box_layout = BoxLayout(self.panel, BoxLayout.Y_AXIS)
        self.panel.setLayout(box_layout)
        self.panel.add(tree_panel)
        self.revalidate()

    def __init__(self):
        self.dir_path = ''

        self.panel = JPanel()
        box_layout = BoxLayout(self.panel, BoxLayout.Y_AXIS)
        self.panel.setLayout(box_layout)
        self.panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10))

        self.choose_dir_label = JLabel('Experiment Folder:')
        self.choose_dir_textField = JTextField(30)
        self.choose_dir_textField.addActionListener(
            ActionListenerFactory(self, self.textField_al))
        self.choose_dir_button = JButton('open')
        self.choose_dir_button.addActionListener(
            ActionListenerFactory(self, self.choose_dir_al))

        self.choose_dir_panel = JPanel()
        self.choose_dir_panel.add(self.choose_dir_label)
        self.choose_dir_panel.add(self.choose_dir_textField)
        self.choose_dir_panel.add(self.choose_dir_button)

        self.panel.add(self.choose_dir_panel)

        # root = DefaultMutableTreeNode()

        # self.meta_data_mode_label = JLabel('Autogenerated meta_data file mode')
        # self.raw_stack_mode = JRadioButton('raw stack mode')
        # self.projection_mode = JRadioButton('projection files mode')
        #
        # self.meta_data_mode = ButtonGroup()
        # self.meta_data_mode.add(self.raw_stack_mode)
        # self.meta_data_mode.add(self.projection_mode)
        #
        # self.meta_data_mode_panel = JPanel(GridLayout(0, 1))
        # self.meta_data_mode_panel.add(self.meta_data_mode_label)
        # self.meta_data_mode_panel.add(self.raw_stack_mode)
        # self.meta_data_mode_panel.add(self.projection_mode)
        #
        # self.panel.add(self.meta_data_mode_panel)

        self.run_button = JButton('Run')
        self.run_button.addActionListener(
            ActionListenerFactory(self, self.run_button_al))
        self.panel.add(self.run_button)

        super(BobGui, self).__init__("BobPy")
        self.getContentPane().add(self.panel)
        self.pack()
        self.setLocationRelativeTo(None)
        self.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE)
        self.setVisible(True)
#####                       Main code                                 #####
###########################################################################

# Set up the fields for the SWING interface
minField = JFormattedTextField( 0 )
minField.addActionListener( ChangedMin(minField) )

maxField = JFormattedTextField( 255 )
maxField.addActionListener( ChangedMax(maxField) )

scoreField = JTextField( "" )
scoreField.addActionListener( NextImage(scoreField) )
scoreField.addActionListener( WriteScore(scoreField) )

button = JButton("Previous image")
button.addActionListener( PreviousImage(scoreField) )

    # Pack all the fields into a JPanel
all = JPanel()
layout = GridLayout(4, 1)
all.setLayout(layout)
all.add( JLabel("  ") )
all.add( button )
all.add( JLabel("Min") )
all.add( minField )
all.add( JLabel("Max") )
all.add(maxField )
all.add( JLabel("Score :") )
all.add(scoreField)
frame = JFrame("CCM scoring")
frame.getContentPane().add(JScrollPane(all))
Beispiel #27
0
class BurpExtender(IBurpExtender, IContextMenuFactory, ITab,
                   IExtensionStateListener, IMessageEditorController,
                   IHttpListener):
    '''
    IBurpExtender:               Hook into burp and inherit base classes
    ITab:                        Create new tabs inside burp
    IMessageEditorTabFactory:    Access createNewInstance
    '''
    def registerExtenderCallbacks(self, callbacks):

        # Set encoding to utf-8 to avoid some errors
        reload(sys)
        sys.setdefaultencoding('utf8')

        # Keep a reference to callback object and helper object
        self._callbacks = callbacks
        self._helpers = callbacks.getHelpers()

        # Set the extension name that shows in the burp extension menu
        callbacks.setExtensionName("InjectionScanner")

        # Create the log and a lock on which to synchronize when adding log entries
        self._log = ArrayList()
        self._logLock = Lock()
        self._httpLock = Lock()

        # The length of the basis used to fetch abnormal data, default to zero
        self._basisLen = 0

        # 1: {POST. GET}; 2: {urlencoded, json, xml}
        self._postGet = 'NaN'
        self._dataType = 'NaN'

        # Scan list
        self._simpleList = [
            '\'', '\"', '/', '/*', '#', ')', '(', ')\'', '(\'', 'and 1=1',
            'and 1=2', 'and 1>2', 'and 12', '+', 'and+12', '/**/and/**/1'
        ]
        self._xmlList = ['a', 'b', 'c', 'd', 'e']  # Not setted

        # Response mutex: True = is blocking; False = free to go
        # self._mutexR = False

        # Other classes instance
        self._dataTable = Guis_DefaultTM()
        self._logTable = Guis_AbstractTM(self)
        self._xh = XMLHandler()
        listeners = Guis_Listeners(self, self._logTable)
        '''
        Setting GUIs
        '''
        # Divide the whole pane two: one upper and one lower pane
        self._mainSplitpane = JSplitPane(JSplitPane.VERTICAL_SPLIT)
        self._mainSplitpane.setResizeWeight(0.4)

        # Initizlize request table
        dataTable = JTable(self._dataTable)
        dataScrollPane = JScrollPane(dataTable)
        dataScrollPane.setPreferredSize(Dimension(0, 125))
        self._dataTable.addTableModelListener(listeners)

        # Initialize log table
        logTable = Guis_LogTable(self._logTable)
        logScrollPane = JScrollPane(logTable)
        logScrollPane.setPreferredSize(Dimension(0, 125))

        # Split the upper pane to two panes
        tableSplitpane = JSplitPane(JSplitPane.HORIZONTAL_SPLIT)
        tableSplitpane.setResizeWeight(0.5)

        # Set the data table to the left and log to the right
        tableSplitpane.setLeftComponent(dataScrollPane)
        tableSplitpane.setRightComponent(logScrollPane)

        # Tabs with request/response viewers
        tabs = JTabbedPane()
        self._requestViewer = callbacks.createMessageEditor(self, False)
        self._responseViewer = callbacks.createMessageEditor(self, False)
        tabs.addTab("Request", self._requestViewer.getComponent())
        tabs.addTab("Response", self._responseViewer.getComponent())

        # Create buttons that do operation with the test
        self._basisLabel = JLabel('Basis: ' + str(self._basisLen))
        self._levelLabel = JLabel('Level:')
        self._setBasisButton = JButton('Set Basis')
        self._hitOnceButton = JButton('Hit Once')
        self._autoScanButton = JButton('Auto Scan')
        self._clearLogButton = JButton('Clear Log')
        self._cancelButton = JButton('Cancel')
        self._levelSelection = JComboBox()

        self._levelSelection.addItem('1')
        self._levelSelection.addItem('2')
        self._levelSelection.addItem('3')
        self._hitOnceButton.addActionListener(listeners)
        self._autoScanButton.addActionListener(listeners)
        self._clearLogButton.addActionListener(listeners)
        self._setBasisButton.addActionListener(listeners)
        self._cancelButton.addActionListener(listeners)
        self._basisLabel.setPreferredSize(Dimension(100, 20))

        # Create bottom pane for holding the buttons
        buttonPane = JPanel()
        buttonPane.setLayout(BorderLayout())
        centerPane = JPanel()
        leftPane = JPanel()
        rightPane = JPanel()
        leftPane.add(self._basisLabel)
        centerPane.add(self._setBasisButton)
        centerPane.add(self._hitOnceButton)
        centerPane.add(self._autoScanButton)
        centerPane.add(self._cancelButton)
        centerPane.add(self._clearLogButton)
        rightPane.add(self._levelLabel)
        rightPane.add(self._levelSelection)
        buttonPane.add(centerPane, BorderLayout.CENTER)
        buttonPane.add(leftPane, BorderLayout.WEST)
        buttonPane.add(rightPane, BorderLayout.EAST)

        # Create and set the bottom panel that holds viewers and buttons
        utilPane = JPanel()
        utilPane.setLayout(BorderLayout())
        utilPane.add(tabs, BorderLayout.CENTER)
        utilPane.add(buttonPane, BorderLayout.SOUTH)

        self._mainSplitpane.setLeftComponent(tableSplitpane)
        self._mainSplitpane.setRightComponent(utilPane)

        # Customize UI components
        callbacks.customizeUiComponent(self._mainSplitpane)
        callbacks.customizeUiComponent(dataTable)
        callbacks.customizeUiComponent(dataScrollPane)
        callbacks.customizeUiComponent(logTable)
        callbacks.customizeUiComponent(logScrollPane)
        callbacks.customizeUiComponent(tabs)
        callbacks.customizeUiComponent(buttonPane)
        callbacks.customizeUiComponent(utilPane)
        callbacks.customizeUiComponent(self._basisLabel)
        callbacks.customizeUiComponent(self._setBasisButton)
        callbacks.customizeUiComponent(self._hitOnceButton)
        callbacks.customizeUiComponent(self._autoScanButton)
        callbacks.customizeUiComponent(self._clearLogButton)
        callbacks.customizeUiComponent(self._levelSelection)
        callbacks.customizeUiComponent(self._cancelButton)

        # Add the custom tab to Burp's UI
        callbacks.addSuiteTab(self)

        # Register the context menu and message editor for new tabs
        callbacks.registerContextMenuFactory(self)

        # Register as a HTTP listener
        callbacks.registerHttpListener(self)

        return

    '''
    ITab implementation
    '''

    def getTabCaption(self):
        return 'InjectionScanner'

    def getUiComponent(self):
        return self._mainSplitpane

    '''
    IContextMenuFactory implementation
    '''

    def createMenuItems(self, invocation):
        menu = []

        # Which part of the interface the user selects
        ctx = invocation.getInvocationContext()

        # Message viewer request will show menu item if selected by the user
        if ctx == 0 or ctx == 2:
            menu.append(
                swing.JMenuItem("Send to InjectionScanner",
                                None,
                                actionPerformed=lambda x, inv=invocation: self.
                                sendToExtender(inv)))

        return menu if menu else None

    '''
    IMessageEditorController Implementation
    '''

    def getHttpService(self):
        return self._currentlyDisplayedItem.getHttpService()

    def getRequest(self):
        return self._currentlyDisplayedItem.getRequest()

    def getResponse(self):
        return self._currentlyDisplayedItem.getResponse()

    '''
    IHttpListener implementation
    '''

    def processHttpMessage(self, toolFlag, messageIsRequest, messageInfo):

        # Skip this function if the message is request
        if messageIsRequest:
            return

        # Lock the log entry in case race condition
        self._logLock.acquire()
        row = self._log.size()

        # Fetch request message
        requestBody = messageInfo.getRequest()
        requestInfo = self._helpers.analyzeResponse(requestBody)
        requestHeaders = requestInfo.getHeaders()
        if self._postGet == 'POST':
            requestData = self._helpers.bytesToString(
                requestBody[requestInfo.getBodyOffset():])
        elif self._postGet == 'GET':
            for header in requestHeaders:

                if 'GET' in header:
                    # If the request is GET, update the GET data
                    requestUrl = re.sub('^GET\s+', '', header, re.IGNORECASE)
                    requestUrl = re.sub('\sHTTP/1.1\S*', '', requestUrl,
                                        re.IGNORECASE)

                    if '?' in requestUrl:
                        requestData = re.sub('\S*\?', '', requestUrl,
                                             re.IGNORECASE)

                    else:
                        print('processHttpMessage: no parameter in GET url')
        else:
            print('processHttpMessage: _postGet not defined')
            self._logLock.release()
            return

        # Fetch the http type (GET/POST)
        httpType = requestHeaders[0].split(' ')

        # Fetch response message
        responseBody = messageInfo.getResponse()
        responseInfo = self._helpers.analyzeResponse(responseBody)
        responseHeaders = responseInfo.getHeaders()
        self._responseLength = ''

        # Fetch the content length
        self._responseLength = self.fetchContentLength(responseHeaders)

        # If the response message is auto-generated, ignore it. If not, add it into the log list
        if self._callbacks.getToolName(toolFlag) != 'Proxy':

            self._log.add(
                LogEntry(httpType[0], requestData,
                         self._callbacks.saveBuffersToTempFiles(messageInfo),
                         self._responseLength))
            self._logTable.fireTableRowsInserted(row, row)

        self._logLock.release()

    '''
    Fetch content length from the headers given
    '''

    def fetchContentLength(self, fromHeaders):

        for header in fromHeaders:
            if re.search('^Content-Length', header, re.IGNORECASE) is not None:
                return re.sub('^Content-Length\:\s+', '', header,
                              re.IGNORECASE)

    '''
    When the user select 'Send to InjectionScanner', call this function
    '''

    def sendToExtender(self, invocation):

        # Init/reset request data before sending to extender
        self.initRequestInfo()

        try:
            # Initialize basic information
            invMessage = invocation.getSelectedMessages()
            requestMessage = invMessage[0]
            requestInfo = self._helpers.analyzeRequest(requestMessage)
            self._requestBody = requestMessage.getRequest()

            # Set the _currentlyDisplayedItem so each time the data is sent to the extender
            self._currentlyDisplayedItem = self._callbacks.saveBuffersToTempFiles(
                requestMessage)

            # Fetch the request data
            bodyLen = len(self._helpers.bytesToString(self._requestBody))
            if requestInfo.getBodyOffset() < bodyLen:
                self._requestData = self._helpers.bytesToString(
                    self._requestBody[requestInfo.getBodyOffset():])
            elif requestInfo.getBodyOffset() == bodyLen:
                self._requestData = ''
            else:
                print('sendToExtender: body length < body offset')

            # Fetch the headers and Http service
            requestHeaders = list(requestInfo.getHeaders())
            self._httpService = requestMessage.getHttpService()

            # Initialize POST/GET identifier and User-Agent
            for header in requestHeaders:
                if re.search('^POST', header, re.IGNORECASE) is not None:
                    self._postGet = 'POST'

                elif re.search('^GET', header, re.IGNORECASE) is not None:
                    self._postGet = 'GET'

                    # If the request is GET, initialize the url and GET data
                    self._requestUrl = re.sub('^GET\s+', '', header,
                                              re.IGNORECASE)
                    self._requestUrl = re.sub('\sHTTP/1.1\S*', '',
                                              self._requestUrl, re.IGNORECASE)

                    if '?' in self._requestUrl:
                        self._requestDataGet = re.sub('\S*\?', '',
                                                      self._requestUrl,
                                                      re.IGNORECASE)

                    else:
                        print('sendToExtender: no parameter in GET url')

                # If the request if POST, fetch the request data type by content type
                if self._postGet == 'POST' and re.search(
                        '^Content-Type', header, re.IGNORECASE) is not None:

                    contentType = re.sub('^Content-Type', '', header,
                                         re.IGNORECASE)
                    if 'urlencoded' in contentType:
                        self._dataType = 'urlencoded'

                    elif 'json' in contentType:
                        self._dataType = 'json'

                    elif 'xml' in contentType or 'http' in conentType:
                        self._dataType = 'xml'

                    else:
                        print(
                            'sendToExtender: _dataType is not supported, do not scan'
                        )

                # Initialze the User-Agent if it exists
                if re.search('^User-Agent', header, re.IGNORECASE) is not None:
                    self._userAgent = re.sub('^User-Agent\:\s+', '', header,
                                             re.IGNORECASE)

            # If there's no content type in the header,fetch from data
            if self._postGet == 'POST' and self._dataType == '':

                if self._requestData != '':

                    if self._requestData[
                            0] == '{' and '}' in self._requestData and ':' in self._requestData:
                        self._dataType = 'json'

                    elif self._requestData[0] == '<' and self._requestData[
                            -1] == '>':
                        self._dataType = 'xml'

                    else:
                        self._dataType = 'urlencoded'

                else:
                    print(
                        'sendToExtender: _postGet is POST but _requestData is null'
                    )

            # Clear the table before adding elements
            self._dataTable.setRowCount(0)

            # Update request viewer
            self.updateRequestViewer()

            # Fill request data
            self.fillRequestData()

        except Exception as e:
            print(e)

    '''
    Fill the data into the request table
    '''

    def fillRequestData(self):

        # If _postGet is GET, also adds URL to the table
        if self._postGet == 'GET':

            dataList = self._requestDataGet.split('&')
            for data in dataList:

                if '=' in data:
                    x = data.split('=', 1)
                    self._dataDict[str(x[0])] = str(x[1])
                    self._dataTable.addRow([str(x[0]), str(x[1])])
                    self._dataLen += 1

            self._dataTable.addRow(['URL', self._requestUrl])
            self._UrlRow = self._dataLen

            if self._userAgent != '':
                self._dataTable.addRow(['User-Agent', self._userAgent])

        elif self._postGet == 'POST':

            if self._dataType == 'urlencoded':

                dataList = self._requestData.split('&')
                for data in dataList:

                    if '=' in data:
                        x = data.split('=', 1)
                        self._dataDict[str(x[0])] = str(x[1])
                        self._dataTable.addRow([str(x[0]), str(x[1])])
                        self._dataLen += 1

            elif self._dataType == 'json':

                self._dataDict = json.loads(self._requestData)
                for key in self._dataDict:

                    # Convert '"' to '\"' to be the same as that in the data
                    value = str(self._dataDict[key])
                    if '\"' in value:
                        value = value.replace('\"', '\\\"')
                    self._dataDict[key] = value

                    self._dataTable.addRow([str(key), self._dataDict[key]])
                    self._dataLen += 1

            elif self._dataType == 'xml':

                # Use xml package to convert the xml string to dict
                # Note1: the xml dict will be in reverse order
                # Note2: the arrtibute will also be added into dict, need to be pop
                # Note3: special characters like \" will be considered as "
                xml.sax.parseString(self._requestData, self._xh)
                self._attr = re.sub('\>(\S*\s*)*', '', self._requestData[1:],
                                    re.IGNORECASE)

                self._dataDict = self._xh.getDict()
                self._dataDict.pop(self._attr)

                for key in self._dataDict:
                    self._dataTable.addRow(
                        [str(key), str(self._dataDict[key])])
                    self._dataLen += 1

            else:
                print('fillRequestData: _dataType not defined')

            if self._userAgent != '':
                self._dataTable.addRow(['User-Agent', self._userAgent])
                self._savedUserAgent = self._userAgent

        else:
            print('fillRequestData: _postGet not defined')

    '''
    Receive & update the response after sending request to the server
    '''

    def receiveResponse(self):

        # Init/reset response data before receiving response
        self.initResponseInfo()

        # Launch the http thread
        self._httpThread = Thread(target=self.makeRequest,
                                  args=(
                                      self._httpService,
                                      self._requestBody,
                                  ))
        self._httpThread.start()

    '''
    Make Http request to a service
    '''

    def makeRequest(self, httpService, requestBody):
        self._httpLock.acquire()

        # Disable the hit buttons before starting the thread
        self._hitOnceButton.setEnabled(False)
        self._autoScanButton.setEnabled(False)

        self._responseMessage = self._callbacks.makeHttpRequest(
            httpService, requestBody)

        # Enable the hit buttons
        self._hitOnceButton.setEnabled(True)
        self._autoScanButton.setEnabled(True)

        # Unblock the mutex
        self._httpLock.release()

    '''
    updateRequestViewer
    '''

    def updateRequestViewer(self):
        self._requestViewer.setMessage(self.getRequest(), True)

    '''
    updateResponseViewer
    '''

    def updateResponseViewer(self):
        self._responseViewer.setMessage(self.getResponse(), False)

    '''
    Level 1 auto: only loop through the data, do not modify the 'submit' section
    '''

    def autoScan1(self):
        # TODO: Add a 'cancel' button to stop when the user think it takes too long
        # TODO: Add XML support
        if self._postGet == 'GET':

            for i in range(0, self._dataLen):

                title = self._dataTable.getValueAt(i, 0)
                baseValue = self._dataDict[title]

                for value in self._simpleList:

                    # TODO: update more value that should not be changed
                    if 'submit' not in title.lower(
                    ) and 'submit' not in self._dataDict[title].lower(
                    ) and 'search' not in title.lower(
                    ) and 'search' not in self._dataDict[title].lower():

                        # Update the table in case the loop interrupt in the middle
                        # Note that the URL will be automatically updated due to this code, so no need to manually update the URL section
                        self._dataTable.setValueAt(value, i, 1)

                        # Send & request the HTTP request/response
                        self.updateRequestViewer()
                        self.receiveResponse()

                # Reset the table
                self._dataTable.setValueAt(baseValue, i, 1)

        if self._postGet == 'POST':

            if self._dataType == 'urlencoded' or self._dataType == 'json':

                for i in range(0, self._dataLen):

                    title = self._dataTable.getValueAt(i, 0)
                    baseValue = self._dataDict[title]

                    if 'submit' in title.lower() or 'submit' in self._dataDict[
                            title].lower() or 'search' in title.lower(
                            ) or 'search' in self._dataDict[title].lower():
                        continue

                    for value in self._simpleList:

                        self._dataTable.setValueAt(value, i, 1)

                        self.updateRequestViewer()
                        self.receiveResponse()

                    # Reset the table
                    self._dataTable.setValueAt(baseValue, i, 1)

            elif self._dataType == 'xml':

                for i in range(0, self._dataLen):

                    title = self._dataTable.getValueAt(i, 0)
                    baseValue = self._dataDict[title]

                    for value in self._xmlList:

                        # Update the table in case the loop interrupt in the middle
                        self._dataTable.setValueAt(value, i, 1)

                        # Send & request the HTTP request/response
                        self.updateRequestViewer()
                        self.receiveResponse()

                    # Reset the table
                    self._dataTable.setValueAt(baseValue, i, 1)

    '''
    Level 2 auto: loop through the data as well as the user agent (if exist)
    '''

    def autoScan2(self):

        # If the User-Agent does not exist, only performs level 1 auto
        if self._userAgent != '':

            baseUserAgent = self._userAgent
            baseExpression = 'User-Agent: ' + baseUserAgent

            for value in self._simpleList:
                oldExpression = 'User-Agent: ' + self._userAgent
                newExpression = 'User-Agent: ' + value

                # Update the values accordingly
                requestBodyString = self._helpers.bytesToString(
                    self._requestBody)
                self._requestBody = requestBodyString.replace(
                    oldExpression, newExpression)
                self._userAgent = value

                self.updateRequestViewer()
                self.receiveResponse()

            # Reset the value back to original after each loop
            requestBodyString = self._helpers.bytesToString(self._requestBody)
            self._requestBody = requestBodyString.replace(
                newExpression, baseExpression)
            self._savedUserAgent = baseUserAgent
            self.updateRequestViewer()

        # Perform level 1 scan also
        self.autoScan1()

    '''
    Level 3 auto: Alpha: use the timer to perform blind insertion
    '''

    # TODO: 目前只支持GET/urlencoded,后续添加更多支持
    def autoScan3(self):

        self._timeReach = False
        timer = Timer(5, self.timeReach)

        # Modify the first element to perform blind injection
        title = self._dataTable.getValueAt(i, 0)
        oldExpression = title + '=' + self._dataDict[title]
        newExpression = title + '=' + '1\' and if(1=0,1, sleep(10)) --+'

        if self._postGet == 'GET':

            # Update the values accordingly
            requestBodyString = self._helpers.bytesToString(self._requestBody)
            self._requestBody = requestBodyString.replace(
                oldExpression, newExpression)
            self._requestDataGet = self._requestDataGet.replace(
                oldExpression, newExpression)
            self._requestUrl = self._requestUrl.replace(
                oldExpression, newExpression)
            self._dataDict[title] = '1\' and if(1=0,1, sleep(10)) --+'
            self._requestModel.setValueAt('1\' and if(1=0,1, sleep(10)) --+',
                                          0, 1)

        elif self._postGet == 'POST':

            if self._dataType == 'urlencoded':

                # Update the values accordingly
                requestBodyString = self._helpers.bytesToString(
                    self._requestBody)
                self._requestBody = requestBodyString.replace(
                    oldExpression, newExpression)
                self._requestData = self._requestData.replace(
                    oldExpression, newExpression)
                self._dataDict[title] = '1\' and if(1=0,1, sleep(10)) --+'
                self._requestModel.setValueAt(
                    '1\' and if(1=0,1, sleep(10)) --+', 0, 1)

            else:
                print('autoScan3: _dataType not supported')

        else:
            print('autoScan3: _postGet not defined')

        timer.start()

        self.updateRequestViewer()
        self.receiveResponse()

        # Print the result
        if self._timeReach:
            print('Delay scan succeed')
        else:
            print('Delay scan failed')

        # Cancel the timer
        timer.cancel()

    def timeReach(self):
        self._timeReach = True

    '''
    Fetch the 'abnormal' payloads that shows very different response length from the normal ones
    '''

    def getAbnormal(self, basis, coefficient):

        # If the basis is not set, do nothing
        abnormList = ArrayList()
        if basis == 0:
            return None

        # Fetch the abnormals from the log list
        for log in self._log:
            if float(log._responseLen) / float(basis) < coefficient or float(
                    basis) / float(log._responseLen) < coefficient:
                abnormList.append(log._payload)

        return abnormList

    '''
    Turn a simple dict of key/value pairs into XML
    '''

    def dictToXml(self, tag, d):

        elem = Element(tag)

        for key, val in d.items():
            child = Element(key)
            child.text = str(val)
            # Add element in reverse order so that the result is correct
            elem.insert(0, child)

        return elem

    '''
    initRequestInfo
    '''

    def initRequestInfo(self):
        self._postGet = ''
        self._userAgent = ''
        self._requestUrl = ''
        self._requestBody = ''
        self._requestData = ''
        self._requestDataGet = ''
        self._httpService = None
        self._dataDict = {}
        self._dataType = ''
        self._dataLen = 0
        self._attr = ''
        self._contentLength = 0
        self._currentlyDisplayedItem = None

    '''
    initResponseInfo
    '''

    def initResponseInfo(self):
        self._responseBody = None
        self._responseMessage = None
        self._responseLength = ''

    '''
    printRequest
    '''

    def printRequest(self):
        print('----------------')
        print(self._postGet)
        print('----------------')
        print(self._userAgent)
        print('----------------')
        print(self._requestUrl)
        print('----------------')
        print(self._requestBody)
        print('----------------')
        print(self._requestData)
        print('----------------')
        print(self._requestDataGet)
        print('----------------')
        print(self._httpService)
        print('----------------')
        print(self._dataDict)
        print('----------------')
        print(self._dataLen)
        print('----------------')
        print(self._attr)
        print('----------------')

    '''
    printResponse
    '''

    def printResponse(self):
        print('----------------')
        print(self._responseBody)
        print('----------------')
        print(self._responseMessage)
        print('----------------')
        print(self._responseLength)
        print('----------------')
#action for the click in the "Change Path" button
class ChangePathAction(awt.event.ActionListener):
    def actionPerformed(self,event):
      path = pickAFolder()
      pics = [makePicture(path+"1.png"),makePicture(path+"2.png"),makePicture(path+"3.png"),
              makePicture(path+"4.png"),makePicture(path+"5.png"),makePicture(path+"6.png"),
              makePicture(path+"7.png"),makePicture(path+"8.png"),makePicture(path+"9.png")]
      lblPath.setText("Path:  " + path)
              
#creates the main frame
frame = JFrame("CST205 - Project 1", size = (800, 180))

#creates the button panel, which will have the 4 buttons
buttonPanel = JPanel(GridLayout(1,4))
button1 = JButton('Median Method')
button1.addActionListener(MedianAction())
button2 = JButton('Average Method')
button2.addActionListener(AverageAction())
button3 = JButton('Grayscale')
button3.addActionListener(GrayscaleAction())
button4 = JButton('Evil Red')
button4.addActionListener(EvilRedAction())

#adds the buttons to the button panel
buttonPanel.add(button1)
buttonPanel.add(button2)
buttonPanel.add(button3)
buttonPanel.add(button4)

#creates the part where the user can change the images path
lblPath = JLabel("Path:  " + path)
Beispiel #29
0
def createButton(text, command, manager):
    button = JButton(text)
    button.setActionCommand(command)
    button.addActionListener(manager)
    return button
################# After OK clicking ###########  
  
# Recover fields from the formular  
if catDialog.wasOKed():   
	
	# Loop over categories and add a button to the panel for each  
	catPanel = Panel(GridLayout(0,4)) # Unlimited number of rows - fix to 4 columns - not possible to use a JPanel, not supported by GenericDialog
	
	listCat = catDialog.getListCategories()
	listShortcut = range( 112, 112+len(listCat) 
)
	
	for index, category in enumerate(listCat): 
		  
		# Create a Button  
		button = JButton(category) # button label 
		if index<12: button.setToolTipText( "Keyboard shortcut: F" + str(index+1) ) # index is 0-based, F shortcut are 1-based
		
		# Bind action to button  
		button.addActionListener(categoryAction)  
		
		# Add a button to the gui for this category  
		button.setFocusable(False) # prevent the button to take the focus, only the window should be able to take the keyboard shortcut
		catPanel.add(button)
	
	
	# Initialize classification gui
	winButton = ButtonDialog(catPanel, browse_mode, run_measure, table_structure)
	winButton.showDialog()
Beispiel #31
0
class BobGui(JFrame):
    def choose_dir_al(self, e):

        dc = DirectoryChooser('Choose a bob_py experiment folder')
        self.dir_path = dc.getDirectory()

        self.choose_dir_textField.setText(self.dir_path)
        self.got_exper(self.dir_path)

    def textField_al(self, e):
        self.dir_path = self.choose_dir_textField.getText()
        self.got_exper(self.dir_path)

    def got_exper(self, dir_path):
        self.exper = bob_py.Exper(dir_path)
        self.make_tree()

    def make_tree(self):
        print('make_tree')
        root = DefaultMutableTreeNode(self.exper.name)

        sb = br.SimilarityBuilder()

        for hseg in self.exper.hsegs():
            all_file_dict = hseg.file_dict()
            all_file_dict.update(hseg.cell_file_dict())
            all_file_dict.update(hseg.bin_file_dict())
            sb.add_group(hseg.name, all_file_dict)

        simprofile, comparisons = sb.simprofile_comparison()

        sim_str = ''
        for val in simprofile:
            sim_str += str(val) + '\n'

        tp = JTextArea(sim_str)

        stp = JScrollPane()
        stp.getViewport().setView(tp)
        #
        # stp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        # stp.setPreferredSize(Dimension(250, 250));
        # tp.setPreferredSize(Dimension(250, 250))
        stp_panel = JPanel(BorderLayout())
        stp_panel.add(tp, BorderLayout.CENTER)

        # self.add(stp_panel, 'grow')

        for hseg in self.exper.hsegs():
            hseg_node = DefaultMutableTreeNode(hseg.name)
            root.add(hseg_node)
            if len(comparisons[hseg.name]) > 0:
                for definer, file_names in comparisons[hseg.name].items():
                    for file_name in file_names:
                        node_str = definer + ': ' + file_name
                        hseg_node.add(DefaultMutableTreeNode(node_str))
            # for file_suf in hseg.file_dict() :
            # hseg_node.add(DefaultMutableTreeNode(file_suf))

        self.tree = JTree(root)
        scrollPane = JScrollPane()
        scrollPane.getViewport().setView((self.tree))
        # scrollPan
        # scrollPane.setPreferredSize(Dimension(300,250))

        tree_panel = JPanel(BorderLayout())
        tree_panel.add(scrollPane, BorderLayout.CENTER)

        combo_panel = JPanel(GridLayout(0, 2, 10, 10))
        # combo_panel.setLayout(BoxLayout(combo_panel, BoxLayout.X_AXIS))
        combo_panel.add(stp_panel)  #, BorderLayout.LINE_START)
        combo_panel.add(tree_panel)  #, BorderLayout.LINE_END)
        self.panel.add(combo_panel)
        # self.add(scrollPane, 'grow')
        self.revalidate()

    def __init__(self):
        super(BobGui, self).__init__("BobPy")

        self.dir_path = ''

        # ml = MigLayout('fill')
        # self.setLayout(ml)
        self.panel = JPanel()
        self.panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10))

        box_layout = BoxLayout(self.panel, BoxLayout.Y_AXIS)

        self.panel.setLayout(box_layout)

        self.choose_dir_label = JLabel('Experiment Folder:')
        self.choose_dir_textField = JTextField(20)
        self.choose_dir_textField.addActionListener(
            ActionListenerFactory(self, self.textField_al))
        self.choose_dir_button = JButton('open')
        self.choose_dir_button.addActionListener(
            ActionListenerFactory(self, self.choose_dir_al))

        self.choose_dir_panel = JPanel()
        self.choose_dir_panel.add(self.choose_dir_label)
        self.choose_dir_panel.add(self.choose_dir_textField)
        self.choose_dir_panel.add(self.choose_dir_button)

        self.panel.add(self.choose_dir_panel)

        self.add(self.panel)
        self.setPreferredSize(Dimension(500, 300))

        self.pack()
        self.setLocationRelativeTo(None)
        self.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE)
        self.setVisible(True)
Beispiel #32
0
    def __init__(self, menuHandles, manager, isDominant, systemPanel, isTemporal=False):
        self.systemPanel = systemPanel
        self.knownPops = 0
        self.ignoreChanges = True
        JPanel()
        self.menuHandles = menuHandles
        self.isDominant = isDominant
        self.isTemporal = isTemporal
        if isDominant:
            self.setLayout(GridLayout(8, 2))
        else:
            self.setLayout(GridLayout(5, 2))
        if isTemporal:
            self.add(JLabel("Ne"))
            ne = JFormattedTextField(NumberFormat.getNumberInstance(Locale.US))
            ne.addPropertyChangeListener(self)
            self.ne = ne
            self.add(ne)
        else:
            self.add(JLabel("Attempted Fst"))
            fst = JFormattedTextField(NumberFormat.getNumberInstance(Locale.US))
            fst.addPropertyChangeListener(self)
            self.fst = fst
            self.add(fst)
        self.add(JLabel("Expected total pops"))
        pops = JFormattedTextField(NumberFormat.getIntegerInstance(Locale.US))
        pops.addPropertyChangeListener(self)
        # self.pops = JComboBox(['1', '2', '4', '8', '12', '16'])
        self.pops = pops
        self.add(self.pops)
        if not isDominant and not isTemporal:
            self.add(JLabel("Mutation model"))
            self.mut = JComboBox(["Infinite Alleles", "Stepwise"])
            self.mut.addItemListener(self)
            self.add(self.mut)
        self.add(JLabel("Subsample size"))
        sampleSize = JFormattedTextField(NumberFormat.getIntegerInstance(Locale.US))
        sampleSize.addPropertyChangeListener(self)
        self.sampleSize = sampleSize
        self.add(self.sampleSize)
        if isDominant:
            self.add(JLabel("Theta"))
            theta = JFormattedTextField(NumberFormat.getNumberInstance(Locale.US))
            theta.addPropertyChangeListener(self)
            self.theta = theta
            self.add(theta)
            theta.setValue(0.1)

            self.add(JLabel("Beta-a"))
            beta1 = JFormattedTextField(NumberFormat.getNumberInstance(Locale.US))
            beta1.addPropertyChangeListener(self)
            self.beta1 = beta1
            self.add(beta1)
            beta1.setValue(0.25)

            self.add(JLabel("Beta-b"))
            beta2 = JFormattedTextField(NumberFormat.getNumberInstance(Locale.US))
            beta2.addPropertyChangeListener(self)
            self.beta2 = beta2
            self.add(beta2)
            beta2.setValue(0.25)

            self.add(JLabel("Critical frequency"))
            crit = JFormattedTextField(NumberFormat.getNumberInstance(Locale.US))
            crit.addPropertyChangeListener(self)
            self.crit = crit
            self.add(crit)
            crit.setValue(0.99)

        run = JButton("Run!")
        run.addActionListener(manager)
        run.setActionCommand("RunFDist")
        self.run = run
        self.add(run)
        cancel = JButton("Stop")
        cancel.addActionListener(manager)
        cancel.setActionCommand("CancelFDist")
        self.cancel = cancel
class BurpExtender(IBurpExtender, IExtensionStateListener, ITab):
    ext_name = "CompuRacerExtension"
    ext_version = '1.2'
    loaded = True
    t = None

    def registerExtenderCallbacks(self, callbacks):
        Cb(callbacks)
        Cb.callbacks.setExtensionName(self.ext_name)

        try:
            global compuracer_communication_lock

            # option picker item objects (for Java compatibility)
            item1 = {'key': 'item1', 'name': '2'}
            item2 = {'key': 'item2', 'name': '3'}
            item3 = {'key': 'item3', 'name': '4'}
            item4 = {'key': 'item4', 'name': '5'}
            item5 = {'key': 'item5', 'name': '10'}
            item6 = {'key': 'item6', 'name': '15'}
            item7 = {'key': 'item7', 'name': '20'}
            item8 = {'key': 'item8', 'name': '25'}
            item9 = {'key': 'item9', 'name': '50'}
            item10 = {'key': 'item10', 'name': '100'}

            # main splitted pane + top pane
            self._main_splitpane = JSplitPane(JSplitPane.VERTICAL_SPLIT)
            self._outer_settings_pane = JPanel(BorderLayout())
            self._settings_pane = JPanel(GridBagLayout())
            c = GridBagConstraints()

            self.label_1 = JLabel("Number of parallel requests:")
            c.fill = GridBagConstraints.NONE
            c.gridx = 0
            c.gridy = 0
            c.insets = Insets(0, 5, 0, 10)
            c.anchor = GridBagConstraints.LINE_START
            self._settings_pane.add(self.label_1, c)

            self.input_parallel_requests = JComboBox([
                Item(item1),
                Item(item2),
                Item(item3),
                Item(item4),
                Item(item5),
                Item(item6),
                Item(item7),
                Item(item8),
                Item(item9),
                Item(item10)
            ])
            self.input_parallel_requests.setSelectedIndex(4)
            self.input_parallel_requests.setToolTipText(
                "Select the number of parallel requests that will be sent")
            self.input_parallel_requests.addActionListener(
                self.change_parallel_requests)
            c.gridx = 1
            c.gridy = 0
            c.insets = Insets(0, 5, 0, 10)
            self._settings_pane.add(self.input_parallel_requests, c)

            self.option_allow_redirects = JCheckBox(
                "Allow redirects", actionPerformed=self.check_allow_redirects)
            self.option_allow_redirects.setToolTipText(
                "Select whether redirect responses are followed")
            c.gridx = 2
            c.gridy = 0
            c.insets = Insets(0, 20, 0, 10)
            self._settings_pane.add(self.option_allow_redirects, c)

            self.option_sync_last_byte = JCheckBox(
                "Sync last byte", actionPerformed=self.check_sync_last_byte)
            self.option_sync_last_byte.setToolTipText(
                "Select whether last byte synchronisation is enabled")
            c.gridx = 2
            c.gridy = 1
            c.insets = Insets(0, 20, 0, 0)
            self._settings_pane.add(self.option_sync_last_byte, c)

            self.label_2 = JLabel("Send timeout in seconds:")
            c.gridx = 0
            c.gridy = 1
            c.insets = Insets(0, 5, 0, 0)
            self._settings_pane.add(self.label_2, c)

            self.input_send_timeout = JComboBox([
                Item(item2),
                Item(item4),
                Item(item5),
                Item(item7),
                Item(item9),
                Item(item10)
            ])
            self.input_send_timeout.setSelectedIndex(3)
            self.input_send_timeout.setToolTipText(
                "Select the wait-for-response timeout after sending the request(s)"
            )
            self.input_send_timeout.addActionListener(self.change_send_timeout)
            c.gridx = 1
            c.gridy = 1
            c.insets = Insets(0, 5, 0, 0)
            self._settings_pane.add(self.input_send_timeout, c)

            self.button_resend_batch = JButton("Resend requests")
            self.button_resend_batch.setToolTipText(
                "Resend all requests with the current configuration")
            self.button_resend_batch.setEnabled(False)
            self.button_resend_batch.addActionListener(
                MenuFactory.start_request_transmitter_button)
            c.gridx = 3
            c.gridy = 0
            c.insets = Insets(0, 20, 0, 10)
            self._settings_pane.add(self.button_resend_batch, c)

            immediate_data_ui_elements[
                "parallel_requests"] = self.input_parallel_requests
            immediate_data_ui_elements[
                "allow_redirects"] = self.option_allow_redirects
            immediate_data_ui_elements[
                "sync_last_byte"] = self.option_sync_last_byte
            immediate_data_ui_elements[
                "send_timeout"] = self.input_send_timeout
            immediate_data_ui_elements[
                "resend_batch"] = self.button_resend_batch

            c = GridBagConstraints()
            c.anchor = GridBagConstraints.WEST
            self._outer_settings_pane.add(self._settings_pane,
                                          BorderLayout.WEST)
            self._main_splitpane.setTopComponent(self._outer_settings_pane)

            self._results_splitpane = JSplitPane(JSplitPane.HORIZONTAL_SPLIT)
            self._main_splitpane.setBottomComponent(self._results_splitpane)

            # table of log entries
            self.tabs_right = JTabbedPane()
            global _textEditors, DEFAULT_RESULTS
            for i in range(3):
                _textEditors.append(Cb.callbacks.createTextEditor())
                _textEditors[-1].setText(str.encode("\n" + DEFAULT_RESULTS))

            self.tabs_right.add("Summary", _textEditors[0].getComponent())
            self.tabs_right.add("Full result", _textEditors[1].getComponent())
            self.tabs_right.add("Config", _textEditors[2].getComponent())
            self._results_splitpane.setRightComponent(self.tabs_right)

            # tabs with request/response viewers
            global _requestViewers, _requestPane
            _requestPane = JTabbedPane()
            _requestViewers.append(
                Cb.callbacks.createMessageEditor(None, False))
            _requestPane.addTab("Request", _requestViewers[-1].getComponent())
            self._results_splitpane.setLeftComponent(_requestPane)

            # customize our UI components
            Cb.callbacks.customizeUiComponent(self._settings_pane)
            Cb.callbacks.customizeUiComponent(self.tabs_right)
            Cb.callbacks.customizeUiComponent(_requestPane)

            # add the custom tab to Burp's UI
            Cb.callbacks.addSuiteTab(self)

        except RuntimeException as e:
            callbacks.printError(traceback.format_exc())
            e = PyException(e)
            print("10")
            print(str(self))
            print("{}\t{}\n{}\n".format(e.type, e.value, e.traceback))
        Cb.callbacks.registerContextMenuFactory(MenuFactory())
        callbacks.registerExtensionStateListener(self)

        self.start_alive_checker()

        Cb.callbacks.printOutput('%s v%s extension loaded\n' %
                                 (self.ext_name, self.ext_version))

    def change_parallel_requests(self, event):
        global immediate_data
        try:
            num_parallel = MenuFactory.item_selected(event)
            if num_parallel != immediate_data['settings'][0]:
                self.update_setting(0, num_parallel,
                                    "number of parallel requests")
        except Exception as e:
            print(e)

    def change_send_timeout(self, event):
        global immediate_data
        try:
            send_timeout = MenuFactory.item_selected(event)
            if send_timeout != immediate_data['settings'][4]:
                self.update_setting(4, send_timeout, "send timeout")
        except Exception as e:
            print(e)

    def check_allow_redirects(self, event):
        global immediate_data
        is_selected = MenuFactory.button_selected(event)
        if is_selected != immediate_data['settings'][2]:
            self.update_setting(2, is_selected, "allow redirects")

    def check_sync_last_byte(self, event):
        global immediate_data
        is_selected = MenuFactory.button_selected(event)
        if is_selected != immediate_data['settings'][3]:
            self.update_setting(3, is_selected, "allow redirects")

    def resend_batches(self, event):
        global _storedRequests
        if _storedRequests is not None:
            self.sen

    # helper method for two methods above
    def update_setting(self, index, new_value, text):
        global immediate_data
        success = True
        print("> Updating {}..".format(text))
        old_value = immediate_data['settings'][index]
        immediate_data['settings'][index] = new_value
        if MenuFactory.set_immediate_mode_settings(
            {'settings': immediate_data['settings']}):
            print("> Success!")
        else:
            print("> Failed!")
            immediate_data['settings'][index] = old_value
            success = False
        return success

    # for ITab
    def getTabCaption(self):
        return "CompuRacer"

    # for ITab
    def getUiComponent(self):
        return self._main_splitpane

    # def getHttpService(self):
    #     global _storedRequest
    #     return _storedRequest.getHttpService()
    #
    # def getRequest(self):
    #     global _storedRequest
    #     return _storedRequest.getRequest()
    #
    # def getResponse(self):
    #     global _storedRequest
    #     return _storedRequest.getResponse()

    def start_alive_checker(self):
        self.t = threading.Thread(name='Alive checker',
                                  target=self.alive_checker)
        self.t.start()

    def closest_match(self, number, list_of_numbers):
        return min(list(zip(list_of_numbers, range(len(list_of_numbers)))),
                   key=lambda item: (abs(item[0] - number), item[1]))

    def alive_checker(self):
        global compuRacer_ip, compuRacer_port, alive_check_path, racer_alive, immediate_mode, compuracer_communication_lock
        unloaded = False
        old_alive = racer_alive
        parallel_req_options = [2, 3, 4, 5, 10, 15, 20, 25, 50, 100]
        send_time_options = [3, 5, 10, 20, 50, 100]
        while not unloaded:
            try:
                with compuracer_communication_lock:
                    response = requests.get("http://{}:{}/{}".format(
                        compuRacer_ip, compuRacer_port, alive_check_path),
                                            timeout=2)
                    racer_alive = response and response.status_code and response.status_code == 200
                    success, mode, settings = MenuFactory.get_immediate_mode_settings(
                    )
                    if success:
                        immediate_data['mode'] = mode
                        immediate_data['settings'] = settings

                        # update UI button states
                        immediate_data_ui_elements[
                            "parallel_requests"].setSelectedIndex(
                                self.closest_match(
                                    immediate_data['settings'][0],
                                    parallel_req_options)[1])
                        immediate_data_ui_elements[
                            "allow_redirects"].setSelected(
                                bool(immediate_data['settings'][2]))
                        immediate_data_ui_elements[
                            "sync_last_byte"].setSelected(
                                bool(immediate_data['settings'][3]))
                        immediate_data_ui_elements[
                            "send_timeout"].setSelectedIndex(
                                self.closest_match(
                                    immediate_data['settings'][4],
                                    send_time_options)[1])

            except Exception as e:
                # it surely did not work
                racer_alive = False
                print(e)
            if racer_alive and not old_alive:
                print("> Racer is now alive!")
                MenuFactory.set_state_of_all_buttons(True)
                old_alive = True
            elif not racer_alive and old_alive:
                print("> Racer became dead!")
                MenuFactory.set_state_of_all_buttons(False)
                old_alive = False
            time.sleep(5)
            if not self.loaded:
                unloaded = True

    def extensionUnloaded(self):
        print("\n> Unloading..")
        self.loaded = False
        self.t.join()
        print("> Done.")
    def show_detectable_objects_dialog(self, e):
        parentComponent = SwingUtilities.windowForComponent(self.panel0)
        self.detectable_obejcts_dialog = JDialog(
            parentComponent, "List of Objects to Detect",
            ModalityType.APPLICATION_MODAL)
        panel = JPanel()
        self.detectable_obejcts_dialog.add(panel)
        gbPanel = GridBagLayout()
        gbcPanel = GridBagConstraints()
        panel.setLayout(gbPanel)

        y = 0
        x = 0
        for line in self.local_settings.getClassesOfInterest():
            if y > 15:
                y = 0
                x = x + 1

            class_check_box = JCheckBox(line['name'])
            self.classes_of_interest_checkboxes.append(class_check_box)
            class_check_box.setEnabled(True)
            class_check_box.setSelected(line['enabled'])
            class_check_box.addItemListener(self.on_class_checkbox_clicked)
            gbcPanel.gridx = x
            gbcPanel.gridy = y
            gbcPanel.gridwidth = 1
            gbcPanel.gridheight = 1
            gbcPanel.fill = GridBagConstraints.BOTH
            gbcPanel.weightx = 1
            gbcPanel.weighty = 1
            gbcPanel.anchor = GridBagConstraints.NORTH
            gbPanel.setConstraints(class_check_box, gbcPanel)
            panel.add(class_check_box)
            y = y + 1

        blank_1_L = JLabel(" ")
        blank_1_L.setEnabled(True)
        gbcPanel.gridx = 0
        gbcPanel.gridy = y + 1
        gbcPanel.gridwidth = 1
        gbcPanel.gridheight = 1
        gbcPanel.fill = GridBagConstraints.BOTH
        gbcPanel.weightx = 1
        gbcPanel.weighty = 0
        gbcPanel.anchor = GridBagConstraints.NORTH
        gbPanel.setConstraints(blank_1_L, gbcPanel)
        panel.add(blank_1_L)

        deselect_all_button = JButton("Deselect all")
        deselect_all_button.setEnabled(True)
        deselect_all_button.addActionListener(self.on_deselect_all_clicked)
        gbcPanel.gridx = 1
        gbcPanel.gridy = y + 2
        gbcPanel.gridwidth = 1
        gbcPanel.gridheight = 1
        gbcPanel.fill = GridBagConstraints.BOTH
        gbcPanel.weightx = 2
        gbcPanel.weighty = 1
        gbcPanel.anchor = GridBagConstraints.NORTH
        gbPanel.setConstraints(deselect_all_button, gbcPanel)
        panel.add(deselect_all_button)

        select_all_button = JButton("Select all")
        select_all_button.setEnabled(True)
        select_all_button.addActionListener(self.on_select_all_clicked)
        gbcPanel.gridx = 3
        gbcPanel.gridy = y + 2
        gbcPanel.gridwidth = 1
        gbcPanel.gridheight = 1
        gbcPanel.fill = GridBagConstraints.BOTH
        gbcPanel.weightx = 2
        gbcPanel.weighty = 1
        gbcPanel.anchor = GridBagConstraints.NORTH
        gbPanel.setConstraints(select_all_button, gbcPanel)
        panel.add(select_all_button)

        blank_2_L = JLabel(" ")
        blank_2_L.setEnabled(True)
        gbcPanel.gridx = 0
        gbcPanel.gridy = y + 3
        gbcPanel.gridwidth = 1
        gbcPanel.gridheight = 1
        gbcPanel.fill = GridBagConstraints.BOTH
        gbcPanel.weightx = 1
        gbcPanel.weighty = 0
        gbcPanel.anchor = GridBagConstraints.NORTH
        gbPanel.setConstraints(blank_2_L, gbcPanel)
        panel.add(blank_2_L)

        cancel_button = JButton("Cancel")
        cancel_button.setEnabled(True)
        cancel_button.addActionListener(
            self.on_cancel_classes_of_interest_click)
        gbcPanel.gridx = 1
        gbcPanel.gridy = y + 4
        gbcPanel.gridwidth = 1
        gbcPanel.gridheight = 1
        gbcPanel.fill = GridBagConstraints.BOTH
        gbcPanel.weightx = 2
        gbcPanel.weighty = 1
        gbcPanel.anchor = GridBagConstraints.NORTH
        gbPanel.setConstraints(cancel_button, gbcPanel)
        panel.add(cancel_button)

        save_button = JButton("Save")
        save_button.setEnabled(True)
        save_button.addActionListener(self.on_save_classes_of_interest_click)
        gbcPanel.gridx = 3
        gbcPanel.gridy = y + 4
        gbcPanel.gridwidth = 1
        gbcPanel.gridheight = 1
        gbcPanel.fill = GridBagConstraints.BOTH
        gbcPanel.weightx = 2
        gbcPanel.weighty = 1
        gbcPanel.anchor = GridBagConstraints.NORTH
        gbPanel.setConstraints(save_button, gbcPanel)
        panel.add(save_button)

        blank_3_L = JLabel(" ")
        blank_3_L.setEnabled(True)
        gbcPanel.gridx = 0
        gbcPanel.gridy = y + 5
        gbcPanel.gridwidth = 1
        gbcPanel.gridheight = 1
        gbcPanel.fill = GridBagConstraints.BOTH
        gbcPanel.weightx = 1
        gbcPanel.weighty = 0
        gbcPanel.anchor = GridBagConstraints.NORTH
        gbPanel.setConstraints(blank_3_L, gbcPanel)
        panel.add(blank_3_L)

        self.detectable_obejcts_dialog.pack()
        screenSize = Toolkit.getDefaultToolkit().getScreenSize()
        self.detectable_obejcts_dialog.setLocation(
            int((screenSize.getWidth() / 2) -
                (self.detectable_obejcts_dialog.getWidth() / 2)),
            int((screenSize.getHeight() / 2) -
                (self.detectable_obejcts_dialog.getHeight() / 2)))
        self.detectable_obejcts_dialog.setVisible(True)
 def _create_new_employee_button(self):
     btn = JButton("New Employee", name="new_employee_button")
     btn.addActionListener(ListenerFactory(ActionListener, self._new_employee))
     return btn
Beispiel #36
0
class BurpExtender(IBurpExtender, ITab, IMessageEditorController,
                   AbstractTableModel):
    """
		Implements IBurpExtender
	"""
    def registerExtenderCallbacks(self, callbacks):

        # Save callbacks and helpers for later use
        self._callbacks = callbacks
        self._helpers = callbacks.getHelpers()

        # Set extension name
        self._callbacks.setExtensionName("Burp XML Export Viewer")

        # Create the log and a lock on which to synchronize when adding log entries
        self._log = ArrayList()
        self._lock = Lock()

        # Main panel
        self._mainPanel = JPanel(BorderLayout())

        # Button to load Burp XML Export file
        self._loadButton = JButton('Select Burp XML Export File')
        self._loadButton.addActionListener(self.loadButtonTapped)
        self._mainPanel.add(self._loadButton, BorderLayout.PAGE_START)

        # File chooser for Burp XML Export file
        self._fc = JFileChooser()
        self._fc.setDialogTitle("Select Burp XML Export File")

        # Splitpane for table and request/response view
        self._splitpane = JSplitPane(JSplitPane.VERTICAL_SPLIT)
        self._mainPanel.add(self._splitpane, BorderLayout.CENTER)

        # Table of log entries
        self._logTable = Table(self)
        self._scrollPane = JScrollPane(self._logTable)
        self._splitpane.setTopComponent(self._scrollPane)

        # Set column width of table
        self._logTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF)
        self._logTable.getColumnModel().getColumn(0).setPreferredWidth(40)
        self._logTable.getColumnModel().getColumn(1).setPreferredWidth(60)
        self._logTable.getColumnModel().getColumn(2).setPreferredWidth(70)
        self._logTable.getColumnModel().getColumn(3).setPreferredWidth(300)
        self._logTable.getColumnModel().getColumn(4).setPreferredWidth(500)
        self._logTable.getColumnModel().getColumn(5).setPreferredWidth(300)
        self._logTable.getColumnModel().getColumn(6).setPreferredWidth(100)
        self._logTable.getColumnModel().getColumn(7).setPreferredWidth(100)
        self._logTable.getColumnModel().getColumn(8).setPreferredWidth(100)
        self._logTable.getColumnModel().getColumn(9).setPreferredWidth(100)
        self._logTable.getColumnModel().getColumn(10).setPreferredWidth(230)
        self._logTable.getColumnModel().getColumn(11).setMaxWidth(100000)

        # Tabs with request and response viewers
        self._tabs = JTabbedPane()
        self._requestViewer = callbacks.createMessageEditor(self, False)
        self._responseViewer = callbacks.createMessageEditor(self, False)
        self._tabs.addTab("Request", self._requestViewer.getComponent())
        self._tabs.addTab("Response", self._responseViewer.getComponent())
        self._splitpane.setBottomComponent(self._tabs)

        # Customize UI components
        self._callbacks.customizeUiComponent(self._mainPanel)
        self._callbacks.customizeUiComponent(self._splitpane)
        self._callbacks.customizeUiComponent(self._logTable)
        self._callbacks.customizeUiComponent(self._scrollPane)
        self._callbacks.customizeUiComponent(self._tabs)

        # Add the custom tab to Burp's UI
        self._callbacks.addSuiteTab(self)

        return

    """
		Helper Functions
	"""

    def loadButtonTapped(self, actionEvent):

        # Display the file chooser dialog
        retVal = self._fc.showOpenDialog(None)

        if retVal == JFileChooser.APPROVE_OPTION:
            self._file = self._fc.getSelectedFile()
            self.resetList()  # clear the table from all previous entries
            self.parseXML(
                self._file)  # parse the file and load all entries to the table
        else:
            print("Open command cancelled by user.")

    def parseXML(self, file):

        # Initialize XML stuff
        dbFactory = DocumentBuilderFactory.newInstance()
        dBuilder = dbFactory.newDocumentBuilder()
        doc = dBuilder.parse(file)
        doc.getDocumentElement().normalize()

        # All entries in Burp's XML Export File have tag <item>...</item>
        nodeList = doc.getElementsByTagName("item")

        # for i in reversed(range(0, nodeList.getLength())):
        for i in range(0, nodeList.getLength()):
            node = nodeList.item(i)

            if node.getNodeType() == Node.ELEMENT_NODE:

                request = node.getElementsByTagName("request").item(
                    0).getTextContent()
                response = node.getElementsByTagName("response").item(
                    0).getTextContent()

                request_isBase64 = node.getElementsByTagName("request").item(
                    0).getAttribute("base64")
                response_isBase64 = node.getElementsByTagName("response").item(
                    0).getAttribute("base64")

                if request_isBase64 == "true":
                    request = Base64.getDecoder().decode(request)

                if response_isBase64 == "true":
                    response = Base64.getDecoder().decode(response)

                info = {
                    "time":
                    node.getElementsByTagName("time").item(0).getTextContent(),
                    "url":
                    node.getElementsByTagName("url").item(0).getTextContent(),
                    "host":
                    node.getElementsByTagName("host").item(0).getTextContent(),
                    "port":
                    node.getElementsByTagName("port").item(0).getTextContent(),
                    "protocol":
                    node.getElementsByTagName("protocol").item(
                        0).getTextContent(),
                    "method":
                    node.getElementsByTagName("method").item(
                        0).getTextContent(),
                    "path":
                    node.getElementsByTagName("path").item(0).getTextContent(),
                    "extension":
                    node.getElementsByTagName("extension").item(
                        0).getTextContent(),
                    "request":
                    request,
                    "status":
                    node.getElementsByTagName("status").item(
                        0).getTextContent(),
                    "responselength":
                    node.getElementsByTagName("responselength").item(
                        0).getTextContent(),
                    "mimetype":
                    node.getElementsByTagName("mimetype").item(
                        0).getTextContent(),
                    "response":
                    response,
                    "comment":
                    node.getElementsByTagName("comment").item(
                        0).getTextContent(),
                    "highlight":
                    ""
                }

                logEntry = LogEntry(info)

                # Remove GET parameters from path component
                # Path component usually looks like this: /some/path/index.html?q=foo&z=faa
                info["path"] = info["path"].split("?")[0]

                # Extract GET parameters
                params = []
                for param in self._helpers.analyzeRequest(
                        logEntry).getParameters():
                    if param.getType() == IParameter.PARAM_URL:
                        params.append("{}={}".format(param.getName(),
                                                     param.getValue()))
                info["params"] = "&".join(params)

                self.addLogEntryToList(logEntry)

    def addLogEntryToList(self, logEntry):
        self._lock.acquire()
        row = self._log.size()
        self._log.add(logEntry)
        self.fireTableRowsInserted(row, row)
        self._lock.release()

    def resetList(self):
        self._lock.acquire()
        self._log.clear()
        self.fireTableRowsInserted(0, 0)
        self._lock.release()

    """
		Implements ITab
	"""

    def getTabCaption(self):
        return "Burp XML Export Viewer"

    def getUiComponent(self):
        return self._mainPanel

    """
		Extends AbstractTableModel
	"""

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

    def getColumnCount(self):
        return 12

    def getColumnName(self, columnIndex):
        if columnIndex == 0:
            return "#"
        if columnIndex == 1:
            return "Method"
        if columnIndex == 2:
            return "Protocol"
        if columnIndex == 3:
            return "Host"
        if columnIndex == 4:
            return "Path"
        if columnIndex == 5:
            return "Parameters"
        if columnIndex == 6:
            return "Status"
        if columnIndex == 7:
            return "Length"
        if columnIndex == 8:
            return "MIME type"
        if columnIndex == 9:
            return "Extension"
        if columnIndex == 10:
            return "Time"
        if columnIndex == 11:
            return "Comment"

        return ""

    def getValueAt(self, rowIndex, columnIndex):
        logEntry = self._log.get(rowIndex)

        if columnIndex == 0:
            return "{}".format(rowIndex)
        if columnIndex == 1:
            return logEntry._info["method"]
        if columnIndex == 2:
            return logEntry._info["protocol"]
        if columnIndex == 3:
            return logEntry.getHttpService().getHost()
        if columnIndex == 4:
            return logEntry._info["path"]
        if columnIndex == 5:
            return logEntry._info["params"]
        if columnIndex == 6:
            return logEntry._info["status"]
        if columnIndex == 7:
            return logEntry._info["responselength"]
        if columnIndex == 8:
            return logEntry._info["mimetype"]
        if columnIndex == 9:
            return logEntry._info["extension"]
        if columnIndex == 10:
            return logEntry._info["time"]
        if columnIndex == 11:
            return logEntry._info["comment"]

        return ""

    """
		Implements IMessageEditorController
		Allows request and response viewers to obtain details about the messages being displayed
	"""

    def getHttpService(self):
        return self._currentlyDisplayedItem.getHttpService()

    def getRequest(self):
        return self._currentlyDisplayedItem.getRequest()

    def getResponse(self):
        return self._currentlyDisplayedItem.getResponse()
Beispiel #37
0
print roi_ni


choice_list = ["foo", "bar", "777"]

lbl1 = JLabel("foo label")
lbl2 = JLabel("bar label")

main_panel = JPanel()

### panel 1
panel1 = JPanel()
panel1.add(lbl1)
cb1 = JComboBox(choice_list)
btn1 = JButton("Accept")
btn1.addActionListener(ButtonListener(btn1))
panel1.add(cb1)
panel1.add(btn1)

### panel 2
panel2 = JPanel()
panel2.add(lbl2)
cb2 = JComboBox(sorted(roi_ni.keys()))
cb2.addActionListener(Listener(lbl2, cb2))
panel2.add(cb2)

### panel 3
pnl3 = JPanel()
lst1 = JList(listmodel)
pnl3.add(lst1)
Beispiel #38
0
    def __init__(self,
                 logtable_factory=None,
                 external_filter_action_listener=None,
                 external_start_button_action_listener=None,
                 external_stop_button_action_listener=None,
                 external_clear_button_action_listener=None,
                 tools_keys=None):
        self.this = JPanel()

        if tools_keys is None:
            tools_keys = []

        self.external_start_button_action_listener = external_start_button_action_listener
        self.external_stop_button_action_listener = external_stop_button_action_listener
        self.external_clear_button_action_listener = external_clear_button_action_listener


        self.this.setLayout(BoxLayout(self.this, BoxLayout.Y_AXIS))

        # main split pane
        splitPane = JSplitPane(JSplitPane.VERTICAL_SPLIT)

        # table of log entries
        logTableModel = LogTableModel()
        self.logTableModel = logTableModel
        if logtable_factory is not None:
            logTable = logtable_factory(logTableModel)
        else:
            # XXX: create a generic logtable that works even without burp to made it work standalone
            raise ValueError("logtable_factory cannot be none")
        scrollPane = JScrollPane(logTable)
        splitPane.setLeftComponent(scrollPane)

        # tabs with request/response viewers
        tabs = JTabbedPane()
        tabs.setBorder(BorderFactory.createLineBorder(Color.black))
        tabs.addTab("Request", logTable.getRequestViewer().getComponent())
        tabs.addTab("Response", logTable.getResponseViewer().getComponent())
        splitPane.setRightComponent(tabs)

        # top control panel
        controlPanel = JPanel(FlowLayout(FlowLayout.LEFT))

        toolLabel = JLabel("Select tool: ")
        controlPanel.add(toolLabel)


        tools = JavaArrayList(tools_keys)
        toolList = JComboBox(tools)
        toolList.addActionListener(external_filter_action_listener)
        controlPanel.add(toolList)

        startButton = JButton("Start")
        self.startButton = startButton
        controlPanel.add(startButton)
        stopButton = JButton("Stop")
        self.stopButton = stopButton
        controlPanel.add(stopButton)
        clearButton = JButton("Clear")
        self.clearButton = clearButton
        startButton.setEnabled(False)
        controlPanel.add(clearButton)
        scopeLabel = JLabel("In-scope items only?")
        controlPanel.add(scopeLabel)
        scopeCheckBox = JCheckBox()
        self.scopeCheckBox = scopeCheckBox
        controlPanel.add(scopeCheckBox)
        filterLabel = JLabel("Filter Query:")
        controlPanel.add(filterLabel)
        queryFilterText = JTextField(40)
        self.queryFilterText = queryFilterText
        controlPanel.add(queryFilterText)

        startButton.addActionListener(self.start_button_action_listener)

        stopButton.addActionListener(self.stop_button_action_listener)

        clearButton.addActionListener(self.clear_button_action_listener)

        controlPanel.setAlignmentX(0)
        self.this.add(controlPanel)
        self.this.add(splitPane)
Beispiel #39
0
inputPanel.add(JLabel("Output Directory"))
outputDirPanel = JPanel()
outputDirPanel.setLayout(BorderLayout())
outputDirTf = JTextField(job.outputDir)
outputDirPanel.add(outputDirTf, BorderLayout.CENTER)
outputDirSelect = JButton("...")


def refreshOutput():
    if job.outputDir:
        outputDirTf.setText(job.outputDir)
    else:
        outputDirTf.setText("")


outputDirSelect.addActionListener(OutputSelectHandler(job, refreshOutput))
outputDirPanel.add(outputDirSelect, BorderLayout.EAST)
inputPanel.add(outputDirPanel)

# Generate default metadata string
# mdList = []
# offsetStr = "Image " + str(i) + " : AnalogPMTOffset = "
# offsetData = getDataPart( job, job.metadata, offsetStr )
# if offsetData != None:
# 	mdList.append( "PMT Offset: " + offsetData )
# powerStr = "Image " + str(i) + " : ExcitationOutPutLevel = "
# powerData =  getDataPart( job, job.metadata, powerStr )
# if powerData != None:
# 	mdList.append( "Laser Power: " + powerData )
# gainStr = "Image " + str(i) + " : PMTVoltage = "
# gainData =  getDataPart( job, job.metadata, gainStr )
Beispiel #40
0
def makeTranslationUI(affines, imp, show=True, print_button_text="Print transforms"):
  """
  A GUI to control the translation components of a list of AffineTransform3D instances.
  When updated, the ImagePlus is refreshed.

  affines: a list (will be read multiple times) of one affine transform per image.
  imp: the ImagePlus that hosts the virtual stack with the transformed images.
  show: defaults to True, whether to make the GUI visible.
  print_button_text: whatever you want the print button to read like, defaults to "Print transforms".
   
  Returns the JFrame, the main JPanel and the lower JButton panel.
  """
  panel = JPanel()
  panel.setBorder(BorderFactory.createEmptyBorder(10,10,10,10))
  gb = GridBagLayout()
  panel.setLayout(gb)
  gc = GBC()
  gc.anchor = GBC.WEST
  gc.fill = GBC.NONE

  # Column labels
  gc.gridy = 0
  for i, title in enumerate(["Camera", "translation X", "translation Y", "translation Z"]):
    gc.gridx = i
    gc.anchor = GBC.CENTER
    label = JLabel(title)
    gb.setConstraints(label, gc)
    panel.add(label)

  gc.anchor = GBC.WEST
  listeners = []
  
  # One row per affine to control: skip the first
  for i, affine in enumerate(affines[1:]):
    gc.gridx = 0
    gc.gridy += 1
    label = JLabel("CM0%i: " % (i + 1))
    gb.setConstraints(label, gc)
    panel.add(label)
    # One JTextField per dimension
    for dimension, translation in enumerate(affine.getTranslation()):
      tf = JTextField(str(translation), 10)
      listener = MatrixTextFieldListener(affine, dimension, tf, imp)
      listeners.append(listener)
      imp.addImageListener(listener) # to disable the JTextField when closed
      tf.addKeyListener(listener)
      tf.addMouseWheelListener(listener)
      gc.gridx += 1
      gb.setConstraints(tf, gc)
      panel.add(tf)

  # Documentation for the user
  help_lines = ["Type a number and push enter,",
                "or use the scroll wheel."]
  gc.gridx = 0
  gc.gridwidth = 4
  for line in help_lines:
    gc.gridy += 1
    help = JLabel(line)
    gb.setConstraints(help, gc)
    panel.add(help)

  # Buttons
  printButton = JButton(print_button_text)
  
  def printTransforms(event):
    for i, aff in enumerate(affines): # print all, including the first
      matrix = zeros(12, 'd')
      aff.toArray(matrix)
      msg = "# Coarse affine matrix " + str(i) + ": \n" + \
            "affine" + str(i) + ".set(*[%f, %f, %f, %f,\n %f, %f, %f, %f,\n %f, %f, %f, %f])" % tuple(matrix.tolist())
      # Print everywhere
      print msg
      IJ.log(msg)
      System.out.println(msg)
      
  
  printButton.addActionListener(printTransforms)
  gc.gridx = 0
  gc.gridy += 1
  gc.gridwidth = 4
  button_panel = JPanel()
  button_panel.add(printButton)
  gb.setConstraints(button_panel, gc)
  panel.add(button_panel)

  frame = JFrame("Translation control")
  frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE)
  frame.addWindowListener(CloseControl(destroyables=listeners))
  frame.getContentPane().add(panel)
  frame.pack()
  frame.setLocationRelativeTo(None) # center in the screen
  frame.setVisible(show)

  return frame, panel, button_panel
Beispiel #41
0
class EmployeeDetails(JPanel):

    def __init__(self, employees):
        JPanel.__init__(self, preferredSize=(400, 200))
        layout = BoxLayout(self, BoxLayout.Y_AXIS)
        self.setLayout(layout)
        self._employees = employees
        employees.add_change_listener(self)
        self._create_status_label()
        self._create_name_editor()
        self._create_start_date_editor()
        self._create_save_button()
        self._adding_employee = False

    def _create_status_label(self):
        self._status_label = JLabel(name='status_label',
                                   font=Font(Font.SANS_SERIF, Font.PLAIN, 11))
        self.add(self._status_label)
        self._add_with_padding(self._status_label, 5)

    def _create_name_editor(self):
        self.add(JLabel(text='Employee Name:'))
        self._name_editor = FixedHeightTextField('name_input')
        self._add_with_padding(self._name_editor, 5)

    def _create_start_date_editor(self):
        self.add(JLabel(text='Start Date (yyyy-mm-dd):'))
        self._start_date_editor = FixedHeightTextField('start_input')
        self._add_with_padding(self._start_date_editor, 5)

    def _create_save_button(self):
        self._save_button = JButton('Save', name='save_button', visible=False)
        self._save_button.addActionListener(ListenerFactory(ActionListener,
                                            self._save_button_pushed))
        self._add_with_padding(self._save_button, 5)

    def _add_with_padding(self, component, padding):
        self.add(component)
        self.add(Box.createRigidArea(Dimension(0, padding)))

    def show_employee(self, employee):
        self._name_editor.setText(employee.name)
        self._start_date_editor.setText(str(employee.startdate))
        self._name_editor.setEditable(False)
        self._start_date_editor.setEditable(False)
        self._save_button.setVisible(False)
        if self._adding_employee:
            self._adding_employee = False
        else:
            self._status_label.setText('')

    def edit_new_employee(self):
        self._name_editor.setText('')
        self._start_date_editor.setText('')
        self._name_editor.setEditable(True)
        self._start_date_editor.setEditable(True)
        self._save_button.setVisible(True)
        self._adding_employee = True

    def _save_button_pushed(self, event):
        self._employees.add(self._name_editor.getText(),
                            self._start_date_editor.getText())

    def employee_added(self, employee):
        self._status_label.setForeground(Color.BLACK)
        self._status_label.setText("Employee '%s' was added successfully." % employee.name)
        self._save_button.setVisible(False)

    def adding_employee_failed(self, reason):
        self._status_label.setForeground(Color.RED)
        self._status_label.setText(reason)
Beispiel #42
0
def makeCropUI(imp, images, tgtDir, panel=None, cropContinuationFn=None):
  """ imp: the ImagePlus to work on.
      images: the list of ImgLib2 images, one per frame, not original but already isotropic.
              (These are views that use a nearest neighbor interpolation using the calibration to scale to isotropy.)
      tgtDir: the target directory where e.g. CSV files will be stored, for ROI, features, pointmatches.
      panel: optional, a JPanel controlled by a GridBagLayout.
      cropContinuationFn: optional, a function to execute after cropping,
                          which is given as arguments the original images,
                          minC, maxC (both define a ROI), and the cropped images. """
  independent = None == panel
  if not panel:
    panel = JPanel()
    panel.setBorder(BorderFactory.createEmptyBorder(10,10,10,10))
    gb = GridBagLayout()
    gc = GBC()
  else:
    gb = panel.getLayout()
    # Constraints of the last component
    gc = gb.getConstraints(panel.getComponent(panel.getComponentCount() - 1))
    
    # Horizontal line to separate prior UI components from crop UI
    gc.gridx = 0
    gc.gridy += 1
    gc.gridwidth = 4
    gc.anchor = GBC.WEST
    gc.fill = GBC.HORIZONTAL
    sep = JSeparator()
    sep.setMinimumSize(Dimension(200, 10))
    gb.setConstraints(sep, gc)
    panel.add(sep)

  # ROI UI header
  title = JLabel("ROI controls:")
  gc.gridy +=1
  gc.anchor = GBC.WEST
  gc.gridwidth = 4
  gb.setConstraints(title, gc)
  panel.add(title)

  # Column labels for the min and max coordinates
  gc.gridy += 1
  gc.gridwidth = 1
  for i, title in enumerate(["", "X", "Y", "Z"]):
    gc.gridx = i
    gc.anchor = GBC.CENTER
    label = JLabel(title)
    gb.setConstraints(label, gc)
    panel.add(label)

  textfields = []
  rms = []

  # Load stored ROI if any
  roi_path = path = os.path.join(tgtDir, "crop-roi.csv")
  if os.path.exists(roi_path):
    with open(roi_path, 'r') as csvfile:
      reader = csv.reader(csvfile, delimiter=',', quotechar="\"")
      reader.next() # header
      minC = map(int, reader.next()[1:])
      maxC = map(int, reader.next()[1:])
      # Place the ROI over the ImagePlus
      imp.setRoi(Roi(minC[0], minC[1], maxC[0] + 1 - minC[0], maxC[1] + 1 - minC[1]))
  else:
    # Use whole image dimensions
    minC = [0, 0, 0]
    maxC = [v -1 for v in Intervals.dimensionsAsLongArray(images[0])]

  # Text fields for the min and max coordinates
  for rowLabel, coords in izip(["min coords: ", "max coords: "],
                               [minC, maxC]):
    gc.gridx = 0
    gc.gridy += 1
    label = JLabel(rowLabel)
    gb.setConstraints(label, gc)
    panel.add(label)
    for i in xrange(3):
      gc.gridx += 1
      tf = JTextField(str(coords[i]), 10)
      gb.setConstraints(tf, gc)
      panel.add(tf)
      textfields.append(tf)
      listener = RoiMaker(imp, textfields, len(textfields) -1)
      rms.append(listener)
      tf.addKeyListener(listener)
      tf.addMouseWheelListener(listener)

  # Listen to changes in the ROI of imp
  rfl = RoiFieldListener(imp, textfields)
  Roi.addRoiListener(rfl)
  # ... and enable cleanup
  ImagePlus.addImageListener(FieldDisabler(rfl, rms))

  # Functions for cropping images
  cropped = None
  cropped_imp = None

  def storeRoi(minC, maxC):
    if os.path.exists(roi_path):
      # Load ROI
      with open(path, 'r') as csvfile:
        reader = csv.reader(csvfile, delimiter=',', quotechar="\"")
        reader.next() # header
        same = True
        for a, b in izip(minC + maxC, map(int, reader.next()[1:] + reader.next()[1:])):
          if a != b:
            same = False
            # Invalidate any CSV files for features and pointmatches: different cropping
            for filename in os.listdir(tgtDir):
              if filename.endswith("features.csv") or filename.endswith("pointmatches.csv"):
                os.remove(os.path.join(tgtDir, filename))
            break
        if same:
          return
    # Store the ROI as crop-roi.csv
    with open(roi_path, 'w') as csvfile:
      w = csv.writer(csvfile, delimiter=',', quotechar="\"", quoting=csv.QUOTE_NONNUMERIC)
      w.writerow(["coords", "x", "y", "z"])
      w.writerow(["min"] + map(int, minC))
      w.writerow(["max"] + map(int, maxC))
  
  def crop(event):
    global cropped, cropped_imp
    coords = [int(float(tf.getText())) for tf in textfields]
    minC = [max(0, c) for c in coords[0:3]]
    maxC = [min(d -1, c) for d, c in izip(Intervals.dimensionsAsLongArray(images[0]), coords[3:6])]
    storeRoi(minC, maxC)
    print "ROI min and max coordinates"
    print minC
    print maxC
    cropped = [Views.zeroMin(Views.interval(img, minC, maxC)) for img in images]
    cropped_imp = showAsStack(cropped, title="cropped")
    cropped_imp.setDisplayRange(imp.getDisplayRangeMin(), imp.getDisplayRangeMax())
    if cropContinuationFn:
      cropContinuationFn(images, minC, maxC, cropped, cropped_imp)

  # Buttons to create a ROI and to crop to ROI,
  # which when activated enables the fine registration buttons
  crop_button = JButton("Crop to ROI")
  crop_button.addActionListener(crop)
  gc.gridx = 0
  gc.gridy += 1
  gc.gridwidth = 4
  gc.anchor = GBC.WEST
  buttons_panel = JPanel()
  buttons_panel.add(crop_button)
  gb.setConstraints(buttons_panel, gc)
  panel.add(buttons_panel)

  if independent:
    frame = JFrame("Crop by ROI")
    frame.getContentPane().add(panel)
    frame.pack()
    frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE)
    frame.addWindowListener(CloseControl(destroyables=rms + [rfl]))
    frame.setVisible(True)
  else:
    # Re-pack the JFrame
    parent = panel.getParent()
    while not isinstance(parent, JFrame) and parent is not None:
      parent = parent.getParent()

    if parent:
      frame = parent
      frame.pack()
      found = False
      for wl in frame.getWindowListeners():
        if isinstance(wl, CloseControl):
          wl.addDestroyables(rms + [rfl])
          found = True
          break
      if not found:
        frame.addWindowListener(CloseControl(destroyables=rms + [rfl]))
      frame.setVisible(True)

  return panel
Beispiel #43
0
class EventsPane(WindowPane, ActionListener, DocumentListener):
    
    def __init__(self, window, api):
        self.api = api
        self.component = JPanel(BorderLayout())

        # Create editor pane
        scrollpane = JScrollPane()
        self.script_area = InputPane(window)
        self.script_area.undo = UndoManager()
        line_numbers = LineNumbering(self.script_area.component)
        scrollpane.viewport.view = self.script_area.component
        scrollpane.rowHeaderView = line_numbers.component
        self.component.add(scrollpane, BorderLayout.CENTER)

        # Create Selection pane
        select_pane = JPanel()
        self.objects_box = JComboBox([], actionCommand="object")
        select_pane.add(self.objects_box)
        self.events_box = JComboBox(
            ["update", "click"],
            actionCommand="event"
        )
        self.event_types = [EventType.UPDATE, EventType.CLICK]
        select_pane.add(self.events_box)
        self.languages = list(ScriptType.values())
        self.language_box = JComboBox(
            [l.getName() for l in self.languages],
            actionCommand="language"
        )        
        select_pane.add(self.language_box)
        self.save_btn = JButton("Save")
        select_pane.add(self.save_btn)
        self.component.add(select_pane, BorderLayout.PAGE_START)

        self.events_box.addActionListener(self)
        self.objects_box.addActionListener(self)
        self.language_box.addActionListener(self)
        self.save_btn.addActionListener(self)
        
        self.current = None
        self.update_geos()
        interface.addEventListener("add", self.event_listener)
        interface.addEventListener("remove", self.event_listener)
        interface.addEventListener("rename", self.event_listener)
        
        # Listen to script_area changes in order to know when the save
        # button can be activated
        self.script_area.doc.addDocumentListener(self)
        
        # Hack to be able to change the objects_box
        self.building_objects_box = False

        self.active = False

    def activate(self):
        self.active = True
        if self.must_update_geos:
            self.update_geos()
    def deactivate(self):
        self.active = False
    
    def indent_selection(self):
        return self.script_area.indent_selection()
    def dedent_selection(self):
        return self.script_area.dedent_selection()

    def update_geos(self):
        self.must_update_geos = False
        try:
            self.building_objects_box = True
            self.objects_box.removeAllItems()
            self.geos = self.api.getAllGeos()
            for geo in self.geos:
                tp = API.Geo.getTypeString(geo)
                label = API.Geo.getLabel(geo)
                self.objects_box.addItem(tp + " " + label)
        finally:
            self.building_objects_box = False
        
        if not self.geos:
            self.current = None
            self.objects_box.enabled = False
            self.events_box.enabled = False
            self.language_box.enabled = False
            self.script_area.input = ""
            self.script_area.component.enabled = False
        else:
            changed = False
            if self.current is None:
                index, event = 0, 1
                changed = True
            else:
                geo, event = self.current
                try:
                    index = self.geos.index(geo)
                except ValueError:
                    index, event = 0, 1
                    changed = True
            self.events_box.selectedIndex = event
            self.objects_box.selectedIndex = index
            self.events_box.enabled = True
            self.objects_box.enabled = True
            self.language_box.enabled = True
            self.script_area.component.enabled = True
            if changed:
                self.update_script_area()
        self.objects_box.repaint()
        self.events_box.repaint()
    
    def event_listener(self, evt, target):
        if self.active:
            self.update_geos()
        else:
            self.must_update_geos = True
    
    def current_script_changed(self):
        self.save_btn.enabled = True
    
    def set_save_btn(self, state):
        self.save_btn.enabled = state
    
    def save_current_script(self):
        if self.current is not None:
            geo, evt = self.current
            lang = self.language_box.selectedIndex
            evt, lang = self.event_types[evt], self.languages[lang]
            script = self.script_area.input
            self.api.setScript(geo, script, evt, lang)
            
    def update_script_area(self):
        self.save_current_script()
        geo_index = self.objects_box.selectedIndex
        if geo_index == -1:
            self.current = None
        else:
            geo = self.geos[geo_index]
            evt = self.events_box.selectedIndex
            self.current = geo, evt
            script = API.Geo.getScript(geo, self.event_types[evt])
            if script is None:
                self.script_area.input = ""
            else:
                self.script_area.input = API.getScriptText(script)
                self.language_box.selectedIndex = API.getScriptType(script).ordinal()
            self.script_area.reset_undo()
        later(self.set_save_btn, False)
        
    def reset(self):
        self.current = None
        self.update_geos()
    
    # Implementation of ActionListener
    def actionPerformed(self, evt):
        if self.building_objects_box:
           return
        if evt.actionCommand == "language":
            self.save_btn.enabled = True
        else:
            self.update_script_area()
    
    # Implementation of DocumentListener
    def changedUpdate(self, evt):
        self.current_script_changed()
    
    def removeUpdate(self, evt):
        self.current_script_changed()
    
    def insertUpdate(self, evt):
        self.current_script_changed()
Beispiel #44
0
def makeRegistrationUI(original_images, original_calibration, coarse_affines, params, images, minC, maxC, cropped, cropped_imp):
  """
  Register cropped images either all to all or all to the first one,
  and print out a config file with the coarse affines,
  the ROI for cropping, and the refined affines post-crop.

  original_images: the original, raw images, with original dimensions.
  original_calibration: the calibration of the images as they are on disk.
  coarse_affines: list of AffineTransform3D, one per image, that specify the translation between images
                  as manually set using the makeTranslationUI.
  params: dictionary with parameters for registering the given cropped images.
          This includes a calibration that is likely [1.0, 1.0, 1.0] as the cropped images
          are expected to have been scaled to isotropy.
  images: the list of near-original images but scaled (by calibration) to isotropy.
          (These are really views of the original images, using nearest neighbor interpolation
           to scale them to isotropy.)
  minC, maxC: the minimum and maximum coordinates of a ROI with which the cropped images were made.
  cropped: the list of images that have been scaled to isotropy, translated and cropped by the ROI.
           (These are really interval views of the images, the latter using nearest neighbor interpolation.)
  cropped_imp: the ImagePlus holding the virtual stack of cropped image views.

  The computed registration will merge the scaling to isotropy + first transform (a translation)
   + roi cropping translation + the params["modelclass"] registration transform, to read directly
   from the original images using a nearest interpolation, for best performance (piling two nearest
   interpolations over one another would result in very slow access to pixel data).
  """

  panel = JPanel()
  panel.setBorder(BorderFactory.createEmptyBorder(10,10,10,10))
  gb = GridBagLayout()
  panel.setLayout(gb)
  gc = GBC()

  calibration = params["calibration"]
  params["cal X"] = calibration[0]
  params["cal Y"] = calibration[1]
  params["cal Z"] = calibration[2]

  # Add a label and a text field for every parameter, with titles for every block
  strings = [["Calibration",
              "cal X", "cal Y", "cal Z"],
             ["Difference of Gaussian",
              "minPeakValue", "sigmaSmaller", "sigmaLarger"],
             ["Feature extraction",
              "radius", "min_angle", "max_per_peak",
              "angle_epsilon", "len_epsilon_sq",
              "pointmatches_nearby", "pointmatches_search_radius"],
             ["RANSAC parameters for the model",
              "maxEpsilon", "minInlierRatio", "minNumInliers",
              "n_iterations", "maxTrust"],
             ["All to all registration",
              "maxAllowedError", "maxPlateauwidth", "maxIterations", "damp"]]
  # Insert all as fields, with values populated from the params dictionary
  # and updating dynamically the params dictionary
  params = dict(params) # copy, will be updated
  insertFloatFields(panel, gb, gc, params, strings)

  # Identity transforms prior to registration
  affines = [affine3D([1, 0, 0, 0,
                       0, 1, 0, 0,
                       0, 0, 1, 0]) for img in cropped]
  
  def run():
    exe = newFixedThreadPool(min(len(cropped), numCPUs()))
    try:
      # Dummy for in-RAM reading of isotropic images
      img_filenames = [str(i) for i in xrange(len(cropped))]
      loader = InRAMLoader(dict(zip(img_filenames, cropped)))
      getCalibration = params.get("getCalibration", None)
      if not getCalibration:
        getCalibration = lambda img: [1.0] * cropped[0].numDimensions()
      csv_dir = params["csv_dir"]
      modelclass = params["modelclass"]
      # Matrices describing the registration on the basis of the cropped images
      matrices = computeOptimizedTransforms(img_filenames, loader, getCalibration,
                                            csv_dir, exe, modelclass, params)
      # Store outside, so they can be e.g. printed, and used beyond here
      for matrix, affine in zip(matrices, affines):
        affine.set(*matrix)

      # Combine the transforms: scaling (by calibration)
      #                         + the coarse registration (i.e. manual translations)
      #                         + the translation introduced by the ROI cropping
      #                         + the affine matrices computed above over the cropped images.
      coarse_matrices = []
      for coarse_affine in coarse_affines:
        matrix = zeros(12, 'd')
        coarse_affine.toArray(matrix)
        coarse_matrices.append(matrix)

      # NOTE: both coarse_matrices and matrices are from the camera X to camera 0. No need to invert them.
      # NOTE: uses identity calibration because the coarse_matrices already include the calibration scaling to isotropy
      transforms = mergeTransforms([1.0, 1.0, 1.0], coarse_matrices, [minC, maxC], matrices, invert2=False)

      print "calibration:", [1.0, 1.0, 1.0]
      print "cmTransforms:\n    %s\n    %s\n    %s\n    %s" % tuple(str(m) for m in coarse_matrices)
      print "ROI", [minC, maxC]
      print "fineTransformsPostROICrop:\n    %s\n    %s\n    %s\n    %s" % tuple(str(m) for m in matrices)
      print "invert2:", False
      
      # Show registered images
      registered = [transformedView(img, transform, interval=cropped[0])
                    for img, transform in izip(original_images, transforms)]
      registered_imp = showAsStack(registered, title="Registered with %s" % params["modelclass"].getSimpleName())
      registered_imp.setDisplayRange(cropped_imp.getDisplayRangeMin(), cropped_imp.getDisplayRangeMax())

      """
      # TEST: same as above, but without merging the transforms. WORKS, same result
      # Copy into ArrayImg, otherwise they are rather slow to browse
      def copy(img1, affine):
        # Copy in two steps. Otherwise the nearest neighbor interpolation on top of another
        # nearest neighbor interpolation takes a huge amount of time
        dimensions = Intervals.dimensionsAsLongArray(img1)
        aimg1 = ArrayImgs.unsignedShorts(dimensions)
        ImgUtil.copy(ImgView.wrap(img1, aimg1.factory()), aimg1)
        img2 = transformedView(aimg1, affine)
        aimg2 = ArrayImgs.unsignedShorts(dimensions)
        ImgUtil.copy(ImgView.wrap(img2, aimg2.factory()), aimg2)
        return aimg2
      futures = [exe.submit(Task(copy, img, affine)) for img, affine in izip(cropped, affines)]
      aimgs = [f.get() for f in futures]
      showAsStack(aimgs, title="DEBUG Registered with %s" % params["modelclass"].getSimpleName())
      """
    except:
      print sys.exc_info()
    finally:
      exe.shutdown()
      SwingUtilities.invokeLater(lambda: run_button.setEnabled(True))

  def launchRun(event):
    # Runs on the event dispatch thread
    run_button.setEnabled(False) # will be re-enabled at the end of run()
    # Fork:
    Thread(run).start()


  def printAffines(event):
    for i, affine in enumerate(affines):
      matrix = zeros(12, 'd')
      affine.toArray(matrix)
      msg = "# Refined post-crop affine matrix " + str(i) + ": \n" + \
            "affine" + str(i) + ".set(*[%f, %f, %f, %f,\n %f, %f, %f, %f,\n %f, %f, %f, %f])" % tuple(matrix.tolist())
      # Print everywhere
      print msg
      IJ.log(msg)
      System.out.println(msg)

  def prepareDeconvolutionScriptUI(event):
    """
    # DEBUG generateDeconvolutionScriptUI: generate params as a loadable serialized file
    with open("/tmp/parameters.pickle", 'w') as f:
      import pickle
      def asArrays(affines):
        arrays = []
        for affine in affines:
          matrix = zeros(12, 'd')
          affine.toArray(matrix)
          arrays.append(matrix)
        return arrays
        
      pickle.dump([params["srcDir"], params["tgtDir"], calibration,
                   asArrays(coarse_affines), [minC, maxC], asArrays(affines)], f)
    """
    generateDeconvolutionScriptUI(params["srcDir"], params["tgtDir"], calibration,
                                  coarse_affines, [minC, maxC], affines)
  
  # Buttons
  panel_buttons = JPanel()
  gc.gridx = 0
  gc.gridy += 1
  gc.gridwidth = 2
  gb.setConstraints(panel_buttons, gc)
  panel.add(panel_buttons)
  
  run_button = JButton("Run")
  run_button.addActionListener(launchRun)
  gb.setConstraints(run_button, gc)
  panel_buttons.add(run_button)
  
  print_button = JButton("Print affines")
  print_button.addActionListener(printAffines)
  panel_buttons.add(print_button)

  prepare_button = JButton("Prepare deconvolution script")
  prepare_button.addActionListener(prepareDeconvolutionScriptUI)
  panel_buttons.add(prepare_button)

  frame = JFrame("Registration")
  frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE)
  frame.addWindowListener(CloseControl())
  frame.getContentPane().add(panel)
  frame.pack()
  frame.setLocationRelativeTo(None) # center in the screen
  frame.setVisible(True)
Beispiel #45
0
class ProfelisPanel(JPanel):
    def __init__(self, frame, name):
        self.frame = frame
        self.exception = None
        self.name = name
        self.searchTerm = None
        self.searchIndex = -1

        self.searchField = JTextField("")
        self.searchField.addActionListener(SearchListener(self))

        self.newGeneFrom = JTextField("")
        self.newGeneTo = JTextField("")
        self.newGeneButton = JButton("New Gene")
        newGeneActionListener = NewGeneActionListener(self)
        self.newGeneFrom.addActionListener(newGeneActionListener)
        self.newGeneTo.addActionListener(newGeneActionListener)
        self.newGeneButton.addActionListener(newGeneActionListener)

        self.markForRemovalButton = JButton("Mark For Removal")
        self.markForRemovalButton.addActionListener(MarkForRemovalListener(self))
        
        self.inGenes = JList(DefaultListModel())
        self.inGenes.selectionMode = ListSelectionModel.SINGLE_SELECTION
        self.inGenes.cellRenderer = ProfelisCellRenderer()
        self.markButtonLabelerTimer = Timer(100, MarkButtonLabeler(self))
        self.markButtonLabelerTimer.start()
        self.loadFile()

        self.outGenes = JList(DefaultListModel())
        self.outGenes.selectionMode = ListSelectionModel.SINGLE_SELECTION
        self.outGenes.cellRenderer = ProfelisCellRenderer()
                
        constraints = GridBagConstraints()
        self.layout = GridBagLayout()
        
        constraints.gridx, constraints.gridy = 0, 0
        constraints.gridwidth, constraints.gridheight = 1, 1
        constraints.fill = GridBagConstraints.NONE
        constraints.weightx, constraints.weighty = 0, 0
        self.add(JLabel("Genes In Artemis File"), constraints)
        constraints.gridx, constraints.gridy = 0, 1
        self.add(JButton(RemoveAction(self)), constraints)
        constraints.gridx, constraints.gridy = 1, 1
        self.add(self.markForRemovalButton, constraints)
        constraints.gridx, constraints.gridy = 2, 1
        self.add(JLabel("Search"), constraints)
        constraints.gridx, constraints.gridy = 3, 1
        constraints.fill = GridBagConstraints.HORIZONTAL
        self.add(self.searchField, constraints)
        constraints.gridx, constraints.gridy = 0, 2
        constraints.gridwidth, constraints.gridheight = 4, 2
        constraints.fill = GridBagConstraints.BOTH
        constraints.weightx, constraints.weighty = 1, 1
        self.add(JScrollPane(self.inGenes), constraints)

        constraints.gridx, constraints.gridy = 4, 0
        constraints.gridwidth, constraints.gridheight = 1, 1
        constraints.fill = GridBagConstraints.NONE
        constraints.weightx, constraints.weighty = 0, 0
        self.add(JLabel("Genes To Add To Artemis File"), constraints)
        constraints.gridx, constraints.gridy = 4, 1
        self.add(self.newGeneButton, constraints)
        constraints.weightx = 1
        constraints.fill = GridBagConstraints.BOTH
        constraints.gridx, constraints.gridy = 5, 1
        self.add(self.newGeneFrom, constraints)
        constraints.weightx = 0
        constraints.fill = GridBagConstraints.NONE
        constraints.gridx, constraints.gridy = 6, 1
        self.add(JLabel("To"), constraints)
        constraints.weightx = 1
        constraints.fill = GridBagConstraints.BOTH
        constraints.gridx, constraints.gridy = 7, 1
        self.add(self.newGeneTo, constraints)

        constraints.weightx = 0
        constraints.fill = GridBagConstraints.NONE
        constraints.gridx, constraints.gridy = 4, 2
        self.add(JButton(AddGenesAction(self)), constraints)
        constraints.gridx, constraints.gridy = 4, 3
        constraints.gridwidth, constraints.gridheight = 4, 1
        constraints.fill = GridBagConstraints.BOTH
        constraints.weightx, constraints.weighty = 1, 1
        self.add(JScrollPane(self.outGenes), constraints)

    def loadFile(self):
        self.inGenes.model.clear()
        self.database, self.evalue, genes = utils.parseBlast(self.name + ".blastp.xml")
        [self.inGenes.model.addElement(gene) for gene in genes]

        artemisInput = open(self.name + ".art", "r")
        lines = artemisInput.readlines()
        artemisInput.close()
        self.restOfFile = self.genome = []
        while lines:
            if re.match("\s+CDS\s+(complement\()?\d+\.\.\d+\)?\n", lines[0]):
                lines = lines[4:]
            elif lines[0].find("ORIGIN") == 0:
                self.genome = map(lambda x: re.sub("\s+", "", x), lines[1:])
                lines = []
            else:
                if lines[0].strip():
                    self.restOfFile.append(lines[0])
                lines = lines[1:]
                
        self.genome = "".join(self.genome)
        self.restOfFile = "".join(self.restOfFile)

    def writeArtemisFile(self):
        output = open(self.name + ".art", "w")
        output.write(self.restOfFile)
        for element in self.inGenes.model.elements():
            output.write(element.toArtemis())
        output.write("\nORIGIN\n\n")
        for i in range(0, len(self.genome), 50):
            output.write(self.genome[i:min(i+50, len(self.genome))] + "\n")
        output.close()
Beispiel #46
0
def generateDeconvolutionScriptUI(srcDir,
                                  tgtDir,
                                  calibration,
                                  preCropAffines,
                                  ROI,
                                  postCropAffines):
  """
  Open an UI to automatically generate a script to:
  1. Register the views of each time point TM folder, and deconvolve them.
  2. Register deconvolved time points to each other, for a range of consecutive time points.

  Will ask for the file path to the kernel file,
  and also for the range of time points to process,
  and for the deconvolution iterations for CM00-CM01, and CM02-CM03.
  """

  template = """
# AUTOMATICALLY GENERATED - %s

import sys, os
sys.path.append("%s")
from lib.isoview import deconvolveTimePoints
from mpicbg.models import RigidModel3D, TranslationModel3D
from net.imglib2.img.display.imagej import ImageJFunctions as IL

# The folder with the sequence of TM\d+ folders, one per time point in the 4D series.
# Each folder should contain 4 KLB files, one per camera view of the IsoView microscope.
srcDir = "%s"

# A folder to save deconvolved images in, and CSV files describing features, point matches and transformations
targetDir = "%s"

# Path to the volume describing the point spread function (PSF)
kernelPath = "%s"

calibration = [%s] # An array with 3 floats (identity--all 1.0--because the coarse affines, that is,
                   # the camera transformations, already include the scaling to isotropy computed using the original calibration.

# The transformations of each timepoint onto the camera at index zero.
def cameraTransformations(dims0, dims1, dims2, dims3, calibration):
  return {
    0: [%s],
    1: [%s],
    2: [%s],
    3: [%s]
  }

# Deconvolution parameters
paramsDeconvolution = {
  "blockSizes": None, # None means the image size + kernel size. Otherwise specify like e.g. [[128, 128, 128]] for img in images]
  "CM_0_1_n_iterations": %i,
  "CM_2_3_n_iterations": %i,
}

# Joint dictionary of parameters
params = {}
params.update(paramsDeconvolution)

# A region of interest for each camera view, for cropping after registration but prior to deconvolution
roi = ([%s], # array of 3 integers, top-left coordinates
       [%s]) # array of 3 integers, bottom-right coordinates

# All 4 cameras relative to CM00
fineTransformsPostROICrop = \
   [[1, 0, 0, 0,
     0, 1, 0, 0,
     0, 0, 1, 0],
    [%s],
    [%s],
    [%s]]

deconvolveTimePoints(srcDir, targetDir, kernelPath, calibration,
                    cameraTransformations, fineTransformsPostROICrop,
                    params, roi, fine_fwd=True, subrange=range(%i, %i))
  """

  od = OpenDialog("Choose kernel file", srcDir)
  kernel_path = od.getPath()
  if not kernel_path:
    JOptionPane.showMessageDialog(None, "Can't proceed without a filepath to the kernel", "Alert", JOptionPane.ERROR_MESSAGE)
    return

  panel = JPanel()
  panel.setBorder(BorderFactory.createEmptyBorder(10,10,10,10))
  gb = GridBagLayout()
  panel.setLayout(gb)
  gc = GBC()

  msg = ["Edit parameters, then push the button",
         "to generate a script that, when run,",
         "will execute the deconvolution for each time point",
         "saving two 3D stacks per time point as ZIP files",
         "in the target directory under subfolder 'deconvolved'.",
         "Find the script in a new Script Editor window.",
         " "]
  gc.gridy = -1 # init
  for line in msg:
    label = JLabel(line)
    gc.anchor = GBC.WEST
    gc.gridx = 0
    gc.gridy += 1
    gc.gridwidth = 2
    gc.gridheight = 1
    gb.setConstraints(label, gc)
    panel.add(label)

  strings = [["Deconvolution iterations",
              "CM_0_1_n_iterations", "CM_2_3_n_iterations"],
             ["Range",
              "First time point", "Last time point"]]
  params = {"CM_0_1_n_iterations": 5,
            "CM_2_3_n_iterations": 7,
            "First time point": 0,
            "Last time point": -1} # -1 means last
  insertFloatFields(panel, gb, gc, params, strings)

  def asString(affine):
    matrix = zeros(12, 'd')
    affine.toArray(matrix)
    return ",".join(imap(str, matrix))

  def generateScript(event):
    script = template % (str(datetime.now()),
                         filter(lambda path: path.endswith("IsoView-GCaMP"), sys.path)[-1],
                         srcDir,
                         tgtDir,
                         kernel_path,
                         ", ".join(imap(str, calibration)),
                         asString(preCropAffines[0]),
                         asString(preCropAffines[1]),
                         asString(preCropAffines[2]),
                         asString(preCropAffines[3]),
                         params["CM_0_1_n_iterations"],
                         params["CM_2_3_n_iterations"],
                         ", ".join(imap(str, ROI[0])),
                         ", ".join(imap(str, ROI[1])),
                         asString(postCropAffines[1]),
                         asString(postCropAffines[2]),
                         asString(postCropAffines[3]),
                         params["First time point"],
                         params["Last time point"])
    tab = None
    for frame in JFrame.getFrames():
      if str(frame).startswith("org.scijava.ui.swing.script.TextEditor["):
        try:
          tab = frame.newTab(script, "python")
          break
        except:
          print sys.exc_info()
    if not tab:
      try:
        now = datetime.now()
        with open(os.path.join(System.getProperty("java.io.tmpdir"),
                               "script-%i-%i-%i_%i:%i.py" % (now.year, now.month, now.day,
                                                             now.hour, now.minute)), 'w') as f:
          f.write(script)
      except:
        print sys.exc_info()
        print script
  

  gen = JButton("Generate script")
  gen.addActionListener(generateScript)
  gc.anchor = GBC.CENTER
  gc.gridx = 0
  gc.gridy += 1
  gc.gridwidth = 2
  gb.setConstraints(gen, gc)
  panel.add(gen)

  frame = JFrame("Generate deconvolution script")
  frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE)
  frame.getContentPane().add(panel)
  frame.pack()
  frame.setLocationRelativeTo(None) # center in the screen
  frame.setVisible(True)
Beispiel #47
0
class EmployeeDetails(JPanel):
    def __init__(self, employees):
        JPanel.__init__(self, preferredSize=(400, 200))
        layout = BoxLayout(self, BoxLayout.Y_AXIS)
        self.setLayout(layout)
        self._employees = employees
        employees.add_change_listener(self)
        self._create_status_label()
        self._create_name_editor()
        self._create_start_date_editor()
        self._create_save_button()
        self._create_vacation_display()
        self._adding_employee = False

    def _create_status_label(self):
        self._status_label = JLabel(name='status_label',
                                    font=Font(Font.SANS_SERIF, Font.PLAIN, 11))
        self.add(self._status_label)
        self._add_with_padding(self._status_label, 5)

    def _create_name_editor(self):
        self.add(JLabel(text='Employee Name:'))
        self._name_editor = FixedHeightTextField('name_input')
        self._add_with_padding(self._name_editor, 5)

    def _create_start_date_editor(self):
        self.add(JLabel(text='Start Date (yyyy-mm-dd):'))
        self._start_date_editor = FixedHeightTextField('start_input')
        self._add_with_padding(self._start_date_editor, 5)

    def _create_save_button(self):
        self._save_button = JButton('Save', name='save_button', visible=False)
        self._save_button.addActionListener(
            ListenerFactory(ActionListener, self._save_button_pushed))
        self._add_with_padding(self._save_button, 5)

    def _create_vacation_display(self):
        #        self._display = JTable()
        #        self._header = self._display.getTableHeader()
        #        self.add(self._header)
        #        self.add(self._display)
        pass

    def _add_with_padding(self, component, padding):
        self.add(component)
        self.add(Box.createRigidArea(Dimension(0, padding)))

    def show_employee(self, employee):
        self._name_editor.setText(employee.name)
        self._start_date_editor.setText(str(employee.startdate))
        self._name_editor.setEditable(False)
        self._start_date_editor.setEditable(False)
        self._save_button.setVisible(False)
        if self._adding_employee:
            self._adding_employee = False
        else:
            self._status_label.setText('')


#        self._display.setVisible(True)
#        self._display.setModel(VacationTableModel(employee))
#        self._header.setVisible(True)

    def edit_new_employee(self):
        self._name_editor.setText('')
        self._start_date_editor.setText('')
        self._name_editor.setEditable(True)
        self._start_date_editor.setEditable(True)
        self._save_button.setVisible(True)
        #        self._display.setVisible(False)
        #        self._header.setVisible(False)
        self._adding_employee = True

    def _save_button_pushed(self, event):
        self._employees.add(self._name_editor.getText(),
                            self._start_date_editor.getText())

    def employee_added(self, employee):
        self._status_label.setForeground(Color.BLACK)
        self._status_label.setText("Employee '%s' was added successfully." %
                                   employee.name)
        self._save_button.setVisible(False)

    def adding_employee_failed(self, reason):
        self._status_label.setForeground(Color.RED)
        self._status_label.setText(reason)
Beispiel #48
0
    def __init__(self,
                 menuHandles,
                 manager,
                 isDominant,
                 systemPanel,
                 isTemporal=False):
        self.systemPanel = systemPanel
        self.knownPops = 0
        self.ignoreChanges = True
        JPanel()
        self.menuHandles = menuHandles
        self.isDominant = isDominant
        self.isTemporal = isTemporal
        if isDominant:
            self.setLayout(GridLayout(8, 2))
        else:
            self.setLayout(GridLayout(5, 2))
        if isTemporal:
            self.add(JLabel('Ne'))
            ne = JFormattedTextField(NumberFormat.getNumberInstance(Locale.US))
            ne.addPropertyChangeListener(self)
            self.ne = ne
            self.add(ne)
            self.add(JLabel('Expected total samples'))
        else:
            self.add(JLabel('Attempted Fst'))
            fst = JFormattedTextField(NumberFormat.getNumberInstance(
                Locale.US))
            fst.addPropertyChangeListener(self)
            self.fst = fst
            self.add(fst)
            self.add(JLabel('Expected total pops'))
        pops = JFormattedTextField(NumberFormat.getIntegerInstance(Locale.US))
        pops.addPropertyChangeListener(self)
        # self.pops = JComboBox(['1', '2', '4', '8', '12', '16'])
        self.pops = pops
        self.add(self.pops)
        if not isDominant and not isTemporal:
            self.add(JLabel('Mutation model'))
            self.mut = JComboBox(['Infinite Alleles', 'Stepwise'])
            self.mut.addItemListener(self)
            self.add(self.mut)
        else:
            self.mut = None
        self.add(JLabel('Subsample size'))
        sampleSize = JFormattedTextField(
            NumberFormat.getIntegerInstance(Locale.US))
        sampleSize.addPropertyChangeListener(self)
        self.sampleSize = sampleSize
        self.add(self.sampleSize)
        if isDominant:
            self.add(JLabel('Theta'))
            theta = JFormattedTextField(
                NumberFormat.getNumberInstance(Locale.US))
            theta.addPropertyChangeListener(self)
            self.theta = theta
            self.add(theta)
            theta.setValue(0.1)

            self.add(JLabel('Beta-a'))
            beta1 = JFormattedTextField(
                NumberFormat.getNumberInstance(Locale.US))
            beta1.addPropertyChangeListener(self)
            self.beta1 = beta1
            self.add(beta1)
            beta1.setValue(0.25)

            self.add(JLabel('Beta-b'))
            beta2 = JFormattedTextField(
                NumberFormat.getNumberInstance(Locale.US))
            beta2.addPropertyChangeListener(self)
            self.beta2 = beta2
            self.add(beta2)
            beta2.setValue(0.25)

            self.add(JLabel('Critical frequency'))
            crit = JFormattedTextField(
                NumberFormat.getNumberInstance(Locale.US))
            crit.addPropertyChangeListener(self)
            self.crit = crit
            self.add(crit)
            crit.setValue(0.99)

        run = JButton('Run!')
        run.addActionListener(manager)
        run.setActionCommand('RunFDist')
        self.run = run
        self.add(run)
class EmployeeDetails(JPanel):
    def __init__(self, employees, dateprovider):
        JPanel.__init__(self, preferredSize=(400, 200))
        layout = BoxLayout(self, BoxLayout.Y_AXIS)
        self.setLayout(layout)
        self._employees = employees
        self._dateprovider = dateprovider
        employees.add_change_listener(self)
        self._create_status_label()
        self._create_name_editor()
        self._create_start_date_editor()
        self._create_save_button()
        self._create_vacation_display()
        self._adding_employee = False

    def _create_status_label(self):
        self._status_label = JLabel(name="status_label", font=Font(Font.SANS_SERIF, Font.PLAIN, 11))
        self.add(self._status_label)
        self._add_with_padding(self._status_label, 5)

    def _create_name_editor(self):
        self.add(JLabel(text="Employee Name:"))
        self._name_editor = FixedHeightTextField("name_input")
        self._add_with_padding(self._name_editor, 5)

    def _create_start_date_editor(self):
        self.add(JLabel(text="Start Date (yyyy-mm-dd):"))
        self._start_date_editor = FixedHeightTextField("start_input")
        self._add_with_padding(self._start_date_editor, 5)

    def _create_save_button(self):
        self._save_button = JButton("Save", name="save_button", visible=False)
        self._save_button.addActionListener(ListenerFactory(ActionListener, self._save_button_pushed))
        self._add_with_padding(self._save_button, 5)

    def _create_vacation_display(self):
        self._display = JTable(name="vacation_display")
        self._header = self._display.getTableHeader()
        self.add(self._header)
        self.add(self._display)

    def _add_with_padding(self, component, padding):
        self.add(component)
        self.add(Box.createRigidArea(Dimension(0, padding)))

    def show_employee(self, employee):
        self._name_editor.setText(employee.name)
        self._start_date_editor.setText(str(employee.startdate))
        self._name_editor.setEditable(False)
        self._start_date_editor.setEditable(False)
        self._save_button.setVisible(False)
        if self._adding_employee:
            self._adding_employee = False
        else:
            self._status_label.setText("")
        self._display.setVisible(True)
        self._display.setModel(VacationTableModel(employee, self._dateprovider))
        self._header.setVisible(True)

    def edit_new_employee(self):
        self._name_editor.setText("")
        self._start_date_editor.setText("")
        self._name_editor.setEditable(True)
        self._start_date_editor.setEditable(True)
        self._save_button.setVisible(True)
        self._display.setVisible(False)
        self._header.setVisible(False)
        self._adding_employee = True

    def _save_button_pushed(self, event):
        self._employees.add(self._name_editor.getText(), self._start_date_editor.getText())

    def employee_added(self, employee):
        self._status_label.setForeground(Color.BLACK)
        self._status_label.setText("Employee '%s' was added successfully." % employee.name)
        self._save_button.setVisible(False)

    def adding_employee_failed(self, reason):
        self._status_label.setForeground(Color.RED)
        self._status_label.setText(reason)
Beispiel #50
0
 def _create_new_employee_button(self):
     btn = JButton('New Employee', name='new_employee_button')
     btn.addActionListener(
         ListenerFactory(ActionListener, self._new_employee))
     return btn
Beispiel #51
0
class BurpExtender(IBurpExtender, ITab, IMessageEditorController, IContextMenuFactory, ActionListener,
                   AbstractTableModel, Runnable):

    #
    # Implement IBurpExtender
    #
    def registerExtenderCallbacks(self, callbacks):
        # Initialize the global stdout stream
        global stdout

        # Keep a reference to our callbacks object
        self._callbacks = callbacks

        # Obtain an extension helpers object
        self._helpers = callbacks.getHelpers()

        # set our extension name
        callbacks.setExtensionName("Burpsuite Yara Scanner")

        # Create the log and a lock on which to synchronize when adding log entries
        self._log = ArrayList()
        self._lock = Lock()

        # main split pane
        splitpane = JSplitPane(JSplitPane.VERTICAL_SPLIT)

        # table of log entries
        logTable = Table(self)
        scrollPane = JScrollPane(logTable)
        splitpane.setLeftComponent(scrollPane)

        # Options panel
        optionsPanel = JPanel()
        optionsPanel.setLayout(GridBagLayout())
        constraints = GridBagConstraints()

        yara_exe_label = JLabel("Yara Executable Location:")
        constraints.fill = GridBagConstraints.HORIZONTAL
        constraints.gridx = 0
        constraints.gridy = 0
        optionsPanel.add(yara_exe_label, constraints)

        self._yara_exe_txtField = JTextField(25)
        constraints.fill = GridBagConstraints.HORIZONTAL
        constraints.gridx = 1
        constraints.gridy = 0
        optionsPanel.add(self._yara_exe_txtField, constraints)

        yara_rules_label = JLabel("Yara Rules File:")
        constraints.fill = GridBagConstraints.HORIZONTAL
        constraints.gridx = 0
        constraints.gridy = 1
        optionsPanel.add(yara_rules_label, constraints)
		
        self._yara_rules_files = Vector()
        self._yara_rules_files.add("< None >")
        self._yara_rules_fileList = JList(self._yara_rules_files)
        constraints.fill = GridBagConstraints.HORIZONTAL
        constraints.gridx = 1
        constraints.gridy = 1
        optionsPanel.add(self._yara_rules_fileList, constraints)
        
        self._yara_rules_select_files_button = JButton("Select Files")
        self._yara_rules_select_files_button.addActionListener(self)
        constraints.fill = GridBagConstraints.HORIZONTAL
        constraints.gridx = 1
        constraints.gridy = 2
        optionsPanel.add(self._yara_rules_select_files_button, constraints)

        self._yara_clear_button = JButton("Clear Yara Results Table")
        self._yara_clear_button.addActionListener(self)
        constraints.fill = GridBagConstraints.HORIZONTAL
        constraints.gridx = 1
        constraints.gridy = 3
        optionsPanel.add(self._yara_clear_button, constraints)

        # Tabs with request/response viewers
        viewerTabs = JTabbedPane()
        self._requestViewer = callbacks.createMessageEditor(self, False)
        self._responseViewer = callbacks.createMessageEditor(self, False)
        viewerTabs.addTab("Request", self._requestViewer.getComponent())
        viewerTabs.addTab("Response", self._responseViewer.getComponent())
        splitpane.setRightComponent(viewerTabs)

        # Tabs for the Yara output and the Options
        self._mainTabs = JTabbedPane()
        self._mainTabs.addTab("Yara Output", splitpane)
        self._mainTabs.addTab("Options", optionsPanel)

        # customize our UI components
        callbacks.customizeUiComponent(splitpane)
        callbacks.customizeUiComponent(logTable)
        callbacks.customizeUiComponent(scrollPane)
        callbacks.customizeUiComponent(viewerTabs)
        callbacks.customizeUiComponent(self._mainTabs)

        # add the custom tab to Burp's UI
        callbacks.addSuiteTab(self)

        # add ourselves as a context menu factory
        callbacks.registerContextMenuFactory(self)

        # Custom Menu Item
        self.menuItem = JMenuItem("Scan with Yara")
        self.menuItem.addActionListener(self)

        # obtain our output stream
        stdout = PrintWriter(callbacks.getStdout(), True)

        # Print a startup notification
        stdout.println("Burpsuite Yara scanner initialized.")

    #
    # Implement ITab
    #
    def getTabCaption(self):
        return "Yara"

    def getUiComponent(self):
        return self._mainTabs

    #
    # Implement IContextMenuFactory
    #
    def createMenuItems(self, invocation):
        if invocation.getInvocationContext() == invocation.CONTEXT_TARGET_SITE_MAP_TREE:
            self.requestResponses = invocation.getSelectedMessages()
            return [self.menuItem]
        else:
            self.requestResponses = None
        return None

    #
    # Implement Action
    #
    def actionPerformed(self, actionEvent):
        global yara_rules
        global yara_path

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

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

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

    #
    # Implement Runnable
    #
    def run(self):
        self.yaraScan()

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

    def getColumnCount(self):
        return 2

    def getColumnName(self, columnIndex):
        if columnIndex == 0:
            return "Rule Name"
        if columnIndex == 1:
            return "URL"
        return ""

    def getValueAt(self, rowIndex, columnIndex):
        logEntry = self._log.get(rowIndex)
        if columnIndex == 0:
            return logEntry._ruleName
        if columnIndex == 1:
            return logEntry._url.toString()
        return ""

    #
    # Implement IMessageEditorController
    # this allows our request/response viewers to obtain details about the messages being displayed
    #

    def getHttpService(self):
        return self._currentlyDisplayedItem.getHttpService()

    def getRequest(self):
        return self._currentlyDisplayedItem.getRequest()

    def getResponse(self):
        return self._currentlyDisplayedItem.getResponse()

    #
    # Implement the Yara scanning logic
    #
    def yaraScan(self):
        # If stdout has not yet been initialized, punt.
        if stdout is None:
            return

        # If the location of the yara executable and rules files are NULL, punt.
        if yara_rules is None or yara_path is None or yara_rules.size() == 0 or yara_rules.contains("< None >") or len(yara_path) == 0:
            JOptionPane.showMessageDialog(None, "Error: Please specify the path to the yara executable and rules file in "
                                                "the options tab.")
            return

        # If iRequestResponses is None, punt.
        if self.requestResponses is None:
            JOptionPane.showMessageDialog(None, "Error: No Request/Responses were selected.")
            return
        else:
            stdout.println("Processing %d item(s)." % len(self.requestResponses))

        # Get the OS temp folder
        os_name = System.getProperty("os.name").lower()

        temp_folder = None
        if "linux" in os_name:
            temp_folder = "/tmp"
        elif "windows" in os_name:
            temp_folder = os.environ.get("TEMP")
            if temp_folder is None:
                temp_folder = os.environ.get("TMP")

        if temp_folder is None:
            stdout.println("Error: Could not determine TEMP folder location.")
            return

        # Keep track of the number of matches.
        matchCount = 0

        # Process the site map selected messages
        for idx, iRequestResponse in enumerate(self.requestResponses):
            # Process the request
            request = iRequestResponse.getRequest()
            if request is not None:
                if len(request) > 0:
                    try:
                        # Yara does not support scanning from stdin so we will need to create a temp file and scan it
                        req_filename = os.path.join(temp_folder, "req_" + str(idx) + ".tmp")
                        req_file = open(req_filename, "wb")
                        req_file.write(request)
                        req_file.close()
                        for rules in yara_rules:
                            yara_req_output = subprocess.check_output([yara_path, rules, req_filename])
                            if yara_req_output is not None and len(yara_req_output) > 0:
                                ruleName = (yara_req_output.split())[0]
                                self._lock.acquire()
                                row = self._log.size()
                                # TODO: Don't add duplicate items to the table
                                self._log.add(LogEntry(ruleName, iRequestResponse, self._helpers.analyzeRequest(iRequestResponse).getUrl()))
                                self.fireTableRowsInserted(row, row)
                                self._lock.release()
                                matchCount += 1
                    except Exception as e:
                        JOptionPane.showMessageDialog(None, "Error running Yara. Please check your configuration and rules.")
                        return
                    finally:
                        # Remove the temp file
                        if req_file is not None:
                            req_file.close()
                        os.remove(req_filename)

            # Process the response
            response = iRequestResponse.getResponse()
            if response is not None:
                if len(response) > 0:
                    try:
                        # Yara does not support scanning from stdin so we will need to create a temp file and scan it
                        resp_filename = os.path.join(temp_folder, "resp_" + str(idx) + ".tmp")
                        resp_file = open(resp_filename, "wb")
                        resp_file.write(response)
                        resp_file.close()
                        for rules in yara_rules:
                            yara_resp_output = subprocess.check_output([yara_path, rules, resp_filename])
                            if yara_resp_output is not None and len(yara_resp_output) > 0:
                                ruleName = (yara_resp_output.split())[0]
                                self._lock.acquire()
                                row = self._log.size()
                                # TODO: Don't add duplicate items to the table
                                self._log.add(LogEntry(ruleName, iRequestResponse, self._helpers.analyzeRequest(iRequestResponse).getUrl()))
                                self.fireTableRowsInserted(row, row)
                                self._lock.release()
                                matchCount += 1
                    except Exception as e:
                        JOptionPane.showMessageDialog(None, "Error running Yara. Please check your configuration and rules.")
                        return
                    finally:
                        # Remove the temp file
                        if resp_file is not None:
                            resp_file.close()
                        os.remove(resp_filename)

        # Print a completion notification
        JOptionPane.showMessageDialog(None, "Yara scanning complete. %d rule(s) matched." % matchCount)
Beispiel #52
0
class ButtonPanel(Panel):
	
	playButton = None
	helpButton = None
	resetButton = None
	exitButton = None

	def __init__(self, inconsolePanel,dialogPanel):
		self.consolePanel = inconsolePanel
		self.dialogPanel = dialogPanel
		Panel.__init__(self, "gap 1px 1px, insets 0 0 0 0, flowy")

	def initUI(self):

		self.setBackground(Color(0, 50, 0))

		self.playButtonS = ImageIcon('bin/gui/media/' + "playButton.png")
		self.helpButtonS = ImageIcon('bin/gui/media/' + "helpButton.png")
		self.resetButtonS = ImageIcon('bin/gui/media/' + "resetButton.png")
		self.exitButtonS = ImageIcon('bin/gui/media/' + "exitButton.png")
		self.playButtonU = ImageIcon('bin/gui/media/' + "playButton_unselected.png")
		self.helpButtonU = ImageIcon('bin/gui/media/' + "helpButton_unselected.png")
		self.resetButtonU = ImageIcon('bin/gui/media/' + "resetButton_unselected.png")
		self.exitButtonU = ImageIcon('bin/gui/media/' + "exitButton_unselected.png")

		class MouseHoverAdap(MouseAdapter):
			def __init__(self, butt, entImage, leaImage):
				self.entImage = entImage
				self.leaImage = leaImage
				self.butt = butt
				self.butt.setIcon(self.leaImage)
			def mouseEntered(self, m):
				self.butt.setIcon(self.entImage)
				#self.butt.repaint()
			def mouseExited(self, m):
				self.butt.setIcon(self.leaImage)
				#self.butt.repaint()


		self.playButton = JButton(self.playButtonS)
		self.playButton.setForeground(Color(0, 245, 0))
		#self.playButton.setPreferredSize(Dimension(playButton.getIconWidth(), playButton.getIconHeight()))
		#self.playButton.setBackground(Color(125, 125, 25))
		self.playButton.setMaximumSize(Dimension(self.playButtonS.getIconWidth(), self.playButtonS.getIconHeight()))
		self.playButton.setContentAreaFilled(False)

		self.helpButton = JButton(self.helpButtonS)
		self.helpButton.setForeground(Color(0, 235, 0))
		self.helpButton.setMaximumSize(Dimension(self.helpButtonS.getIconWidth(), self.helpButtonS.getIconHeight()))
		self.helpButton.setContentAreaFilled(False)

		self.resetButton = JButton(self.resetButtonS)
		self.resetButton.setForeground(Color(0, 225, 0))
		self.resetButton.setMaximumSize(Dimension(self.resetButtonS.getIconWidth(), self.resetButtonS.getIconHeight()))
		self.resetButton.setContentAreaFilled(False)

		self.exitButton = JButton(self.exitButtonS)
		self.exitButton.setForeground(Color(0, 215, 0))
		self.exitButton.setContentAreaFilled(False)
		self.exitButton.setMaximumSize(Dimension(self.exitButtonS.getIconWidth(), self.exitButtonS.getIconHeight()))
		
		# self.playButton.addMouseListener(MouseHoverAdap(self.playButton, self.playButtonS, self.playButtonU))
		# self.helpButton.addMouseListener(MouseHoverAdap(self.helpButton, self.helpButtonS, self.helpButtonU))
		# self.resetButton.addMouseListener(MouseHoverAdap(self.resetButton, self.resetButtonS, self.resetButtonU))
		# self.exitButton.addMouseListener(MouseHoverAdap(self.exitButton, self.exitButtonS, self.exitButtonU))


		class PlayButtonActionListener(ActionListener):
			def actionPerformed(button, e):
				self.dialogPanel.speak(self.consolePanel.console.do_play(''))
		self.playButton.addActionListener(PlayButtonActionListener())

		class HelpBUttonActionListener(ActionListener):
			def actionPerformed(button, e):
				self.dialogPanel.speak(self.consolePanel.console.do_hint(''))
		self.helpButton.addActionListener(HelpBUttonActionListener())

		class ResetButtonActionListener(ActionListener):
			def actionPerformed(button, e):
				self.dialogPanel.speak(self.consolePanel.console.do_reset(''))
		self.resetButton.addActionListener(ResetButtonActionListener())

		class ExitButtonActionListener(ActionListener):
			def actionPerformed(button, e):
				System.exit(0)
		self.exitButton.addActionListener(ExitButtonActionListener())





	def addUI(self):
		self.add(self.playButton, "push, grow")
		self.add(self.helpButton, "push, grow")
		self.add(self.resetButton, "push, grow")
		self.add(self.exitButton, "push, grow")