Example #1
0
    def __init__(self):

        self.holdPanel = JPanel()
        self.topPanel = JPanel()
        self.bottomPanel = JPanel()

        self.holdPanel.setBackground(Color.decode('#dddee6'))
        self.topPanel.setBackground(Color.decode('#dddee6'))
        self.bottomPanel.setBackground(Color.decode('#dddee6'))

        self.topPanel.setPreferredSize(Dimension(300, 30))

        self.regBar = JProgressBar()
        self.gatePassBar = JProgressBar()
        self.regLabel = JLabel('Register : ')
        self.gatepassLabel = JLabel('          Gate Pass : '******'')
        self.gatePercentlabel = JLabel('')

        self.refreshButton = JButton('Refresh',
                                     actionPerformed=self.updateProgress)

        self.regBar.setMinimum(0)
        self.regBar.setMaximum(100)
        self.regBar.setStringPainted(True)

        self.gatePassBar.setMinimum(0)
        self.gatePassBar.setMaximum(100)
        self.gatePassBar.setStringPainted(True)

        self.setLayout(BorderLayout())

        self.updateProgress(None)
Example #2
0
    def testJProgressBar(self):
        percentCompleteDummy = DummyObject()

        progressBar = JProgressBar(0, 10)
        self.group.bind(progressBar, 'value', self.dummy, 'value')
        self.group.bind(progressBar, 'percentComplete',
                        percentCompleteDummy, 'value')

        assert self.dummy.value == 0
        assert percentCompleteDummy.value == 0

        progressBar.setValue(2)
        assert self.dummy.value == 2
        assert percentCompleteDummy.value == 0.2
Example #3
0
  def initializeDisplay(self, queries, swing):
    """
    queries: A list of the fasts files to be processed.
    swing:   If true then updates about progress will be displayed in a swing window, otherwise they will be written to stdout.
    
    Initializes the interface for telling the user about progress in the pipeline.  Queries is used to count the
    number of queries the pipeline will process and to size the swing display(if it is used) so that text
    isn't cutoff at the edge of the window.  The swing display is setup if swing is true.
    """
  
    self.numJobs = len(queries)
    if swing:
      self.frame = JFrame("Neofelis")
      self.frame.addWindowListener(PipelineWindowAdapter(self))
      contentPane = JPanel(GridBagLayout())
      self.frame.setContentPane(contentPane)
      self.globalLabel = JLabel(max(queries, key = len))
      self.globalProgress = JProgressBar(0, self.numJobs)
      self.currentLabel = JLabel(max(self.messages, key = len))
      self.currentProgress = JProgressBar(0, len(self.messages))
      self.doneButton = JButton(DoneAction(self.frame))
      self.doneButton.setEnabled(False)

      constraints = GridBagConstraints()
      
      constraints.gridx, constraints.gridy = 0, 0
      constraints.gridwidth, constraints.gridheight = 1, 1
      constraints.weightx = 1
      constraints.fill = GridBagConstraints.HORIZONTAL
      contentPane.add(self.globalLabel, constraints)
      constraints.gridy = 1
      contentPane.add(self.globalProgress, constraints)
      constraints.gridy = 2
      contentPane.add(self.currentLabel, constraints)
      constraints.gridy = 3
      contentPane.add(self.currentProgress, constraints)
      constraints.gridy = 4
      constraints.weightx = 0
      constraints.fill = GridBagConstraints.NONE
      constraints.anchor = GridBagConstraints.LINE_END
      contentPane.add(self.doneButton, constraints)
    
      self.frame.pack()
      self.frame.setResizable(False)
      self.globalLabel.setText(" ")
      self.currentLabel.setText(" ")
      self.frame.setLocationRelativeTo(None)
      self.frame.setVisible(True)
Example #4
0
    def initializeDisplay(self, queries, swing):
        """
    queries: A list of the fasts files to be processed.
    swing:   If true then updates about progress will be displayed in a swing window, otherwise they will be written to stdout.
    
    Initializes the interface for telling the user about progress in the pipeline.  Queries is used to count the
    number of queries the pipeline will process and to size the swing display(if it is used) so that text
    isn't cutoff at the edge of the window.  The swing display is setup if swing is true.
    """

        self.numJobs = len(queries)
        if swing:
            self.frame = JFrame("Neofelis")
            self.frame.addWindowListener(PipelineWindowAdapter(self))
            contentPane = JPanel(GridBagLayout())
            self.frame.setContentPane(contentPane)
            self.globalLabel = JLabel(max(queries, key=len))
            self.globalProgress = JProgressBar(0, self.numJobs)
            self.currentLabel = JLabel(max(self.messages, key=len))
            self.currentProgress = JProgressBar(0, len(self.messages))
            self.doneButton = JButton(DoneAction(self.frame))
            self.doneButton.setEnabled(False)

            constraints = GridBagConstraints()

            constraints.gridx, constraints.gridy = 0, 0
            constraints.gridwidth, constraints.gridheight = 1, 1
            constraints.weightx = 1
            constraints.fill = GridBagConstraints.HORIZONTAL
            contentPane.add(self.globalLabel, constraints)
            constraints.gridy = 1
            contentPane.add(self.globalProgress, constraints)
            constraints.gridy = 2
            contentPane.add(self.currentLabel, constraints)
            constraints.gridy = 3
            contentPane.add(self.currentProgress, constraints)
            constraints.gridy = 4
            constraints.weightx = 0
            constraints.fill = GridBagConstraints.NONE
            constraints.anchor = GridBagConstraints.LINE_END
            contentPane.add(self.doneButton, constraints)

            self.frame.pack()
            self.frame.setResizable(False)
            self.globalLabel.setText(" ")
            self.currentLabel.setText(" ")
            self.frame.setLocationRelativeTo(None)
            self.frame.setVisible(True)
Example #5
0
    def __init__(self, parent, title, modal, app):
        JDialog.__init__(self, parent, title, modal)

        #Download and Read Dialog
        border = BorderFactory.createEmptyBorder(5, 7, 5, 7)
        self.getContentPane().setBorder(border)
        self.setLayout(BoxLayout(self.getContentPane(), BoxLayout.Y_AXIS))

        panel = JPanel()
        panel.setAlignmentX(0.5)
        panel.setLayout(BoxLayout(panel, BoxLayout.Y_AXIS))
        panel.add(Box.createRigidArea(Dimension(0, 10)))

        self.progressLbl = JLabel(
            app.strings.getString("downloading_and_reading_errors"))
        panel.add(self.progressLbl)

        panel.add(Box.createRigidArea(Dimension(0, 10)))

        self.progressBar = JProgressBar(0, 100, value=0)
        panel.add(self.progressBar)
        self.add(panel)

        self.add(Box.createRigidArea(Dimension(0, 20)))

        cancelBtn = JButton(app.strings.getString("cancel"),
                            ImageProvider.get("cancel"),
                            actionPerformed=app.on_cancelBtn_clicked)
        cancelBtn.setAlignmentX(0.5)
        self.add(cancelBtn)

        self.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE)
        self.pack()
Example #6
0
 def __init__(self, extender):
     # Initialize self
     super(FooterPanel, self).__init__()
     self.extender = extender
     self.setLayout(GridLayout(2, 1))
     # Create children
     self.progressInput = JProgressBar(0, 10000)
     self.progressOutput = JProgressBar(0, 10000)
     self.credit = JPanel()
     # Configure children
     self.progressInput.string = 'Ready'
     self.progressOutput.string = 'Ready'
     self.progressInput.stringPainted = True
     self.progressOutput.stringPainted = True
     # Add children
     self.add(self.progressInput)
     self.add(self.progressOutput)
    def loadPanel(self):
        panel = JPanel()

        panel.setLayout(BoxLayout(panel, BoxLayout.Y_AXIS))

        bottomButtonBarPanel = JPanel()
        bottomButtonBarPanel.setLayout(BoxLayout(bottomButtonBarPanel, BoxLayout.X_AXIS))
        bottomButtonBarPanel.setAlignmentX(1.0)

        self.runButton = JButton("Run", actionPerformed=self.start)
        self.cancelButton = JButton("Close", actionPerformed=self.cancel)

        bottomButtonBarPanel.add(Box.createHorizontalGlue());
        bottomButtonBarPanel.add(self.runButton)
        bottomButtonBarPanel.add(self.cancelButton)

        # Dimension(width,height)    
        bottom = JPanel()
        bottom.setLayout(BoxLayout(bottom, BoxLayout.X_AXIS))
        bottom.setAlignmentX(1.0)

        self.progressBar = JProgressBar()
        self.progressBar.setIndeterminate(False)
        self.progressBar.setMaximum(100)
        self.progressBar.setValue(0)

        bottom.add(self.progressBar)

        self.statusTextArea = JTextArea()
        self.statusTextArea.setEditable(False)
        scrollPane = JScrollPane(self.statusTextArea)
        scrollPanel = JPanel()
        scrollPanel.setLayout(BoxLayout(scrollPanel, BoxLayout.X_AXIS))
        scrollPanel.setAlignmentX(1.0)
        scrollPanel.add(scrollPane)

        panel.add(scrollPanel)
        panel.add(bottomButtonBarPanel)
        panel.add(bottom)

        self.add(panel)
        self.setTitle("Determine Session Cookie(s)")
        self.setSize(450, 300)
        self.setLocationRelativeTo(None)
        self.setVisible(True)


        original_request_bytes = self.selected_message.getRequest()
        http_service = self.selected_message.getHttpService()
        helpers = self.callbacks.getHelpers()
        request_info = helpers.analyzeRequest(http_service, original_request_bytes)
        parameters = request_info.getParameters();
        cookie_parameters = [parameter for parameter in parameters if parameter.getType() == IParameter.PARAM_COOKIE]
        num_requests_needed = len(cookie_parameters) + 2
        self.statusTextArea.append("This may require up to " + str(num_requests_needed) + " requests to be made. Hit 'Run' to begin.\n")
Example #8
0
    def _constructResultsPanel(self, insets):
        resultsPanel = JPanel(GridBagLayout())

        self._progressBar = JProgressBar()
        self._progressBar.setStringPainted(True)
        self._progressBar.setMinimum(0)
        progressBarContraints = GridBagConstraints()
        progressBarContraints.gridx = 0
        progressBarContraints.gridy = 0
        progressBarContraints.fill = GridBagConstraints.HORIZONTAL

        resultsPanel.add(self._progressBar, progressBarContraints)

        self._resultsTableModel = ResultsTableModel(COLUMNS, 0)
        resultsTable = JTable(self._resultsTableModel)
        resultsTable.setAutoCreateRowSorter(True)
        cellRenderer = ColoredTableCellRenderer()
        for index in [5, 6, 7, 8, 9]:
            column = resultsTable.columnModel.getColumn(index)
            column.cellRenderer = cellRenderer
        resultsTable.getColumnModel().getColumn(0).setPreferredWidth(99999999)
        resultsTable.getColumnModel().getColumn(1).setMinWidth(160)
        resultsTable.getColumnModel().getColumn(2).setMinWidth(100)
        resultsTable.getColumnModel().getColumn(3).setMinWidth(80)
        resultsTable.getColumnModel().getColumn(4).setMinWidth(80)
        resultsTable.getColumnModel().getColumn(5).setMinWidth(110)
        resultsTable.getColumnModel().getColumn(6).setMinWidth(110)
        resultsTable.getColumnModel().getColumn(7).setMinWidth(90)
        resultsTable.getColumnModel().getColumn(8).setMinWidth(110)
        resultsTable.getColumnModel().getColumn(9).setMinWidth(110)
        resultsTable.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS)
        resultsScrollPane = JScrollPane(resultsTable)
        resultsScrollPaneConstraints = GridBagConstraints()
        resultsScrollPaneConstraints.gridx = 0
        resultsScrollPaneConstraints.gridy = 1
        resultsScrollPaneConstraints.weightx = 1
        resultsScrollPaneConstraints.weighty = 1
        resultsScrollPaneConstraints.fill = GridBagConstraints.BOTH
        resultsPanel.add(resultsScrollPane, resultsScrollPaneConstraints)

        return resultsPanel
Example #9
0
    def run(self):
        frame = JFrame('ProgressBar1',
                       size=(280, 125),
                       locationRelativeTo=None,
                       defaultCloseOperation=JFrame.EXIT_ON_CLOSE)
        frame.getContentPane().setBorder(
            BorderFactory.createEmptyBorder(20, 20, 20, 20))

        panel = JPanel()
        self.button = panel.add(JButton('Start', actionPerformed=self.start))
        self.progressBar = panel.add(JProgressBar())
        frame.add(panel, BorderLayout.NORTH)
        frame.setVisible(1)
Example #10
0
    def __init__(self, parent, title, modal, app):
        """Restore the tools data by:
           - downloading the tools list
           - downloading the tools jar files
           - extracting the tools data from jar files
        """
        self.app = app
        border = BorderFactory.createEmptyBorder(5, 7, 5, 7)
        mainPane = self.getContentPane()
        mainPane.setLayout(BorderLayout(5, 5))
        mainPane.setBorder(border)
        self.setPreferredSize(Dimension(400, 200))
        self.taskOutput = JMultilineLabel(
            self.app.strings.getString("checking_for_updates"))
        self.taskOutput.setMaxWidth(350)
        self.progressBar = JProgressBar(0, 100, value=0, stringPainted=True)
        self.progressBar.setIndeterminate(True)
        self.cancelBtn = JButton("Cancel",
                                 actionPerformed=self.on_cancelBtn_clicked,
                                 enabled=True)
        self.okBtn = JButton("Ok",
                             actionPerformed=self.on_okBtn_clicked,
                             enabled=False)

        mainPane.add(self.taskOutput, BorderLayout.CENTER)
        bottomPanel = JPanel(BorderLayout(5, 5))
        bottomPanel.add(self.progressBar, BorderLayout.PAGE_START)
        buttonsPanel = JPanel()
        buttonsPanel.add(self.okBtn)
        buttonsPanel.add(self.cancelBtn)
        bottomPanel.add(buttonsPanel, BorderLayout.PAGE_END)
        mainPane.add(bottomPanel, BorderLayout.PAGE_END)
        self.pack()

        self.task = DownloaderTask(self)
        self.task.addPropertyChangeListener(self)
        self.task.execute()
   def __init__(self):
      self.mainDir = ""
   
      self.frame = JFrame("Dots Quality Check", size=(250,300))
      self.frame.setLocation(20,120)
      self.Panel = JPanel(GridLayout(0,1))
      self.frame.add(self.Panel)

      self.openNextButton = JButton('Open Next Random',actionPerformed=openRandom)
      self.Panel.add(self.openNextButton)
      
      self.saveButton = JButton('Save',actionPerformed=save)
      self.saveButton.setEnabled(False)
      self.Panel.add(self.saveButton)

      self.cropButton = JButton('Crop values from here', actionPerformed=cropVals)
      self.Panel.add(self.cropButton)

      self.DiscardButton = JButton('Discard cell', actionPerformed=discardCell)
      self.DiscardButton.setEnabled(True)
      self.Panel.add(self.DiscardButton)

      self.quitButton = JButton('Quit script',actionPerformed=quit)
      self.Panel.add(self.quitButton)

      annoPanel = JPanel()
      #add gridlayout
      wtRButton = JRadioButton("wt", actionCommand="wt")
      defectRButton = JRadioButton("Defect", actionCommand="defect")
      annoPanel.add(wtRButton)
      annoPanel.add(defectRButton)
      self.aButtonGroup = ButtonGroup()
      self.aButtonGroup.add(wtRButton)
      self.aButtonGroup.add(defectRButton)
      
      self.Panel.add(annoPanel)

      self.ProgBar = JProgressBar()
      self.ProgBar.setStringPainted(True)
      self.ProgBar.setValue(0)
      self.Panel.add(self.ProgBar)

      self.pathLabel = JLabel("-- No main directory chosen --")
      self.pathLabel.setHorizontalAlignment( SwingConstants.CENTER )
      self.Panel.add(self.pathLabel)

      
      WindowManager.addWindow(self.frame)
      self.show()
    def __init__(self):
        self.mainDir = ""

        self.setTitle("Dots Quality Check")
        self.setSize(250, 300)
        self.setLocation(20,120)
        self.addWindowFocusListener(self)
        
        self.Panel = JPanel(GridLayout(0,1))
        self.add(self.Panel)
        self.openNextButton = JButton("Open Next Random", actionPerformed=self.openRandom)
        self.Panel.add(self.openNextButton)
        self.saveButton = JButton("Save", actionPerformed=self.save, enabled=False)
        self.Panel.add(self.saveButton)
        self.cropButton = JButton("Crop values from here", actionPerformed=self.cropVals)
        self.Panel.add(self.cropButton)
        self.DiscardButton = JButton("Discard cell", actionPerformed=self.discardCell)
        self.Panel.add(self.DiscardButton)
        self.quitButton = JButton("Quit script",actionPerformed=self.quit)
        self.Panel.add(self.quitButton)

        annoPanel = JPanel()
        #add gridlayout
        self.wtRButton = JRadioButton("wt", actionCommand="wt")
        self.wtRButton.addActionListener(self)
        self.defectRButton = JRadioButton("Defect", actionCommand="defect")
        self.defectRButton.addActionListener(self)
        annoPanel.add(self.wtRButton)
        annoPanel.add(self.defectRButton)
        self.aButtonGroup = ButtonGroup()
        self.aButtonGroup.add(self.wtRButton)
        self.aButtonGroup.add(self.defectRButton)
      
        self.Panel.add(annoPanel)

        self.ProgBar = JProgressBar()
        self.ProgBar.setStringPainted(True)
        self.ProgBar.setValue(0)
        self.Panel.add(self.ProgBar)

        self.pathLabel = JLabel("-- No main directory chosen --")
        self.pathLabel.setHorizontalAlignment( SwingConstants.CENTER )
        self.Panel.add(self.pathLabel)
      
        WindowManager.addWindow(self)
        self.show()
Example #13
0
    def __init__(self, parent, title, modal, app):
        """Restore the tools data by:
           - downloading the tools list
           - downloading the tools jar files
           - extracting the tools data from jar files
        """
        self.app = app
        border = BorderFactory.createEmptyBorder(5, 7, 5, 7)
        mainPane = self.getContentPane()
        mainPane.setLayout(BorderLayout(5, 5))
        mainPane.setBorder(border)
        self.setPreferredSize(Dimension(400, 200))
        self.taskOutput = JMultilineLabel(self.app.strings.getString("checking_for_updates"))
        self.taskOutput.setMaxWidth(350)
        self.progressBar = JProgressBar(0, 100, value=0, stringPainted=True)
        self.progressBar.setIndeterminate(True)
        self.cancelBtn = JButton("Cancel",
                                 actionPerformed=self.on_cancelBtn_clicked,
                                 enabled=True)
        self.okBtn = JButton("Ok",
                             actionPerformed=self.on_okBtn_clicked,
                             enabled=False)

        mainPane.add(self.taskOutput, BorderLayout.CENTER)
        bottomPanel = JPanel(BorderLayout(5, 5))
        bottomPanel.add(self.progressBar, BorderLayout.PAGE_START)
        buttonsPanel = JPanel()
        buttonsPanel.add(self.okBtn)
        buttonsPanel.add(self.cancelBtn)
        bottomPanel.add(buttonsPanel, BorderLayout.PAGE_END)
        mainPane.add(bottomPanel, BorderLayout.PAGE_END)
        self.pack()

        self.task = DownloaderTask(self)
        self.task.addPropertyChangeListener(self)
        self.task.execute()
class MenueFrame(object):
   def __init__(self):
      self.mainDir = ""
   
      self.frame = JFrame("Dots Quality Check", size=(250,300))
      self.frame.setLocation(20,120)
      self.Panel = JPanel(GridLayout(0,1))
      self.frame.add(self.Panel)

      self.openNextButton = JButton('Open Next Random',actionPerformed=openRandom)
      self.Panel.add(self.openNextButton)
      
      self.saveButton = JButton('Save',actionPerformed=save)
      self.saveButton.setEnabled(False)
      self.Panel.add(self.saveButton)

      self.cropButton = JButton('Crop values from here', actionPerformed=cropVals)
      self.Panel.add(self.cropButton)

      self.DiscardButton = JButton('Discard cell', actionPerformed=discardCell)
      self.DiscardButton.setEnabled(True)
      self.Panel.add(self.DiscardButton)

      self.quitButton = JButton('Quit script',actionPerformed=quit)
      self.Panel.add(self.quitButton)

      annoPanel = JPanel()
      #add gridlayout
      wtRButton = JRadioButton("wt", actionCommand="wt")
      defectRButton = JRadioButton("Defect", actionCommand="defect")
      annoPanel.add(wtRButton)
      annoPanel.add(defectRButton)
      self.aButtonGroup = ButtonGroup()
      self.aButtonGroup.add(wtRButton)
      self.aButtonGroup.add(defectRButton)
      
      self.Panel.add(annoPanel)

      self.ProgBar = JProgressBar()
      self.ProgBar.setStringPainted(True)
      self.ProgBar.setValue(0)
      self.Panel.add(self.ProgBar)

      self.pathLabel = JLabel("-- No main directory chosen --")
      self.pathLabel.setHorizontalAlignment( SwingConstants.CENTER )
      self.Panel.add(self.pathLabel)

      
      WindowManager.addWindow(self.frame)
      self.show()

   def show(self):
      self.frame.visible = True

   def getFrame(self):
      return self.frame

   def setSaveActive(self):
      self.saveButton.setEnabled(True)
      self.show()

   def setSaveInactive(self):
      self.saveButton.setEnabled(False)
      self.show()

   def setMainDir(self, path):
      self.mainDir = path
      self.pathLabel.setText("MainDir: " + os.path.basename(os.path.split(self.mainDir)[0]))

   def getMainDir(self):
      return self.mainDir

   def setProgBarMax(self, maximum):
      self.ProgBar.setMaximum(maximum)

   def setProgBarVal(self, value):
      self.ProgBar.setValue(value)

   def close():
      WindowManager.removeWindow(self.frame)
      self.frame.dispose()     
Example #15
0
class BottomPanel(JPanel):
    def __init__(self):

        self.holdPanel = JPanel()
        self.topPanel = JPanel()
        self.bottomPanel = JPanel()

        self.holdPanel.setBackground(Color.decode('#dddee6'))
        self.topPanel.setBackground(Color.decode('#dddee6'))
        self.bottomPanel.setBackground(Color.decode('#dddee6'))

        self.topPanel.setPreferredSize(Dimension(300, 30))

        self.regBar = JProgressBar()
        self.gatePassBar = JProgressBar()
        self.regLabel = JLabel('Register : ')
        self.gatepassLabel = JLabel('          Gate Pass : '******'')
        self.gatePercentlabel = JLabel('')

        self.refreshButton = JButton('Refresh',
                                     actionPerformed=self.updateProgress)

        self.regBar.setMinimum(0)
        self.regBar.setMaximum(100)
        self.regBar.setStringPainted(True)

        self.gatePassBar.setMinimum(0)
        self.gatePassBar.setMaximum(100)
        self.gatePassBar.setStringPainted(True)

        self.setLayout(BorderLayout())

        self.updateProgress(None)

    def updateProgress(self, e):

        progress = client.get_progress()
        regTotal = progress[0]
        regRecog = progress[1]
        gateTotal = progress[2]
        gateRecog = progress[3]

        regPercent = int((regRecog * 100) / regTotal)
        gatePercent = int((gateRecog * 100) / gateTotal)

        self.regBar.setValue(regPercent)
        self.gatePassBar.setValue(gatePercent)

        self.regBar.setString(str(regPercent) + '%')
        self.gatePassBar.setString(str(gatePercent) + '%')

        self.regPercentlabel.setText(str(regRecog) + '/' + str(regTotal))
        self.gatePercentlabel.setText(
            str(gateRecog) + '/' + str(gateTotal) + '           ')

        if regPercent <= 30:
            regColor = Color.RED
        elif regPercent > 30 and regPercent < 50:
            regColor = Color.ORANGE
        elif regPercent >= 50 and regPercent <= 100:
            regColor = Color.GREEN

        if gatePercent <= 30:
            gateColor = Color.RED
        elif gatePercent > 30 and gatePercent < 50:
            gateColor = Color.ORANGE
        elif gatePercent >= 50 and gatePercent <= 100:
            gateColor = Color.GREEN

        self.regBar.setForeground(regColor)
        self.gatePassBar.setForeground(gateColor)

        self.holdPanel.add(self.regLabel)
        self.holdPanel.add(self.regBar)
        self.holdPanel.add(self.regPercentlabel)
        self.holdPanel.add(self.gatepassLabel)
        self.holdPanel.add(self.gatePassBar)
        self.holdPanel.add(self.gatePercentlabel)
        self.holdPanel.add(self.refreshButton)

        self.add(self.holdPanel, BorderLayout.CENTER)
        self.add(self.topPanel, BorderLayout.PAGE_START)
        self.add(self.bottomPanel, BorderLayout.PAGE_END)

        self.validate()
Example #16
0
class BurpExtender(IBurpExtender, ITab, IExtensionStateListener):
    # Define the global variables for the burp plugin
    EXTENSION_NAME = "UPnP BHunter"
    ipv4_selected = True
    services_dict = {}
    ip_service_dict = {}
    STOP_THREAD = False

    #Some  SSDP m-search parameters are based upon "UPnP Device Architecture v2.0"
    SSDP_MULTICAST_IPv4 = ["239.255.255.250"]
    SSDP_MULTICAST_IPv6 = ["FF02::C", "FF05::C"]
    SSDP_MULTICAST_PORT = 1900
    ST_ALL = "ssdp:all"
    ST_ROOTDEV = "upnp:rootdevice"
    PLACEHOLDER = "FUZZ_HERE"
    SSDP_TIMEOUT = 2

    def registerExtenderCallbacks(self, callbacks):
        # Get a reference to callbacks object
        self.callbacks = callbacks
        # Get the useful extension helpers object
        self.helpers = callbacks.getHelpers()
        # Set the extension name
        self.callbacks.setExtensionName(self.EXTENSION_NAME)
        self.callbacks.registerExtensionStateListener(self)
        # Draw plugin user interface
        self.drawPluginUI()
        self.callbacks.addSuiteTab(self)
        # Plugin loading message
        print("[+] Burp plugin UPnP BHunter loaded successfully")
        return

    def drawPluginUI(self):
        # Create the plugin user interface
        self.pluginTab = JPanel()
        self.uiTitle = JLabel('UPnP BHunter Load, Aim and Fire Console')
        self.uiTitle.setFont(Font('Tahoma', Font.BOLD, 14))
        self.uiTitle.setForeground(Color(250, 100, 0))
        self.uiPanelA = JSplitPane(JSplitPane.VERTICAL_SPLIT)
        self.uiPanelA.setMaximumSize(Dimension(2500, 1000))
        self.uiPanelA.setDividerSize(2)
        self.uiPanelB = JSplitPane(JSplitPane.VERTICAL_SPLIT)
        self.uiPanelB.setDividerSize(2)
        self.uiPanelA.setBottomComponent(self.uiPanelB)
        self.uiPanelA.setBorder(BorderFactory.createLineBorder(Color.gray))

        # Create and configure labels and text fields
        self.labeltitle_step1 = JLabel("[1st STEP] Discover UPnP Locations")
        self.labeltitle_step1.setFont(Font('Tahoma', Font.BOLD, 14))
        self.labeltitle_step2 = JLabel(
            "[2nd STEP] Select a UPnP Service and Action")
        self.labeltitle_step2.setFont(Font('Tahoma', Font.BOLD, 14))
        self.labeltitle_step3 = JLabel("[3rd STEP] Time to Attack it")
        self.labeltitle_step3.setFont(Font('Tahoma', Font.BOLD, 14))
        self.labelsubtitle_step1 = JLabel(
            "Specify the IP version address in scope and start UPnP discovery")
        self.labelsubtitle_step2 = JLabel(
            "Select which of the found UPnP services will be probed")
        self.labelsubtitle_step3 = JLabel(
            "Review and modify the request, then send it to one of the attack tools"
        )
        self.label_step1 = JLabel("Target IP")
        self.label_step2 = JLabel("Found UPnp Services")
        self.labelstatus = JLabel("             Status")
        self.labelempty_step1 = JLabel("                ")
        self.labelempty_step2 = JLabel("  ")
        self.labelupnp = JLabel("UPnP list")
        self.labelip = JLabel("IP list")
        self.labelactions = JLabel("Actions")
        self.labelNoneServiceFound = JLabel("  ")
        self.labelNoneServiceFound.setFont(Font('Tahoma', Font.BOLD, 12))
        self.labelNoneServiceFound.setForeground(Color.red)

        # Create combobox for IP version selection
        self.ip_versions = ["IPv4", "IPv6"]
        self.combo_ipversion = JComboBox(self.ip_versions)
        self.combo_ipversion.setSelectedIndex(0)
        self.combo_ipversion.setEnabled(True)

        # Create and configure progress bar
        self.progressbar = JProgressBar(0, 100)
        self.progressbar.setString("Ready")
        self.progressbar.setStringPainted(True)

        # Create and configure buttons
        self.startbutton = JButton("Start Discovery",
                                   actionPerformed=self.startHunting)
        self.clearbutton = JButton("Clear All", actionPerformed=self.clearAll)
        self.intruderbutton = JButton("Send to Intruder",
                                      actionPerformed=self.sendToIntruder)
        self.repeaterbutton = JButton("Send to Repeater",
                                      actionPerformed=self.sendToRepeater)
        #self.WANrepeaterbutton = JButton("to Repeater", actionPerformed=self.sendWANUPnPToRepeater)
        self.textarea_request = JTextArea(18, 90)
        self.intruderbutton.setEnabled(False)
        self.repeaterbutton.setEnabled(False)

        # Class neeeded to handle the target combobox in second step panel
        class TargetComboboxListener(ActionListener):
            def __init__(self, upnpcombo_targets, upnpcombo_services,
                         ip_service_dict):
                self.upnpcombo_targets = upnpcombo_targets
                self.upnpcombo_services = upnpcombo_services
                self.ip_service_dict = ip_service_dict

            def actionPerformed(self, event):
                try:
                    # Update the location url combobox depending on the IP combobox
                    selected_target = self.upnpcombo_targets.getSelectedItem()
                    if self.ip_service_dict and selected_target:
                        self.upnpcombo_services.removeAllItems()
                        for service_url in self.ip_service_dict[
                                selected_target]:
                            self.upnpcombo_services.addItem(service_url)
                        self.upnpcombo_services.setSelectedIndex(0)
                except BaseException as e:
                    print("[!] Exception selecting service: \"%s\" ") % e

        # Class neeeded to handle the service combobox in second step panel
        class ServiceComboboxListener(ActionListener):
            def __init__(self, upnpcombo_services, upnpcombo_actions,
                         services_dict):
                self.upnpcombo_services = upnpcombo_services
                self.upnpcombo_actions = upnpcombo_actions
                self.services = services_dict

            def actionPerformed(self, event):
                try:
                    # Update the location url combobox depending on the IP combobox
                    selected_service = self.upnpcombo_services.getSelectedItem(
                    )
                    if self.services and selected_service:
                        self.upnpcombo_actions.removeAllItems()
                        actions = self.services[selected_service]
                        for action in actions:
                            self.upnpcombo_actions.addItem(action)
                        self.upnpcombo_actions.setSelectedIndex(0)
                except BaseException as e:
                    print("[!] Exception selecting service: \"%s\" ") % e

        # Class neeeded to handle the action combobox in second step panel
        class ActionComboboxListener(ActionListener):
            def __init__(self, upnpcombo_services, upnpcombo_actions,
                         textarea_request, services_dict):
                self.upnpcombo_services = upnpcombo_services
                self.upnpcombo_actions = upnpcombo_actions
                self.textarea_request = textarea_request
                self.services = services_dict

            def actionPerformed(self, event):
                try:
                    # Update the location url combobox depending on the IP combobox
                    selected_action = self.upnpcombo_actions.getSelectedItem()
                    selected_service = self.upnpcombo_services.getSelectedItem(
                    )
                    if self.services and selected_action:
                        self.textarea_request.setText(
                            self.services[selected_service][selected_action])
                except BaseException as e:
                    print("[!] Exception selecting action: \"%s\" ") % e

        self.upnpactions = ["       "]
        self.upnpcombo_actions = JComboBox(self.upnpactions)
        self.upnpcombo_actions.setSelectedIndex(0)
        self.upnpcombo_actions.setEnabled(False)

        # Create the combo box, select item at index 0 (first item in list)
        self.upnpservices = ["       "]
        self.upnpcombo_services = JComboBox(self.upnpservices)
        self.upnpcombo_services.setSelectedIndex(0)
        self.upnpcombo_services.setEnabled(False)

        # Create the combo box, select item at index 0 (first item in list)
        self.upnptargets = ["       "]
        self.upnpcombo_targets = JComboBox(self.upnptargets)
        self.upnpcombo_targets.setSelectedIndex(0)
        self.upnpcombo_targets.setEnabled(False)

        # Set the action listeners for all the comboboxes
        self.upnpcombo_targets.addActionListener(
            TargetComboboxListener(self.upnpcombo_targets,
                                   self.upnpcombo_services,
                                   self.ip_service_dict))
        self.upnpcombo_services.addActionListener(
            ServiceComboboxListener(self.upnpcombo_services,
                                    self.upnpcombo_actions,
                                    self.services_dict))
        self.upnpcombo_actions.addActionListener(
            ActionComboboxListener(self.upnpcombo_services,
                                   self.upnpcombo_actions,
                                   self.textarea_request, self.services_dict))

        # Configuring first step panel
        self.panel_step1 = JPanel()
        self.panel_step1.setPreferredSize(Dimension(2250, 100))
        self.panel_step1.setBorder(EmptyBorder(10, 10, 10, 10))
        self.panel_step1.setLayout(BorderLayout(15, 15))
        self.titlepanel_step1 = JPanel()
        self.titlepanel_step1.setLayout(BorderLayout())
        self.titlepanel_step1.add(self.labeltitle_step1, BorderLayout.NORTH)
        self.titlepanel_step1.add(self.labelsubtitle_step1)
        self.targetpanel_step1 = JPanel()
        self.targetpanel_step1.add(self.label_step1)
        self.targetpanel_step1.add(self.combo_ipversion)
        self.targetpanel_step1.add(self.startbutton)
        self.targetpanel_step1.add(self.clearbutton)
        self.targetpanel_step1.add(self.labelstatus)
        self.targetpanel_step1.add(self.progressbar)
        self.emptypanel_step1 = JPanel()
        self.emptypanel_step1.setLayout(BorderLayout())
        self.emptypanel_step1.add(self.labelempty_step1, BorderLayout.WEST)

        # Assembling first step panel components
        self.panel_step1.add(self.titlepanel_step1, BorderLayout.NORTH)
        self.panel_step1.add(self.targetpanel_step1, BorderLayout.WEST)
        self.panel_step1.add(self.emptypanel_step1, BorderLayout.SOUTH)
        self.uiPanelA.setTopComponent(self.panel_step1)

        # Configure second step panel
        self.panel_step2 = JPanel()
        self.panel_step2.setPreferredSize(Dimension(2250, 100))
        self.panel_step2.setBorder(EmptyBorder(10, 10, 10, 10))
        self.panel_step2.setLayout(BorderLayout(15, 15))
        self.titlepanel_step2 = JPanel()
        self.titlepanel_step2.setLayout(BorderLayout())
        self.titlepanel_step2.add(self.labeltitle_step2, BorderLayout.NORTH)
        self.titlepanel_step2.add(self.labelsubtitle_step2)
        self.selectpanel_step2 = JPanel()
        self.selectpanel_step2.add(self.labelip)
        self.selectpanel_step2.add(self.upnpcombo_targets)
        self.selectpanel_step2.add(self.labelupnp)
        self.selectpanel_step2.add(self.upnpcombo_services)
        self.selectpanel_step2.add(self.labelactions)
        self.selectpanel_step2.add(self.upnpcombo_actions)
        self.emptypanel_step2 = JPanel()
        self.emptypanel_step2.setLayout(BorderLayout())
        self.emptypanel_step2.add(self.labelempty_step2, BorderLayout.WEST)
        self.emptypanel_step2.add(self.labelNoneServiceFound)

        # Assembling second step panel components
        self.panel_step2.add(self.titlepanel_step2, BorderLayout.NORTH)
        self.panel_step2.add(self.selectpanel_step2, BorderLayout.WEST)
        self.panel_step2.add(self.emptypanel_step2, BorderLayout.SOUTH)
        self.uiPanelB.setTopComponent(self.panel_step2)

        # Configuring third step panel
        self.panel_step3 = JPanel()
        self.panel_step3.setPreferredSize(Dimension(2250, 100))
        self.panel_step3.setBorder(EmptyBorder(10, 10, 10, 10))
        self.panel_step3.setLayout(BorderLayout(15, 15))
        self.titlepanel_step3 = JPanel()
        self.titlepanel_step3.setLayout(BorderLayout())
        self.titlepanel_step3.add(self.labeltitle_step3, BorderLayout.NORTH)
        self.titlepanel_step3.add(self.labelsubtitle_step3)
        self.underpanel_step3 = JPanel()
        self.underpanel_step3.setLayout(BorderLayout())
        self.underpanel_step3.add((JScrollPane(self.textarea_request)),
                                  BorderLayout.NORTH)
        self.actionpanel_step3 = JPanel()
        self.actionpanel_step3.add(self.intruderbutton)
        self.actionpanel_step3.add(self.repeaterbutton)
        self.extrapanel_step3 = JPanel()
        self.extrapanel_step3.setLayout(BorderLayout())
        self.extrapanel_step3.add(self.actionpanel_step3, BorderLayout.WEST)

        # Assembling thirdd step panel components
        self.panel_step3.add(self.titlepanel_step3, BorderLayout.NORTH)
        self.panel_step3.add(self.underpanel_step3, BorderLayout.WEST)
        self.panel_step3.add(self.extrapanel_step3, BorderLayout.SOUTH)
        self.uiPanelB.setBottomComponent(self.panel_step3)

        # Assembling the group of all panels
        layout = GroupLayout(self.pluginTab)
        self.pluginTab.setLayout(layout)
        layout.setHorizontalGroup(
            layout.createParallelGroup(GroupLayout.Alignment.LEADING).addGroup(
                layout.createSequentialGroup().addGap(10, 10, 10).addGroup(
                    layout.createParallelGroup(
                        GroupLayout.Alignment.LEADING).addComponent(
                            self.uiTitle).addGap(15, 15, 15).addComponent(
                                self.uiPanelA)).addContainerGap(
                                    26, Short.MAX_VALUE)))
        layout.setVerticalGroup(
            layout.createParallelGroup(GroupLayout.Alignment.LEADING).addGroup(
                layout.createSequentialGroup().addGap(15, 15, 15).addComponent(
                    self.uiTitle).addGap(15, 15, 15).addComponent(
                        self.uiPanelA).addGap(20, 20, 20).addGap(20, 20, 20)))

    def extensionUnloaded(self):
        # Unload the plugin, and if running stop the background thread
        if self.upnpcombo_services.isEnabled():
            if self.th.isAlive():
                print("[+] Stopping thread %s") % self.th.getName()
                self.STOP_THREAD = True
                self.th.join()
            else:
                print("Thread %s already dead") % self.th.getName()
        print("[+] Burp plugin UPnP BHunter successfully unloaded")
        return

    def getTabCaption(self):
        return self.EXTENSION_NAME

    def getUiComponent(self):
        return self.pluginTab

    def clearAll(self, e=None):
        # Reset all data of the plugin
        self.services_dict.clear()
        self.progressbar.setString("Ready")
        self.progressbar.setValue(0)
        self.upnpcombo_targets.removeAllItems()
        self.upnpcombo_targets.setEnabled(False)
        self.upnpcombo_services.removeAllItems()
        self.upnpcombo_services.setEnabled(False)
        self.upnpcombo_actions.removeAllItems()
        self.upnpcombo_actions.setEnabled(False)
        self.intruderbutton.setEnabled(False)
        self.repeaterbutton.setEnabled(False)
        self.labelNoneServiceFound.setText(" ")
        self.textarea_request.setText(" ")
        print("[+] Clearing all data")
        return

    def startHunting(self, e=None):
        # Starting the UPnP hunt
        def startHunting_run():

            # Initialize the internal parameters every time the start-discovery button is clicked
            self.services_dict.clear()
            found_loc = []
            discovery_files = []
            self.labelNoneServiceFound.setText(" ")
            self.intruderbutton.setEnabled(False)
            self.repeaterbutton.setEnabled(False)

            # Then determine if targerting IPv4 or IPv6 adresses
            if self.combo_ipversion.getSelectedItem() == "IPv4":
                self.ipv4_selected = True
                print("[+] Selected IPv4 address scope")
            else:
                self.ipv4_selected = False
                print("[+] Selected IPv6 address scope")

            # And here finally the hunt could start
            self.progressbar.setString("Running...")
            self.progressbar.setValue(20)
            found_loc = self.discoverUpnpLocations()
            self.progressbar.setValue(40)
            discovery_files = self.downloadXMLfiles(found_loc)
            self.progressbar.setValue(60)
            self.buildSOAPs(discovery_files)
            self.progressbar.setValue(80)
            self.progressbar.setString("Done")
            self.progressbar.setValue(100)
            self.updateComboboxList(self.services_dict)

            # Update the comboboxes list with the discovered UPnPs
            if (self.services_dict):
                self.upnpcombo_targets.setEnabled(True)
                self.upnpcombo_services.setEnabled(True)
                self.upnpcombo_actions.setEnabled(True)
                self.intruderbutton.setEnabled(True)
                self.repeaterbutton.setEnabled(True)

            if self.STOP_THREAD:
                return

        # Start a background thread to run the above nested function in order to prevent the blocking of plugin UI
        self.th = threading.Thread(target=startHunting_run)
        #self.th.daemon = True    # This does not seem to be useful
        self.th.setName("th-BHunter")
        self.th.start()

    def ssdpReqBuilder(self, ssdp_timeout, st_type, ssdp_ip, ssdp_port):
        # Builder of the two ssdp msearch request types
        msearch_req = "M-SEARCH * HTTP/1.1\r\n" \
        "HOST: {0}:{1}\r\n" \
        "MAN: \"ssdp:discover\"\r\n" \
        "MX: {2}\r\n" \
        "ST: {3}\r\n" \
        "\r\n" \
        .format(ssdp_ip, ssdp_port, ssdp_timeout, st_type)
        return msearch_req

    def sendMsearch(self, ssdp_req, ssdp_ip, ssdp_port):
        # Send the ssdp request and retrieve response
        buf_resp = set()
        if self.ipv4_selected:
            print("[+] Creating IPv4 SSDP multicast request")
            sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        else:
            print("[+] Creating IPv6 SSDP multicast request")
            sock = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)
        sock.setblocking(0)
        # Sending ssdp requests
        while len(ssdp_req):
            # Blocking socket client until the request is completely sent
            try:
                sent = sock.sendto(ssdp_req.encode("ASCII"),
                                   (ssdp_ip, ssdp_port))
                ssdp_req = ssdp_req[sent:]
            except socket.error, exc:
                if exc.errno != errno.EAGAIN:
                    print("[E] Got error %s with socket when sending") % exc
                    sock.close()
                    raise exc
                print("[!] Blocking socket until ", len(ssdp_req), " is sent.")
                select.select([], [sock], [])
                continue
        # Retrieving ssdp responses
        num_resp = 0
        while sock:
            # Blocking socket until there are ssdp responses to be read or timeout is reached
            readable, __, __ = select.select([sock], [], [], self.SSDP_TIMEOUT)
            if not readable:
                # Timeout reached without receiving any ssdp response
                if num_resp == 0:
                    print(
                        "[!] Got timeout without receiving any ssdp response.")
                break
            else:
                num_resp = num_resp + 1
                # Almost an ssdp response was received
                if readable[0]:
                    try:
                        data = sock.recv(1024)
                        if data:
                            buf_resp.add(data.decode('ASCII'))
                    except socket.error, exc:
                        print("[E] Got error %s with socket when receiving"
                              ) % exc
                        sock.close()
                        raise exc
Example #17
0
    def drawPluginUI(self):
        # Create the plugin user interface
        self.pluginTab = JPanel()
        self.uiTitle = JLabel('UPnP BHunter Load, Aim and Fire Console')
        self.uiTitle.setFont(Font('Tahoma', Font.BOLD, 14))
        self.uiTitle.setForeground(Color(250, 100, 0))
        self.uiPanelA = JSplitPane(JSplitPane.VERTICAL_SPLIT)
        self.uiPanelA.setMaximumSize(Dimension(2500, 1000))
        self.uiPanelA.setDividerSize(2)
        self.uiPanelB = JSplitPane(JSplitPane.VERTICAL_SPLIT)
        self.uiPanelB.setDividerSize(2)
        self.uiPanelA.setBottomComponent(self.uiPanelB)
        self.uiPanelA.setBorder(BorderFactory.createLineBorder(Color.gray))

        # Create and configure labels and text fields
        self.labeltitle_step1 = JLabel("[1st STEP] Discover UPnP Locations")
        self.labeltitle_step1.setFont(Font('Tahoma', Font.BOLD, 14))
        self.labeltitle_step2 = JLabel(
            "[2nd STEP] Select a UPnP Service and Action")
        self.labeltitle_step2.setFont(Font('Tahoma', Font.BOLD, 14))
        self.labeltitle_step3 = JLabel("[3rd STEP] Time to Attack it")
        self.labeltitle_step3.setFont(Font('Tahoma', Font.BOLD, 14))
        self.labelsubtitle_step1 = JLabel(
            "Specify the IP version address in scope and start UPnP discovery")
        self.labelsubtitle_step2 = JLabel(
            "Select which of the found UPnP services will be probed")
        self.labelsubtitle_step3 = JLabel(
            "Review and modify the request, then send it to one of the attack tools"
        )
        self.label_step1 = JLabel("Target IP")
        self.label_step2 = JLabel("Found UPnp Services")
        self.labelstatus = JLabel("             Status")
        self.labelempty_step1 = JLabel("                ")
        self.labelempty_step2 = JLabel("  ")
        self.labelupnp = JLabel("UPnP list")
        self.labelip = JLabel("IP list")
        self.labelactions = JLabel("Actions")
        self.labelNoneServiceFound = JLabel("  ")
        self.labelNoneServiceFound.setFont(Font('Tahoma', Font.BOLD, 12))
        self.labelNoneServiceFound.setForeground(Color.red)

        # Create combobox for IP version selection
        self.ip_versions = ["IPv4", "IPv6"]
        self.combo_ipversion = JComboBox(self.ip_versions)
        self.combo_ipversion.setSelectedIndex(0)
        self.combo_ipversion.setEnabled(True)

        # Create and configure progress bar
        self.progressbar = JProgressBar(0, 100)
        self.progressbar.setString("Ready")
        self.progressbar.setStringPainted(True)

        # Create and configure buttons
        self.startbutton = JButton("Start Discovery",
                                   actionPerformed=self.startHunting)
        self.clearbutton = JButton("Clear All", actionPerformed=self.clearAll)
        self.intruderbutton = JButton("Send to Intruder",
                                      actionPerformed=self.sendToIntruder)
        self.repeaterbutton = JButton("Send to Repeater",
                                      actionPerformed=self.sendToRepeater)
        #self.WANrepeaterbutton = JButton("to Repeater", actionPerformed=self.sendWANUPnPToRepeater)
        self.textarea_request = JTextArea(18, 90)
        self.intruderbutton.setEnabled(False)
        self.repeaterbutton.setEnabled(False)

        # Class neeeded to handle the target combobox in second step panel
        class TargetComboboxListener(ActionListener):
            def __init__(self, upnpcombo_targets, upnpcombo_services,
                         ip_service_dict):
                self.upnpcombo_targets = upnpcombo_targets
                self.upnpcombo_services = upnpcombo_services
                self.ip_service_dict = ip_service_dict

            def actionPerformed(self, event):
                try:
                    # Update the location url combobox depending on the IP combobox
                    selected_target = self.upnpcombo_targets.getSelectedItem()
                    if self.ip_service_dict and selected_target:
                        self.upnpcombo_services.removeAllItems()
                        for service_url in self.ip_service_dict[
                                selected_target]:
                            self.upnpcombo_services.addItem(service_url)
                        self.upnpcombo_services.setSelectedIndex(0)
                except BaseException as e:
                    print("[!] Exception selecting service: \"%s\" ") % e

        # Class neeeded to handle the service combobox in second step panel
        class ServiceComboboxListener(ActionListener):
            def __init__(self, upnpcombo_services, upnpcombo_actions,
                         services_dict):
                self.upnpcombo_services = upnpcombo_services
                self.upnpcombo_actions = upnpcombo_actions
                self.services = services_dict

            def actionPerformed(self, event):
                try:
                    # Update the location url combobox depending on the IP combobox
                    selected_service = self.upnpcombo_services.getSelectedItem(
                    )
                    if self.services and selected_service:
                        self.upnpcombo_actions.removeAllItems()
                        actions = self.services[selected_service]
                        for action in actions:
                            self.upnpcombo_actions.addItem(action)
                        self.upnpcombo_actions.setSelectedIndex(0)
                except BaseException as e:
                    print("[!] Exception selecting service: \"%s\" ") % e

        # Class neeeded to handle the action combobox in second step panel
        class ActionComboboxListener(ActionListener):
            def __init__(self, upnpcombo_services, upnpcombo_actions,
                         textarea_request, services_dict):
                self.upnpcombo_services = upnpcombo_services
                self.upnpcombo_actions = upnpcombo_actions
                self.textarea_request = textarea_request
                self.services = services_dict

            def actionPerformed(self, event):
                try:
                    # Update the location url combobox depending on the IP combobox
                    selected_action = self.upnpcombo_actions.getSelectedItem()
                    selected_service = self.upnpcombo_services.getSelectedItem(
                    )
                    if self.services and selected_action:
                        self.textarea_request.setText(
                            self.services[selected_service][selected_action])
                except BaseException as e:
                    print("[!] Exception selecting action: \"%s\" ") % e

        self.upnpactions = ["       "]
        self.upnpcombo_actions = JComboBox(self.upnpactions)
        self.upnpcombo_actions.setSelectedIndex(0)
        self.upnpcombo_actions.setEnabled(False)

        # Create the combo box, select item at index 0 (first item in list)
        self.upnpservices = ["       "]
        self.upnpcombo_services = JComboBox(self.upnpservices)
        self.upnpcombo_services.setSelectedIndex(0)
        self.upnpcombo_services.setEnabled(False)

        # Create the combo box, select item at index 0 (first item in list)
        self.upnptargets = ["       "]
        self.upnpcombo_targets = JComboBox(self.upnptargets)
        self.upnpcombo_targets.setSelectedIndex(0)
        self.upnpcombo_targets.setEnabled(False)

        # Set the action listeners for all the comboboxes
        self.upnpcombo_targets.addActionListener(
            TargetComboboxListener(self.upnpcombo_targets,
                                   self.upnpcombo_services,
                                   self.ip_service_dict))
        self.upnpcombo_services.addActionListener(
            ServiceComboboxListener(self.upnpcombo_services,
                                    self.upnpcombo_actions,
                                    self.services_dict))
        self.upnpcombo_actions.addActionListener(
            ActionComboboxListener(self.upnpcombo_services,
                                   self.upnpcombo_actions,
                                   self.textarea_request, self.services_dict))

        # Configuring first step panel
        self.panel_step1 = JPanel()
        self.panel_step1.setPreferredSize(Dimension(2250, 100))
        self.panel_step1.setBorder(EmptyBorder(10, 10, 10, 10))
        self.panel_step1.setLayout(BorderLayout(15, 15))
        self.titlepanel_step1 = JPanel()
        self.titlepanel_step1.setLayout(BorderLayout())
        self.titlepanel_step1.add(self.labeltitle_step1, BorderLayout.NORTH)
        self.titlepanel_step1.add(self.labelsubtitle_step1)
        self.targetpanel_step1 = JPanel()
        self.targetpanel_step1.add(self.label_step1)
        self.targetpanel_step1.add(self.combo_ipversion)
        self.targetpanel_step1.add(self.startbutton)
        self.targetpanel_step1.add(self.clearbutton)
        self.targetpanel_step1.add(self.labelstatus)
        self.targetpanel_step1.add(self.progressbar)
        self.emptypanel_step1 = JPanel()
        self.emptypanel_step1.setLayout(BorderLayout())
        self.emptypanel_step1.add(self.labelempty_step1, BorderLayout.WEST)

        # Assembling first step panel components
        self.panel_step1.add(self.titlepanel_step1, BorderLayout.NORTH)
        self.panel_step1.add(self.targetpanel_step1, BorderLayout.WEST)
        self.panel_step1.add(self.emptypanel_step1, BorderLayout.SOUTH)
        self.uiPanelA.setTopComponent(self.panel_step1)

        # Configure second step panel
        self.panel_step2 = JPanel()
        self.panel_step2.setPreferredSize(Dimension(2250, 100))
        self.panel_step2.setBorder(EmptyBorder(10, 10, 10, 10))
        self.panel_step2.setLayout(BorderLayout(15, 15))
        self.titlepanel_step2 = JPanel()
        self.titlepanel_step2.setLayout(BorderLayout())
        self.titlepanel_step2.add(self.labeltitle_step2, BorderLayout.NORTH)
        self.titlepanel_step2.add(self.labelsubtitle_step2)
        self.selectpanel_step2 = JPanel()
        self.selectpanel_step2.add(self.labelip)
        self.selectpanel_step2.add(self.upnpcombo_targets)
        self.selectpanel_step2.add(self.labelupnp)
        self.selectpanel_step2.add(self.upnpcombo_services)
        self.selectpanel_step2.add(self.labelactions)
        self.selectpanel_step2.add(self.upnpcombo_actions)
        self.emptypanel_step2 = JPanel()
        self.emptypanel_step2.setLayout(BorderLayout())
        self.emptypanel_step2.add(self.labelempty_step2, BorderLayout.WEST)
        self.emptypanel_step2.add(self.labelNoneServiceFound)

        # Assembling second step panel components
        self.panel_step2.add(self.titlepanel_step2, BorderLayout.NORTH)
        self.panel_step2.add(self.selectpanel_step2, BorderLayout.WEST)
        self.panel_step2.add(self.emptypanel_step2, BorderLayout.SOUTH)
        self.uiPanelB.setTopComponent(self.panel_step2)

        # Configuring third step panel
        self.panel_step3 = JPanel()
        self.panel_step3.setPreferredSize(Dimension(2250, 100))
        self.panel_step3.setBorder(EmptyBorder(10, 10, 10, 10))
        self.panel_step3.setLayout(BorderLayout(15, 15))
        self.titlepanel_step3 = JPanel()
        self.titlepanel_step3.setLayout(BorderLayout())
        self.titlepanel_step3.add(self.labeltitle_step3, BorderLayout.NORTH)
        self.titlepanel_step3.add(self.labelsubtitle_step3)
        self.underpanel_step3 = JPanel()
        self.underpanel_step3.setLayout(BorderLayout())
        self.underpanel_step3.add((JScrollPane(self.textarea_request)),
                                  BorderLayout.NORTH)
        self.actionpanel_step3 = JPanel()
        self.actionpanel_step3.add(self.intruderbutton)
        self.actionpanel_step3.add(self.repeaterbutton)
        self.extrapanel_step3 = JPanel()
        self.extrapanel_step3.setLayout(BorderLayout())
        self.extrapanel_step3.add(self.actionpanel_step3, BorderLayout.WEST)

        # Assembling thirdd step panel components
        self.panel_step3.add(self.titlepanel_step3, BorderLayout.NORTH)
        self.panel_step3.add(self.underpanel_step3, BorderLayout.WEST)
        self.panel_step3.add(self.extrapanel_step3, BorderLayout.SOUTH)
        self.uiPanelB.setBottomComponent(self.panel_step3)

        # Assembling the group of all panels
        layout = GroupLayout(self.pluginTab)
        self.pluginTab.setLayout(layout)
        layout.setHorizontalGroup(
            layout.createParallelGroup(GroupLayout.Alignment.LEADING).addGroup(
                layout.createSequentialGroup().addGap(10, 10, 10).addGroup(
                    layout.createParallelGroup(
                        GroupLayout.Alignment.LEADING).addComponent(
                            self.uiTitle).addGap(15, 15, 15).addComponent(
                                self.uiPanelA)).addContainerGap(
                                    26, Short.MAX_VALUE)))
        layout.setVerticalGroup(
            layout.createParallelGroup(GroupLayout.Alignment.LEADING).addGroup(
                layout.createSequentialGroup().addGap(15, 15, 15).addComponent(
                    self.uiTitle).addGap(15, 15, 15).addComponent(
                        self.uiPanelA).addGap(20, 20, 20).addGap(20, 20, 20)))
Example #18
0
class BurpExtender(
          IBurpExtender, ITab, IContextMenuFactory, IMessageEditorController):

    # Implement IBurpExtender
    def registerExtenderCallbacks(self, callbacks):

        callbacks.registerContextMenuFactory(self)

        self._callbacks = callbacks
        self._helpers = callbacks.getHelpers()

        callbacks.setExtensionName(EXTENSION_NAME)

        # Construct UI
        insets = Insets(3, 3, 3, 3)
        self._messageEditor = callbacks.createMessageEditor(self, True)
        attackPanel = self._constructAttackPanel(
            insets, self._messageEditor.getComponent())
        resultsPanel = self._constructResultsPanel(insets)
        aboutPanel = self._constructAboutPanel(insets)
        self._tabbedPane = JTabbedPane()
        self._tabbedPane.addTab("Attack", attackPanel)
        self._tabbedPane.addTab("Results", resultsPanel)
        self._tabbedPane.addTab("About", aboutPanel)
        callbacks.addSuiteTab(self)

    # Implement ITab
    def getTabCaption(self):
        return EXTENSION_NAME

    def getUiComponent(self):
        return self._tabbedPane

    # Implement IMessageEditorController
    def getHttpService(self):
        self._updateClassFromUI()
        return self._httpService

    def getRequest(self):
        self._updateClassFromUI()
        return self._request

    def getResponse(self):
        return None

    # Implement IContextMenuFactory
    def createMenuItems(self, contextMenuInvocation):
        messages = contextMenuInvocation.getSelectedMessages()

        # Only add menu item if a single request is selected
        if len(messages) == 1:
            self._contextMenuData = messages
            menu_item = JMenuItem(
                "Send to {}".format(EXTENSION_NAME),
                actionPerformed=self._contextMenuItemClicked
            )
            return [menu_item]

    def _contextMenuItemClicked(self, _):
        httpRequestResponse = self._contextMenuData[0]

        # Update instance variables with request data
        self._httpService = httpRequestResponse.getHttpService()
        self._request = httpRequestResponse.getRequest()

        # Update fields in tab
        self._hostTextField.setText(self._httpService.getHost())
        self._portTextField.setText(str(self._httpService.getPort()))
        self._protocolCheckBox.setSelected(
            True if self._httpService.getProtocol() == "https" else False)
        self._messageEditor.setMessage(self._request, True)

    def _startAttack(self, _):

        # Switch to results tab
        self._tabbedPane.setSelectedIndex(1)

        # Clear results table
        self._resultsTableModel.setRowCount(0)

        # Set progress bar to 0%
        self._progressBar.setValue(0)

        Thread(target=self._makeHttpRequests).start()

    def _makeHttpRequests(self):

        # Set class variables from values in UI
        self._updateClassFromUI()

        self._responses = {}

        # Set progress bar max to number of requests
        self._progressBar.setMaximum(len(self._payloads) * self._numReq)

        for payload in self._payloads:
            self._responses[payload] = []
            # Stick payload into request at specified position
            # Use lambda function for replacement string to stop slashes being
            # escaped
            request = sub("\xa7[^\xa7]*\xa7", lambda x: payload, self._request)
            request = self._updateContentLength(request)
            for _ in xrange(self._numReq):
                # Make request and work out how long it took in ms. This method
                # is crude, but it's as good as we can get with current Burp
                # APIs.
                # See https://support.portswigger.net/customer/portal/questions/16227838-request-response-timing # noqa: E501
                startTime = time()
                response = self._callbacks.makeHttpRequest(
                    self._httpService, request)
                endTime = time()
                duration = (endTime - startTime) * 1000

                self._progressBar.setValue(self._progressBar.getValue() + 1)

                self._responses[payload].append(duration)

            # If all responses for this payload have
            # been added to array, add to results table.
            results = self._responses[payload]
            numReqs = self._numReq
            statusCode = response.getStatusCode()
            analysis = self._helpers.analyzeResponse(
                response.getResponse())
            for header in analysis.getHeaders():
                if header.lower().startswith("content-length"):
                    content_length = int(header.split(": ")[1])
            meanTime = round(mean(results), 3)
            medianTime = round(median(results), 3)
            stdDevTime = round(stdDev(results), 3)
            minTime = int(min(results))
            maxTime = int(max(results))
            rowData = [
                payload, numReqs, statusCode,
                len(response.getResponse()), content_length, minTime,
                maxTime, meanTime, medianTime, stdDevTime]
            self._resultsTableModel.addRow(rowData)

    def _updateClassFromUI(self):
        host = self._hostTextField.text
        port = int(self._portTextField.text)
        protocol = "https" if self._protocolCheckBox.isSelected() else "http"
        # In an effort to prevent DNS queries introducing a delay, an attempt
        # was made to use the IP address of the destination web server instead
        # of the hostname when building the HttpService. Unfortunately it
        # caused issues with HTTPS requests, probably because of SNIs. As an
        # alternative, the hostname is resolved in the next line and hopefully
        # it will be cached at that point.
        gethostbyname(host)

        self._httpService = self._helpers.buildHttpService(
            host, port, protocol)
        self._request = self._messageEditor.getMessage()
        self._numReq = int(self._requestsNumTextField.text)
        self._payloads = set(self._payloadTextArea.text.split("\n"))

    def _addPayload(self, _):
        request = self._messageEditor.getMessage()
        selection = self._messageEditor.getSelectionBounds()
        if selection[0] == selection[1]:
            # No text selected so in/out points are same
            request.insert(selection[0], 0xa7)
            request.insert(selection[1], 0xa7)
        else:
            request.insert(selection[0], 0xa7)
            request.insert(selection[1]+1, 0xa7)
        self._messageEditor.setMessage(request, True)

    def _clearPayloads(self, _):
        request = self._messageEditor.getMessage()
        request = self._helpers.bytesToString(request).replace("\xa7", "")
        self._messageEditor.setMessage(request, True)

    def _updateContentLength(self, request):
        messageSize = len(request)
        bodyOffset = self._helpers.analyzeRequest(request).getBodyOffset()
        contentLength = messageSize - bodyOffset
        contentLengthHeader = "Content-Length: {}".format(contentLength)
        request = sub("Content-Length: \\d+", contentLengthHeader, request)
        return request

    def _constructAttackPanel(self, insets, messageEditorComponent):
        attackPanel = JPanel(GridBagLayout())

        targetHeadingLabel = JLabel("<html><b>Target</b></html>")
        targetHeadingLabelConstraints = GridBagConstraints()
        targetHeadingLabelConstraints.gridx = 0
        targetHeadingLabelConstraints.gridy = 0
        targetHeadingLabelConstraints.gridwidth = 4
        targetHeadingLabelConstraints.anchor = GridBagConstraints.LINE_START
        targetHeadingLabelConstraints.insets = insets
        attackPanel.add(targetHeadingLabel, targetHeadingLabelConstraints)

        startAttackButton = JButton("<html><b>Start Attack</b></html>",
                                    actionPerformed=self._startAttack)
        startAttackButtonConstraints = GridBagConstraints()
        startAttackButtonConstraints.gridx = 4
        startAttackButtonConstraints.gridy = 0
        startAttackButtonConstraints.insets = insets
        attackPanel.add(startAttackButton, startAttackButtonConstraints)

        hostLabel = JLabel("Host:")
        hostLabelConstraints = GridBagConstraints()
        hostLabelConstraints.gridx = 0
        hostLabelConstraints.gridy = 1
        hostLabelConstraints.anchor = GridBagConstraints.LINE_START
        hostLabelConstraints.insets = insets
        attackPanel.add(hostLabel, hostLabelConstraints)

        self._hostTextField = JTextField(25)
        self._hostTextField.setMinimumSize(
            self._hostTextField.getPreferredSize())
        hostTextFieldConstraints = GridBagConstraints()
        hostTextFieldConstraints.gridx = 1
        hostTextFieldConstraints.gridy = 1
        hostTextFieldConstraints.weightx = 1
        hostTextFieldConstraints.gridwidth = 2
        hostTextFieldConstraints.anchor = GridBagConstraints.LINE_START
        hostTextFieldConstraints.insets = insets
        attackPanel.add(self._hostTextField, hostTextFieldConstraints)

        portLabel = JLabel("Port:")
        portLabelConstraints = GridBagConstraints()
        portLabelConstraints.gridx = 0
        portLabelConstraints.gridy = 2
        portLabelConstraints.anchor = GridBagConstraints.LINE_START
        portLabelConstraints.insets = insets
        attackPanel.add(portLabel, portLabelConstraints)

        self._portTextField = JTextField(5)
        self._portTextField.setMinimumSize(
            self._portTextField.getPreferredSize())
        portTextFieldConstraints = GridBagConstraints()
        portTextFieldConstraints.gridx = 1
        portTextFieldConstraints.gridy = 2
        portTextFieldConstraints.gridwidth = 2
        portTextFieldConstraints.anchor = GridBagConstraints.LINE_START
        portTextFieldConstraints.insets = insets
        attackPanel.add(self._portTextField, portTextFieldConstraints)

        self._protocolCheckBox = JCheckBox("Use HTTPS")
        protocolCheckBoxConstraints = GridBagConstraints()
        protocolCheckBoxConstraints.gridx = 0
        protocolCheckBoxConstraints.gridy = 3
        protocolCheckBoxConstraints.gridwidth = 3
        protocolCheckBoxConstraints.anchor = GridBagConstraints.LINE_START
        protocolCheckBoxConstraints.insets = insets
        attackPanel.add(self._protocolCheckBox, protocolCheckBoxConstraints)

        requestHeadingLabel = JLabel("<html><b>Request</b></html>")
        requestHeadingLabelConstraints = GridBagConstraints()
        requestHeadingLabelConstraints.gridx = 0
        requestHeadingLabelConstraints.gridy = 4
        requestHeadingLabelConstraints.gridwidth = 4
        requestHeadingLabelConstraints.anchor = GridBagConstraints.LINE_START
        requestHeadingLabelConstraints.insets = insets
        attackPanel.add(requestHeadingLabel, requestHeadingLabelConstraints)

        messageEditorComponentConstraints = GridBagConstraints()
        messageEditorComponentConstraints.gridx = 0
        messageEditorComponentConstraints.gridy = 5
        messageEditorComponentConstraints.weightx = 1
        messageEditorComponentConstraints.weighty = .75
        messageEditorComponentConstraints.gridwidth = 4
        messageEditorComponentConstraints.gridheight = 2
        messageEditorComponentConstraints.fill = GridBagConstraints.BOTH
        messageEditorComponentConstraints.insets = insets
        attackPanel.add(
            messageEditorComponent, messageEditorComponentConstraints)

        addPayloadButton = JButton(
            "Add \xa7", actionPerformed=self._addPayload)
        addPayloadButtonConstraints = GridBagConstraints()
        addPayloadButtonConstraints.gridx = 4
        addPayloadButtonConstraints.gridy = 5
        addPayloadButtonConstraints.fill = GridBagConstraints.HORIZONTAL
        addPayloadButtonConstraints.insets = insets
        attackPanel.add(addPayloadButton, addPayloadButtonConstraints)

        clearPayloadButton = JButton(
            "Clear \xa7", actionPerformed=self._clearPayloads)
        clearPayloadButtonConstraints = GridBagConstraints()
        clearPayloadButtonConstraints.gridx = 4
        clearPayloadButtonConstraints.gridy = 6
        clearPayloadButtonConstraints.anchor = GridBagConstraints.PAGE_START
        clearPayloadButtonConstraints.fill = GridBagConstraints.HORIZONTAL
        clearPayloadButtonConstraints.insets = insets
        attackPanel.add(clearPayloadButton, clearPayloadButtonConstraints)

        payloadHeadingLabel = JLabel("<html><b>Payloads<b></html>")
        payloadHeadingLabelConstraints = GridBagConstraints()
        payloadHeadingLabelConstraints.gridx = 0
        payloadHeadingLabelConstraints.gridy = 7
        payloadHeadingLabelConstraints.gridwidth = 4
        payloadHeadingLabelConstraints.anchor = GridBagConstraints.LINE_START
        payloadHeadingLabelConstraints.insets = insets
        attackPanel.add(payloadHeadingLabel, payloadHeadingLabelConstraints)

        self._payloadTextArea = JTextArea()
        payloadScrollPane = JScrollPane(self._payloadTextArea)
        payloadScrollPaneConstraints = GridBagConstraints()
        payloadScrollPaneConstraints.gridx = 0
        payloadScrollPaneConstraints.gridy = 8
        payloadScrollPaneConstraints.weighty = .25
        payloadScrollPaneConstraints.gridwidth = 3
        payloadScrollPaneConstraints.fill = GridBagConstraints.BOTH
        payloadScrollPaneConstraints.insets = insets
        attackPanel.add(payloadScrollPane, payloadScrollPaneConstraints)

        requestsNumLabel = JLabel("Number of requests for each payload:")
        requestsNumLabelConstraints = GridBagConstraints()
        requestsNumLabelConstraints.gridx = 0
        requestsNumLabelConstraints.gridy = 9
        requestsNumLabelConstraints.gridwidth = 2
        requestsNumLabelConstraints.anchor = GridBagConstraints.LINE_START
        requestsNumLabelConstraints.insets = insets
        attackPanel.add(requestsNumLabel, requestsNumLabelConstraints)

        self._requestsNumTextField = JTextField("100", 4)
        self._requestsNumTextField.setMinimumSize(
            self._requestsNumTextField.getPreferredSize())
        requestsNumTextFieldConstraints = GridBagConstraints()
        requestsNumTextFieldConstraints.gridx = 2
        requestsNumTextFieldConstraints.gridy = 9
        requestsNumTextFieldConstraints.anchor = GridBagConstraints.LINE_START
        requestsNumTextFieldConstraints.insets = insets
        attackPanel.add(
            self._requestsNumTextField, requestsNumTextFieldConstraints)

        return attackPanel

    def _constructResultsPanel(self, insets):
        resultsPanel = JPanel(GridBagLayout())

        self._progressBar = JProgressBar()
        self._progressBar.setStringPainted(True)
        self._progressBar.setMinimum(0)
        progressBarContraints = GridBagConstraints()
        progressBarContraints.gridx = 0
        progressBarContraints.gridy = 0
        progressBarContraints.fill = GridBagConstraints.HORIZONTAL

        resultsPanel.add(self._progressBar, progressBarContraints)

        self._resultsTableModel = ResultsTableModel(COLUMNS, 0)
        resultsTable = JTable(self._resultsTableModel)
        resultsTable.setAutoCreateRowSorter(True)
        cellRenderer = ColoredTableCellRenderer()
        for index in [5, 6, 7, 8, 9]:
            column = resultsTable.columnModel.getColumn(index)
            column.cellRenderer = cellRenderer
        resultsTable.getColumnModel().getColumn(0).setPreferredWidth(99999999)
        resultsTable.getColumnModel().getColumn(1).setMinWidth(160)
        resultsTable.getColumnModel().getColumn(2).setMinWidth(100)
        resultsTable.getColumnModel().getColumn(3).setMinWidth(80)
        resultsTable.getColumnModel().getColumn(4).setMinWidth(80)
        resultsTable.getColumnModel().getColumn(5).setMinWidth(110)
        resultsTable.getColumnModel().getColumn(6).setMinWidth(110)
        resultsTable.getColumnModel().getColumn(7).setMinWidth(90)
        resultsTable.getColumnModel().getColumn(8).setMinWidth(110)
        resultsTable.getColumnModel().getColumn(9).setMinWidth(110)
        resultsTable.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS)
        resultsScrollPane = JScrollPane(resultsTable)
        resultsScrollPaneConstraints = GridBagConstraints()
        resultsScrollPaneConstraints.gridx = 0
        resultsScrollPaneConstraints.gridy = 1
        resultsScrollPaneConstraints.weightx = 1
        resultsScrollPaneConstraints.weighty = 1
        resultsScrollPaneConstraints.fill = GridBagConstraints.BOTH
        resultsPanel.add(resultsScrollPane, resultsScrollPaneConstraints)

        return resultsPanel

    def _constructAboutPanel(self, insets):
        aboutPanel = JPanel(GridBagLayout())
        with open("about.html") as file:
            aboutBody = file.read()
        aboutLabel = JLabel(
                aboutBody.format(extension_name=EXTENSION_NAME))
        aboutLabelConstraints = GridBagConstraints()
        aboutLabelConstraints.weightx = 1
        aboutLabelConstraints.weighty = 1
        aboutLabelConstraints.insets = insets
        aboutLabelConstraints.fill = GridBagConstraints.HORIZONTAL
        aboutLabelConstraints.anchor = GridBagConstraints.PAGE_START
        aboutPanel.add(aboutLabel, aboutLabelConstraints)

        return aboutPanel
Example #19
0
class ToolsProgressDialog(JDialog, PropertyChangeListener):
    def __init__(self, parent, title, modal, app):
        """Restore the tools data by:
           - downloading the tools list
           - downloading the tools jar files
           - extracting the tools data from jar files
        """
        self.app = app
        border = BorderFactory.createEmptyBorder(5, 7, 5, 7)
        mainPane = self.getContentPane()
        mainPane.setLayout(BorderLayout(5, 5))
        mainPane.setBorder(border)
        self.setPreferredSize(Dimension(400, 200))
        self.taskOutput = JMultilineLabel(self.app.strings.getString("checking_for_updates"))
        self.taskOutput.setMaxWidth(350)
        self.progressBar = JProgressBar(0, 100, value=0, stringPainted=True)
        self.progressBar.setIndeterminate(True)
        self.cancelBtn = JButton("Cancel",
                                 actionPerformed=self.on_cancelBtn_clicked,
                                 enabled=True)
        self.okBtn = JButton("Ok",
                             actionPerformed=self.on_okBtn_clicked,
                             enabled=False)

        mainPane.add(self.taskOutput, BorderLayout.CENTER)
        bottomPanel = JPanel(BorderLayout(5, 5))
        bottomPanel.add(self.progressBar, BorderLayout.PAGE_START)
        buttonsPanel = JPanel()
        buttonsPanel.add(self.okBtn)
        buttonsPanel.add(self.cancelBtn)
        bottomPanel.add(buttonsPanel, BorderLayout.PAGE_END)
        mainPane.add(bottomPanel, BorderLayout.PAGE_END)
        self.pack()

        self.task = DownloaderTask(self)
        self.task.addPropertyChangeListener(self)
        self.task.execute()

    def propertyChange(self, e):
        # Invoked when task's progress property changes.
        if e.propertyName == "progress":
            if e.newValue == 2:
                text = self.app.strings.getString("downloading_tools_list")
            elif e.newValue == 3:
                text = self.app.strings.getString("tools_not_downloaded_warning")
            elif e.newValue == 5:
                text = self.app.strings.getString("downloading_tools_data")
            elif e.newValue == 6:
                text = self.app.strings.getString("i_cannot_download_the_tool_files")
            elif e.newValue == 7:
                text = self.app.strings.getString("extracting_jar_files")
            elif e.newValue == 8:
                text = self.app.strings.getString("tools_updated")
            self.taskOutput.setText("<html>" + text + "</html>")

    def on_cancelBtn_clicked(self, e):
        self.dispose()
        self.task.cancel(True)

    def on_okBtn_clicked(self, e):
        self.dispose()
    def __init__(self, imgData):
        n = imgData.size()
        win = JFrame("Point Marker Panel")
        win.setPreferredSize(Dimension(350, 590))
        win.setSize(win.getPreferredSize())
        pan = JPanel()
        pan.setLayout(BoxLayout(pan, BoxLayout.Y_AXIS))
        win.getContentPane().add(pan)

        progressPanel = JPanel()
        progressPanel.setLayout(BoxLayout(progressPanel, BoxLayout.Y_AXIS))
        positionBar = JProgressBar()
        positionBar.setMinimum(0)
        positionBar.setMaximum(n)
        positionBar.setStringPainted(True)
        progressPanel.add(Box.createGlue())
        progressPanel.add(positionBar)

        progressBar = JProgressBar()
        progressBar.setMinimum(0)
        progressBar.setMaximum(n)
        progressBar.setStringPainted(True)
        progressPanel.add(progressBar)
        progressPanel.setBorder(BorderFactory.createEmptyBorder(0,10,0,10))
        pan.add(progressPanel)

        pan.add(Box.createRigidArea(Dimension(5,5)))
        savePanel = JPanel()
        savePanel.setLayout(BoxLayout(savePanel, BoxLayout.Y_AXIS))
        saveMessageLabel = JLabel("<html><u>Save Often</u></html>")
        savePanel.add(saveMessageLabel)
        savePanel.setAlignmentX(Component.CENTER_ALIGNMENT)
        savePanel.setBorder(BorderFactory.createEmptyBorder(0,10,0,10))
        pan.add(savePanel)
        # pan.add(saveMessageLabel)

        pan.add(Box.createRigidArea(Dimension(5,5)))
        calPanel = JPanel()
        calPanel.setLayout(BoxLayout(calPanel, BoxLayout.Y_AXIS))
        calPanelIn = JPanel()
        calPanelIn.setLayout(BoxLayout(calPanelIn, BoxLayout.X_AXIS))
        pixelSizeText = JTextField(12)
        pixelSizeText.setHorizontalAlignment(JTextField.RIGHT)
        # pixelSizeText.setMaximumSize(pixelSizeText.getPreferredSize())
        unitText = JTextField(10)
        # unitText.setMaximumSize(unitText.getPreferredSize())
        pixelSizeText.setText("Enter Pixel Size Here")
        calPanelIn.add(pixelSizeText)
        unitText.setText("Unit")
        calPanelIn.add(unitText)
        calPanelIn.setAlignmentX(Component.CENTER_ALIGNMENT)
        calPanelIn.setBorder(BorderFactory.createTitledBorder("Custom Calibration"))
        calPanel.add(calPanelIn)
        calPanelIn.setAlignmentX(Component.CENTER_ALIGNMENT)
        calPanel.setBorder(BorderFactory.createEmptyBorder(0,10,0,10))
        pan.add(calPanel)

        pan.add(Box.createRigidArea(Dimension(5,5)))
        helpPanel = JPanel()
        helpPanel.setLayout(BoxLayout(helpPanel, BoxLayout.Y_AXIS))
        helpLable = JLabel("<html><ul>\
                            <li>Focus on Image Window</li>\
                            <li>Select multi-point Tool</li>\
                            <li>Click to Draw Points</li>\
                            <li>Drag to Move Points</li>\
                            <li>\"Alt\" + Click to Erase Points</li>\
                            <li>Optional: Customize Calibration Above\
                                 and Refresh Images\
                                (won't be written to files)</li>\
                            </html>")
        helpLable.setBorder(BorderFactory.createTitledBorder("Usage"))
        keyTagOpen = "<span style=\"background-color: #FFFFFF\"><b><kbd>"
        keyTagClose = "</kbd></b></span>"
        keyLable = JLabel("<html><ul>\
                            <li>Next Image --- " + keyTagOpen + "&lt" + \
                                keyTagClose + "</li>\
                            <li>Previous Image --- " + keyTagOpen + ">" + \
                                keyTagClose + "</li>\
                            <li>Save --- " + keyTagOpen + "`" + keyTagClose + \
                                " (upper-left to TAB key)</li>\
                            <li>Next Unmarked Image --- " + keyTagOpen + \
                                "TAB" + keyTagClose + "</li></ul>\
                            </html>")
        keyLable.setBorder(BorderFactory.createTitledBorder("Keyboard Shortcuts"))
        helpPanel.add(helpLable)
        helpPanel.add(keyLable)
        helpPanel.setAlignmentX(Component.CENTER_ALIGNMENT)
        helpPanel.setBorder(BorderFactory.createEmptyBorder(0,10,0,10))
        pan.add(helpPanel)

        # pan.add(Box.createRigidArea(Dimension(0, 10)))
        infoPanel = JPanel()
        infoPanel.setLayout(BoxLayout(infoPanel, BoxLayout.Y_AXIS))
        infoLabel = JLabel()
        infoLabel.setBorder(BorderFactory.createTitledBorder("Project Info"))
        infoPanel.add(infoLabel)
        infoPanel.setAlignmentX(Component.CENTER_ALIGNMENT)
        infoPanel.setBorder(BorderFactory.createEmptyBorder(0,10,0,10))
        pan.add(infoPanel)

        win.setVisible(True)

        self.imgData = imgData
        self.win = win
        # self.progressPanel = progressPanel
        self.positionBar = positionBar
        self.progressBar = progressBar
        self.saveMessageLabel = saveMessageLabel
        self.infoLabel = infoLabel
        self.pixelSizeText = pixelSizeText
        self.unitText = unitText
        self.update()
Example #21
0
class Pipeline():
  def __init__(self):
    #If a swing interface is asked for this will be the JFrame.
    self.frame = None
    #Keeps track of the number of queries processed.
    self.jobCount = 0
    #Keeps track of the query currently being processed.
    self.currentJob = ""
    #Keeps track of the massage to be displayed.
    self.message = 0
    #Messages to be displayed at each stage in the processing of a single query.
    self.messages = ["Searching for genes via genemark",
                     "Extending genes found via genemark",
                     "Searching for intergenic genes",
                     "Removing overlapping genes",
                     "Searching for promoters",
                     "Using transterm to find terminators",
                     "Removing transcription signals which conflict with genes",
                     "Using tRNAscan to find transfer RNAs",
                     "Writing Artemis file",
                     "Writing summary .xml, .html, and .xls files"]
    self.exception = None

  def initializeDisplay(self, queries, swing):
    """
    queries: A list of the fasts files to be processed.
    swing:   If true then updates about progress will be displayed in a swing window, otherwise they will be written to stdout.
    
    Initializes the interface for telling the user about progress in the pipeline.  Queries is used to count the
    number of queries the pipeline will process and to size the swing display(if it is used) so that text
    isn't cutoff at the edge of the window.  The swing display is setup if swing is true.
    """
  
    self.numJobs = len(queries)
    if swing:
      self.frame = JFrame("Neofelis")
      self.frame.addWindowListener(PipelineWindowAdapter(self))
      contentPane = JPanel(GridBagLayout())
      self.frame.setContentPane(contentPane)
      self.globalLabel = JLabel(max(queries, key = len))
      self.globalProgress = JProgressBar(0, self.numJobs)
      self.currentLabel = JLabel(max(self.messages, key = len))
      self.currentProgress = JProgressBar(0, len(self.messages))
      self.doneButton = JButton(DoneAction(self.frame))
      self.doneButton.setEnabled(False)

      constraints = GridBagConstraints()
      
      constraints.gridx, constraints.gridy = 0, 0
      constraints.gridwidth, constraints.gridheight = 1, 1
      constraints.weightx = 1
      constraints.fill = GridBagConstraints.HORIZONTAL
      contentPane.add(self.globalLabel, constraints)
      constraints.gridy = 1
      contentPane.add(self.globalProgress, constraints)
      constraints.gridy = 2
      contentPane.add(self.currentLabel, constraints)
      constraints.gridy = 3
      contentPane.add(self.currentProgress, constraints)
      constraints.gridy = 4
      constraints.weightx = 0
      constraints.fill = GridBagConstraints.NONE
      constraints.anchor = GridBagConstraints.LINE_END
      contentPane.add(self.doneButton, constraints)
    
      self.frame.pack()
      self.frame.setResizable(False)
      self.globalLabel.setText(" ")
      self.currentLabel.setText(" ")
      self.frame.setLocationRelativeTo(None)
      self.frame.setVisible(True)

  def updateProgress(self, job):
    """
    query: Name of the query currently being processed.
    
    This function use used for updating the progress shown in the interface.  If job is not equal to currentJob then
    global progress is incremented and shown and the currentProgress is reset and shown.  If job is equal to currentJob
    then the globalProgress does not change and currentProgress is increased.
    """
    if self.exception:
      raise self.exception
    
    if self.frame:
      if job != self.currentJob:
        self.currentProgress.setValue(self.currentProgress.getMaximum())
        self.globalLabel.setText(job)
        self.globalProgress.setValue(self.jobCount)
        print "Processing %s, %.2f%% done" % (job, 100.0*self.jobCount/self.numJobs)
        self.jobCount += 1
        self.currentJob = job
        self.message = -1
      self.message += 1
      print "    %s, %.2f%% done" % (self.messages[self.message], 100.0*self.message/len(self.messages))
      self.currentProgress.setValue(self.message)
      self.currentLabel.setText(self.messages[self.message])
    else:
      if job != self.currentJob:
        print "Processing %s, %.2f%% done" % (job, 100.0*self.jobCount/self.numJobs)
        self.jobCount += 1
        self.currentJob = job
        self.message = -1
      self.message += 1
      print "    %s, %.2f%% done" % (self.messages[self.message], 100.0*self.message/len(self.messages))

  def finished(self):
    """
    This function is to be called at the end of the pipeline.  Informs the user that the pipeline is finished
    and if a swing interface is being used the Done button is enabled.
    """
    print "Processing 100.00% done"
    if self.frame:
      self.globalLabel.setText("Finished")
      self.globalProgress.setValue(self.globalProgress.getMaximum())
      self.currentLabel.setText(" ")
      self.currentProgress.setValue(self.currentProgress.getMaximum())
      self.doneButton.setEnabled(True)
      while self.frame.isVisible():
        pass

  def run(self, blastLocation, genemarkLocation, transtermLocation, tRNAscanLocation, database, eValue, matrix, minLength, scaffoldingDistance, promoterScoreCutoff, queries, swing = False, email = ""):
    """
    blastLocation:       Directory blast was installed in.
    genemarkLocation:    Directory genemark was installed in.
    transtermLocation:   Directory transterm was installed in.
    tRNAscanLocation:    Directory tRNAscan was installed in.
    database:            Name of the blast database to use.
    eValue:              The e value used whenever a blast search is done.
    matrix:              The matrix to use when running genemark.  If None then genemark is run heuristically.
    minLength:           Minimum length of any genes included in the resulting annotation.
    scaffoldingDistance: The maximum length allowed between genes when contiguous regions of genes are being identified
    promoterScoreCutoff: Minimum score allowed for any promoters included in the resulting annotation
    queries:             A list of faster files to process.
    swing:               If true a swing window will be used to updated the user about the pipeline's progress.
    email:               If this is a non-empty string an email will be sent to the address in the string when the pipeline is done.  This will be attempted with the sendmail command on the local computer.
    
    The main pipeline function.  For every query genemark is used to predict genes, these genes are then extended to any preferable starts.  Then the pipeline searches
    for any intergenic genes(genes between those found by genemark) and these are combined with the extended genemark genes.  Then the genes are pruned to remove
    any undesirable genes found in the intergenic stage.  BPROM and Transterm are used to find promoters and terminators, which are then pruned to remove any
    signals which are inside or too far away from any genes.  Next, tRNAscan is used to find any transfer RNAs in the genome.  Finally, all the remaining genes,
    promoters, and terminators are written to an artemis file in the directory of the query with the same name but with a .art extension, and .xml, .html, and
    .xls files will be generating describing the blast results of the final genes.
    """
    self.initializeDisplay(queries, swing)

    try:
      for query in queries:
        name = os.path.splitext(query)[0]
        queryDirectory, name = os.path.split(name)
        
        genome = utils.loadGenome(query)
        swapFileName = "query" + str(id(self)) + ".fas"
        queryFile = open(swapFileName, "w")
        queryFile.write(">" + name + "\n")
        for i in range(0, len(genome), 50):
          queryFile.write(genome[i:min(i+50, len(genome))] + "\n")
        queryFile.close()

        self.updateProgress(query)
        initialGenes = genemark.findGenes(swapFileName, name, blastLocation, database, eValue, genemarkLocation, matrix, self)
      
        self.updateProgress(query)
        extendedGenes = extend.extendGenes(swapFileName, initialGenes, name, blastLocation, database, eValue, self)
    
        self.updateProgress(query)
        intergenicGenes = intergenic.findIntergenics(swapFileName, extendedGenes, name, minLength, blastLocation, database, eValue, self)

        genes = {}
        for k, v in extendedGenes.items() + intergenicGenes.items():
          genes[k] = v
        
        self.updateProgress(query)
        scaffolded = scaffolds.refineScaffolds(genes, scaffoldingDistance)
 
        self.updateProgress(query)
        initialPromoters = promoters.findPromoters(swapFileName, name, promoterScoreCutoff, self.frame)
    
        self.updateProgress(query)
        initialTerminators = terminators.findTerminators(swapFileName, name, genes.values(), transtermLocation)
      
        self.updateProgress(query)
        filteredSignals = signals.filterSignals(scaffolded.values(), initialPromoters + initialTerminators)
        filteredPromoters = filter(lambda x: isinstance(x, promoters.Promoter), filteredSignals)
        filteredTerminators = filter(lambda x: isinstance(x, terminators.Terminator), filteredSignals)

        self.updateProgress(query)
        transferRNAs = rna.findtRNAs(tRNAscanLocation, swapFileName)

        os.remove(swapFileName)

        self.updateProgress(query)
        artemis.writeArtemisFile(os.path.splitext(query)[0] + ".art", genome, scaffolded.values(), filteredPromoters, filteredTerminators, transferRNAs)

        self.updateProgress(query)
        report.report(name, scaffolded, os.path.splitext(query)[0])

      if email:
        if not os.path.isfile("EMAIL_MESSAGE"):
          message = open("EMAIL_MESSAGE", "w")
          message.write("Subject: Annotation Complete\nYour genome has been annotated.\n")
          message.close()
        
        sent = False
        while not sent:
          message = open("EMAIL_MESSAGE", "r")
          sendmailProcess = subprocess.Popen(["/usr/sbin/sendmail", "-F", "Neofelis", "-f", "*****@*****.**", email],
                                             stdin = message,
                                             stdout = subprocess.PIPE)
          result = ""
          nextRead = sendmailProcess.stdout.read()
          while nextRead:
            result += nextRead
            nextRead = sendmailProcess.stdout.read()
          sent = not result.strip()
          message.close()
    
      self.finished()
    except PipelineException:
      return
class DetermineCookieFrame(JFrame):
    """ This is the GUI for for the user to control the actions when
        determining which cookie is the session cookie.
    """

    def __init__(self, callbacks, selected_message):
        super(DetermineCookieFrame, self).__init__()
        self.callbacks = callbacks
        self.selected_message = selected_message
        self.windowClosing = self.close

    def loadPanel(self):
        panel = JPanel()

        panel.setLayout(BoxLayout(panel, BoxLayout.Y_AXIS))

        bottomButtonBarPanel = JPanel()
        bottomButtonBarPanel.setLayout(BoxLayout(bottomButtonBarPanel, BoxLayout.X_AXIS))
        bottomButtonBarPanel.setAlignmentX(1.0)

        self.runButton = JButton("Run", actionPerformed=self.start)
        self.cancelButton = JButton("Close", actionPerformed=self.cancel)

        bottomButtonBarPanel.add(Box.createHorizontalGlue());
        bottomButtonBarPanel.add(self.runButton)
        bottomButtonBarPanel.add(self.cancelButton)

        # Dimension(width,height)    
        bottom = JPanel()
        bottom.setLayout(BoxLayout(bottom, BoxLayout.X_AXIS))
        bottom.setAlignmentX(1.0)

        self.progressBar = JProgressBar()
        self.progressBar.setIndeterminate(False)
        self.progressBar.setMaximum(100)
        self.progressBar.setValue(0)

        bottom.add(self.progressBar)

        self.statusTextArea = JTextArea()
        self.statusTextArea.setEditable(False)
        scrollPane = JScrollPane(self.statusTextArea)
        scrollPanel = JPanel()
        scrollPanel.setLayout(BoxLayout(scrollPanel, BoxLayout.X_AXIS))
        scrollPanel.setAlignmentX(1.0)
        scrollPanel.add(scrollPane)

        panel.add(scrollPanel)
        panel.add(bottomButtonBarPanel)
        panel.add(bottom)

        self.add(panel)
        self.setTitle("Determine Session Cookie(s)")
        self.setSize(450, 300)
        self.setLocationRelativeTo(None)
        self.setVisible(True)


        original_request_bytes = self.selected_message.getRequest()
        http_service = self.selected_message.getHttpService()
        helpers = self.callbacks.getHelpers()
        request_info = helpers.analyzeRequest(http_service, original_request_bytes)
        parameters = request_info.getParameters();
        cookie_parameters = [parameter for parameter in parameters if parameter.getType() == IParameter.PARAM_COOKIE]
        num_requests_needed = len(cookie_parameters) + 2
        self.statusTextArea.append("This may require up to " + str(num_requests_needed) + " requests to be made. Hit 'Run' to begin.\n")

    def start(self, event):
        global cancelThread
        cancelThread = False
        self.runButton.setEnabled(False)
        self.cancelButton.setText("Cancel")
        thread = ThreadDetermineCookie(self.callbacks, self.selected_message, self.statusTextArea, self.progressBar)
        thread.start()

    def cancel(self, event):
        self.setVisible(False);
        self.dispose();

    def close(self, event):
        global cancelThread
        cancelThread = True
class JythonGui(ItemListener):
    def __init__(self, instructionsURI=''):
        self.instructionsURI = instructionsURI

        self.logger = logging.getLogger('sasi_runner_gui')
        self.logger.addHandler(logging.StreamHandler())
        def log_fn(msg):
            self.log_msg(msg)
        self.logger.addHandler(FnLogHandler(log_fn))
        self.logger.setLevel(logging.DEBUG)

        self.selected_input_file = None
        self.selected_output_file = None

        self.frame = JFrame(
            "SASI Runner",
            defaultCloseOperation = WindowConstants.EXIT_ON_CLOSE,
        )
        self.frame.size = (650, 600,)

        self.main_panel = JPanel()
        self.main_panel.layout = BoxLayout(self.main_panel, BoxLayout.Y_AXIS)
        self.frame.add(self.main_panel)

        self.top_panel = JPanel(SpringLayout())
        self.top_panel.alignmentX = Component.CENTER_ALIGNMENT
        self.main_panel.add(self.top_panel)

        self.stageCounter = 1
        def getStageLabel(txt):
            label = JLabel("%s. %s" % (self.stageCounter, txt))
            self.stageCounter += 1
            return label

        # Instructions link.
        self.top_panel.add(getStageLabel("Read the instructions:"))
        instructionsButton = JButton(
            ('<HTML><FONT color="#000099">'
             '<U>open instructions</U></FONT><HTML>'),
            actionPerformed=self.browseInstructions)
        instructionsButton.setHorizontalAlignment(SwingConstants.LEFT);
        instructionsButton.setBorderPainted(False);
        instructionsButton.setOpaque(False);
        instructionsButton.setBackground(Color.WHITE);
        instructionsButton.setToolTipText(self.instructionsURI);
        self.top_panel.add(instructionsButton)

        # 'Select input' elements.
        self.top_panel.add(getStageLabel(
            "Select a SASI .zip file or data folder:"))
        self.top_panel.add(
            JButton("Select input...", actionPerformed=self.openInputChooser))

        # 'Select output' elements.
        self.top_panel.add(getStageLabel("Specify an output file:"))
        self.top_panel.add(
            JButton("Specify output...", actionPerformed=self.openOutputChooser))

        # 'Set result fields' elements.
        result_fields = [
            {'id': 'gear_id', 'label': 'Gear', 'selected': True, 
             'enabled': False}, 
            {'id': 'substrate_id', 'label': 'Substrate', 'selected': True}, 
            {'id': 'energy_id', 'label': 'Energy', 'selected': False},
            {'id': 'feature_id', 'label': 'Feature', 'selected': False}, 
            {'id': 'feature_category_id', 'label': 'Feature Category', 
             'selected': False}
        ]
        self.selected_result_fields = {}
        resolutionLabelPanel = JPanel(GridLayout(0,1))
        resolutionLabelPanel.add(getStageLabel("Set result resolution:"))
        resolutionLabelPanel.add(
            JLabel(("<html><i>This sets the specificity with which<br>"
                    "results will be grouped. Note that enabling<br>"
                    "more fields can *greatly* increase resulting<br>"
                    "output sizes and run times.</i>")))
        #self.top_panel.add(getStageLabel("Set result resolution:"))
        self.top_panel.add(resolutionLabelPanel)
        checkPanel = JPanel(GridLayout(0, 1))
        self.top_panel.add(checkPanel) 
        self.resultFieldCheckBoxes = {}
        for result_field in result_fields:
            self.selected_result_fields.setdefault(
                result_field['id'], result_field['selected'])
            checkBox = JCheckBox(
                result_field['label'], result_field['selected'])
            checkBox.setEnabled(result_field.get('enabled', True))
            checkBox.addItemListener(self)
            checkPanel.add(checkBox)
            self.resultFieldCheckBoxes[checkBox] = result_field

        # 'Run' elements.
        self.top_panel.add(getStageLabel("Run SASI: (this might take a while)"))
        self.run_button = JButton("Run...", actionPerformed=self.runSASI)
        self.top_panel.add(self.run_button)

        SpringUtilities.makeCompactGrid(
            self.top_panel, self.stageCounter - 1, 2, 6, 6, 6, 6)

        # Progress bar.
        self.progressBar = JProgressBar(0, 100)
        self.main_panel.add(self.progressBar)

        # Log panel.
        self.log_panel = JPanel()
        self.log_panel.alignmentX = Component.CENTER_ALIGNMENT
        self.log_panel.setBorder(EmptyBorder(10,10,10,10))
        self.main_panel.add(self.log_panel)
        self.log_panel.setLayout(BorderLayout())
        self.log = JTextArea()
        self.log.editable = False
        self.logScrollPane = JScrollPane(self.log)
        self.logScrollPane.setVerticalScrollBarPolicy(
            JScrollPane.VERTICAL_SCROLLBAR_ALWAYS)
        self.logScrollBar = self.logScrollPane.getVerticalScrollBar()
        self.log_panel.add(self.logScrollPane, BorderLayout.CENTER)

        # File selectors
        self.inputChooser = JFileChooser()
        self.inputChooser.fileSelectionMode = JFileChooser.FILES_AND_DIRECTORIES

        self.outputChooser = JFileChooser()
        defaultOutputFile = os.path.join(System.getProperty("user.home"),
                                         "sasi_project.zip")

        self.outputChooser.setSelectedFile(File(defaultOutputFile));
        self.outputChooser.fileSelectionMode = JFileChooser.FILES_ONLY

        self.frame.setLocationRelativeTo(None)
        self.frame.visible = True

    def browseInstructions(self, event):
        """ Open a browser to the instructions page. """
        browseURI(self.instructionsURI)

    def itemStateChanged(self, event):
        """ Listen for checkbox changes. """
        checkBox = event.getItemSelectable()
        is_selected = (event.getStateChange() == ItemEvent.SELECTED)
        result_field = self.resultFieldCheckBoxes[checkBox]
        self.selected_result_fields[result_field['id']] = is_selected

    def log_msg(self, msg):
        """ Print message to log and scroll to bottom. """
        self.log.append(msg + "\n")
        self.log.setCaretPosition(self.log.getDocument().getLength())

    def openInputChooser(self, event):
        ret = self.inputChooser.showOpenDialog(self.frame)
        if ret == JFileChooser.APPROVE_OPTION:
            self.selected_input_file = self.inputChooser.selectedFile
            self.log_msg("Selected '%s' as input." % self.selected_input_file.path)

    def openOutputChooser(self, event):
        ret = self.outputChooser.showSaveDialog(self.frame)
        if ret == JFileChooser.APPROVE_OPTION:
            selectedPath = self.outputChooser.selectedFile.path
            if not selectedPath.endswith('.zip'):
                zipPath = selectedPath + '.zip'
                self.outputChooser.setSelectedFile(File(zipPath))
            self.selected_output_file = self.outputChooser.selectedFile
            self.log_msg(
                "Selected '%s' as output." % self.selected_output_file.path)

    def runSASI(self, event):
        try:
            self.validateParameters()
        except Exception as e:
            self.log_msg("ERROR: '%s'" % e)

        # Run task in a separate thread, so that log
        # messages will be shown as task progresses.
        def run_task():
            self.tmp_dir = tempfile.mkdtemp(prefix="sasi_runner.")
            self.db_file = os.path.join(self.tmp_dir, "sasi_runner.db")

            self.progressBar.setValue(0)
            self.progressBar.setIndeterminate(True)

            def get_connection():
                engine = create_engine('h2+zxjdbc:////%s' % self.db_file)
                con = engine.connect()
                return con

            try:
                # Set result fields.
                result_fields = []
                for field_id, is_selected in self.selected_result_fields.items():
                    if is_selected: result_fields.append(field_id)

                task = RunSasiTask(
                    input_path=self.selected_input_file.path,
                    output_file=self.selected_output_file.path,
                    logger=self.logger,
                    get_connection=get_connection,
                    config={
                        'result_fields': result_fields,
                        'run_model': {
                            'run': {
                                'batch_size': 'auto',
                            }
                        },
                        'output': {
                            'batch_size': 'auto',
                        },
                    }
                )
                task.call()
            except Exception as e:
                self.logger.exception("Could not complete task")

            self.progressBar.setIndeterminate(False)
            self.progressBar.setValue(100)

            try:
                shutil.rmtree(self.tmp_dir)
            except:
                pass

        Thread(target=run_task).start()

    def validateParameters(self):
        return True
    def __init__(self, instructionsURI=""):
        self.instructionsURI = instructionsURI

        self.logger = logging.getLogger("sasi_gridder_gui")
        self.logger.addHandler(logging.StreamHandler())

        def log_fn(msg):
            self.log_msg(msg)

        self.logger.addHandler(FnLogHandler(log_fn))
        self.logger.setLevel(logging.DEBUG)

        self.selected_input_file = None
        self.selected_output_file = None

        self.frame = JFrame("SASI Gridder", defaultCloseOperation=WindowConstants.EXIT_ON_CLOSE)
        self.frame.size = (650, 600)

        self.main_panel = JPanel()
        self.main_panel.layout = BoxLayout(self.main_panel, BoxLayout.Y_AXIS)
        self.frame.add(self.main_panel)

        self.top_panel = JPanel(SpringLayout())
        self.top_panel.alignmentX = Component.CENTER_ALIGNMENT
        self.main_panel.add(self.top_panel)

        self.stageCounter = 1

        def getStageLabel(txt):
            label = JLabel("%s. %s" % (self.stageCounter, txt))
            self.stageCounter += 1
            return label

        # Instructions link.
        self.top_panel.add(getStageLabel("Read the instructions:"))
        instructionsButton = JButton(
            ('<HTML><FONT color="#000099">' "<U>open instructions</U></FONT><HTML>"),
            actionPerformed=self.browseInstructions,
        )
        instructionsButton.setHorizontalAlignment(SwingConstants.LEFT)
        instructionsButton.setBorderPainted(False)
        instructionsButton.setOpaque(False)
        instructionsButton.setBackground(Color.WHITE)
        instructionsButton.setToolTipText(self.instructionsURI)
        self.top_panel.add(instructionsButton)

        # Select input elements.
        self.top_panel.add(getStageLabel("Select an input data folder:"))
        self.top_panel.add(JButton("Select input...", actionPerformed=self.openInputChooser))

        # Select output elements.
        self.top_panel.add(getStageLabel("Specify an output file:"))
        self.top_panel.add(JButton("Specify output...", actionPerformed=self.openOutputChooser))

        # Run elements.
        self.top_panel.add(getStageLabel("Run SASI Gridder: (this might take a hwile"))
        self.run_button = JButton("Run...", actionPerformed=self.runSASIGridder)
        self.top_panel.add(self.run_button)

        SpringUtilities.makeCompactGrid(self.top_panel, self.stageCounter - 1, 2, 6, 6, 6, 6)

        # Progress bar.
        self.progressBar = JProgressBar(0, 100)
        self.main_panel.add(self.progressBar)

        # Log panel.
        self.log_panel = JPanel()
        self.log_panel.alignmentX = Component.CENTER_ALIGNMENT
        self.log_panel.setBorder(EmptyBorder(10, 10, 10, 10))
        self.main_panel.add(self.log_panel)
        self.log_panel.setLayout(BorderLayout())
        self.log = JTextArea()
        self.log.editable = False
        self.logScrollPane = JScrollPane(self.log)
        self.logScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS)
        self.log_panel.add(self.logScrollPane, BorderLayout.CENTER)

        # File selectors
        self.inputChooser = JFileChooser()
        self.inputChooser.fileSelectionMode = JFileChooser.FILES_AND_DIRECTORIES
        self.outputChooser = JFileChooser()
        self.outputChooser.fileSelectionMode = JFileChooser.FILES_ONLY
        defaultOutputFile = os.path.join(System.getProperty("user.home"), "gridded_efforts.csv")
        self.outputChooser.setSelectedFile(File(defaultOutputFile))

        self.frame.setLocationRelativeTo(None)
        self.frame.visible = True
class DetermineCookieFrame(JFrame):
    """ This is the GUI for for the user to control the actions when
        determining which cookie is the session cookie.
    """
    def __init__(self, callbacks, selected_message):
        super(DetermineCookieFrame, self).__init__()
        self.callbacks = callbacks
        self.selected_message = selected_message
        self.windowClosing = self.close

    def loadPanel(self):
        panel = JPanel()

        panel.setLayout(BoxLayout(panel, BoxLayout.Y_AXIS))

        bottomButtonBarPanel = JPanel()
        bottomButtonBarPanel.setLayout(
            BoxLayout(bottomButtonBarPanel, BoxLayout.X_AXIS))
        bottomButtonBarPanel.setAlignmentX(1.0)

        self.runButton = JButton("Run", actionPerformed=self.start)
        self.cancelButton = JButton("Close", actionPerformed=self.cancel)

        bottomButtonBarPanel.add(Box.createHorizontalGlue())
        bottomButtonBarPanel.add(self.runButton)
        bottomButtonBarPanel.add(self.cancelButton)

        # Dimension(width,height)
        bottom = JPanel()
        bottom.setLayout(BoxLayout(bottom, BoxLayout.X_AXIS))
        bottom.setAlignmentX(1.0)

        self.progressBar = JProgressBar()
        self.progressBar.setIndeterminate(False)
        self.progressBar.setMaximum(100)
        self.progressBar.setValue(0)

        bottom.add(self.progressBar)

        self.statusTextArea = JTextArea()
        self.statusTextArea.setEditable(False)
        scrollPane = JScrollPane(self.statusTextArea)
        scrollPanel = JPanel()
        scrollPanel.setLayout(BoxLayout(scrollPanel, BoxLayout.X_AXIS))
        scrollPanel.setAlignmentX(1.0)
        scrollPanel.add(scrollPane)

        panel.add(scrollPanel)
        panel.add(bottomButtonBarPanel)
        panel.add(bottom)

        self.add(panel)
        self.setTitle("Determine Session Cookie(s)")
        self.setSize(450, 300)
        self.setLocationRelativeTo(None)
        self.setVisible(True)

        original_request_bytes = self.selected_message.getRequest()
        http_service = self.selected_message.getHttpService()
        helpers = self.callbacks.getHelpers()
        request_info = helpers.analyzeRequest(http_service,
                                              original_request_bytes)
        parameters = request_info.getParameters()
        cookie_parameters = [
            parameter for parameter in parameters
            if parameter.getType() == IParameter.PARAM_COOKIE
        ]
        num_requests_needed = len(cookie_parameters) + 2
        self.statusTextArea.append(
            "This may require up to " + str(num_requests_needed) +
            " requests to be made. Hit 'Run' to begin.\n")

    def start(self, event):
        global cancelThread
        cancelThread = False
        self.runButton.setEnabled(False)
        self.cancelButton.setText("Cancel")
        thread = ThreadDetermineCookie(self.callbacks, self.selected_message,
                                       self.statusTextArea, self.progressBar)
        thread.start()

    def cancel(self, event):
        self.setVisible(False)
        self.dispose()

    def close(self, event):
        global cancelThread
        cancelThread = True
Example #26
0
class ToolsProgressDialog(JDialog, PropertyChangeListener):
    def __init__(self, parent, title, modal, app):
        """Restore the tools data by:
           - downloading the tools list
           - downloading the tools jar files
           - extracting the tools data from jar files
        """
        self.app = app
        border = BorderFactory.createEmptyBorder(5, 7, 5, 7)
        mainPane = self.getContentPane()
        mainPane.setLayout(BorderLayout(5, 5))
        mainPane.setBorder(border)
        self.setPreferredSize(Dimension(400, 200))
        self.taskOutput = JMultilineLabel(
            self.app.strings.getString("checking_for_updates"))
        self.taskOutput.setMaxWidth(350)
        self.progressBar = JProgressBar(0, 100, value=0, stringPainted=True)
        self.progressBar.setIndeterminate(True)
        self.cancelBtn = JButton("Cancel",
                                 actionPerformed=self.on_cancelBtn_clicked,
                                 enabled=True)
        self.okBtn = JButton("Ok",
                             actionPerformed=self.on_okBtn_clicked,
                             enabled=False)

        mainPane.add(self.taskOutput, BorderLayout.CENTER)
        bottomPanel = JPanel(BorderLayout(5, 5))
        bottomPanel.add(self.progressBar, BorderLayout.PAGE_START)
        buttonsPanel = JPanel()
        buttonsPanel.add(self.okBtn)
        buttonsPanel.add(self.cancelBtn)
        bottomPanel.add(buttonsPanel, BorderLayout.PAGE_END)
        mainPane.add(bottomPanel, BorderLayout.PAGE_END)
        self.pack()

        self.task = DownloaderTask(self)
        self.task.addPropertyChangeListener(self)
        self.task.execute()

    def propertyChange(self, e):
        # Invoked when task's progress property changes.
        if e.propertyName == "progress":
            if e.newValue == 2:
                text = self.app.strings.getString("downloading_tools_list")
            elif e.newValue == 3:
                text = self.app.strings.getString(
                    "tools_not_downloaded_warning")
            elif e.newValue == 5:
                text = self.app.strings.getString("downloading_tools_data")
            elif e.newValue == 6:
                text = self.app.strings.getString(
                    "i_cannot_download_the_tool_files")
            elif e.newValue == 7:
                text = self.app.strings.getString("extracting_jar_files")
            elif e.newValue == 8:
                text = self.app.strings.getString("tools_updated")
            self.taskOutput.setText("<html>" + text + "</html>")

    def on_cancelBtn_clicked(self, e):
        self.dispose()
        self.task.cancel(True)

    def on_okBtn_clicked(self, e):
        self.dispose()
Example #27
0
lbl2.setBounds(40,50,200,20)
f2_btn_label = JButton("Browse", actionPerformed = f2_clic_browse2)
f2_btn_label.setBounds(170,50,100,20)
f2_txt2 = JTextField(10)
f2_txt2.setBounds(280, 50, 120,20)

# Button Previous
f2_btn_prev = JButton("Previous", actionPerformed = f2_clic_prev)
f2_btn_prev.setBounds(40,120,100,20)

# Button Next
f2_btn_next = JButton("Next", actionPerformed = f2_clic_next)
f2_btn_next.setBounds(300,120,100,20)

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

frame2.add(lbl1)
frame2.add(f2_btn_original)
frame2.add(f2_txt1)

frame2.add(lbl2)
frame2.add(f2_btn_label)
frame2.add(f2_txt2)

frame2.add(f2_btn_prev)
frame2.add(f2_btn_next)

frame2.add(progressBar)
Example #28
0
    def drawPluginUI(self):
        # Create the plugin user interface
        self.pluginTab = JPanel()
        self.uiTitle = JLabel('UPnP BHunter Load, Aim and Fire Console')
        self.uiTitle.setFont(Font('Tahoma', Font.BOLD, 14))
        self.uiTitle.setForeground(Color(250, 100, 0))
        self.uiPanelA = JSplitPane(JSplitPane.VERTICAL_SPLIT)
        self.uiPanelA.setMaximumSize(Dimension(2500, 1000))
        self.uiPanelA.setDividerSize(2)
        self.uiPanelB = JSplitPane(JSplitPane.VERTICAL_SPLIT)
        self.uiPanelB.setDividerSize(2)
        self.uiPanelA.setBottomComponent(self.uiPanelB)
        self.uiPanelA.setBorder(BorderFactory.createLineBorder(Color.gray))

        # Create and configure labels and text fields
        self.labeltitle_step1 = JLabel("[1st STEP] Discover UPnP Locations")
        self.labeltitle_step1.setFont(Font('Tahoma', Font.BOLD, 14))
        self.labeltitle_step2 = JLabel("[2nd STEP] Select an UPnP Service")
        self.labeltitle_step2.setFont(Font('Tahoma', Font.BOLD, 14))
        self.labeltitle_step3 = JLabel("[3rd STEP] Time to Attack it")
        self.labeltitle_step3.setFont(Font('Tahoma', Font.BOLD, 14))
        self.labelsubtitle_step1 = JLabel(
            "Specify the IP version address in scope and start UPnP discovery")
        self.labelsubtitle_step2 = JLabel(
            "Select which of the found UPnP services will be probed")
        self.labelsubtitle_step3 = JLabel(
            "Select how to test the extracted UPnP SOAP requests having input arguments"
        )
        self.label_step1 = JLabel("Target IP")
        self.label_step2 = JLabel("Found UPnp Services")
        self.label_step3 = JLabel("Send all the extracted SOAP requests     ")
        self.labelstatus = JLabel("             Status")
        self.labelempty_step1 = JLabel("                ")
        self.labelempty_step2 = JLabel("  ")
        self.labelupnp = JLabel("UPnP list")
        self.labelip = JLabel("IP list")
        self.labelLANHOST = JLabel(
            "Send the interesting LANHostConfigManagement SOAP requests     ")
        self.labelWANCONNECTION = JLabel(
            "Send the interesting WANIP/PPPConnection SOAP requests     ")
        self.labelSOAPnum = JLabel("0")
        self.labelLANHOSTnum = JLabel("0")
        self.labelWANCONNECTIONnum = JLabel("0")
        self.labelNoneServiceFound = JLabel("  ")
        self.labelNoneServiceFound.setFont(Font('Tahoma', Font.BOLD, 12))
        self.labelNoneServiceFound.setForeground(Color.red)

        # Create combobox for IP version selection
        self.ip_versions = ["IPv4", "IPv6"]
        self.combo_ipversion = JComboBox(self.ip_versions)
        self.combo_ipversion.setSelectedIndex(0)
        self.combo_ipversion.setEnabled(True)

        # Create and configure progress bar
        self.progressbar = JProgressBar(0, 100)
        self.progressbar.setString("Ready")
        self.progressbar.setStringPainted(True)

        # Create and configure buttons
        self.startbutton = JButton("Start Discovery",
                                   actionPerformed=self.startHunting)
        self.clearbutton = JButton("Clear All", actionPerformed=self.clearAll)
        self.confirmbutton = JButton("Confirm Selection",
                                     actionPerformed=self.selectUPnPService)
        self.intruderbutton = JButton("to Intruder",
                                      actionPerformed=self.sendUPnPToIntruder)
        self.LANrepeaterbutton = JButton(
            "to Repeater", actionPerformed=self.sendLANUPnPToRepeater)
        self.WANrepeaterbutton = JButton(
            "to Repeater", actionPerformed=self.sendWANUPnPToRepeater)
        self.confirmbutton.setEnabled(False)
        self.intruderbutton.setEnabled(False)
        self.LANrepeaterbutton.setEnabled(False)
        self.WANrepeaterbutton.setEnabled(False)

        # Create the combo box, select item at index 0 (first item in list)
        self.upnpservices = ["       "]
        self.upnpcombo_services = JComboBox(self.upnpservices)
        self.upnpcombo_services.setSelectedIndex(0)
        self.upnpcombo_services.setEnabled(False)

        # Class neeeded to handle the combobox in second step panel
        class ComboboxListener(ActionListener):
            def __init__(self, upnpcombo_targets, upnpcombo_services,
                         scope_dict):
                self.upnpcombo_targets = upnpcombo_targets
                self.upnpcombo_services = upnpcombo_services
                self.scope_dict = scope_dict

            def actionPerformed(self, event):
                # Update the location url combobox depending on the IP combobox
                selected_target = self.upnpcombo_targets.getSelectedItem()
                if self.scope_dict and selected_target:
                    self.upnpcombo_services.removeAllItems()
                    for scope_url in self.scope_dict[selected_target]:
                        self.upnpcombo_services.addItem(scope_url)
                    self.upnpcombo_services.setSelectedIndex(0)

        # Create the combo box, select item at index 0 (first item in list)
        self.upnptargets = ["       "]
        self.upnpcombo_targets = JComboBox(self.upnptargets)
        self.upnpcombo_targets.setSelectedIndex(0)
        self.upnpcombo_targets.setEnabled(False)
        self.upnpcombo_targets.addActionListener(
            ComboboxListener(self.upnpcombo_targets, self.upnpcombo_services,
                             self.scope_dict))

        # Configuring first step panel
        self.panel_step1 = JPanel()
        self.panel_step1.setPreferredSize(Dimension(2250, 100))
        self.panel_step1.setBorder(EmptyBorder(10, 10, 10, 10))
        self.panel_step1.setLayout(BorderLayout(15, 15))
        self.titlepanel_step1 = JPanel()
        self.titlepanel_step1.setLayout(BorderLayout())
        self.titlepanel_step1.add(self.labeltitle_step1, BorderLayout.NORTH)
        self.titlepanel_step1.add(self.labelsubtitle_step1)
        self.targetpanel_step1 = JPanel()
        self.targetpanel_step1.add(self.label_step1)
        self.targetpanel_step1.add(self.combo_ipversion)
        self.targetpanel_step1.add(self.startbutton)
        self.targetpanel_step1.add(self.clearbutton)
        self.targetpanel_step1.add(self.labelstatus)
        self.targetpanel_step1.add(self.progressbar)
        self.emptypanel_step1 = JPanel()
        self.emptypanel_step1.setLayout(BorderLayout())
        self.emptypanel_step1.add(self.labelempty_step1, BorderLayout.WEST)

        # Assembling first step panel components
        self.panel_step1.add(self.titlepanel_step1, BorderLayout.NORTH)
        self.panel_step1.add(self.targetpanel_step1, BorderLayout.WEST)
        self.panel_step1.add(self.emptypanel_step1, BorderLayout.SOUTH)
        self.uiPanelA.setTopComponent(self.panel_step1)

        # Configure second step panel
        self.panel_step2 = JPanel()
        self.panel_step2.setPreferredSize(Dimension(2250, 100))
        self.panel_step2.setBorder(EmptyBorder(10, 10, 10, 10))
        self.panel_step2.setLayout(BorderLayout(15, 15))
        self.titlepanel_step2 = JPanel()
        self.titlepanel_step2.setLayout(BorderLayout())
        self.titlepanel_step2.add(self.labeltitle_step2, BorderLayout.NORTH)
        self.titlepanel_step2.add(self.labelsubtitle_step2)
        self.selectpanel_step2 = JPanel()
        self.selectpanel_step2.add(self.labelip)
        self.selectpanel_step2.add(self.upnpcombo_targets)
        self.selectpanel_step2.add(self.labelupnp)
        self.selectpanel_step2.add(self.upnpcombo_services)
        self.selectpanel_step2.add(self.confirmbutton)
        self.emptypanel_step2 = JPanel()
        self.emptypanel_step2.setLayout(BorderLayout())
        self.emptypanel_step2.add(self.labelempty_step2, BorderLayout.WEST)
        self.emptypanel_step2.add(self.labelNoneServiceFound)

        # Assembling second step panel components
        self.panel_step2.add(self.titlepanel_step2, BorderLayout.NORTH)
        self.panel_step2.add(self.selectpanel_step2, BorderLayout.WEST)
        self.panel_step2.add(self.emptypanel_step2, BorderLayout.SOUTH)
        self.uiPanelB.setTopComponent(self.panel_step2)

        # Configuring third step panel
        self.panel_step3 = JPanel()
        self.panel_step3.setPreferredSize(Dimension(2250, 100))
        self.panel_step3.setBorder(EmptyBorder(10, 10, 10, 10))
        self.panel_step3.setLayout(BorderLayout(15, 15))
        self.titlepanel_step3 = JPanel()
        self.titlepanel_step3.setLayout(BorderLayout())
        self.titlepanel_step3.add(self.labeltitle_step3, BorderLayout.NORTH)
        self.titlepanel_step3.add(self.labelsubtitle_step3)
        self.underpanel_step3 = JPanel()

        underlayout = GroupLayout(self.underpanel_step3)
        self.underpanel_step3.setLayout(underlayout)
        underlayout.setAutoCreateGaps(True)
        underlayout.setAutoCreateContainerGaps(True)
        left2right = underlayout.createSequentialGroup()
        firstcolumn = underlayout.createParallelGroup()
        firstcolumn.addComponent(self.label_step3, GroupLayout.PREFERRED_SIZE,
                                 GroupLayout.PREFERRED_SIZE,
                                 GroupLayout.PREFERRED_SIZE)
        firstcolumn.addComponent(self.labelLANHOST, GroupLayout.PREFERRED_SIZE,
                                 GroupLayout.PREFERRED_SIZE,
                                 GroupLayout.PREFERRED_SIZE)
        firstcolumn.addComponent(self.labelWANCONNECTION,
                                 GroupLayout.PREFERRED_SIZE,
                                 GroupLayout.PREFERRED_SIZE,
                                 GroupLayout.PREFERRED_SIZE)
        secondcolumn = underlayout.createParallelGroup()
        secondcolumn.addComponent(self.labelSOAPnum)
        secondcolumn.addComponent(self.labelLANHOSTnum)
        secondcolumn.addComponent(self.labelWANCONNECTIONnum)
        thirdcolumn = underlayout.createParallelGroup()
        thirdcolumn.addComponent(self.intruderbutton)
        thirdcolumn.addComponent(self.LANrepeaterbutton)
        thirdcolumn.addComponent(self.WANrepeaterbutton)
        left2right.addGroup(firstcolumn)
        left2right.addGroup(secondcolumn)
        left2right.addGroup(thirdcolumn)
        top2bottom = underlayout.createSequentialGroup()
        firstrow = underlayout.createParallelGroup()
        firstrow.addComponent(self.label_step3, GroupLayout.PREFERRED_SIZE,
                              GroupLayout.PREFERRED_SIZE,
                              GroupLayout.PREFERRED_SIZE)
        firstrow.addComponent(self.labelSOAPnum)
        firstrow.addComponent(self.intruderbutton)
        secondrow = underlayout.createParallelGroup()
        secondrow.addComponent(self.labelLANHOST, GroupLayout.PREFERRED_SIZE,
                               GroupLayout.PREFERRED_SIZE,
                               GroupLayout.PREFERRED_SIZE)
        secondrow.addComponent(self.labelLANHOSTnum)
        secondrow.addComponent(self.LANrepeaterbutton)
        thirdrow = underlayout.createParallelGroup()
        thirdrow.addComponent(self.labelWANCONNECTION,
                              GroupLayout.PREFERRED_SIZE,
                              GroupLayout.PREFERRED_SIZE,
                              GroupLayout.PREFERRED_SIZE)
        thirdrow.addComponent(self.labelWANCONNECTIONnum)
        thirdrow.addComponent(self.WANrepeaterbutton)
        top2bottom.addGroup(firstrow)
        top2bottom.addGroup(secondrow)
        top2bottom.addGroup(thirdrow)
        underlayout.setHorizontalGroup(left2right)
        underlayout.setVerticalGroup(top2bottom)

        # Assembling thirdd step panel components
        self.panel_step3.add(self.titlepanel_step3, BorderLayout.NORTH)
        self.panel_step3.add(self.underpanel_step3, BorderLayout.WEST)
        self.uiPanelB.setBottomComponent(self.panel_step3)

        # Assembling the group of all panels
        layout = GroupLayout(self.pluginTab)
        self.pluginTab.setLayout(layout)
        layout.setHorizontalGroup(
            layout.createParallelGroup(GroupLayout.Alignment.LEADING).addGroup(
                layout.createSequentialGroup().addGap(10, 10, 10).addGroup(
                    layout.createParallelGroup(
                        GroupLayout.Alignment.LEADING).addComponent(
                            self.uiTitle).addGap(15, 15, 15).addComponent(
                                self.uiPanelA)).addContainerGap(
                                    26, Short.MAX_VALUE)))
        layout.setVerticalGroup(
            layout.createParallelGroup(GroupLayout.Alignment.LEADING).addGroup(
                layout.createSequentialGroup().addGap(15, 15, 15).addComponent(
                    self.uiTitle).addGap(15, 15, 15).addComponent(
                        self.uiPanelA).addGap(20, 20, 20).addGap(20, 20, 20)))
class JythonGui(object):
    def __init__(self, instructionsURI=""):
        self.instructionsURI = instructionsURI

        self.logger = logging.getLogger("sasi_gridder_gui")
        self.logger.addHandler(logging.StreamHandler())

        def log_fn(msg):
            self.log_msg(msg)

        self.logger.addHandler(FnLogHandler(log_fn))
        self.logger.setLevel(logging.DEBUG)

        self.selected_input_file = None
        self.selected_output_file = None

        self.frame = JFrame("SASI Gridder", defaultCloseOperation=WindowConstants.EXIT_ON_CLOSE)
        self.frame.size = (650, 600)

        self.main_panel = JPanel()
        self.main_panel.layout = BoxLayout(self.main_panel, BoxLayout.Y_AXIS)
        self.frame.add(self.main_panel)

        self.top_panel = JPanel(SpringLayout())
        self.top_panel.alignmentX = Component.CENTER_ALIGNMENT
        self.main_panel.add(self.top_panel)

        self.stageCounter = 1

        def getStageLabel(txt):
            label = JLabel("%s. %s" % (self.stageCounter, txt))
            self.stageCounter += 1
            return label

        # Instructions link.
        self.top_panel.add(getStageLabel("Read the instructions:"))
        instructionsButton = JButton(
            ('<HTML><FONT color="#000099">' "<U>open instructions</U></FONT><HTML>"),
            actionPerformed=self.browseInstructions,
        )
        instructionsButton.setHorizontalAlignment(SwingConstants.LEFT)
        instructionsButton.setBorderPainted(False)
        instructionsButton.setOpaque(False)
        instructionsButton.setBackground(Color.WHITE)
        instructionsButton.setToolTipText(self.instructionsURI)
        self.top_panel.add(instructionsButton)

        # Select input elements.
        self.top_panel.add(getStageLabel("Select an input data folder:"))
        self.top_panel.add(JButton("Select input...", actionPerformed=self.openInputChooser))

        # Select output elements.
        self.top_panel.add(getStageLabel("Specify an output file:"))
        self.top_panel.add(JButton("Specify output...", actionPerformed=self.openOutputChooser))

        # Run elements.
        self.top_panel.add(getStageLabel("Run SASI Gridder: (this might take a hwile"))
        self.run_button = JButton("Run...", actionPerformed=self.runSASIGridder)
        self.top_panel.add(self.run_button)

        SpringUtilities.makeCompactGrid(self.top_panel, self.stageCounter - 1, 2, 6, 6, 6, 6)

        # Progress bar.
        self.progressBar = JProgressBar(0, 100)
        self.main_panel.add(self.progressBar)

        # Log panel.
        self.log_panel = JPanel()
        self.log_panel.alignmentX = Component.CENTER_ALIGNMENT
        self.log_panel.setBorder(EmptyBorder(10, 10, 10, 10))
        self.main_panel.add(self.log_panel)
        self.log_panel.setLayout(BorderLayout())
        self.log = JTextArea()
        self.log.editable = False
        self.logScrollPane = JScrollPane(self.log)
        self.logScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS)
        self.log_panel.add(self.logScrollPane, BorderLayout.CENTER)

        # File selectors
        self.inputChooser = JFileChooser()
        self.inputChooser.fileSelectionMode = JFileChooser.FILES_AND_DIRECTORIES
        self.outputChooser = JFileChooser()
        self.outputChooser.fileSelectionMode = JFileChooser.FILES_ONLY
        defaultOutputFile = os.path.join(System.getProperty("user.home"), "gridded_efforts.csv")
        self.outputChooser.setSelectedFile(File(defaultOutputFile))

        self.frame.setLocationRelativeTo(None)
        self.frame.visible = True

    def browseInstructions(self, event):
        """ Open a browser to the instructions page. """
        browseURI(self.instructionsURI)
        return

    def log_msg(self, msg):
        self.log.append(msg + "\n")
        self.log.setCaretPosition(self.log.getDocument().getLength())

    def openInputChooser(self, event):
        ret = self.inputChooser.showOpenDialog(self.frame)
        if ret == JFileChooser.APPROVE_OPTION:
            self.selected_input_file = self.inputChooser.selectedFile
            self.log_msg("Selected '%s' as input." % self.selected_input_file.path)

    def openOutputChooser(self, event):
        ret = self.outputChooser.showSaveDialog(self.frame)
        if ret == JFileChooser.APPROVE_OPTION:
            self.selected_output_file = self.outputChooser.selectedFile
            self.log_msg("Selected '%s' as output." % self.selected_output_file.path)

    def runSASIGridder(self, event):
        try:
            self.validateParameters()
        except Exception as e:
            self.log_msg("ERROR: '%s'" % e)

        # Run task in a separate thread, so that log
        # messages will be shown as task progresses.
        def run_task():

            self.progressBar.setValue(0)
            self.progressBar.setIndeterminate(True)

            try:
                input_dir = self.selected_input_file.path
                output_path = self.selected_output_file.path

                grid_path = os.path.join(input_dir, "grid", "grid.shp")

                stat_areas_path = os.path.join(input_dir, "stat_areas", "stat_areas.shp")

                raw_efforts_path = os.path.join(input_dir, "raw_efforts.csv")

                gear_mappings_path = os.path.join(input_dir, "gear_mappings.csv")

                gear_mappings = {}
                with open(gear_mappings_path, "rb") as f:
                    r = csv.DictReader(f)
                    for mapping in r:
                        gear_mappings[mapping["trip_type"]] = mapping["gear_code"]

                task = SASIGridderTask(
                    grid_path=grid_path,
                    raw_efforts_path=raw_efforts_path,
                    stat_areas_path=stat_areas_path,
                    output_path=output_path,
                    logger=self.logger,
                    gear_mappings=gear_mappings,
                    effort_limit=None,
                )
                task.call()
            except Exception as e:
                self.logger.exception("Could not complete task")

            self.progressBar.setIndeterminate(False)
            self.progressBar.setValue(100)

        Thread(target=run_task).start()

    def validateParameters(self):
        return True
Example #30
0
def main():
    all_files = currentSelectedItems
    total = len(all_files)
    jprog = JProgressBar(0, total)
    jprog.setStringPainted(True)
    jframe.getContentPane().add(jprog)
    jframe.getContentPane().add(jbutton)
    jframe.setVisible(True)
    try:
        statusLabel.setText("Selected " + str(total) + " items")
        discovered = 0
        for idx, item in enumerate(all_files):
            if cancelled:
                return "User cancelled"
            jprog.setValue(idx)
            statusLabel.setText("Processing %d of %d" % (idx, total))
            md5 = item.digests.md5
            # Item needs an md5 to check against, so move on if there isn't one
            if not md5:
                continue
            response = send_request(md5)
            if not response:
                return
            cm = item.getCustomMetadata()
            if response == "404":
                cm.putText("VirusTotal", "Item md5 not matched in database")
            else:
                data = json.load(response)
                malicious = data["data"]["attributes"]["last_analysis_stats"]["malicious"]
                if malicious > 0:
                    discovered += 1

                cm.putInteger("AVs identifying item as malicious", malicious)
                for scanner, res in data["data"]["attributes"]["last_analysis_results"].iteritems():
                    if res["result"] is not None:
                        cm.putText("VirusTotal " + scanner, res["result"])
                # vHash
                if SET_VHASH and ("vhash" in data["data"]["attributes"]):
                    cm.putText("vHash", data["data"]["attributes"]["vhash"])
                # Import Hash
                if SET_IMPHASH and ("pe_info" in data["data"]["attributes"]) and \
                        ("imphash" in data["data"]["attributes"]["pe_info"]):
                    cm.putText("Import Hash", data["data"]["attributes"]["pe_info"]["imphash"])
                # Authentihash
                if SET_AUTHENTIHASH and ("authentihash" in data["data"]["attributes"]):
                    cm.putText("Authentihash", data["data"]["attributes"]["authentihash"])
                # Crowd sourced yara results
                if SET_YARA and ("crowdsourced_yara_results" in data["data"]["attributes"]):
                    yara_matches = []
                    for yara in data["data"]["attributes"]["crowdsourced_yara_results"]:
                        yara_matches += [yara["rule_name"]]
                    cm.putText("Matched Yara Rules", ", ".join(yara_matches))
                # Virus Total defined tags. Often this can be a list that needs to be looped through
                if SET_TAGS and ("tags" in data["data"]["attributes"]):
                    for tag in data["data"]["attributes"]["tags"]:
                        item.addTag("VirusTotal|" + tag)

                time.sleep(SLEEP_TIME)

        jprog.setValue(total)
        statusLabel.setText("Done")
        return "VirusTotal Search has finished. %d potentially malicious items found from the %d selected." % (discovered, total)

    except Exception:
        import traceback
        print('generic exception: ' + traceback.format_exc())
        return
Example #31
0
class Pipeline():
    def __init__(self):
        #If a swing interface is asked for this will be the JFrame.
        self.frame = None
        #Keeps track of the number of queries processed.
        self.jobCount = 0
        #Keeps track of the query currently being processed.
        self.currentJob = ""
        #Keeps track of the massage to be displayed.
        self.message = 0
        #Messages to be displayed at each stage in the processing of a single query.
        self.messages = [
            "Searching for genes via genemark",
            "Extending genes found via genemark",
            "Searching for intergenic genes", "Removing overlapping genes",
            "Searching for promoters", "Using transterm to find terminators",
            "Removing transcription signals which conflict with genes",
            "Writing Artemis file", "Writing summary file"
        ]
        self.exception = None

    def initializeDisplay(self, queries, swing):
        """
    queries: A list of the fasts files to be processed.
    swing:   If true then updates about progress will be displayed in a swing window, otherwise they will be written to stdout.
    
    Initializes the interface for telling the user about progress in the pipeline.  Queries is used to count the
    number of queries the pipeline will process and to size the swing display(if it is used) so that text
    isn't cutoff at the edge of the window.  The swing display is setup if swing is true.
    """

        self.numJobs = len(queries)
        if swing:
            self.frame = JFrame("Neofelis")
            self.frame.addWindowListener(PipelineWindowAdapter(self))
            contentPane = JPanel(GridBagLayout())
            self.frame.setContentPane(contentPane)
            self.globalLabel = JLabel(max(queries, key=len))
            self.globalProgress = JProgressBar(0, self.numJobs)
            self.currentLabel = JLabel(max(self.messages, key=len))
            self.currentProgress = JProgressBar(0, len(self.messages))
            self.doneButton = JButton(DoneAction(self.frame))
            self.doneButton.setEnabled(False)

            constraints = GridBagConstraints()

            constraints.gridx, constraints.gridy = 0, 0
            constraints.gridwidth, constraints.gridheight = 1, 1
            constraints.weightx = 1
            constraints.fill = GridBagConstraints.HORIZONTAL
            contentPane.add(self.globalLabel, constraints)
            constraints.gridy = 1
            contentPane.add(self.globalProgress, constraints)
            constraints.gridy = 2
            contentPane.add(self.currentLabel, constraints)
            constraints.gridy = 3
            contentPane.add(self.currentProgress, constraints)
            constraints.gridy = 4
            constraints.weightx = 0
            constraints.fill = GridBagConstraints.NONE
            constraints.anchor = GridBagConstraints.LINE_END
            contentPane.add(self.doneButton, constraints)

            self.frame.pack()
            self.frame.setResizable(False)
            self.globalLabel.setText(" ")
            self.currentLabel.setText(" ")
            self.frame.setLocationRelativeTo(None)
            self.frame.setVisible(True)

    def updateProgress(self, job):
        """
    query: Name of the query currently being processed.
    
    This function use used for updating the progress shown in the interface.  If job is not equal to currentJob then
    global progress is incremented and shown and the currentProgress is reset and shown.  If job is equal to currentJob
    then the globalProgress does not change and currentProgress is incremented.
    """
        if self.exception:
            raise self.exception

        if self.frame:
            if job != self.currentJob:
                self.currentProgress.setValue(
                    self.currentProgress.getMaximum())
                self.globalLabel.setText(job)
                self.globalProgress.setValue(self.jobCount)
                print "Processing %s, %.2f%% done" % (
                    job, 100.0 * self.jobCount / self.numJobs)
                self.jobCount += 1
                self.currentJob = job
                self.message = -1
            self.message += 1
            print "    %s, %.2f%% done" % (self.messages[self.message], 100.0 *
                                           self.message / len(self.messages))
            self.currentProgress.setValue(self.message)
            self.currentLabel.setText(self.messages[self.message])
        else:
            if job != self.currentJob:
                print "Processing %s, %.2f%% done" % (
                    job, 100.0 * self.jobCount / self.numJobs)
                self.jobCount += 1
                self.currentJob = job
                self.message = -1
            self.message += 1
            print "    %s, %.2f%% done" % (self.messages[self.message], 100.0 *
                                           self.message / len(self.messages))

    def finished(self):
        """
    This function is to be called at the end of the pipeline.  Informs the user that the pipeline is finished
    and if a swing interface is being used the Done button is enabled.
    """
        print "Processing 100.00% done"
        if self.frame:
            self.globalLabel.setText("Finished")
            self.globalProgress.setValue(self.globalProgress.getMaximum())
            self.currentLabel.setText(" ")
            self.currentProgress.setValue(self.currentProgress.getMaximum())
            self.doneButton.setEnabled(True)
            while self.frame.isVisible():
                pass

    def run(self,
            blastLocation,
            genemarkLocation,
            transtermLocation,
            database,
            eValue,
            matrix,
            minLength,
            scaffoldingDistance,
            ldfCutoff,
            queries,
            swing=False,
            email=""):
        """
    blastLocation:       Directory blast was installed in.
    genemarkLocation:    Directory genemark was installed in.
    transtermLocation:   Directory transterm was installed in.
    database:            Name of the blast database to use.
    eValue:              The e value used whenever a blast search is done.
    matrix:              The matrix to use when running genemark.  If None then genemark is run heuristically.
    minLength:           Minimum length of any genes included in the resulting annotation.
    scaffoldingDistance: The maximum length allowed between genes when contiguous regions of genes are being identified
    ldfCutoff:           Minimum LDF allowed for any promoters included in the resulting annotation
    queries:             A list of faster files to process.
    swing:               If true a swing window will be used to updated the user about the pipeline's progress.
    email:               If this is a non-empty string an email will be sent to the address in the string when the pipeline is done.  The local machine will be used as
                         an SMTP server and this will not work if it isn't.
    
    The main pipeline function.  For every query genemark is used to predict genes, these genes are then extended to any preferable starts.  Then the pipeline searches
    for any intergenic genes(genes between those found by genemark) and these are combined with the extended genemark genes.  Then the genes are pruned to remove
    any undesirable genes found in the intergenic stage.  BPROM and Transterm are used to find promoters and terminators, which are then pruned to remove any
    signals which are inside or too far away from any genes.  Finally, all the remaining genes, promoters, and terminators ar written to an artemis file in the directory
    of the query with the same name but with a .art extension, and .dat and .xls files will be generating describing the blast results of the final genes.
    """
        self.initializeDisplay(queries, swing)

        try:
            for query in queries:
                name = os.path.splitext(query)[0]
                queryDirectory, name = os.path.split(name)

                genome = utils.loadGenome(query)
                swapFileName = "query" + str(id(self)) + ".fas"
                queryFile = open(swapFileName, "w")
                queryFile.write(">" + name + "\n")
                for i in range(0, len(genome), 50):
                    queryFile.write(genome[i:min(i + 50, len(genome))] + "\n")
                queryFile.close()

                self.updateProgress(query)
                initialGenes = genemark.findGenes(swapFileName, name,
                                                  blastLocation, database,
                                                  eValue, genemarkLocation,
                                                  matrix, self)
                #artemis.writeArtemisFile(os.path.splitext(query)[0] + ".genemark.art", genome, initialGenes.values())

                self.updateProgress(query)
                extendedGenes = extend.extendGenes(swapFileName, initialGenes,
                                                   name, blastLocation,
                                                   database, eValue, self)
                #artemis.writeArtemisFile(os.path.splitext(query)[0] + ".extended.art", genome, extendedGenes.values())

                self.updateProgress(query)
                intergenicGenes = intergenic.findIntergenics(
                    swapFileName, extendedGenes, name, minLength,
                    blastLocation, database, eValue, self)
                #artemis.writeArtemisFile(os.path.splitext(query)[0] + ".intergenic.art", genome, intergenicGenes.values())
                genes = {}
                for k, v in extendedGenes.items() + intergenicGenes.items():
                    genes[k] = v

                self.updateProgress(query)
                scaffolded = scaffolds.refineScaffolds(genes,
                                                       scaffoldingDistance)

                self.updateProgress(query)
                initialPromoters = promoters.findPromoters(swapFileName, name)

                self.updateProgress(query)
                initialTerminators = terminators.findTerminators(
                    swapFileName, name, genes.values(), transtermLocation)

                self.updateProgress(query)
                filteredSignals = signals.filterSignals(
                    scaffolded.values(), initialPromoters + initialTerminators)
                filteredPromoters = filter(
                    lambda x: isinstance(x, promoters.Promoter),
                    filteredSignals)
                filteredTerminators = filter(
                    lambda x: isinstance(x, terminators.Terminator),
                    filteredSignals)

                self.updateProgress(query)
                artemis.writeArtemisFile(
                    os.path.splitext(query)[0] + ".art", genome,
                    scaffolded.values(), filteredPromoters,
                    filteredTerminators)

                self.updateProgress(query)
                report.report(name, scaffolded, os.path.splitext(query)[0])

            if email:
                message = MIMEText("Your genome has been annotated.")
                message["Subject"] = "Annotation complete"
                message["From"] = "Neofelis"
                message["To"] = email

                smtp = smtplib.SMTP("tmpl.arizona.edu", 587)
                smtp.ehlo()
                smtp.starttls()
                smtp.ehlo
                smtp.sendmail("Neofelis", [email], message.as_string())
                smtp.close()

            self.finished()
        except PipelineException:
            return
Example #32
0
class Gui(JFrame):
    '''
    classdocs
    '''


    def __init__(self, pP):
        '''
        Constructor
        '''
        self.pP = pP
        self.annotationType = self.pP.getAnnotationType()
        
        self.setTitle("Random Picture Picker")

        #annotation Panel
        annoPanel = JPanel()
        annoPanel.setBorder(BorderFactory.createTitledBorder("Annotations"))
        annoPLayout = GroupLayout(annoPanel)
        annoPanel.setLayout(annoPLayout)
        annoPLayout.setAutoCreateContainerGaps(True)
        annoPLayout.setAutoCreateGaps(True)        

        # dynamic creation of annotation panel
        # yesNoIgnore, int, number, list
        if len(self.pP.getAnnotationType()) == 1:
            self.annoField = JTextField("", 16)
            annoPLayout.setHorizontalGroup(annoPLayout.createParallelGroup().addComponent(self.annoField))
            annoPLayout.setVerticalGroup(annoPLayout.createSequentialGroup().addComponent(self.annoField))
        elif len(self.pP.getAnnotationType()) > 1:
            choices = pP.getAnnotationType()
            print "choices", choices
            choiceBtns = []
            self.annoField = ButtonGroup()
            for c in choices:
                Btn = JRadioButton(c, actionCommand=c)
                self.annoField.add(Btn)
                choiceBtns.append(Btn)
          
            h = annoPLayout.createParallelGroup()
            for b in choiceBtns:
                h.addComponent(b)
            annoPLayout.setHorizontalGroup(h)
            
            v = annoPLayout.createSequentialGroup()
            for b in choiceBtns:
                v.addComponent(b)
            annoPLayout.setVerticalGroup(v)


        # Control Panel
        ctrlPanel = JPanel()
        ctrlPLayout = GroupLayout(ctrlPanel, autoCreateContainerGaps=True, autoCreateGaps=True)
        ctrlPanel.setLayout(ctrlPLayout)
        
        nextImgButton = JButton("Next >", actionPerformed=self.nextPicture)
        prevImgButton = JButton("< Prev", actionPerformed=self.pP.prevPicture)
        quitButton = JButton("Quit", actionPerformed=self.exit)

        ctrlPLayout.setHorizontalGroup(ctrlPLayout.createParallelGroup(GroupLayout.Alignment.CENTER)
                                       .addGroup(ctrlPLayout.createSequentialGroup()
                                                 .addComponent(prevImgButton)
                                                 .addComponent(nextImgButton))
                                       .addComponent(quitButton))
        ctrlPLayout.setVerticalGroup(ctrlPLayout.createSequentialGroup()
                                     .addGroup(ctrlPLayout.createParallelGroup()
                                               .addComponent(prevImgButton)
                                               .addComponent(nextImgButton))
                                     .addComponent(quitButton))
        ctrlPLayout.linkSize(SwingConstants.HORIZONTAL, quitButton)

        
        statusPanel = JPanel()   # contains status information: progress bar
        self.progressBar = JProgressBar()
        self.progressBar.setStringPainted(True)
        self.progressBar.setValue(0)
        statusPanel.add(self.progressBar)
        
        #MainLayout
        mainLayout = GroupLayout(self.getContentPane())
        self.getContentPane().setLayout(mainLayout)
        
        mainLayout.setHorizontalGroup(mainLayout.createParallelGroup(GroupLayout.Alignment.CENTER)
                                    .addComponent(annoPanel)
                                    .addComponent(ctrlPanel)
                                    .addComponent(statusPanel)
                                    )
        mainLayout.setVerticalGroup(mainLayout.createSequentialGroup()
                                    .addComponent(annoPanel)
                                    .addComponent(ctrlPanel)
                                    .addComponent(statusPanel)
                                    )
        mainLayout.linkSize(SwingConstants.HORIZONTAL, annoPanel, ctrlPanel, statusPanel)
         
      
        self.pack()
        self.setVisible(True)
        
        self.pP.nextPicture()
        
    def nextPicture(self, event):
        percent = (float(len(self.pP.usedList))/len(self.pP.pictureList))*100
        self.progressBar.setValue(int(percent))

        self.setAnnotation()
        self.pP.nextPicture()

        #try:
        #    self.setAnnotation()
        #    self.pP.nextPicture()
        #except AttributeError:
        #    print "Please choose something!"
     
    def setAnnotationField(self, a):
        if len(self.pP.getAnnotationType()) > 1:
            [Rbutton.setSelected(True) for Rbutton in self.annoField.getElements() if Rbutton.getActionCommand()==a]
        if len(self.pP.getAnnotationType()) == 1:
            self.annoField.setText(a)
        
    #rename this method to something clearer!    
    def setAnnotation(self):
        if len(self.pP.getAnnotationType()) > 1:
            annotation = self.annoField.getSelection().getActionCommand()
        if len(self.pP.getAnnotationType()) == 1:
            annotation = self.annoField.getText()
            self.annoField.setText(None)
        self.pP.getCurrentPicture().annotate(annotation)
        
    def getAnnotation(self):
        return self.annotation
    
    def exit(self, event):
        self.pP.exit()
        self.dispose()
    def __init__(self, instructionsURI=''):
        self.instructionsURI = instructionsURI

        self.logger = logging.getLogger('sasi_runner_gui')
        self.logger.addHandler(logging.StreamHandler())
        def log_fn(msg):
            self.log_msg(msg)
        self.logger.addHandler(FnLogHandler(log_fn))
        self.logger.setLevel(logging.DEBUG)

        self.selected_input_file = None
        self.selected_output_file = None

        self.frame = JFrame(
            "SASI Runner",
            defaultCloseOperation = WindowConstants.EXIT_ON_CLOSE,
        )
        self.frame.size = (650, 600,)

        self.main_panel = JPanel()
        self.main_panel.layout = BoxLayout(self.main_panel, BoxLayout.Y_AXIS)
        self.frame.add(self.main_panel)

        self.top_panel = JPanel(SpringLayout())
        self.top_panel.alignmentX = Component.CENTER_ALIGNMENT
        self.main_panel.add(self.top_panel)

        self.stageCounter = 1
        def getStageLabel(txt):
            label = JLabel("%s. %s" % (self.stageCounter, txt))
            self.stageCounter += 1
            return label

        # Instructions link.
        self.top_panel.add(getStageLabel("Read the instructions:"))
        instructionsButton = JButton(
            ('<HTML><FONT color="#000099">'
             '<U>open instructions</U></FONT><HTML>'),
            actionPerformed=self.browseInstructions)
        instructionsButton.setHorizontalAlignment(SwingConstants.LEFT);
        instructionsButton.setBorderPainted(False);
        instructionsButton.setOpaque(False);
        instructionsButton.setBackground(Color.WHITE);
        instructionsButton.setToolTipText(self.instructionsURI);
        self.top_panel.add(instructionsButton)

        # 'Select input' elements.
        self.top_panel.add(getStageLabel(
            "Select a SASI .zip file or data folder:"))
        self.top_panel.add(
            JButton("Select input...", actionPerformed=self.openInputChooser))

        # 'Select output' elements.
        self.top_panel.add(getStageLabel("Specify an output file:"))
        self.top_panel.add(
            JButton("Specify output...", actionPerformed=self.openOutputChooser))

        # 'Set result fields' elements.
        result_fields = [
            {'id': 'gear_id', 'label': 'Gear', 'selected': True, 
             'enabled': False}, 
            {'id': 'substrate_id', 'label': 'Substrate', 'selected': True}, 
            {'id': 'energy_id', 'label': 'Energy', 'selected': False},
            {'id': 'feature_id', 'label': 'Feature', 'selected': False}, 
            {'id': 'feature_category_id', 'label': 'Feature Category', 
             'selected': False}
        ]
        self.selected_result_fields = {}
        resolutionLabelPanel = JPanel(GridLayout(0,1))
        resolutionLabelPanel.add(getStageLabel("Set result resolution:"))
        resolutionLabelPanel.add(
            JLabel(("<html><i>This sets the specificity with which<br>"
                    "results will be grouped. Note that enabling<br>"
                    "more fields can *greatly* increase resulting<br>"
                    "output sizes and run times.</i>")))
        #self.top_panel.add(getStageLabel("Set result resolution:"))
        self.top_panel.add(resolutionLabelPanel)
        checkPanel = JPanel(GridLayout(0, 1))
        self.top_panel.add(checkPanel) 
        self.resultFieldCheckBoxes = {}
        for result_field in result_fields:
            self.selected_result_fields.setdefault(
                result_field['id'], result_field['selected'])
            checkBox = JCheckBox(
                result_field['label'], result_field['selected'])
            checkBox.setEnabled(result_field.get('enabled', True))
            checkBox.addItemListener(self)
            checkPanel.add(checkBox)
            self.resultFieldCheckBoxes[checkBox] = result_field

        # 'Run' elements.
        self.top_panel.add(getStageLabel("Run SASI: (this might take a while)"))
        self.run_button = JButton("Run...", actionPerformed=self.runSASI)
        self.top_panel.add(self.run_button)

        SpringUtilities.makeCompactGrid(
            self.top_panel, self.stageCounter - 1, 2, 6, 6, 6, 6)

        # Progress bar.
        self.progressBar = JProgressBar(0, 100)
        self.main_panel.add(self.progressBar)

        # Log panel.
        self.log_panel = JPanel()
        self.log_panel.alignmentX = Component.CENTER_ALIGNMENT
        self.log_panel.setBorder(EmptyBorder(10,10,10,10))
        self.main_panel.add(self.log_panel)
        self.log_panel.setLayout(BorderLayout())
        self.log = JTextArea()
        self.log.editable = False
        self.logScrollPane = JScrollPane(self.log)
        self.logScrollPane.setVerticalScrollBarPolicy(
            JScrollPane.VERTICAL_SCROLLBAR_ALWAYS)
        self.logScrollBar = self.logScrollPane.getVerticalScrollBar()
        self.log_panel.add(self.logScrollPane, BorderLayout.CENTER)

        # File selectors
        self.inputChooser = JFileChooser()
        self.inputChooser.fileSelectionMode = JFileChooser.FILES_AND_DIRECTORIES

        self.outputChooser = JFileChooser()
        defaultOutputFile = os.path.join(System.getProperty("user.home"),
                                         "sasi_project.zip")

        self.outputChooser.setSelectedFile(File(defaultOutputFile));
        self.outputChooser.fileSelectionMode = JFileChooser.FILES_ONLY

        self.frame.setLocationRelativeTo(None)
        self.frame.visible = True
Example #34
0
    def __init__(self, pP):
        '''
        Constructor
        '''
        self.pP = pP
        self.annotationType = self.pP.getAnnotationType()
        
        self.setTitle("Random Picture Picker")

        #annotation Panel
        annoPanel = JPanel()
        annoPanel.setBorder(BorderFactory.createTitledBorder("Annotations"))
        annoPLayout = GroupLayout(annoPanel)
        annoPanel.setLayout(annoPLayout)
        annoPLayout.setAutoCreateContainerGaps(True)
        annoPLayout.setAutoCreateGaps(True)        

        # dynamic creation of annotation panel
        # yesNoIgnore, int, number, list
        if len(self.pP.getAnnotationType()) == 1:
            self.annoField = JTextField("", 16)
            annoPLayout.setHorizontalGroup(annoPLayout.createParallelGroup().addComponent(self.annoField))
            annoPLayout.setVerticalGroup(annoPLayout.createSequentialGroup().addComponent(self.annoField))
        elif len(self.pP.getAnnotationType()) > 1:
            choices = pP.getAnnotationType()
            print "choices", choices
            choiceBtns = []
            self.annoField = ButtonGroup()
            for c in choices:
                Btn = JRadioButton(c, actionCommand=c)
                self.annoField.add(Btn)
                choiceBtns.append(Btn)
          
            h = annoPLayout.createParallelGroup()
            for b in choiceBtns:
                h.addComponent(b)
            annoPLayout.setHorizontalGroup(h)
            
            v = annoPLayout.createSequentialGroup()
            for b in choiceBtns:
                v.addComponent(b)
            annoPLayout.setVerticalGroup(v)


        # Control Panel
        ctrlPanel = JPanel()
        ctrlPLayout = GroupLayout(ctrlPanel, autoCreateContainerGaps=True, autoCreateGaps=True)
        ctrlPanel.setLayout(ctrlPLayout)
        
        nextImgButton = JButton("Next >", actionPerformed=self.nextPicture)
        prevImgButton = JButton("< Prev", actionPerformed=self.pP.prevPicture)
        quitButton = JButton("Quit", actionPerformed=self.exit)

        ctrlPLayout.setHorizontalGroup(ctrlPLayout.createParallelGroup(GroupLayout.Alignment.CENTER)
                                       .addGroup(ctrlPLayout.createSequentialGroup()
                                                 .addComponent(prevImgButton)
                                                 .addComponent(nextImgButton))
                                       .addComponent(quitButton))
        ctrlPLayout.setVerticalGroup(ctrlPLayout.createSequentialGroup()
                                     .addGroup(ctrlPLayout.createParallelGroup()
                                               .addComponent(prevImgButton)
                                               .addComponent(nextImgButton))
                                     .addComponent(quitButton))
        ctrlPLayout.linkSize(SwingConstants.HORIZONTAL, quitButton)

        
        statusPanel = JPanel()   # contains status information: progress bar
        self.progressBar = JProgressBar()
        self.progressBar.setStringPainted(True)
        self.progressBar.setValue(0)
        statusPanel.add(self.progressBar)
        
        #MainLayout
        mainLayout = GroupLayout(self.getContentPane())
        self.getContentPane().setLayout(mainLayout)
        
        mainLayout.setHorizontalGroup(mainLayout.createParallelGroup(GroupLayout.Alignment.CENTER)
                                    .addComponent(annoPanel)
                                    .addComponent(ctrlPanel)
                                    .addComponent(statusPanel)
                                    )
        mainLayout.setVerticalGroup(mainLayout.createSequentialGroup()
                                    .addComponent(annoPanel)
                                    .addComponent(ctrlPanel)
                                    .addComponent(statusPanel)
                                    )
        mainLayout.linkSize(SwingConstants.HORIZONTAL, annoPanel, ctrlPanel, statusPanel)
         
      
        self.pack()
        self.setVisible(True)
        
        self.pP.nextPicture()
Example #35
0
    def __init__(self, imgData):
        n = imgData.size()
        win = JFrame("Point Marker Panel")
        win.setPreferredSize(Dimension(350, 590))
        win.setSize(win.getPreferredSize())
        pan = JPanel()
        pan.setLayout(BoxLayout(pan, BoxLayout.Y_AXIS))
        win.getContentPane().add(pan)

        progressPanel = JPanel()
        progressPanel.setLayout(BoxLayout(progressPanel, BoxLayout.Y_AXIS))
        positionBar = JProgressBar()
        positionBar.setMinimum(0)
        positionBar.setMaximum(n)
        positionBar.setStringPainted(True)
        progressPanel.add(Box.createGlue())
        progressPanel.add(positionBar)

        progressBar = JProgressBar()
        progressBar.setMinimum(0)
        progressBar.setMaximum(n)
        progressBar.setStringPainted(True)
        progressPanel.add(progressBar)
        progressPanel.setBorder(BorderFactory.createEmptyBorder(0, 10, 0, 10))
        pan.add(progressPanel)

        pan.add(Box.createRigidArea(Dimension(5, 5)))
        savePanel = JPanel()
        savePanel.setLayout(BoxLayout(savePanel, BoxLayout.Y_AXIS))
        saveMessageLabel = JLabel("<html><u>Save Often</u></html>")
        savePanel.add(saveMessageLabel)
        savePanel.setAlignmentX(Component.CENTER_ALIGNMENT)
        savePanel.setBorder(BorderFactory.createEmptyBorder(0, 10, 0, 10))
        pan.add(savePanel)
        # pan.add(saveMessageLabel)

        pan.add(Box.createRigidArea(Dimension(5, 5)))
        calPanel = JPanel()
        calPanel.setLayout(BoxLayout(calPanel, BoxLayout.Y_AXIS))
        calPanelIn = JPanel()
        calPanelIn.setLayout(BoxLayout(calPanelIn, BoxLayout.X_AXIS))
        pixelSizeText = JTextField(12)
        pixelSizeText.setHorizontalAlignment(JTextField.RIGHT)
        # pixelSizeText.setMaximumSize(pixelSizeText.getPreferredSize())
        unitText = JTextField(10)
        # unitText.setMaximumSize(unitText.getPreferredSize())
        pixelSizeText.setText("Enter Pixel Size Here")
        calPanelIn.add(pixelSizeText)
        unitText.setText("Unit")
        calPanelIn.add(unitText)
        calPanelIn.setAlignmentX(Component.CENTER_ALIGNMENT)
        calPanelIn.setBorder(
            BorderFactory.createTitledBorder("Custom Calibration"))
        calPanel.add(calPanelIn)
        calPanelIn.setAlignmentX(Component.CENTER_ALIGNMENT)
        calPanel.setBorder(BorderFactory.createEmptyBorder(0, 10, 0, 10))
        pan.add(calPanel)

        pan.add(Box.createRigidArea(Dimension(5, 5)))
        helpPanel = JPanel()
        helpPanel.setLayout(BoxLayout(helpPanel, BoxLayout.Y_AXIS))
        helpLable = JLabel("<html><ul>\
                            <li>Focus on Image Window</li>\
                            <li>Select multi-point Tool</li>\
                            <li>Click to Draw Points</li>\
                            <li>Drag to Move Points</li>\
                            <li>\"Alt\" + Click to Erase Points</li>\
                            <li>Optional: Customize Calibration Above\
                                 and Refresh Images\
                                (won't be written to files)</li>\
                            </html>")
        helpLable.setBorder(BorderFactory.createTitledBorder("Usage"))
        keyTagOpen = "<span style=\"background-color: #FFFFFF\"><b><kbd>"
        keyTagClose = "</kbd></b></span>"
        keyLable = JLabel("<html><ul>\
                            <li>Next Image --- "                                                 + keyTagOpen + "&lt" + \
                                keyTagClose + "</li>\
                            <li>Previous Image --- "                                                     + keyTagOpen + ">" + \
                                keyTagClose + "</li>\
                            <li>Save --- "                                           + keyTagOpen + "`" + keyTagClose + \
                                " (upper-left to TAB key)</li>\
                            <li>Next Unmarked Image --- "                                                          + keyTagOpen + \
                                "TAB" + keyTagClose + "</li></ul>\
                            </html>"                                    )
        keyLable.setBorder(
            BorderFactory.createTitledBorder("Keyboard Shortcuts"))
        helpPanel.add(helpLable)
        helpPanel.add(keyLable)
        helpPanel.setAlignmentX(Component.CENTER_ALIGNMENT)
        helpPanel.setBorder(BorderFactory.createEmptyBorder(0, 10, 0, 10))
        pan.add(helpPanel)

        # pan.add(Box.createRigidArea(Dimension(0, 10)))
        infoPanel = JPanel()
        infoPanel.setLayout(BoxLayout(infoPanel, BoxLayout.Y_AXIS))
        infoLabel = JLabel()
        infoLabel.setBorder(BorderFactory.createTitledBorder("Project Info"))
        infoPanel.add(infoLabel)
        infoPanel.setAlignmentX(Component.CENTER_ALIGNMENT)
        infoPanel.setBorder(BorderFactory.createEmptyBorder(0, 10, 0, 10))
        pan.add(infoPanel)

        win.setVisible(True)

        self.imgData = imgData
        self.win = win
        # self.progressPanel = progressPanel
        self.positionBar = positionBar
        self.progressBar = progressBar
        self.saveMessageLabel = saveMessageLabel
        self.infoLabel = infoLabel
        self.pixelSizeText = pixelSizeText
        self.unitText = unitText
        self.update()
    def loadPanel(self):
        panel = JPanel()

        panel.setLayout(BoxLayout(panel, BoxLayout.Y_AXIS))

        bottomButtonBarPanel = JPanel()
        bottomButtonBarPanel.setLayout(
            BoxLayout(bottomButtonBarPanel, BoxLayout.X_AXIS))
        bottomButtonBarPanel.setAlignmentX(1.0)

        self.runButton = JButton("Run", actionPerformed=self.start)
        self.cancelButton = JButton("Close", actionPerformed=self.cancel)

        bottomButtonBarPanel.add(Box.createHorizontalGlue())
        bottomButtonBarPanel.add(self.runButton)
        bottomButtonBarPanel.add(self.cancelButton)

        # Dimension(width,height)
        bottom = JPanel()
        bottom.setLayout(BoxLayout(bottom, BoxLayout.X_AXIS))
        bottom.setAlignmentX(1.0)

        self.progressBar = JProgressBar()
        self.progressBar.setIndeterminate(False)
        self.progressBar.setMaximum(100)
        self.progressBar.setValue(0)

        bottom.add(self.progressBar)

        self.statusTextArea = JTextArea()
        self.statusTextArea.setEditable(False)
        scrollPane = JScrollPane(self.statusTextArea)
        scrollPanel = JPanel()
        scrollPanel.setLayout(BoxLayout(scrollPanel, BoxLayout.X_AXIS))
        scrollPanel.setAlignmentX(1.0)
        scrollPanel.add(scrollPane)

        panel.add(scrollPanel)
        panel.add(bottomButtonBarPanel)
        panel.add(bottom)

        self.add(panel)
        self.setTitle("Determine Session Cookie(s)")
        self.setSize(450, 300)
        self.setLocationRelativeTo(None)
        self.setVisible(True)

        original_request_bytes = self.selected_message.getRequest()
        http_service = self.selected_message.getHttpService()
        helpers = self.callbacks.getHelpers()
        request_info = helpers.analyzeRequest(http_service,
                                              original_request_bytes)
        parameters = request_info.getParameters()
        cookie_parameters = [
            parameter for parameter in parameters
            if parameter.getType() == IParameter.PARAM_COOKIE
        ]
        num_requests_needed = len(cookie_parameters) + 2
        self.statusTextArea.append(
            "This may require up to " + str(num_requests_needed) +
            " requests to be made. Hit 'Run' to begin.\n")
class MenueFrame(JFrame, ActionListener, WindowFocusListener): # should extend JFrame
    def __init__(self):
        self.mainDir = ""

        self.setTitle("Dots Quality Check")
        self.setSize(250, 300)
        self.setLocation(20,120)
        self.addWindowFocusListener(self)
        
        self.Panel = JPanel(GridLayout(0,1))
        self.add(self.Panel)
        self.openNextButton = JButton("Open Next Random", actionPerformed=self.openRandom)
        self.Panel.add(self.openNextButton)
        self.saveButton = JButton("Save", actionPerformed=self.save, enabled=False)
        self.Panel.add(self.saveButton)
        self.cropButton = JButton("Crop values from here", actionPerformed=self.cropVals)
        self.Panel.add(self.cropButton)
        self.DiscardButton = JButton("Discard cell", actionPerformed=self.discardCell)
        self.Panel.add(self.DiscardButton)
        self.quitButton = JButton("Quit script",actionPerformed=self.quit)
        self.Panel.add(self.quitButton)

        annoPanel = JPanel()
        #add gridlayout
        self.wtRButton = JRadioButton("wt", actionCommand="wt")
        self.wtRButton.addActionListener(self)
        self.defectRButton = JRadioButton("Defect", actionCommand="defect")
        self.defectRButton.addActionListener(self)
        annoPanel.add(self.wtRButton)
        annoPanel.add(self.defectRButton)
        self.aButtonGroup = ButtonGroup()
        self.aButtonGroup.add(self.wtRButton)
        self.aButtonGroup.add(self.defectRButton)
      
        self.Panel.add(annoPanel)

        self.ProgBar = JProgressBar()
        self.ProgBar.setStringPainted(True)
        self.ProgBar.setValue(0)
        self.Panel.add(self.ProgBar)

        self.pathLabel = JLabel("-- No main directory chosen --")
        self.pathLabel.setHorizontalAlignment( SwingConstants.CENTER )
        self.Panel.add(self.pathLabel)
      
        WindowManager.addWindow(self)
        self.show()

    # - - - -   B U T T O N   M E T H O D S  - - - -
    # - - - - - -  - - - - - - - - - - - - - - - - -
    def openRandom(self, event):      # when click here: get random cell and meas.measure(csv, tif, savePath)
        if self.mainDir == "":
            self.mainDir = DirectoryChooser("Random QC - Please choose main directory containing ctrl and test folders").getDirectory()
            self.pathLabel.setText("MainDir: " + os.path.basename(os.path.split(self.mainDir)[0]))
        try:
            # should be complete disposal!
            self.cT.closeWindows()
        finally:
            inFiles = glob.glob(os.path.join(self.mainDir, "*", G_OPENSUBDIR, "val_*.csv"))  # glob.glob returns list of paths
            uncheckedCells = [cell(csvPath) for csvPath in inFiles if cell(csvPath).processed == False]
            if len(uncheckedCells) > 0:
                self.cell = random.choice(uncheckedCells)
                #update progressbar
                self.ProgBar.setMaximum(len(inFiles)-1)
                self.ProgBar.setValue(len(inFiles)-len(uncheckedCells))
                # open imp and resultstable
                self.cT = correctionTable(self.cell, self) #self, openPath_csv, mF
                self.RBActionListener.setCell(self.cell)
                # delete previous Radiobutton annotation
                self.wtRButton.setSelected(False)
                self.defectRButton.setSelected(True)
            else:
                print "All cells measured!"

    def save(self, event):
        savepath = self.cell.getQcCsvPath()
        anaphase = self.cell.getAnOn()
        timeInterval = self.cT.getImp().getCalibration().frameInterval
        annotation = self.getAnnotation()
        position = str(self.cell.position)
        cellIndex = str(self.cell.cellNo)
        if not os.path.exists(os.path.split(savepath)[0]): # check if save folder present.
            os.makedirs(os.path.split(savepath)[0]) # create save folder, if not present
        f = open(savepath, "w")
        # Position Cell Phenotype Frame Time AnOn Distance ch0x ch0y ch0z ch0vol ch1x ch1y ch1z ch1vol
        f.write("Position,Cell,Phenotype,Frame,Time,Anaphase,Distance,ch0x,ch0y,ch0z,ch0vol,ch1x,ch1y,ch1z,ch1vol\n")
        for i in range(self.cT.getLineCount()):
            frame, distance, a = self.cT.getLine(i).split("\t")
            corrFrame = str(int(frame)-int(anaphase))
            time = "%.f" % (round(timeInterval) * int(corrFrame))
            if distance == "NA":
                ch0x, ch0y, ch0z, ch0vol, ch1x, ch1y, ch1z, ch1vol = ("NA," * 7 + "NA\n").split(",")
            else:
                ch0x, ch0y, ch0z, ch0vol, ch1x, ch1y, ch1z, ch1vol = self.cT.getXYZtable()[i]
            f.write(position+","+cellIndex+","+annotation+","+corrFrame+","+time+","+anaphase+","+distance+","+ch0x+","+ch0y+","+ch0z+","+ch0vol+","+ch1x+","+ch1y+","+ch1z+","+ch1vol)
        f.close()
        print "Successfully saved!"

    def cropVals(self, event): #"this function deletes all values with frame > current cursor"   
        for line in range(self.cT.getSelectionEnd(), self.cT.getLineCount(), 1):
            frame, distance, AOCol = self.cT.getLine(line).split("\t")
            self.cT.setLine(line, frame + "\tNA" + "\t" + AOCol)

    def discardCell(self, event):
        if not os.path.exists(os.path.split(self.cell.getQcCsvPath() )[0]): # check if save folder present.
            os.makedirs(os.path.split(self.cell.getQcCsvPath() )[0]) # create save folder, if not present.
        f = open(self.cell.getQcCsvPath() ,"w")
        # Write dummy header. Position Cell Phenotype Frame Time AnOn Distance ch0x ch0y ch0z ch0vol ch1x ch1y ch1z ch1vol
        f.write("Position,Cell,Phenotype,Frame,Time,AnOn,Distance,ch0x,ch0y,ch0z,ch0vol,ch1x,ch1y,ch1z,ch1vol\n")
        f.close()
        print "Discarded cell - saved dummy" 

    def quit(self, event):
        try:
            self.cT.closeWindows()
        finally:
            WindowManager.removeWindow(self)
            self.dispose()

    # Methods implementing ActionListener interfaces:
    def actionPerformed(self, e):
        # this function is called when RadioButtons are changed
        self.cell.annotate( e.getSource().getActionCommand() )
        self.setSaveActive()

    def windowGainedFocus(self, e):
        pass

    def windowLostFocus(self, e):
        pass
        

    # - - - - - - - - - - - - -
    # - get and set methods - -
    # - - - - - - - - - - - - -
    def getAnnotation(self):
        return self.aButtonGroup.getSelection().getActionCommand()

    def getMainDir(self):
        return self.mainDir

    def setSaveActive(self):
        if (self.cell.getAnnotation() != None and self.cell.getAnOn() != None):
            self.saveButton.setEnabled(True)
            self.show()

    def setSaveInactive(self):
        self.saveButton.setEnabled(False)
        self.show()

    def setMainDir(self, path):
        self.mainDir = path
        self.pathLabel.setText("MainDir: " + os.path.basename(os.path.split(self.mainDir)[0]))