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()
def initUI(self): basic = JPanel() basic.setLayout(BoxLayout(basic, BoxLayout.Y_AXIS)) self.add(basic) basic.add(Box.createVerticalGlue()) bottom = JPanel() bottom.setAlignmentX(1.0) bottom.setLayout(BoxLayout(bottom, BoxLayout.X_AXIS)) #okButton = JButton("OK", actionPerformed=self.onQuit) self.text_area = JTextArea(editable = False, wrapStyleWord = True, lineWrap = True,) basic.add(self.text_area) self.text_area.text=str(config.DHOSTS) closeButton = JButton(u"Close 关闭", actionPerformed=self.onQuit) #bottom.add(okButton) bottom.add(Box.createRigidArea(Dimension(5, 0))) bottom.add(closeButton) bottom.add(Box.createRigidArea(Dimension(15, 0))) basic.add(bottom) basic.add(Box.createRigidArea(Dimension(0, 15))) self.setTitle(u"A DNS Proxy using TCP...一个使用TCP协议的DNS代理") self.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) self.setSize(500, 300) self.setLocationRelativeTo(None) self.setVisible(True)
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()
def createPanel(scroll=False, ptop=0, pleft=0, pbottom=0, pright=0): panel = JPanel() panel.setLayout(BoxLayout(panel, BoxLayout.PAGE_AXIS)) panel.setAlignmentX(Component.LEFT_ALIGNMENT) panel.setBorder(EmptyBorder(ptop, pleft, pbottom, pright)) # if scroll: # scrollpane = JScrollPane(panel) # scrollpane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED) # scrollpane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER) # return JPanel().add(scrollpane) return panel
def __init__(self, parent, title, modal, app): border = BorderFactory.createEmptyBorder(5, 7, 5, 7) self.getContentPane().setBorder(border) self.setLayout(BoxLayout(self.getContentPane(), BoxLayout.Y_AXIS)) #Intro falsePositivePng = File.separator.join( [app.SCRIPTDIR, "images", "icons", "not_error36.png"]) introLbl = JMultilineLabel( app.strings.getString("manual_false_positives_info")) introLbl.setMaxWidth(600) #Table table = JTable() columns = [ app.strings.getString("Tool"), app.strings.getString("Check"), app.strings.getString("Error_id"), app.strings.getString("OSM_id") ] self.tableModel = MyTableModel([], columns) table.setModel(self.tableModel) scrollPane = JScrollPane(table) scrollPane.setAlignmentX(0.0) #OK button btnPanel = JPanel(FlowLayout(FlowLayout.CENTER)) okBtn = JButton("OK", ImageProvider.get("ok"), actionPerformed=self.on_okBtn_clicked) btnPanel.add(okBtn) btnPanel.setAlignmentX(0.0) #Layout headerPnl = JPanel() headerPnl.setLayout(BoxLayout(headerPnl, BoxLayout.X_AXIS)) headerPnl.add(JLabel(ImageIcon(falsePositivePng))) headerPnl.add(Box.createRigidArea(Dimension(10, 0))) headerPnl.add(introLbl) headerPnl.setAlignmentX(0.0) self.add(headerPnl) self.add(Box.createRigidArea(Dimension(0, 10))) self.add(scrollPane) self.add(Box.createRigidArea(Dimension(0, 10))) self.add(btnPanel) self.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE) self.pack()
def __init__(self, parent, title, modal, app): border = BorderFactory.createEmptyBorder(5, 7, 5, 7) self.getContentPane().setBorder(border) self.setLayout(BoxLayout(self.getContentPane(), BoxLayout.Y_AXIS)) #Intro falsePositivePng = File.separator.join([app.SCRIPTDIR, "images", "icons", "not_error36.png"]) introLbl = JMultilineLabel(app.strings.getString("manual_false_positives_info")) introLbl.setMaxWidth(600) #Table table = JTable() columns = [app.strings.getString("Tool"), app.strings.getString("Check"), app.strings.getString("Error_id"), app.strings.getString("OSM_id")] self.tableModel = MyTableModel([], columns) table.setModel(self.tableModel) scrollPane = JScrollPane(table) scrollPane.setAlignmentX(0.0) #OK button btnPanel = JPanel(FlowLayout(FlowLayout.CENTER)) okBtn = JButton("OK", ImageProvider.get("ok"), actionPerformed=self.on_okBtn_clicked) btnPanel.add(okBtn) btnPanel.setAlignmentX(0.0) #Layout headerPnl = JPanel() headerPnl.setLayout(BoxLayout(headerPnl, BoxLayout.X_AXIS)) headerPnl.add(JLabel(ImageIcon(falsePositivePng))) headerPnl.add(Box.createRigidArea(Dimension(10, 0))) headerPnl.add(introLbl) headerPnl.setAlignmentX(0.0) self.add(headerPnl) self.add(Box.createRigidArea(Dimension(0, 10))) self.add(scrollPane) self.add(Box.createRigidArea(Dimension(0, 10))) self.add(btnPanel) self.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE) self.pack()
def getUiComponent(self): self.panel = JPanel() self.panel.setLayout(BoxLayout(self.panel, BoxLayout.PAGE_AXIS)) self.uiCommandLine = JPanel() self.uiCommandLine.setLayout( BoxLayout(self.uiCommandLine, BoxLayout.LINE_AXIS)) self.uiCommandLine.setAlignmentX(JPanel.LEFT_ALIGNMENT) self.uiCommandLine.add(JLabel("Command line for local search: ")) self.uiCommand = JTextField(40) self.uiCommand.setMaximumSize(self.uiCommand.getPreferredSize()) self.uiCommandLine.add(self.uiCommand) self.panel.add(self.uiCommandLine) uiOptionsLine = JPanel() uiOptionsLine.setLayout(BoxLayout(uiOptionsLine, BoxLayout.LINE_AXIS)) uiOptionsLine.setAlignmentX(JPanel.LEFT_ALIGNMENT) self.uiHaveIBeenPwnd = JCheckBox("haveibeenpwned") uiOptionsLine.add(self.uiHaveIBeenPwnd) uiOptionsLine.add(Box.createRigidArea(Dimension(10, 0))) self.uiLocalCheck = JCheckBox("Local check") uiOptionsLine.add(self.uiLocalCheck) uiOptionsLine.add(Box.createRigidArea(Dimension(10, 0))) self.panel.add(uiOptionsLine) self.panel.add(Box.createRigidArea(Dimension(0, 10))) uiButtonsLine = JPanel() uiButtonsLine.setLayout(BoxLayout(uiButtonsLine, BoxLayout.LINE_AXIS)) uiButtonsLine.setAlignmentX(JPanel.LEFT_ALIGNMENT) uiButtonsLine.add(JButton("Apply", actionPerformed=self.applyConfigUI)) uiButtonsLine.add(JButton("Reset", actionPerformed=self.resetConfigUI)) self.panel.add(uiButtonsLine) self.uiAbout = JPanel() self.uiAbout.setLayout(BoxLayout(self.uiAbout, BoxLayout.LINE_AXIS)) self.uiAbout.setAlignmentX(JPanel.LEFT_ALIGNMENT) self.uiAbout.add( JLabel( "<html><a href=\"https://twitter.com/_chipik\">https://twitter.com/_chipik</a></html>" )) self.panel.add(self.uiAbout) self.resetConfigUI(None) return self.panel
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 __init__(self, parent, title, modal, app): from java.awt import CardLayout self.app = app border = BorderFactory.createEmptyBorder(5, 7, 7, 7) self.getContentPane().setBorder(border) self.setLayout(BoxLayout(self.getContentPane(), BoxLayout.Y_AXIS)) self.FAVAREALAYERNAME = "Favourite zone editing" info = JLabel(self.app.strings.getString("Create_a_new_favourite_zone")) info.setAlignmentX(Component.LEFT_ALIGNMENT) #Name nameLbl = JLabel(self.app.strings.getString("fav_zone_name")) self.nameTextField = JTextField(20) self.nameTextField.setMaximumSize(self.nameTextField.getPreferredSize()) self.nameTextField.setToolTipText(self.app.strings.getString("fav_zone_name_tooltip")) namePanel = JPanel() namePanel.setLayout(BoxLayout(namePanel, BoxLayout.X_AXIS)) namePanel.add(nameLbl) namePanel.add(Box.createHorizontalGlue()) namePanel.add(self.nameTextField) #Country countryLbl = JLabel(self.app.strings.getString("fav_zone_country")) self.countryTextField = JTextField(20) self.countryTextField.setMaximumSize(self.countryTextField.getPreferredSize()) self.countryTextField.setToolTipText(self.app.strings.getString("fav_zone_country_tooltip")) countryPanel = JPanel() countryPanel.setLayout(BoxLayout(countryPanel, BoxLayout.X_AXIS)) countryPanel.add(countryLbl) countryPanel.add(Box.createHorizontalGlue()) countryPanel.add(self.countryTextField) #Type modeLbl = JLabel(self.app.strings.getString("fav_zone_type")) RECTPANEL = "rectangle" POLYGONPANEL = "polygon" BOUNDARYPANEL = "boundary" self.modesStrings = [RECTPANEL, POLYGONPANEL, BOUNDARYPANEL] modesComboModel = DefaultComboBoxModel() for i in (self.app.strings.getString("rectangle"), self.app.strings.getString("delimited_by_a_closed_way"), self.app.strings.getString("delimited_by_an_administrative_boundary")): modesComboModel.addElement(i) self.modesComboBox = JComboBox(modesComboModel, actionListener=self, editable=False) #- Rectangle self.rectPanel = JPanel() self.rectPanel.setLayout(BoxLayout(self.rectPanel, BoxLayout.Y_AXIS)) capturePane = JPanel() capturePane.setLayout(BoxLayout(capturePane, BoxLayout.X_AXIS)) capturePane.setAlignmentX(Component.LEFT_ALIGNMENT) josmP = JPanel() self.captureRBtn = JRadioButton(self.app.strings.getString("capture_area")) self.captureRBtn.addActionListener(self) self.captureRBtn.setSelected(True) self.bboxFromJosmBtn = JButton(self.app.strings.getString("get_current_area"), actionPerformed=self.on_bboxFromJosmBtn_clicked) self.bboxFromJosmBtn.setToolTipText(self.app.strings.getString("get_capture_area_tooltip")) josmP.add(self.bboxFromJosmBtn) capturePane.add(self.captureRBtn) capturePane.add(Box.createHorizontalGlue()) capturePane.add(self.bboxFromJosmBtn) manualPane = JPanel() manualPane.setLayout(BoxLayout(manualPane, BoxLayout.X_AXIS)) manualPane.setAlignmentX(Component.LEFT_ALIGNMENT) self.manualRBtn = JRadioButton(self.app.strings.getString("use_this_bbox")) self.manualRBtn.addActionListener(self) self.bboxTextField = JTextField(20) self.bboxTextField.setMaximumSize(self.bboxTextField.getPreferredSize()) self.bboxTextField.setToolTipText(self.app.strings.getString("fav_bbox_tooltip")) self.bboxTextFieldDefaultBorder = self.bboxTextField.getBorder() self.bboxTextField.getDocument().addDocumentListener(TextListener(self)) manualPane.add(self.manualRBtn) manualPane.add(Box.createHorizontalGlue()) manualPane.add(self.bboxTextField) group = ButtonGroup() group.add(self.captureRBtn) group.add(self.manualRBtn) previewPane = JPanel() previewPane.setLayout(BoxLayout(previewPane, BoxLayout.X_AXIS)) previewPane.setAlignmentX(Component.LEFT_ALIGNMENT) bboxPreviewInfo = JTextField(self.app.strings.getString("coordinates"), editable=0, border=None) bboxPreviewInfo.setMaximumSize(bboxPreviewInfo.getPreferredSize()) self.bboxPreviewTextField = JTextField(20, editable=0, border=None) self.bboxPreviewTextField.setMaximumSize(self.bboxPreviewTextField.getPreferredSize()) previewPane.add(bboxPreviewInfo) previewPane.add(Box.createHorizontalGlue()) previewPane.add(self.bboxPreviewTextField) self.rectPanel.add(capturePane) self.rectPanel.add(Box.createRigidArea(Dimension(0, 10))) self.rectPanel.add(manualPane) self.rectPanel.add(Box.createRigidArea(Dimension(0, 20))) self.rectPanel.add(previewPane) #- Polygon (closed way) drawn by hand self.polygonPanel = JPanel(BorderLayout()) self.polygonPanel.setLayout(BoxLayout(self.polygonPanel, BoxLayout.Y_AXIS)) polyInfo = JLabel("<html>%s</html>" % self.app.strings.getString("polygon_info")) polyInfo.setFont(polyInfo.getFont().deriveFont(Font.ITALIC)) polyInfo.setAlignmentX(Component.LEFT_ALIGNMENT) editPolyPane = JPanel() editPolyPane.setAlignmentX(Component.LEFT_ALIGNMENT) editPolyBtn = JButton(self.app.strings.getString("create_fav_layer"), actionPerformed=self.create_new_zone_editing_layer) editPolyBtn.setToolTipText(self.app.strings.getString("create_fav_layer_tooltip")) editPolyPane.add(editPolyBtn) self.polygonPanel.add(polyInfo) self.polygonPanel.add(Box.createRigidArea(Dimension(0, 15))) self.polygonPanel.add(editPolyPane) self.polygonPanel.add(Box.createRigidArea(Dimension(0, 15))) #- Administrative Boundary self.boundaryPanel = JPanel() self.boundaryPanel.setLayout(BoxLayout(self.boundaryPanel, BoxLayout.Y_AXIS)) boundaryInfo = JLabel("<html>%s</html>" % app.strings.getString("boundary_info")) boundaryInfo.setFont(boundaryInfo.getFont().deriveFont(Font.ITALIC)) boundaryInfo.setAlignmentX(Component.LEFT_ALIGNMENT) boundaryTagsPanel = JPanel(GridLayout(3, 3, 5, 5)) boundaryTagsPanel.setAlignmentX(Component.LEFT_ALIGNMENT) boundaryTagsPanel.add(JLabel("name =")) self.nameTagTextField = JTextField(20) boundaryTagsPanel.add(self.nameTagTextField) boundaryTagsPanel.add(JLabel("admin_level =")) self.adminLevelTagTextField = JTextField(20) self.adminLevelTagTextField.setToolTipText(self.app.strings.getString("adminLevel_tooltip")) boundaryTagsPanel.add(self.adminLevelTagTextField) boundaryTagsPanel.add(JLabel(self.app.strings.getString("other_tag"))) self.optionalTagTextField = JTextField(20) self.optionalTagTextField.setToolTipText("key=value") boundaryTagsPanel.add(self.optionalTagTextField) downloadBoundariesPane = JPanel() downloadBoundariesPane.setAlignmentX(Component.LEFT_ALIGNMENT) downloadBoundariesBtn = JButton(self.app.strings.getString("download_boundary"), actionPerformed=self.on_downloadBoundariesBtn_clicked) downloadBoundariesBtn.setToolTipText(self.app.strings.getString("download_boundary_tooltip")) downloadBoundariesPane.add(downloadBoundariesBtn) self.boundaryPanel.add(boundaryInfo) self.boundaryPanel.add(Box.createRigidArea(Dimension(0, 15))) self.boundaryPanel.add(boundaryTagsPanel) self.boundaryPanel.add(Box.createRigidArea(Dimension(0, 10))) self.boundaryPanel.add(downloadBoundariesPane) self.editingPanels = {"rectangle": self.rectPanel, "polygon": self.polygonPanel, "boundary": self.boundaryPanel} #Main buttons self.okBtn = JButton(self.app.strings.getString("OK"), ImageProvider.get("ok"), actionPerformed=self.on_okBtn_clicked) self.cancelBtn = JButton(self.app.strings.getString("cancel"), ImageProvider.get("cancel"), actionPerformed=self.close_dialog) self.previewBtn = JButton(self.app.strings.getString("Preview_zone"), actionPerformed=self.on_previewBtn_clicked) self.previewBtn.setToolTipText(self.app.strings.getString("preview_zone_tooltip")) okBtnSize = self.okBtn.getPreferredSize() viewBtnSize = self.previewBtn.getPreferredSize() viewBtnSize.height = okBtnSize.height self.previewBtn.setPreferredSize(viewBtnSize) #layout self.add(info) self.add(Box.createRigidArea(Dimension(0, 15))) namePanel.setAlignmentX(Component.LEFT_ALIGNMENT) self.add(namePanel) self.add(Box.createRigidArea(Dimension(0, 15))) countryPanel.setAlignmentX(Component.LEFT_ALIGNMENT) self.add(countryPanel) self.add(Box.createRigidArea(Dimension(0, 15))) modeLbl.setAlignmentX(Component.LEFT_ALIGNMENT) self.add(modeLbl) self.add(Box.createRigidArea(Dimension(0, 5))) self.add(self.modesComboBox) self.modesComboBox.setAlignmentX(Component.LEFT_ALIGNMENT) self.add(Box.createRigidArea(Dimension(0, 15))) self.configPanel = JPanel(CardLayout()) self.configPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)) self.configPanel.add(self.rectPanel, RECTPANEL) self.configPanel.add(self.polygonPanel, POLYGONPANEL) self.configPanel.add(self.boundaryPanel, BOUNDARYPANEL) self.configPanel.setAlignmentX(Component.LEFT_ALIGNMENT) self.add(self.configPanel) buttonsPanel = JPanel() buttonsPanel.add(self.okBtn) buttonsPanel.add(self.cancelBtn) buttonsPanel.add(self.previewBtn) buttonsPanel.setAlignmentX(Component.LEFT_ALIGNMENT) self.add(buttonsPanel) self.addWindowListener(self) self.pack()
def reloadComponent(game,dialog,node): c = None text = node.getAttribute("text") if node.hasAttribute("text") else "" align = int(node.getAttribute("align")) if node.hasAttribute("align") else 0 #Components if node.nodeName=="jpanel": c = JPanel() c.setBackground(Color.BLACK) layout = createLayoutManager(c,node.getAttribute("layout") if node.hasAttribute("layout") else "flow") c.setLayout(layout) c.setOpaque(False) if node.getAttribute("opaque"): c.setOpaque(node.getAttribute("opaque")=="true") if node.getAttribute("background"): if(node.getAttribute("background")=="orange"): c.setBackground(Color.ORANGE) elif(node.getAttribute("background")=="green"): c.setBackground(Color.GREEN) for child in node.childNodes: if child.nodeName!="#text": if node.getAttribute("layout")=="gridbag": c.add(reloadComponent(game,dialog,child),getGridBagConstraints(game,child)) else: c.add(reloadComponent(game,dialog,child)) elif node.nodeName=="jlabel": c = JLabel(text,align) elif node.nodeName=="jbutton": c = JButton(text) if node.hasAttribute("enabled"): c.setEnabled(node.getAttribute("enabled")=="true"); elif node.nodeName=="settingspanel": c = SettingsPanel(game) for g in node.childNodes: if g.nodeName=="group": c.addGroup(int(g.getAttribute("id")),g.getAttribute("label")) for h in g.childNodes: if h.nodeName=="heading": c.addHeading(int(g.getAttribute("id")),h.getAttribute("label")) for s in h.childNodes: if s.nodeName=="setting": #<setting id="1" name="DISPLAY_REAL_WORLD_TIME" type="checkbox" label="Show Real-World Time"></setting> if s.getAttribute("items")!="": c.addSettingWithItems(int(g.getAttribute("id")),int(s.getAttribute("id")),s.getAttribute("label"),s.getAttribute("type"),s.getAttribute("items").split(",")) else: c.addSetting(int(g.getAttribute("id")),int(s.getAttribute("id")),s.getAttribute("label"),s.getAttribute("type")) c.finalizeSettingsPanel() dialog.registerSettingsPanel(int(node.getAttribute("id")),c) elif node.nodeName=="logspanel": c = LogsPanel(game) for g in node.childNodes: if g.nodeName=="group": c.addLog(int(g.getAttribute("id")),g.getAttribute("label")) c.finalizeLogsPanel() dialog.registerLogsPanel(int(node.getAttribute("id")),c) elif node.nodeName=="nglcanvas": c = NGLCanvas(game,int(getCascadingAttribute(game,node,"width")),int(getCascadingAttribute(game,node,"height"))) dialog.registerCanvas(int(node.getAttribute("id")),c) #Layout if node.parentNode.getAttribute("layout")=="absolute": c.setBounds(getBounds(game,node)) elif node.parentNode.getAttribute("layout")=="box-y": c.setAlignmentX(Component.CENTER_ALIGNMENT); if node.hasAttribute("width") and node.hasAttribute("height"): c.setPreferredSize(Dimension(int(getCascadingAttribute(game,node,"width")),int(getCascadingAttribute(game,node,"height")))) if node.hasAttribute("minWidth") and node.hasAttribute("minHeight"): c.setMinimumSize(Dimension(int(node.getAttribute("minWidth")),int(node.getAttribute("minHeight")))) if node.hasAttribute("maxWidth") and node.hasAttribute("maxHeight"): c.setMaximumSize(Dimension(int(node.getAttribute("maxWidth")),int(node.getAttribute("maxHeight")))) elif node.parentNode.getAttribute("layout")=="box-x": c.setAlignmentY(Component.CENTER_ALIGNMENT); if node.hasAttribute("width") and node.hasAttribute("height"): c.setPreferredSize(Dimension(int(getCascadingAttribute(game,node,"width")),int(getCascadingAttribute(game,node,"height")))) if node.hasAttribute("minWidth") and node.hasAttribute("minHeight"): c.setMinimumSize(Dimension(int(node.getAttribute("minWidth")),int(node.getAttribute("minHeight")))) if node.hasAttribute("maxWidth") and node.hasAttribute("maxHeight"): c.setMaximumSize(Dimension(int(node.getAttribute("maxWidth")),int(node.getAttribute("maxHeight")))) if node.nodeName!="nglcanvas" and node.nodeName!="jpanel" and node.nodeName!="settingspanel": addListeners(game,c,node) return c;
class NewZoneDialog(JDialog, ActionListener, WindowListener): """Dialog for favourite zone editing """ def __init__(self, parent, title, modal, app): from java.awt import CardLayout self.app = app border = BorderFactory.createEmptyBorder(5, 7, 7, 7) self.getContentPane().setBorder(border) self.setLayout(BoxLayout(self.getContentPane(), BoxLayout.Y_AXIS)) self.FAVAREALAYERNAME = "Favourite zone editing" info = JLabel(self.app.strings.getString("Create_a_new_favourite_zone")) info.setAlignmentX(Component.LEFT_ALIGNMENT) #Name nameLbl = JLabel(self.app.strings.getString("fav_zone_name")) self.nameTextField = JTextField(20) self.nameTextField.setMaximumSize(self.nameTextField.getPreferredSize()) self.nameTextField.setToolTipText(self.app.strings.getString("fav_zone_name_tooltip")) namePanel = JPanel() namePanel.setLayout(BoxLayout(namePanel, BoxLayout.X_AXIS)) namePanel.add(nameLbl) namePanel.add(Box.createHorizontalGlue()) namePanel.add(self.nameTextField) #Country countryLbl = JLabel(self.app.strings.getString("fav_zone_country")) self.countryTextField = JTextField(20) self.countryTextField.setMaximumSize(self.countryTextField.getPreferredSize()) self.countryTextField.setToolTipText(self.app.strings.getString("fav_zone_country_tooltip")) countryPanel = JPanel() countryPanel.setLayout(BoxLayout(countryPanel, BoxLayout.X_AXIS)) countryPanel.add(countryLbl) countryPanel.add(Box.createHorizontalGlue()) countryPanel.add(self.countryTextField) #Type modeLbl = JLabel(self.app.strings.getString("fav_zone_type")) RECTPANEL = "rectangle" POLYGONPANEL = "polygon" BOUNDARYPANEL = "boundary" self.modesStrings = [RECTPANEL, POLYGONPANEL, BOUNDARYPANEL] modesComboModel = DefaultComboBoxModel() for i in (self.app.strings.getString("rectangle"), self.app.strings.getString("delimited_by_a_closed_way"), self.app.strings.getString("delimited_by_an_administrative_boundary")): modesComboModel.addElement(i) self.modesComboBox = JComboBox(modesComboModel, actionListener=self, editable=False) #- Rectangle self.rectPanel = JPanel() self.rectPanel.setLayout(BoxLayout(self.rectPanel, BoxLayout.Y_AXIS)) capturePane = JPanel() capturePane.setLayout(BoxLayout(capturePane, BoxLayout.X_AXIS)) capturePane.setAlignmentX(Component.LEFT_ALIGNMENT) josmP = JPanel() self.captureRBtn = JRadioButton(self.app.strings.getString("capture_area")) self.captureRBtn.addActionListener(self) self.captureRBtn.setSelected(True) self.bboxFromJosmBtn = JButton(self.app.strings.getString("get_current_area"), actionPerformed=self.on_bboxFromJosmBtn_clicked) self.bboxFromJosmBtn.setToolTipText(self.app.strings.getString("get_capture_area_tooltip")) josmP.add(self.bboxFromJosmBtn) capturePane.add(self.captureRBtn) capturePane.add(Box.createHorizontalGlue()) capturePane.add(self.bboxFromJosmBtn) manualPane = JPanel() manualPane.setLayout(BoxLayout(manualPane, BoxLayout.X_AXIS)) manualPane.setAlignmentX(Component.LEFT_ALIGNMENT) self.manualRBtn = JRadioButton(self.app.strings.getString("use_this_bbox")) self.manualRBtn.addActionListener(self) self.bboxTextField = JTextField(20) self.bboxTextField.setMaximumSize(self.bboxTextField.getPreferredSize()) self.bboxTextField.setToolTipText(self.app.strings.getString("fav_bbox_tooltip")) self.bboxTextFieldDefaultBorder = self.bboxTextField.getBorder() self.bboxTextField.getDocument().addDocumentListener(TextListener(self)) manualPane.add(self.manualRBtn) manualPane.add(Box.createHorizontalGlue()) manualPane.add(self.bboxTextField) group = ButtonGroup() group.add(self.captureRBtn) group.add(self.manualRBtn) previewPane = JPanel() previewPane.setLayout(BoxLayout(previewPane, BoxLayout.X_AXIS)) previewPane.setAlignmentX(Component.LEFT_ALIGNMENT) bboxPreviewInfo = JTextField(self.app.strings.getString("coordinates"), editable=0, border=None) bboxPreviewInfo.setMaximumSize(bboxPreviewInfo.getPreferredSize()) self.bboxPreviewTextField = JTextField(20, editable=0, border=None) self.bboxPreviewTextField.setMaximumSize(self.bboxPreviewTextField.getPreferredSize()) previewPane.add(bboxPreviewInfo) previewPane.add(Box.createHorizontalGlue()) previewPane.add(self.bboxPreviewTextField) self.rectPanel.add(capturePane) self.rectPanel.add(Box.createRigidArea(Dimension(0, 10))) self.rectPanel.add(manualPane) self.rectPanel.add(Box.createRigidArea(Dimension(0, 20))) self.rectPanel.add(previewPane) #- Polygon (closed way) drawn by hand self.polygonPanel = JPanel(BorderLayout()) self.polygonPanel.setLayout(BoxLayout(self.polygonPanel, BoxLayout.Y_AXIS)) polyInfo = JLabel("<html>%s</html>" % self.app.strings.getString("polygon_info")) polyInfo.setFont(polyInfo.getFont().deriveFont(Font.ITALIC)) polyInfo.setAlignmentX(Component.LEFT_ALIGNMENT) editPolyPane = JPanel() editPolyPane.setAlignmentX(Component.LEFT_ALIGNMENT) editPolyBtn = JButton(self.app.strings.getString("create_fav_layer"), actionPerformed=self.create_new_zone_editing_layer) editPolyBtn.setToolTipText(self.app.strings.getString("create_fav_layer_tooltip")) editPolyPane.add(editPolyBtn) self.polygonPanel.add(polyInfo) self.polygonPanel.add(Box.createRigidArea(Dimension(0, 15))) self.polygonPanel.add(editPolyPane) self.polygonPanel.add(Box.createRigidArea(Dimension(0, 15))) #- Administrative Boundary self.boundaryPanel = JPanel() self.boundaryPanel.setLayout(BoxLayout(self.boundaryPanel, BoxLayout.Y_AXIS)) boundaryInfo = JLabel("<html>%s</html>" % app.strings.getString("boundary_info")) boundaryInfo.setFont(boundaryInfo.getFont().deriveFont(Font.ITALIC)) boundaryInfo.setAlignmentX(Component.LEFT_ALIGNMENT) boundaryTagsPanel = JPanel(GridLayout(3, 3, 5, 5)) boundaryTagsPanel.setAlignmentX(Component.LEFT_ALIGNMENT) boundaryTagsPanel.add(JLabel("name =")) self.nameTagTextField = JTextField(20) boundaryTagsPanel.add(self.nameTagTextField) boundaryTagsPanel.add(JLabel("admin_level =")) self.adminLevelTagTextField = JTextField(20) self.adminLevelTagTextField.setToolTipText(self.app.strings.getString("adminLevel_tooltip")) boundaryTagsPanel.add(self.adminLevelTagTextField) boundaryTagsPanel.add(JLabel(self.app.strings.getString("other_tag"))) self.optionalTagTextField = JTextField(20) self.optionalTagTextField.setToolTipText("key=value") boundaryTagsPanel.add(self.optionalTagTextField) downloadBoundariesPane = JPanel() downloadBoundariesPane.setAlignmentX(Component.LEFT_ALIGNMENT) downloadBoundariesBtn = JButton(self.app.strings.getString("download_boundary"), actionPerformed=self.on_downloadBoundariesBtn_clicked) downloadBoundariesBtn.setToolTipText(self.app.strings.getString("download_boundary_tooltip")) downloadBoundariesPane.add(downloadBoundariesBtn) self.boundaryPanel.add(boundaryInfo) self.boundaryPanel.add(Box.createRigidArea(Dimension(0, 15))) self.boundaryPanel.add(boundaryTagsPanel) self.boundaryPanel.add(Box.createRigidArea(Dimension(0, 10))) self.boundaryPanel.add(downloadBoundariesPane) self.editingPanels = {"rectangle": self.rectPanel, "polygon": self.polygonPanel, "boundary": self.boundaryPanel} #Main buttons self.okBtn = JButton(self.app.strings.getString("OK"), ImageProvider.get("ok"), actionPerformed=self.on_okBtn_clicked) self.cancelBtn = JButton(self.app.strings.getString("cancel"), ImageProvider.get("cancel"), actionPerformed=self.close_dialog) self.previewBtn = JButton(self.app.strings.getString("Preview_zone"), actionPerformed=self.on_previewBtn_clicked) self.previewBtn.setToolTipText(self.app.strings.getString("preview_zone_tooltip")) okBtnSize = self.okBtn.getPreferredSize() viewBtnSize = self.previewBtn.getPreferredSize() viewBtnSize.height = okBtnSize.height self.previewBtn.setPreferredSize(viewBtnSize) #layout self.add(info) self.add(Box.createRigidArea(Dimension(0, 15))) namePanel.setAlignmentX(Component.LEFT_ALIGNMENT) self.add(namePanel) self.add(Box.createRigidArea(Dimension(0, 15))) countryPanel.setAlignmentX(Component.LEFT_ALIGNMENT) self.add(countryPanel) self.add(Box.createRigidArea(Dimension(0, 15))) modeLbl.setAlignmentX(Component.LEFT_ALIGNMENT) self.add(modeLbl) self.add(Box.createRigidArea(Dimension(0, 5))) self.add(self.modesComboBox) self.modesComboBox.setAlignmentX(Component.LEFT_ALIGNMENT) self.add(Box.createRigidArea(Dimension(0, 15))) self.configPanel = JPanel(CardLayout()) self.configPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)) self.configPanel.add(self.rectPanel, RECTPANEL) self.configPanel.add(self.polygonPanel, POLYGONPANEL) self.configPanel.add(self.boundaryPanel, BOUNDARYPANEL) self.configPanel.setAlignmentX(Component.LEFT_ALIGNMENT) self.add(self.configPanel) buttonsPanel = JPanel() buttonsPanel.add(self.okBtn) buttonsPanel.add(self.cancelBtn) buttonsPanel.add(self.previewBtn) buttonsPanel.setAlignmentX(Component.LEFT_ALIGNMENT) self.add(buttonsPanel) self.addWindowListener(self) self.pack() def update_gui_from_preferences(self): self.nameTextField.setText(self.app.newZone.name) #Reset rectangle mode bboxStr = ",".join(["%0.4f" % x for x in self.app.newZone.bbox]) self.bboxTextField.setText(bboxStr) self.bboxPreviewTextField.setText(bboxStr) self.bboxFromJosmBtn.setEnabled(True) self.bboxTextField.setEnabled(False) #Reset polygon mode self.polygonAsString = "" #Reset boundary mode self.boundaryAsString = "" self.modesComboBox.setSelectedIndex(0) def actionPerformed(self, e): #Show the panel for configuring the favourite area of the #selected type if e.getSource() == self.modesComboBox: cl = self.configPanel.getLayout() selectedMode = self.modesStrings[self.modesComboBox.selectedIndex] cl.show(self.configPanel, selectedMode) #Activate bbox input for rectangular favourite zone mode elif e.getSource() == self.captureRBtn: self.bboxFromJosmBtn.setEnabled(True) self.bboxTextField.setEnabled(False) else: self.bboxFromJosmBtn.setEnabled(False) self.bboxTextField.setEnabled(True) def on_bboxFromJosmBtn_clicked(self, widget): """Read bbox currently shown in JOSM """ bbox = self.app.get_frame_bounds() self.bboxPreviewTextField.setText(",".join(["%0.4f" % x for x in bbox])) ### Manage layer for creating a new favourite zone from polygon or boundary def create_new_zone_editing_layer(self, e=None): """Open a new dataset where the user can draw a closed way to delimit the favourite area """ layer = self.get_new_zone_editing_layer() if layer is not None: self.app.mv.setActiveLayer(layer) else: Main.main.addLayer(OsmDataLayer(DataSet(), self.FAVAREALAYERNAME, None)) Main.main.parent.toFront() def get_new_zone_editing_layer(self): """Check if the layer for editing the favourite area yet exists """ for layer in self.app.mv.getAllLayers(): if layer.getName() == self.FAVAREALAYERNAME: return layer return None def remove_new_zone_editing_layer(self): layer = self.get_new_zone_editing_layer() if layer is not None: self.app.mv.removeLayer(layer) def on_zone_edited(self): """Read ways that delimit the favourite area and convert them to jts geometry """ if self.modesComboBox.getSelectedIndex() == 0: mode = "rectangle" elif self.modesComboBox.getSelectedIndex() == 1: mode = "polygon" elif self.modesComboBox.getSelectedIndex() == 2: mode = "boundary" if mode in ("polygon", "boundary"): layer = self.get_new_zone_editing_layer() if layer is not None: self.app.mv.setActiveLayer(layer) else: if mode == "polygon": msg = self.app.strings.getString("polygon_fav_layer_missing_msg") else: msg = self.app.strings.getString("boundary_fav_layer_missing_msg") JOptionPane.showMessageDialog(self, msg, self.app.strings.getString("Warning"), JOptionPane.WARNING_MESSAGE) return dataset = self.app.mv.editLayer.data areaWKT = self.read_area_from_osm_ways(mode, dataset) if areaWKT is None: print "I could not read the new favourite area." else: if mode == "polygon": self.polygonAsString = areaWKT else: self.boundaryAsString = areaWKT return mode def read_area_from_osm_ways(self, mode, dataset): """Read way in favourite area editing layer and convert them to WKT """ converter = JTSConverter(False) lines = [converter.convert(way) for way in dataset.ways] polygonizer = Polygonizer() polygonizer.add(lines) polygons = polygonizer.getPolygons() multipolygon = GeometryFactory().createMultiPolygon(list(polygons)) multipolygonWKT = WKTWriter().write(multipolygon) if multipolygonWKT == "MULTIPOLYGON EMPTY": if mode == "polygon": msg = self.app.strings.getString("empty_ways_polygon_msg") else: msg = self.app.strings.getString("empty_ways_boundaries_msg") JOptionPane.showMessageDialog(self, msg, self.app.strings.getString("Warning"), JOptionPane.WARNING_MESSAGE) return return multipolygonWKT def on_downloadBoundariesBtn_clicked(self, e): """Download puter ways of administrative boundaries from Overpass API """ adminLevel = self.adminLevelTagTextField.getText() name = self.nameTagTextField.getText() optional = self.optionalTagTextField.getText() if (adminLevel, name, optional) == ("", "", ""): JOptionPane.showMessageDialog(self, self.app.strings.getString("enter_a_tag_msg"), self.app.strings.getString("Warning"), JOptionPane.WARNING_MESSAGE) return optTag = "" if optional.find("=") != -1: if len(optional.split("=")) == 2: key, value = optional.split("=") optTag = '["%s"="%s"]' % (URLEncoder.encode(key, "UTF-8"), URLEncoder.encode(value.replace(" ", "%20"), "UTF-8")) self.create_new_zone_editing_layer() overpassurl = 'http://127.0.0.1:8111/import?url=' overpassurl += 'http://overpass-api.de/api/interpreter?data=' overpassquery = 'relation["admin_level"="%s"]' % adminLevel overpassquery += '["name"="%s"]' % URLEncoder.encode(name, "UTF-8") overpassquery += '%s;(way(r:"outer");node(w););out meta;' % optTag overpassurl += overpassquery.replace(" ", "%20") print overpassurl self.app.send_to_josm(overpassurl) ### Buttons ############################################################ def create_new_zone(self, mode): """Read data entered on gui and create a new zone """ name = self.nameTextField.getText() country = self.countryTextField.getText().upper() #error: name if name.replace(" ", "") == "": JOptionPane.showMessageDialog(self, self.app.strings.getString("missing_name_warning"), self.app.strings.getString("missing_name_warning_title"), JOptionPane.WARNING_MESSAGE) return False if name in [z.name for z in self.app.tempZones]: JOptionPane.showMessageDialog(self, self.app.strings.getString("duplicate_name_warning"), self.app.strings.getString("duplicate_name_warning_title"), JOptionPane.WARNING_MESSAGE) return False #zone type zType = mode #error: geometry type not defined if zType == "polygon" and self.polygonAsString == ""\ or zType == "boundary" and self.boundaryAsString == "": JOptionPane.showMessageDialog(self, self.app.strings.getString("zone_not_correctly_build_warning"), self.app.strings.getString("zone_not_correctly_build_warning_title"), JOptionPane.WARNING_MESSAGE) return False #geometry string if zType == "rectangle": geomString = self.bboxPreviewTextField.getText() elif zType == "polygon": geomString = self.polygonAsString else: geomString = self.boundaryAsString self.app.newZone = Zone(self.app, name, zType, geomString, country) #self.app.newZone.print_info() return True def on_okBtn_clicked(self, event): """Add new zone to temp zones """ mode = self.on_zone_edited() if self.create_new_zone(mode): self.app.tempZones.append(self.app.newZone) self.app.preferencesFrame.zonesTable.getModel().addRow([self.app.newZone.country, self.app.newZone.icon, self.app.newZone.name]) maxIndex = len(self.app.tempZones) - 1 self.app.preferencesFrame.zonesTable.setRowSelectionInterval(maxIndex, maxIndex) self.close_dialog() self.app.preferencesFrame.check_removeBtn_status() self.app.preferencesFrame.zonesTable.scrollRectToVisible( self.app.preferencesFrame.zonesTable.getCellRect( self.app.preferencesFrame.zonesTable.getRowCount() - 1, 0, True)) def on_previewBtn_clicked(self, e): """Show the favourite area on a map """ mode = self.on_zone_edited() if not self.create_new_zone(mode): return zone = self.app.newZone if zone.zType == "rectangle": wktString = zone.bbox_to_wkt_string() else: wktString = zone.wktGeom script = '/*http://stackoverflow.com/questions/11954401/wkt-and-openlayers*/' script += '\nfunction init() {' script += '\n var map = new OpenLayers.Map({' script += '\n div: "map",' script += '\n projection: new OpenLayers.Projection("EPSG:900913"),' script += '\n displayProjection: new OpenLayers.Projection("EPSG:4326"),' script += '\n layers: [' script += '\n new OpenLayers.Layer.OSM()' script += '\n ]' script += '\n });' script += '\n var wkt = new OpenLayers.Format.WKT();' script += '\n var polygonFeature = wkt.read("%s");' % wktString script += '\n var vectors = new OpenLayers.Layer.Vector("Favourite area");' script += '\n map.addLayer(vectors);' script += '\n polygonFeature.geometry.transform(map.displayProjection, map.getProjectionObject());' script += '\n vectors.addFeatures([polygonFeature]);' script += '\n map.zoomToExtent(vectors.getDataExtent());' script += '\n};' scriptFile = open(File.separator.join([self.app.SCRIPTDIR, "html", "script.js"]), "w") scriptFile.write(script) scriptFile.close() OpenBrowser.displayUrl(File.separator.join([self.app.SCRIPTDIR, "html", "favourite_area.html"])) def windowClosing(self, windowEvent): self.close_dialog() def close_dialog(self, e=None): #delete favourite zone editing layer if present self.remove_new_zone_editing_layer() self.dispose() self.app.preferencesFrame.setEnabled(True) self.app.preferencesFrame.toFront()
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 + "<" + \ 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()
class BurpExtender(IBurpExtender, IScannerCheck, ITab): base_url = "haveibeenpwned.com" cmd = "ssh dl-adm query_email ~emailhere~" def registerExtenderCallbacks(self, callbacks): self._callbacks = callbacks self._helpers = callbacks.getHelpers() # set our extension name callbacks.setExtensionName("Cheburek") self._stdout = PrintWriter(callbacks.getStdout(), True) self._stdout.println("Hello 1337") # add the custom tab to Burp's UI self.confCommand = self._callbacks.loadExtensionSetting( "cheburek.command") or self.cmd saved_haveibeenpwnd = self._callbacks.loadExtensionSetting( "cheburek.haveibeenpwnd") if saved_haveibeenpwnd == "True": self.confHaveIBeenPwnd = True elif saved_haveibeenpwnd == "False": self.confHaveIBeenPwnd = False else: self.confHaveIBeenPwnd = bool(int(saved_haveibeenpwnd or True)) saved_localcheck = self._callbacks.loadExtensionSetting( "cheburek.localcheck") if saved_localcheck == "True": self.confLocalCheck = True elif saved_localcheck == "False": self.confLocalCheck = False else: self.confLocalCheck = bool(int(saved_localcheck or False)) callbacks.addSuiteTab(self) self.applyConfig() callbacks.registerScannerCheck(self) def applyConfig(self): self._callbacks.saveExtensionSetting("cheburek.command", self.confCommand) self._callbacks.saveExtensionSetting("cheburek.haveibeenpwnd", str(int(self.confHaveIBeenPwnd))) self._callbacks.saveExtensionSetting("cheburek.localcheck", str(int(self.confLocalCheck))) ### ITab ### def getTabCaption(self): return "Cheburek" def applyConfigUI(self, event): self.confCommand = self.uiCommand.getText() self.confHaveIBeenPwnd = self.uiHaveIBeenPwnd.isSelected() self.confLocalCheck = self.uiLocalCheck.isSelected() self.applyConfig() def resetConfigUI(self, event): self.uiCommand.setText(self.confCommand) self.uiHaveIBeenPwnd.setSelected(self.confHaveIBeenPwnd) self.uiLocalCheck.setSelected(self.confLocalCheck) def getUiComponent(self): self.panel = JPanel() self.panel.setLayout(BoxLayout(self.panel, BoxLayout.PAGE_AXIS)) self.uiCommandLine = JPanel() self.uiCommandLine.setLayout( BoxLayout(self.uiCommandLine, BoxLayout.LINE_AXIS)) self.uiCommandLine.setAlignmentX(JPanel.LEFT_ALIGNMENT) self.uiCommandLine.add(JLabel("Command line for local search: ")) self.uiCommand = JTextField(40) self.uiCommand.setMaximumSize(self.uiCommand.getPreferredSize()) self.uiCommandLine.add(self.uiCommand) self.panel.add(self.uiCommandLine) uiOptionsLine = JPanel() uiOptionsLine.setLayout(BoxLayout(uiOptionsLine, BoxLayout.LINE_AXIS)) uiOptionsLine.setAlignmentX(JPanel.LEFT_ALIGNMENT) self.uiHaveIBeenPwnd = JCheckBox("haveibeenpwned") uiOptionsLine.add(self.uiHaveIBeenPwnd) uiOptionsLine.add(Box.createRigidArea(Dimension(10, 0))) self.uiLocalCheck = JCheckBox("Local check") uiOptionsLine.add(self.uiLocalCheck) uiOptionsLine.add(Box.createRigidArea(Dimension(10, 0))) self.panel.add(uiOptionsLine) self.panel.add(Box.createRigidArea(Dimension(0, 10))) uiButtonsLine = JPanel() uiButtonsLine.setLayout(BoxLayout(uiButtonsLine, BoxLayout.LINE_AXIS)) uiButtonsLine.setAlignmentX(JPanel.LEFT_ALIGNMENT) uiButtonsLine.add(JButton("Apply", actionPerformed=self.applyConfigUI)) uiButtonsLine.add(JButton("Reset", actionPerformed=self.resetConfigUI)) self.panel.add(uiButtonsLine) self.uiAbout = JPanel() self.uiAbout.setLayout(BoxLayout(self.uiAbout, BoxLayout.LINE_AXIS)) self.uiAbout.setAlignmentX(JPanel.LEFT_ALIGNMENT) self.uiAbout.add( JLabel( "<html><a href=\"https://twitter.com/_chipik\">https://twitter.com/_chipik</a></html>" )) self.panel.add(self.uiAbout) self.resetConfigUI(None) return self.panel # END ITAB def _get_matches(self, response): str_response = self._helpers.bytesToString(response) # best regex winner :) regex = re.compile( ("([a-z0-9!#$%&'*+\/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+\/=?^_`" "{|}~-]+)*(@|\sat\s)(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(\.|" "\sdot\s))+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)")) emails = re.findall(regex, str_response) for email in emails: self._stdout.println('Found {}'.format(email[0])) return emails def _get_pointer(self, response, match): matches = [] start = 0 reslen = len(response) matchlen = len(match) while start < reslen: start = self._helpers.indexOf(response, match, True, start, reslen) if start == -1: break matches.append(array('i', [start, start + matchlen])) start += matchlen return matches # helper that do a request to https://haveibeenpwned.com/ def _do_online_check(self, email): headers = { 'User-Agent': 'Chebuzilla/5.0 (Chebuntosh; Intel Cheb-OS-Rek 13.37; rv:59.0) ChebuGeko/20100101 Cheburefox/1337.0' } connect = httplib.HTTPSConnection(self.base_url) connect.request('GET', '/api/v2/breachedaccount/{}'.format(email), headers=headers) response = connect.getresponse() if response.status == 200: html = response.read() self._stdout.println('Got {}. Status = {}'.format( email, response.status)) jresp = json.loads(html) rez_info = '' for br in jresp['Breaches']: rez_li = '' for li in br['DataClasses']: rez_li = '{}<li>{}</li>'.format(rez_li, li) rez_info = '{}<br>{} ({})<br><ul>{}</ul>'.format( rez_info, br['Title'], br['BreachDate'], rez_li) return rez_info if response.status == 404: self._stdout.println('Nothing :( Status = {}'.format( response.status)) if response.status == 403: self._stdout.println('API request was blocked. Status = {}'.format( response.status)) return 0 # helper that do a local search def _do_local_check(self, email): self._stdout.println("Checking local db for {}".format(email)) try: cmd = self.confCommand.replace("~emailhere~", email) self._stdout.println("Exec:{}".format(cmd)) returned_output = subprocess.check_output(shlex.split(cmd)) self._stdout.println("Result: {}".format(returned_output)) returned_output = "Breached passwords:<br><br>{}".format( returned_output).replace('\n', '<br>') except subprocess.CalledProcessError: self._stdout.println("Nothing found locally for {}".format(email)) returned_output = '' return returned_output def _check_email(self, email): self._stdout.println('Let\'s check {}'.format(email)) info = info2 = issue = '' if self.confHaveIBeenPwnd: info = self._do_online_check(email) if self.confLocalCheck: info2 = self._do_local_check(email) if info or info2: issue = self._reportIssue(email, info + info2) return issue def _reportIssue(self, email, info): issue = CustomScanIssue( self._baseRequestResponse.getHttpService(), self._helpers.analyzeRequest(self._baseRequestResponse).getUrl(), [ self._callbacks.applyMarkers( self._baseRequestResponse, None, self._get_pointer(self._baseRequestResponse.getResponse(), bytearray(email, 'utf8'))) ], "Potentially compromised account", "Email address <b>{}</b> potentially has been compromised in a data breach<br><br>{}" .format(email, info), "Information") return issue def doPassiveScan(self, baseRequestResponse): self._baseRequestResponse = baseRequestResponse matches = self._get_matches(self._baseRequestResponse.getResponse()) issues = [] if (len(matches) == 0): return None else: for email in matches: issue = self._check_email(email[0]) if issue: issues.append(issue) return issues def consolidateDuplicateIssues(self, existingIssue, newIssue): if existingIssue.getIssueName() == newIssue.getIssueName(): return -1 return 0
def __init__(self, app): #java import from javax.swing import JPanel, JButton, JLabel, ImageIcon,\ JScrollPane, BorderFactory, WindowConstants,\ BoxLayout, Box from java.awt import FlowLayout, Dimension, Component from java.io import File #josm import from org.openstreetmap.josm import Main from org.openstreetmap.josm.tools import ImageProvider from org.openstreetmap.josm.gui.widgets import HtmlPanel, UrlLabel JDialog.__init__(self, Main.parent, app.strings.getString("error_info_title"), True) self.app = app self.setSize(400, 480) border = BorderFactory.createEmptyBorder(5, 7, 5, 7) self.getContentPane().setBorder(border) self.setLayout(BoxLayout(self.getContentPane(), BoxLayout.Y_AXIS)) #Intro intro = HtmlPanel("<html><i>%s</i></html>" % self.app.strings.getString("error_info_intro")) intro.setAlignmentX(Component.LEFT_ALIGNMENT) #User info userLbl = JLabel(self.app.strings.getString("Last_user")) userLbl.setAlignmentX(JLabel.LEFT_ALIGNMENT) self.userInfoPanel = HtmlPanel() self.userInfoPanel.getEditorPane().addHyperlinkListener(self) self.userInfoPanel.setAlignmentX(Component.LEFT_ALIGNMENT) #Panel with current error's info errorLbl = JLabel(self.app.strings.getString("Error_info")) errorLbl.setAlignmentX(JLabel.LEFT_ALIGNMENT) self.errorInfoPanel = HtmlPanel() self.errorInfoPanel.getEditorPane().addHyperlinkListener(self) self.scrollPane = JScrollPane(self.errorInfoPanel) self.scrollPane.setAlignmentX(Component.LEFT_ALIGNMENT) #OK button btnPanel = JPanel(FlowLayout(FlowLayout.CENTER)) okBtn = JButton(self.app.strings.getString("OK"), ImageProvider.get("ok"), actionPerformed=self.on_okBtn_clicked) btnPanel.add(okBtn) btnPanel.setAlignmentX(Component.LEFT_ALIGNMENT) #Layout self.add(intro) self.add(Box.createRigidArea(Dimension(0, 7))) self.add(userLbl) self.add(Box.createRigidArea(Dimension(0, 5))) self.add(self.userInfoPanel) self.add(Box.createRigidArea(Dimension(0, 7))) self.add(errorLbl) self.add(Box.createRigidArea(Dimension(0, 5))) self.add(self.scrollPane) self.add(Box.createRigidArea(Dimension(0, 7))) self.add(btnPanel) self.setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE)
def __init__(self, logtable_factory=None, external_filter_action_listener=None, external_start_button_action_listener=None, external_stop_button_action_listener=None, external_clear_button_action_listener=None, tools_keys=None): self.this = JPanel() if tools_keys is None: tools_keys = [] self.external_start_button_action_listener = external_start_button_action_listener self.external_stop_button_action_listener = external_stop_button_action_listener self.external_clear_button_action_listener = external_clear_button_action_listener self.this.setLayout(BoxLayout(self.this, BoxLayout.Y_AXIS)) # main split pane splitPane = JSplitPane(JSplitPane.VERTICAL_SPLIT) # table of log entries logTableModel = LogTableModel() self.logTableModel = logTableModel if logtable_factory is not None: logTable = logtable_factory(logTableModel) else: # XXX: create a generic logtable that works even without burp to made it work standalone raise ValueError("logtable_factory cannot be none") scrollPane = JScrollPane(logTable) splitPane.setLeftComponent(scrollPane) # tabs with request/response viewers tabs = JTabbedPane() tabs.setBorder(BorderFactory.createLineBorder(Color.black)) tabs.addTab("Request", logTable.getRequestViewer().getComponent()) tabs.addTab("Response", logTable.getResponseViewer().getComponent()) splitPane.setRightComponent(tabs) # top control panel controlPanel = JPanel(FlowLayout(FlowLayout.LEFT)) toolLabel = JLabel("Select tool: ") controlPanel.add(toolLabel) tools = JavaArrayList(tools_keys) toolList = JComboBox(tools) toolList.addActionListener(external_filter_action_listener) controlPanel.add(toolList) startButton = JButton("Start") self.startButton = startButton controlPanel.add(startButton) stopButton = JButton("Stop") self.stopButton = stopButton controlPanel.add(stopButton) clearButton = JButton("Clear") self.clearButton = clearButton startButton.setEnabled(False) controlPanel.add(clearButton) scopeLabel = JLabel("In-scope items only?") controlPanel.add(scopeLabel) scopeCheckBox = JCheckBox() self.scopeCheckBox = scopeCheckBox controlPanel.add(scopeCheckBox) filterLabel = JLabel("Filter Query:") controlPanel.add(filterLabel) queryFilterText = JTextField(40) self.queryFilterText = queryFilterText controlPanel.add(queryFilterText) startButton.addActionListener(self.start_button_action_listener) stopButton.addActionListener(self.stop_button_action_listener) clearButton.addActionListener(self.clear_button_action_listener) controlPanel.setAlignmentX(0) self.this.add(controlPanel) self.this.add(splitPane)
def createPanel(): panel = JPanel() panel.setLayout(BoxLayout(panel, BoxLayout.PAGE_AXIS)) panel.setAlignmentX(Component.LEFT_ALIGNMENT) return panel
def __init__(self, parent, title, app): from javax.swing import JCheckBox, JRadioButton, ButtonGroup self.app = app border = BorderFactory.createEmptyBorder(5, 7, 5, 7) self.getContentPane().setBorder(border) self.getContentPane().setLayout(BorderLayout(0, 5)) self.tabbedPane = JTabbedPane() #1 Tab: general panel1 = JPanel() panel1.setBorder(BorderFactory.createEmptyBorder(7, 7, 7, 7)) panel1.setLayout(BoxLayout(panel1, BoxLayout.PAGE_AXIS)) #Checkbutton to enable/disable update check when script starts self.updateCBtn = JCheckBox(self.app.strings.getString("updateCBtn")) self.updateCBtn.setToolTipText(self.app.strings.getString("updateCBtn_tooltip")) #Download tools downloadBtn = JButton(self.app.strings.getString("updatesBtn"), ImageProvider.get("dialogs", "refresh"), actionPerformed=self.on_downloadBtn_clicked) downloadBtn.setToolTipText(self.app.strings.getString("updatesBtn_tooltip")) #Checkbuttons for enabling/disabling tools toolsPanel = JPanel(BorderLayout(0, 5)) title = self.app.strings.getString("enable_disable_tools") toolsPanel.setBorder(BorderFactory.createTitledBorder(title)) infoLbl = JLabel(self.app.strings.getString("JOSM_restart_warning")) infoLbl.setFont(infoLbl.getFont().deriveFont(Font.ITALIC)) toolsPanel.add(infoLbl, BorderLayout.PAGE_START) toolsStatusPane = JPanel(GridLayout(len(self.app.realTools), 0)) self.toolsCBtns = [] for tool in self.app.realTools: toolCBtn = JCheckBox() toolCBtn.addItemListener(self) toolLbl = JLabel(tool.title, tool.bigIcon, JLabel.LEFT) self.toolsCBtns.append(toolCBtn) toolPane = JPanel() toolPane.setLayout(BoxLayout(toolPane, BoxLayout.X_AXIS)) toolPane.add(toolCBtn) toolPane.add(toolLbl) toolsStatusPane.add(toolPane) toolsPanel.add(toolsStatusPane, BorderLayout.CENTER) #Radiobuttons for enabling/disabling layers when a new one #is added layersPanel = JPanel(GridLayout(0, 1)) title = self.app.strings.getString("errors_layers_manager") layersPanel.setBorder(BorderFactory.createTitledBorder(title)) errorLayersLbl = JLabel(self.app.strings.getString("errors_layers_info")) errorLayersLbl.setFont(errorLayersLbl.getFont().deriveFont(Font.ITALIC)) layersPanel.add(errorLayersLbl) self.layersRBtns = {} group = ButtonGroup() for mode in self.app.layersModes: layerRBtn = JRadioButton(self.app.strings.getString("%s" % mode)) group.add(layerRBtn) layersPanel.add(layerRBtn) self.layersRBtns[mode] = layerRBtn #Max number of errors text field self.maxErrorsNumberTextField = JTextField() self.maxErrorsNumberTextField.setToolTipText(self.app.strings.getString("maxErrorsNumberTextField_tooltip")) self.maxErrorsNumberTFieldDefaultBorder = self.maxErrorsNumberTextField.getBorder() self.maxErrorsNumberTextField.getDocument().addDocumentListener(ErrNumTextListener(self)) #layout self.updateCBtn.setAlignmentX(Component.LEFT_ALIGNMENT) panel1.add(self.updateCBtn) panel1.add(Box.createRigidArea(Dimension(0, 15))) downloadBtn.setAlignmentX(Component.LEFT_ALIGNMENT) panel1.add(downloadBtn) panel1.add(Box.createRigidArea(Dimension(0, 15))) toolsPanel.setAlignmentX(Component.LEFT_ALIGNMENT) panel1.add(toolsPanel) panel1.add(Box.createRigidArea(Dimension(0, 15))) layersPanel.setAlignmentX(Component.LEFT_ALIGNMENT) panel1.add(layersPanel) panel1.add(Box.createRigidArea(Dimension(0, 15))) maxErrP = JPanel(BorderLayout(5, 0)) maxErrP.add(JLabel(self.app.strings.getString("max_errors_number")), BorderLayout.LINE_START) maxErrP.add(self.maxErrorsNumberTextField, BorderLayout.CENTER) p = JPanel(BorderLayout()) p.add(maxErrP, BorderLayout.PAGE_START) p.setAlignmentX(Component.LEFT_ALIGNMENT) panel1.add(p) self.tabbedPane.addTab(self.app.strings.getString("tab_1_title"), None, panel1, None) #2 Tab: favourite zones panel2 = JPanel(BorderLayout(5, 15)) panel2.setBorder(BorderFactory.createEmptyBorder(7, 7, 7, 7)) #status topPanel = JPanel() topPanel.setLayout(BoxLayout(topPanel, BoxLayout.Y_AXIS)) infoPanel = HtmlPanel(self.app.strings.getString("fav_zones_info")) infoPanel.getEditorPane().addHyperlinkListener(self) infoPanel.setAlignmentX(Component.LEFT_ALIGNMENT) self.favZoneStatusCBtn = JCheckBox(self.app.strings.getString("activate_fav_area"), actionListener=self) self.favZoneStatusCBtn.setToolTipText(self.app.strings.getString("activate_fav_area_tooltip")) self.favZoneStatusCBtn.setAlignmentX(Component.LEFT_ALIGNMENT) topPanel.add(infoPanel) topPanel.add(Box.createRigidArea(Dimension(0, 10))) topPanel.add(self.favZoneStatusCBtn) #table self.zonesTable = JTable() tableSelectionModel = self.zonesTable.getSelectionModel() tableSelectionModel.addListSelectionListener(ZonesTableListener(self)) columns = ["", self.app.strings.getString("Type"), self.app.strings.getString("Name")] tableModel = ZonesTableModel([], columns) self.zonesTable.setModel(tableModel) self.scrollPane = JScrollPane(self.zonesTable) #map self.zonesMap = JMapViewer() self.zonesMap.setZoomContolsVisible(False) self.zonesMap.setMinimumSize(Dimension(100, 200)) #buttons self.removeBtn = JButton(self.app.strings.getString("Remove"), ImageProvider.get("dialogs", "delete"), actionPerformed=self.on_removeBtn_clicked) self.removeBtn.setToolTipText(self.app.strings.getString("remove_tooltip")) newBtn = JButton(self.app.strings.getString("New"), ImageProvider.get("dialogs", "add"), actionPerformed=self.on_newBtn_clicked) newBtn.setToolTipText(self.app.strings.getString("new_tooltip")) #layout panel2.add(topPanel, BorderLayout.PAGE_START) panel2.add(self.scrollPane, BorderLayout.LINE_START) panel2.add(self.zonesMap, BorderLayout.CENTER) self.buttonsPanel = JPanel() self.buttonsPanel.add(self.removeBtn) self.buttonsPanel.add(newBtn) panel2.add(self.buttonsPanel, BorderLayout.PAGE_END) self.tabbedPane.addTab(self.app.strings.getString("tab_2_title"), None, panel2, None) #3 Tab Tools options panel3 = JPanel() panel3.setLayout(BoxLayout(panel3, BoxLayout.Y_AXIS)) panel3.setBorder(BorderFactory.createEmptyBorder(7, 7, 7, 7)) for tool in self.app.realTools: if hasattr(tool, 'prefs'): p = JPanel(FlowLayout(FlowLayout.LEFT)) p.setBorder(BorderFactory.createTitledBorder(tool.title)) p.add(tool.prefsGui) panel3.add(p) self.tabbedPane.addTab(self.app.strings.getString("tab_3_title"), None, panel3, None) self.add(self.tabbedPane, BorderLayout.CENTER) exitPanel = JPanel() saveBtn = JButton(self.app.strings.getString("OK"), ImageProvider.get("ok"), actionPerformed=self.on_saveBtn_clicked) cancelBtn = JButton(self.app.strings.getString("cancel"), ImageProvider.get("cancel"), actionPerformed=self.on_cancelBtn_clicked) saveBtn.setToolTipText(self.app.strings.getString("save_preferences")) saveBtn.setAlignmentX(0.5) exitPanel.add(saveBtn) exitPanel.add(cancelBtn) self.add(exitPanel, BorderLayout.PAGE_END) self.addWindowListener(self) self.pack()
def __init__(self, app): from java.awt import Dialog from java.awt import CardLayout JDialog.__init__(self, app.preferencesFrame, app.strings.getString("Create_a_new_favourite_zone"), Dialog.ModalityType.DOCUMENT_MODAL) self.app = app border = BorderFactory.createEmptyBorder(5, 7, 7, 7) self.getContentPane().setBorder(border) self.setLayout(BoxLayout(self.getContentPane(), BoxLayout.Y_AXIS)) self.FAVAREALAYERNAME = "Favourite zone editing" info = JLabel(self.app.strings.getString("Create_a_new_favourite_zone")) info.setAlignmentX(Component.LEFT_ALIGNMENT) #Name nameLbl = JLabel(self.app.strings.getString("fav_zone_name")) self.nameTextField = JTextField(20) self.nameTextField.setMaximumSize(self.nameTextField.getPreferredSize()) self.nameTextField.setToolTipText(self.app.strings.getString("fav_zone_name_tooltip")) namePanel = JPanel() namePanel.setLayout(BoxLayout(namePanel, BoxLayout.X_AXIS)) namePanel.add(nameLbl) namePanel.add(Box.createHorizontalGlue()) namePanel.add(self.nameTextField) #Country countryLbl = JLabel(self.app.strings.getString("fav_zone_country")) self.countryTextField = JTextField(20) self.countryTextField.setMaximumSize(self.countryTextField.getPreferredSize()) self.countryTextField.setToolTipText(self.app.strings.getString("fav_zone_country_tooltip")) countryPanel = JPanel() countryPanel.setLayout(BoxLayout(countryPanel, BoxLayout.X_AXIS)) countryPanel.add(countryLbl) countryPanel.add(Box.createHorizontalGlue()) countryPanel.add(self.countryTextField) #Type modeLbl = JLabel(self.app.strings.getString("fav_zone_type")) RECTPANEL = "rectangle" POLYGONPANEL = "polygon" BOUNDARYPANEL = "boundary" self.modesStrings = [RECTPANEL, POLYGONPANEL, BOUNDARYPANEL] modesComboModel = DefaultComboBoxModel() for i in (self.app.strings.getString("rectangle"), self.app.strings.getString("delimited_by_a_closed_way"), self.app.strings.getString("delimited_by_an_administrative_boundary")): modesComboModel.addElement(i) self.modesComboBox = JComboBox(modesComboModel, actionListener=self, editable=False) #- Rectangle self.rectPanel = JPanel() self.rectPanel.setLayout(BoxLayout(self.rectPanel, BoxLayout.Y_AXIS)) capturePane = JPanel() capturePane.setLayout(BoxLayout(capturePane, BoxLayout.X_AXIS)) capturePane.setAlignmentX(Component.LEFT_ALIGNMENT) josmP = JPanel() self.captureRBtn = JRadioButton(self.app.strings.getString("capture_area")) self.captureRBtn.addActionListener(self) self.captureRBtn.setSelected(True) self.bboxFromJosmBtn = JButton(self.app.strings.getString("get_current_area"), actionPerformed=self.on_bboxFromJosmBtn_clicked) self.bboxFromJosmBtn.setToolTipText(self.app.strings.getString("get_capture_area_tooltip")) josmP.add(self.bboxFromJosmBtn) capturePane.add(self.captureRBtn) capturePane.add(Box.createHorizontalGlue()) capturePane.add(self.bboxFromJosmBtn) manualPane = JPanel() manualPane.setLayout(BoxLayout(manualPane, BoxLayout.X_AXIS)) manualPane.setAlignmentX(Component.LEFT_ALIGNMENT) self.manualRBtn = JRadioButton(self.app.strings.getString("use_this_bbox")) self.manualRBtn.addActionListener(self) self.bboxTextField = JTextField(20) self.bboxTextField.setMaximumSize(self.bboxTextField.getPreferredSize()) self.bboxTextField.setToolTipText(self.app.strings.getString("fav_bbox_tooltip")) self.bboxTextFieldDefaultBorder = self.bboxTextField.getBorder() self.bboxTextField.getDocument().addDocumentListener(TextListener(self)) manualPane.add(self.manualRBtn) manualPane.add(Box.createHorizontalGlue()) manualPane.add(self.bboxTextField) group = ButtonGroup() group.add(self.captureRBtn) group.add(self.manualRBtn) previewPane = JPanel() previewPane.setLayout(BoxLayout(previewPane, BoxLayout.X_AXIS)) previewPane.setAlignmentX(Component.LEFT_ALIGNMENT) bboxPreviewInfo = JTextField(self.app.strings.getString("coordinates"), editable=0, border=None) bboxPreviewInfo.setMaximumSize(bboxPreviewInfo.getPreferredSize()) self.bboxPreviewTextField = JTextField(20, editable=0, border=None) self.bboxPreviewTextField.setMaximumSize(self.bboxPreviewTextField.getPreferredSize()) previewPane.add(bboxPreviewInfo) previewPane.add(Box.createHorizontalGlue()) previewPane.add(self.bboxPreviewTextField) self.rectPanel.add(capturePane) self.rectPanel.add(Box.createRigidArea(Dimension(0, 10))) self.rectPanel.add(manualPane) self.rectPanel.add(Box.createRigidArea(Dimension(0, 20))) self.rectPanel.add(previewPane) #- Polygon (closed way) drawn by hand self.polygonPanel = JPanel(BorderLayout()) self.polygonPanel.setLayout(BoxLayout(self.polygonPanel, BoxLayout.Y_AXIS)) polyInfo = JLabel("<html>%s</html>" % self.app.strings.getString("polygon_info")) polyInfo.setFont(polyInfo.getFont().deriveFont(Font.ITALIC)) polyInfo.setAlignmentX(Component.LEFT_ALIGNMENT) editPolyPane = JPanel() editPolyPane.setAlignmentX(Component.LEFT_ALIGNMENT) editPolyBtn = JButton(self.app.strings.getString("create_fav_layer"), actionPerformed=self.create_new_zone_editing_layer) editPolyBtn.setToolTipText(self.app.strings.getString("create_fav_layer_tooltip")) editPolyPane.add(editPolyBtn) self.polygonPanel.add(polyInfo) self.polygonPanel.add(Box.createRigidArea(Dimension(0, 15))) self.polygonPanel.add(editPolyPane) self.polygonPanel.add(Box.createRigidArea(Dimension(0, 15))) #- Administrative Boundary self.boundaryPanel = JPanel() self.boundaryPanel.setLayout(BoxLayout(self.boundaryPanel, BoxLayout.Y_AXIS)) boundaryInfo = JLabel("<html>%s</html>" % app.strings.getString("boundary_info")) boundaryInfo.setFont(boundaryInfo.getFont().deriveFont(Font.ITALIC)) boundaryInfo.setAlignmentX(Component.LEFT_ALIGNMENT) boundaryTagsPanel = JPanel(GridLayout(3, 3, 5, 5)) boundaryTagsPanel.setAlignmentX(Component.LEFT_ALIGNMENT) boundaryTagsPanel.add(JLabel("name =")) self.nameTagTextField = JTextField(20) boundaryTagsPanel.add(self.nameTagTextField) boundaryTagsPanel.add(UrlLabel("http://wiki.openstreetmap.org/wiki/Key:admin_level#admin_level", "admin_level =")) self.adminLevelTagTextField = JTextField(20) self.adminLevelTagTextField.setToolTipText(self.app.strings.getString("adminLevel_tooltip")) boundaryTagsPanel.add(self.adminLevelTagTextField) boundaryTagsPanel.add(JLabel(self.app.strings.getString("other_tag"))) self.optionalTagTextField = JTextField(20) self.optionalTagTextField.setToolTipText("key=value") boundaryTagsPanel.add(self.optionalTagTextField) downloadBoundariesPane = JPanel() downloadBoundariesPane.setAlignmentX(Component.LEFT_ALIGNMENT) downloadBoundariesBtn = JButton(self.app.strings.getString("download_boundary"), actionPerformed=self.on_downloadBoundariesBtn_clicked) downloadBoundariesBtn.setToolTipText(self.app.strings.getString("download_boundary_tooltip")) downloadBoundariesPane.add(downloadBoundariesBtn) self.boundaryPanel.add(boundaryInfo) self.boundaryPanel.add(Box.createRigidArea(Dimension(0, 15))) self.boundaryPanel.add(boundaryTagsPanel) self.boundaryPanel.add(Box.createRigidArea(Dimension(0, 10))) self.boundaryPanel.add(downloadBoundariesPane) self.editingPanels = {"rectangle": self.rectPanel, "polygon": self.polygonPanel, "boundary": self.boundaryPanel} #Main buttons self.okBtn = JButton(self.app.strings.getString("OK"), ImageProvider.get("ok"), actionPerformed=self.on_okBtn_clicked) self.cancelBtn = JButton(self.app.strings.getString("cancel"), ImageProvider.get("cancel"), actionPerformed=self.close_dialog) self.previewBtn = JButton(self.app.strings.getString("Preview_zone"), actionPerformed=self.on_previewBtn_clicked) self.previewBtn.setToolTipText(self.app.strings.getString("preview_zone_tooltip")) okBtnSize = self.okBtn.getPreferredSize() viewBtnSize = self.previewBtn.getPreferredSize() viewBtnSize.height = okBtnSize.height self.previewBtn.setPreferredSize(viewBtnSize) #layout self.add(info) self.add(Box.createRigidArea(Dimension(0, 15))) namePanel.setAlignmentX(Component.LEFT_ALIGNMENT) self.add(namePanel) self.add(Box.createRigidArea(Dimension(0, 15))) countryPanel.setAlignmentX(Component.LEFT_ALIGNMENT) self.add(countryPanel) self.add(Box.createRigidArea(Dimension(0, 15))) modeLbl.setAlignmentX(Component.LEFT_ALIGNMENT) self.add(modeLbl) self.add(Box.createRigidArea(Dimension(0, 5))) self.add(self.modesComboBox) self.modesComboBox.setAlignmentX(Component.LEFT_ALIGNMENT) self.add(Box.createRigidArea(Dimension(0, 15))) self.configPanel = JPanel(CardLayout()) self.configPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)) self.configPanel.add(self.rectPanel, RECTPANEL) self.configPanel.add(self.polygonPanel, POLYGONPANEL) self.configPanel.add(self.boundaryPanel, BOUNDARYPANEL) self.configPanel.setAlignmentX(Component.LEFT_ALIGNMENT) self.add(self.configPanel) buttonsPanel = JPanel() buttonsPanel.add(self.okBtn) buttonsPanel.add(self.cancelBtn) buttonsPanel.add(self.previewBtn) buttonsPanel.setAlignmentX(Component.LEFT_ALIGNMENT) self.add(buttonsPanel) self.addWindowListener(self) self.pack()
class NewZoneDialog(JDialog, ActionListener, WindowListener): """Dialog for favourite zone editing """ def __init__(self, app): from java.awt import Dialog from java.awt import CardLayout JDialog.__init__(self, app.preferencesFrame, app.strings.getString("Create_a_new_favourite_zone"), Dialog.ModalityType.DOCUMENT_MODAL) self.app = app border = BorderFactory.createEmptyBorder(5, 7, 7, 7) self.getContentPane().setBorder(border) self.setLayout(BoxLayout(self.getContentPane(), BoxLayout.Y_AXIS)) self.FAVAREALAYERNAME = "Favourite zone editing" info = JLabel(self.app.strings.getString("Create_a_new_favourite_zone")) info.setAlignmentX(Component.LEFT_ALIGNMENT) #Name nameLbl = JLabel(self.app.strings.getString("fav_zone_name")) self.nameTextField = JTextField(20) self.nameTextField.setMaximumSize(self.nameTextField.getPreferredSize()) self.nameTextField.setToolTipText(self.app.strings.getString("fav_zone_name_tooltip")) namePanel = JPanel() namePanel.setLayout(BoxLayout(namePanel, BoxLayout.X_AXIS)) namePanel.add(nameLbl) namePanel.add(Box.createHorizontalGlue()) namePanel.add(self.nameTextField) #Country countryLbl = JLabel(self.app.strings.getString("fav_zone_country")) self.countryTextField = JTextField(20) self.countryTextField.setMaximumSize(self.countryTextField.getPreferredSize()) self.countryTextField.setToolTipText(self.app.strings.getString("fav_zone_country_tooltip")) countryPanel = JPanel() countryPanel.setLayout(BoxLayout(countryPanel, BoxLayout.X_AXIS)) countryPanel.add(countryLbl) countryPanel.add(Box.createHorizontalGlue()) countryPanel.add(self.countryTextField) #Type modeLbl = JLabel(self.app.strings.getString("fav_zone_type")) RECTPANEL = "rectangle" POLYGONPANEL = "polygon" BOUNDARYPANEL = "boundary" self.modesStrings = [RECTPANEL, POLYGONPANEL, BOUNDARYPANEL] modesComboModel = DefaultComboBoxModel() for i in (self.app.strings.getString("rectangle"), self.app.strings.getString("delimited_by_a_closed_way"), self.app.strings.getString("delimited_by_an_administrative_boundary")): modesComboModel.addElement(i) self.modesComboBox = JComboBox(modesComboModel, actionListener=self, editable=False) #- Rectangle self.rectPanel = JPanel() self.rectPanel.setLayout(BoxLayout(self.rectPanel, BoxLayout.Y_AXIS)) capturePane = JPanel() capturePane.setLayout(BoxLayout(capturePane, BoxLayout.X_AXIS)) capturePane.setAlignmentX(Component.LEFT_ALIGNMENT) josmP = JPanel() self.captureRBtn = JRadioButton(self.app.strings.getString("capture_area")) self.captureRBtn.addActionListener(self) self.captureRBtn.setSelected(True) self.bboxFromJosmBtn = JButton(self.app.strings.getString("get_current_area"), actionPerformed=self.on_bboxFromJosmBtn_clicked) self.bboxFromJosmBtn.setToolTipText(self.app.strings.getString("get_capture_area_tooltip")) josmP.add(self.bboxFromJosmBtn) capturePane.add(self.captureRBtn) capturePane.add(Box.createHorizontalGlue()) capturePane.add(self.bboxFromJosmBtn) manualPane = JPanel() manualPane.setLayout(BoxLayout(manualPane, BoxLayout.X_AXIS)) manualPane.setAlignmentX(Component.LEFT_ALIGNMENT) self.manualRBtn = JRadioButton(self.app.strings.getString("use_this_bbox")) self.manualRBtn.addActionListener(self) self.bboxTextField = JTextField(20) self.bboxTextField.setMaximumSize(self.bboxTextField.getPreferredSize()) self.bboxTextField.setToolTipText(self.app.strings.getString("fav_bbox_tooltip")) self.bboxTextFieldDefaultBorder = self.bboxTextField.getBorder() self.bboxTextField.getDocument().addDocumentListener(TextListener(self)) manualPane.add(self.manualRBtn) manualPane.add(Box.createHorizontalGlue()) manualPane.add(self.bboxTextField) group = ButtonGroup() group.add(self.captureRBtn) group.add(self.manualRBtn) previewPane = JPanel() previewPane.setLayout(BoxLayout(previewPane, BoxLayout.X_AXIS)) previewPane.setAlignmentX(Component.LEFT_ALIGNMENT) bboxPreviewInfo = JTextField(self.app.strings.getString("coordinates"), editable=0, border=None) bboxPreviewInfo.setMaximumSize(bboxPreviewInfo.getPreferredSize()) self.bboxPreviewTextField = JTextField(20, editable=0, border=None) self.bboxPreviewTextField.setMaximumSize(self.bboxPreviewTextField.getPreferredSize()) previewPane.add(bboxPreviewInfo) previewPane.add(Box.createHorizontalGlue()) previewPane.add(self.bboxPreviewTextField) self.rectPanel.add(capturePane) self.rectPanel.add(Box.createRigidArea(Dimension(0, 10))) self.rectPanel.add(manualPane) self.rectPanel.add(Box.createRigidArea(Dimension(0, 20))) self.rectPanel.add(previewPane) #- Polygon (closed way) drawn by hand self.polygonPanel = JPanel(BorderLayout()) self.polygonPanel.setLayout(BoxLayout(self.polygonPanel, BoxLayout.Y_AXIS)) polyInfo = JLabel("<html>%s</html>" % self.app.strings.getString("polygon_info")) polyInfo.setFont(polyInfo.getFont().deriveFont(Font.ITALIC)) polyInfo.setAlignmentX(Component.LEFT_ALIGNMENT) editPolyPane = JPanel() editPolyPane.setAlignmentX(Component.LEFT_ALIGNMENT) editPolyBtn = JButton(self.app.strings.getString("create_fav_layer"), actionPerformed=self.create_new_zone_editing_layer) editPolyBtn.setToolTipText(self.app.strings.getString("create_fav_layer_tooltip")) editPolyPane.add(editPolyBtn) self.polygonPanel.add(polyInfo) self.polygonPanel.add(Box.createRigidArea(Dimension(0, 15))) self.polygonPanel.add(editPolyPane) self.polygonPanel.add(Box.createRigidArea(Dimension(0, 15))) #- Administrative Boundary self.boundaryPanel = JPanel() self.boundaryPanel.setLayout(BoxLayout(self.boundaryPanel, BoxLayout.Y_AXIS)) boundaryInfo = JLabel("<html>%s</html>" % app.strings.getString("boundary_info")) boundaryInfo.setFont(boundaryInfo.getFont().deriveFont(Font.ITALIC)) boundaryInfo.setAlignmentX(Component.LEFT_ALIGNMENT) boundaryTagsPanel = JPanel(GridLayout(3, 3, 5, 5)) boundaryTagsPanel.setAlignmentX(Component.LEFT_ALIGNMENT) boundaryTagsPanel.add(JLabel("name =")) self.nameTagTextField = JTextField(20) boundaryTagsPanel.add(self.nameTagTextField) boundaryTagsPanel.add(UrlLabel("http://wiki.openstreetmap.org/wiki/Key:admin_level#admin_level", "admin_level =")) self.adminLevelTagTextField = JTextField(20) self.adminLevelTagTextField.setToolTipText(self.app.strings.getString("adminLevel_tooltip")) boundaryTagsPanel.add(self.adminLevelTagTextField) boundaryTagsPanel.add(JLabel(self.app.strings.getString("other_tag"))) self.optionalTagTextField = JTextField(20) self.optionalTagTextField.setToolTipText("key=value") boundaryTagsPanel.add(self.optionalTagTextField) downloadBoundariesPane = JPanel() downloadBoundariesPane.setAlignmentX(Component.LEFT_ALIGNMENT) downloadBoundariesBtn = JButton(self.app.strings.getString("download_boundary"), actionPerformed=self.on_downloadBoundariesBtn_clicked) downloadBoundariesBtn.setToolTipText(self.app.strings.getString("download_boundary_tooltip")) downloadBoundariesPane.add(downloadBoundariesBtn) self.boundaryPanel.add(boundaryInfo) self.boundaryPanel.add(Box.createRigidArea(Dimension(0, 15))) self.boundaryPanel.add(boundaryTagsPanel) self.boundaryPanel.add(Box.createRigidArea(Dimension(0, 10))) self.boundaryPanel.add(downloadBoundariesPane) self.editingPanels = {"rectangle": self.rectPanel, "polygon": self.polygonPanel, "boundary": self.boundaryPanel} #Main buttons self.okBtn = JButton(self.app.strings.getString("OK"), ImageProvider.get("ok"), actionPerformed=self.on_okBtn_clicked) self.cancelBtn = JButton(self.app.strings.getString("cancel"), ImageProvider.get("cancel"), actionPerformed=self.close_dialog) self.previewBtn = JButton(self.app.strings.getString("Preview_zone"), actionPerformed=self.on_previewBtn_clicked) self.previewBtn.setToolTipText(self.app.strings.getString("preview_zone_tooltip")) okBtnSize = self.okBtn.getPreferredSize() viewBtnSize = self.previewBtn.getPreferredSize() viewBtnSize.height = okBtnSize.height self.previewBtn.setPreferredSize(viewBtnSize) #layout self.add(info) self.add(Box.createRigidArea(Dimension(0, 15))) namePanel.setAlignmentX(Component.LEFT_ALIGNMENT) self.add(namePanel) self.add(Box.createRigidArea(Dimension(0, 15))) countryPanel.setAlignmentX(Component.LEFT_ALIGNMENT) self.add(countryPanel) self.add(Box.createRigidArea(Dimension(0, 15))) modeLbl.setAlignmentX(Component.LEFT_ALIGNMENT) self.add(modeLbl) self.add(Box.createRigidArea(Dimension(0, 5))) self.add(self.modesComboBox) self.modesComboBox.setAlignmentX(Component.LEFT_ALIGNMENT) self.add(Box.createRigidArea(Dimension(0, 15))) self.configPanel = JPanel(CardLayout()) self.configPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)) self.configPanel.add(self.rectPanel, RECTPANEL) self.configPanel.add(self.polygonPanel, POLYGONPANEL) self.configPanel.add(self.boundaryPanel, BOUNDARYPANEL) self.configPanel.setAlignmentX(Component.LEFT_ALIGNMENT) self.add(self.configPanel) buttonsPanel = JPanel() buttonsPanel.add(self.okBtn) buttonsPanel.add(self.cancelBtn) buttonsPanel.add(self.previewBtn) buttonsPanel.setAlignmentX(Component.LEFT_ALIGNMENT) self.add(buttonsPanel) self.addWindowListener(self) self.pack() def update_gui_from_preferences(self): self.nameTextField.setText(self.app.newZone.name) #Reset rectangle mode bboxStr = ",".join(["%0.4f" % x for x in self.app.newZone.bbox]) self.bboxTextField.setText(bboxStr) self.bboxPreviewTextField.setText(bboxStr) self.bboxFromJosmBtn.setEnabled(True) self.bboxTextField.setEnabled(False) #Reset polygon mode self.polygonAsString = "" #Reset boundary mode self.boundaryAsString = "" self.modesComboBox.setSelectedIndex(0) def actionPerformed(self, e): #Show the panel for configuring the favourite area of the #selected type if e.getSource() == self.modesComboBox: cl = self.configPanel.getLayout() selectedMode = self.modesStrings[self.modesComboBox.selectedIndex] cl.show(self.configPanel, selectedMode) #Activate bbox input for rectangular favourite zone mode elif e.getSource() == self.captureRBtn: self.bboxFromJosmBtn.setEnabled(True) self.bboxTextField.setEnabled(False) else: self.bboxFromJosmBtn.setEnabled(False) self.bboxTextField.setEnabled(True) def on_bboxFromJosmBtn_clicked(self, widget): """Read bbox currently shown in JOSM """ bbox = self.app.get_frame_bounds() self.bboxPreviewTextField.setText(",".join(["%0.4f" % x for x in bbox])) ### Manage layer for creating a new favourite zone from polygon or boundary def create_new_zone_editing_layer(self, e=None): """Open a new dataset where the user can draw a closed way to delimit the favourite area """ layer = self.get_new_zone_editing_layer() if layer is not None: self.app.mv.setActiveLayer(layer) else: Main.main.addLayer(OsmDataLayer(DataSet(), self.FAVAREALAYERNAME, None)) Main.main.parent.toFront() def get_new_zone_editing_layer(self): """Check if the layer for editing the favourite area yet exists """ for layer in self.app.mv.getAllLayers(): if layer.getName() == self.FAVAREALAYERNAME: return layer return None def remove_new_zone_editing_layer(self): layer = self.get_new_zone_editing_layer() if layer is not None: self.app.mv.removeLayer(layer) def on_zone_edited(self): """Read ways that delimit the favourite area and convert them to jts geometry """ if self.modesComboBox.getSelectedIndex() == 0: mode = "rectangle" elif self.modesComboBox.getSelectedIndex() == 1: mode = "polygon" elif self.modesComboBox.getSelectedIndex() == 2: mode = "boundary" if mode in ("polygon", "boundary"): layer = self.get_new_zone_editing_layer() if layer is not None: self.app.mv.setActiveLayer(layer) else: if mode == "polygon": msg = self.app.strings.getString("polygon_fav_layer_missing_msg") else: msg = self.app.strings.getString("boundary_fav_layer_missing_msg") JOptionPane.showMessageDialog(self, msg, self.app.strings.getString("Warning"), JOptionPane.WARNING_MESSAGE) return dataset = self.app.mv.editLayer.data areaWKT = self.read_area_from_osm_ways(mode, dataset) if areaWKT is None: print "I could not read the new favourite area." else: if mode == "polygon": self.polygonAsString = areaWKT else: self.boundaryAsString = areaWKT return mode def read_area_from_osm_ways(self, mode, dataset): """Read way in favourite area editing layer and convert them to WKT """ converter = JTSConverter(False) lines = [converter.convert(way) for way in dataset.ways] polygonizer = Polygonizer() polygonizer.add(lines) polygons = polygonizer.getPolygons() multipolygon = GeometryFactory().createMultiPolygon(list(polygons)) multipolygonWKT = WKTWriter().write(multipolygon) if multipolygonWKT == "MULTIPOLYGON EMPTY": if mode == "polygon": msg = self.app.strings.getString("empty_ways_polygon_msg") else: msg = self.app.strings.getString("empty_ways_boundaries_msg") JOptionPane.showMessageDialog(self, msg, self.app.strings.getString("Warning"), JOptionPane.WARNING_MESSAGE) return return multipolygonWKT def on_downloadBoundariesBtn_clicked(self, e): """Download puter ways of administrative boundaries from Overpass API """ adminLevel = self.adminLevelTagTextField.getText() name = self.nameTagTextField.getText() optional = self.optionalTagTextField.getText() if (adminLevel, name, optional) == ("", "", ""): JOptionPane.showMessageDialog(self, self.app.strings.getString("enter_a_tag_msg"), self.app.strings.getString("Warning"), JOptionPane.WARNING_MESSAGE) return optTag = "" if optional.find("=") != -1: if len(optional.split("=")) == 2: key, value = optional.split("=") optTag = '["%s"="%s"]' % (URLEncoder.encode(key, "UTF-8"), URLEncoder.encode(value.replace(" ", "%20"), "UTF-8")) self.create_new_zone_editing_layer() overpassurl = 'http://127.0.0.1:8111/import?url=' overpassurl += 'http://overpass-api.de/api/interpreter?data=' overpassquery = 'relation["admin_level"="%s"]' % adminLevel overpassquery += '["name"="%s"]' % URLEncoder.encode(name, "UTF-8") overpassquery += '%s;(way(r:"outer");node(w););out meta;' % optTag overpassurl += overpassquery.replace(" ", "%20") print overpassurl self.app.send_to_josm(overpassurl) ### Buttons ############################################################ def create_new_zone(self, mode): """Read data entered on gui and create a new zone """ name = self.nameTextField.getText() country = self.countryTextField.getText().upper() #error: name if name.replace(" ", "") == "": JOptionPane.showMessageDialog(self, self.app.strings.getString("missing_name_warning"), self.app.strings.getString("missing_name_warning_title"), JOptionPane.WARNING_MESSAGE) return False if name in [z.name for z in self.app.tempZones]: JOptionPane.showMessageDialog(self, self.app.strings.getString("duplicate_name_warning"), self.app.strings.getString("duplicate_name_warning_title"), JOptionPane.WARNING_MESSAGE) return False #zone type zType = mode #error: geometry type not defined if zType == "polygon" and self.polygonAsString == ""\ or zType == "boundary" and self.boundaryAsString == "": JOptionPane.showMessageDialog(self, self.app.strings.getString("zone_not_correctly_build_warning"), self.app.strings.getString("zone_not_correctly_build_warning_title"), JOptionPane.WARNING_MESSAGE) return False #geometry string if zType == "rectangle": geomString = self.bboxPreviewTextField.getText() elif zType == "polygon": geomString = self.polygonAsString else: geomString = self.boundaryAsString self.app.newZone = Zone(self.app, name, zType, geomString, country) #self.app.newZone.print_info() return True def on_okBtn_clicked(self, event): """Add new zone to temp zones """ mode = self.on_zone_edited() if self.create_new_zone(mode): self.app.tempZones.append(self.app.newZone) self.app.preferencesFrame.zonesTable.getModel().addRow([self.app.newZone.country, self.app.newZone.icon, self.app.newZone.name]) maxIndex = len(self.app.tempZones) - 1 self.app.preferencesFrame.zonesTable.setRowSelectionInterval(maxIndex, maxIndex) self.close_dialog() self.app.preferencesFrame.check_removeBtn_status() self.app.preferencesFrame.zonesTable.scrollRectToVisible( self.app.preferencesFrame.zonesTable.getCellRect( self.app.preferencesFrame.zonesTable.getRowCount() - 1, 0, True)) def on_previewBtn_clicked(self, e): """Show the favourite area on a map """ mode = self.on_zone_edited() if not self.create_new_zone(mode): return zone = self.app.newZone if zone.zType == "rectangle": wktString = zone.bbox_to_wkt_string() else: wktString = zone.wktGeom script = '/*http://stackoverflow.com/questions/11954401/wkt-and-openlayers*/' script += '\nfunction init() {' script += '\n var map = new OpenLayers.Map({' script += '\n div: "map",' script += '\n projection: new OpenLayers.Projection("EPSG:900913"),' script += '\n displayProjection: new OpenLayers.Projection("EPSG:4326"),' script += '\n layers: [' script += '\n new OpenLayers.Layer.OSM()' script += '\n ]' script += '\n });' script += '\n var wkt = new OpenLayers.Format.WKT();' script += '\n var polygonFeature = wkt.read("%s");' % wktString script += '\n var vectors = new OpenLayers.Layer.Vector("Favourite area");' script += '\n map.addLayer(vectors);' script += '\n polygonFeature.geometry.transform(map.displayProjection, map.getProjectionObject());' script += '\n vectors.addFeatures([polygonFeature]);' script += '\n map.zoomToExtent(vectors.getDataExtent());' script += '\n};' scriptFile = open(File.separator.join([self.app.SCRIPTDIR, "html", "script.js"]), "w") scriptFile.write(script) scriptFile.close() OpenBrowser.displayUrl(File.separator.join([self.app.SCRIPTDIR, "html", "favourite_area.html"])) def windowClosing(self, windowEvent): self.close_dialog() def close_dialog(self, e=None): #delete favourite zone editing layer if present self.remove_new_zone_editing_layer() self.dispose() self.app.preferencesFrame.toFront()
class BurpExtender(IBurpExtender, IHttpListener, IContextMenuFactory, ITab): def registerExtenderCallbacks(self, callbacks): self.callbacks = callbacks self.helpers = callbacks.getHelpers() callbacks.setExtensionName("Storing HTTP Requests/Responses into ElasticSearch") self.callbacks.registerHttpListener(self) self.callbacks.registerContextMenuFactory(self) self.out = callbacks.getStdout() self.lastTimestamp = None self.confESHost = self.callbacks.loadExtensionSetting("elasticburp.host") or ES_host self.confESIndex = self.callbacks.loadExtensionSetting("elasticburp.index") or ES_index self.confBurpTools = int(self.callbacks.loadExtensionSetting("elasticburp.tools") or Burp_Tools) saved_onlyresp = self.callbacks.loadExtensionSetting("elasticburp.onlyresp") if saved_onlyresp == "True": self.confBurpOnlyResp = True elif saved_onlyresp == "False": self.confBurpOnlyResp = False else: self.confBurpOnlyResp = bool(int(saved_onlyresp or Burp_onlyResponses)) self.callbacks.addSuiteTab(self) self.applyConfig() def applyConfig(self): try: print("Connecting to '%s', index '%s'" % (self.confESHost, self.confESIndex)) self.es = connections.create_connection(hosts=[self.confESHost]) self.idx = Index(self.confESIndex) self.idx.doc_type(DocHTTPRequestResponse) if self.idx.exists(): self.idx.open() else: self.idx.create() self.callbacks.saveExtensionSetting("elasticburp.host", self.confESHost) self.callbacks.saveExtensionSetting("elasticburp.index", self.confESIndex) self.callbacks.saveExtensionSetting("elasticburp.tools", str(self.confBurpTools)) self.callbacks.saveExtensionSetting("elasticburp.onlyresp", str(int(self.confBurpOnlyResp))) except Exception as e: JOptionPane.showMessageDialog(self.panel, "<html><p style='width: 300px'>Error while initializing ElasticSearch: %s</p></html>" % (str(e)), "Error", JOptionPane.ERROR_MESSAGE) ### ITab ### def getTabCaption(self): return "ElasticBurp" def applyConfigUI(self, event): #self.idx.close() self.confESHost = self.uiESHost.getText() self.confESIndex = self.uiESIndex.getText() self.confBurpTools = int((self.uiCBSuite.isSelected() and IBurpExtenderCallbacks.TOOL_SUITE) | (self.uiCBTarget.isSelected() and IBurpExtenderCallbacks.TOOL_TARGET) | (self.uiCBProxy.isSelected() and IBurpExtenderCallbacks.TOOL_PROXY) | (self.uiCBSpider.isSelected() and IBurpExtenderCallbacks.TOOL_SPIDER) | (self.uiCBScanner.isSelected() and IBurpExtenderCallbacks.TOOL_SCANNER) | (self.uiCBIntruder.isSelected() and IBurpExtenderCallbacks.TOOL_INTRUDER) | (self.uiCBRepeater.isSelected() and IBurpExtenderCallbacks.TOOL_REPEATER) | (self.uiCBSequencer.isSelected() and IBurpExtenderCallbacks.TOOL_SEQUENCER) | (self.uiCBExtender.isSelected() and IBurpExtenderCallbacks.TOOL_EXTENDER)) self.confBurpOnlyResp = self.uiCBOptRespOnly.isSelected() self.applyConfig() def resetConfigUI(self, event): self.uiESHost.setText(self.confESHost) self.uiESIndex.setText(self.confESIndex) self.uiCBSuite.setSelected(bool(self.confBurpTools & IBurpExtenderCallbacks.TOOL_SUITE)) self.uiCBTarget.setSelected(bool(self.confBurpTools & IBurpExtenderCallbacks.TOOL_TARGET)) self.uiCBProxy.setSelected(bool(self.confBurpTools & IBurpExtenderCallbacks.TOOL_PROXY)) self.uiCBSpider.setSelected(bool(self.confBurpTools & IBurpExtenderCallbacks.TOOL_SPIDER)) self.uiCBScanner.setSelected(bool(self.confBurpTools & IBurpExtenderCallbacks.TOOL_SCANNER)) self.uiCBIntruder.setSelected(bool(self.confBurpTools & IBurpExtenderCallbacks.TOOL_INTRUDER)) self.uiCBRepeater.setSelected(bool(self.confBurpTools & IBurpExtenderCallbacks.TOOL_REPEATER)) self.uiCBSequencer.setSelected(bool(self.confBurpTools & IBurpExtenderCallbacks.TOOL_SEQUENCER)) self.uiCBExtender.setSelected(bool(self.confBurpTools & IBurpExtenderCallbacks.TOOL_EXTENDER)) self.uiCBOptRespOnly.setSelected(self.confBurpOnlyResp) def getUiComponent(self): self.panel = JPanel() self.panel.setLayout(BoxLayout(self.panel, BoxLayout.PAGE_AXIS)) self.uiESHostLine = JPanel() self.uiESHostLine.setLayout(BoxLayout(self.uiESHostLine, BoxLayout.LINE_AXIS)) self.uiESHostLine.setAlignmentX(JPanel.LEFT_ALIGNMENT) self.uiESHostLine.add(JLabel("ElasticSearch Host: ")) self.uiESHost = JTextField(40) self.uiESHost.setMaximumSize(self.uiESHost.getPreferredSize()) self.uiESHostLine.add(self.uiESHost) self.panel.add(self.uiESHostLine) self.uiESIndexLine = JPanel() self.uiESIndexLine.setLayout(BoxLayout(self.uiESIndexLine, BoxLayout.LINE_AXIS)) self.uiESIndexLine.setAlignmentX(JPanel.LEFT_ALIGNMENT) self.uiESIndexLine.add(JLabel("ElasticSearch Index: ")) self.uiESIndex = JTextField(40) self.uiESIndex.setMaximumSize(self.uiESIndex.getPreferredSize()) self.uiESIndexLine.add(self.uiESIndex) self.panel.add(self.uiESIndexLine) uiToolsLine = JPanel() uiToolsLine.setLayout(BoxLayout(uiToolsLine, BoxLayout.LINE_AXIS)) uiToolsLine.setAlignmentX(JPanel.LEFT_ALIGNMENT) self.uiCBSuite = JCheckBox("Suite") uiToolsLine.add(self.uiCBSuite) uiToolsLine.add(Box.createRigidArea(Dimension(10, 0))) self.uiCBTarget = JCheckBox("Target") uiToolsLine.add(self.uiCBTarget) uiToolsLine.add(Box.createRigidArea(Dimension(10, 0))) self.uiCBProxy = JCheckBox("Proxy") uiToolsLine.add(self.uiCBProxy) uiToolsLine.add(Box.createRigidArea(Dimension(10, 0))) self.uiCBSpider = JCheckBox("Spider") uiToolsLine.add(self.uiCBSpider) uiToolsLine.add(Box.createRigidArea(Dimension(10, 0))) self.uiCBScanner = JCheckBox("Scanner") uiToolsLine.add(self.uiCBScanner) uiToolsLine.add(Box.createRigidArea(Dimension(10, 0))) self.uiCBIntruder = JCheckBox("Intruder") uiToolsLine.add(self.uiCBIntruder) uiToolsLine.add(Box.createRigidArea(Dimension(10, 0))) self.uiCBRepeater = JCheckBox("Repeater") uiToolsLine.add(self.uiCBRepeater) uiToolsLine.add(Box.createRigidArea(Dimension(10, 0))) self.uiCBSequencer = JCheckBox("Sequencer") uiToolsLine.add(self.uiCBSequencer) uiToolsLine.add(Box.createRigidArea(Dimension(10, 0))) self.uiCBExtender = JCheckBox("Extender") uiToolsLine.add(self.uiCBExtender) self.panel.add(uiToolsLine) self.panel.add(Box.createRigidArea(Dimension(0, 10))) uiOptionsLine = JPanel() uiOptionsLine.setLayout(BoxLayout(uiOptionsLine, BoxLayout.LINE_AXIS)) uiOptionsLine.setAlignmentX(JPanel.LEFT_ALIGNMENT) self.uiCBOptRespOnly = JCheckBox("Process only responses (include requests)") uiOptionsLine.add(self.uiCBOptRespOnly) self.panel.add(uiOptionsLine) self.panel.add(Box.createRigidArea(Dimension(0, 10))) uiButtonsLine = JPanel() uiButtonsLine.setLayout(BoxLayout(uiButtonsLine, BoxLayout.LINE_AXIS)) uiButtonsLine.setAlignmentX(JPanel.LEFT_ALIGNMENT) uiButtonsLine.add(JButton("Apply", actionPerformed=self.applyConfigUI)) uiButtonsLine.add(JButton("Reset", actionPerformed=self.resetConfigUI)) self.panel.add(uiButtonsLine) self.resetConfigUI(None) return self.panel ### IHttpListener ### def processHttpMessage(self, tool, isRequest, msg): if not tool & self.confBurpTools or isRequest and self.confBurpOnlyResp: return doc = self.genESDoc(msg) doc.save() ### IContextMenuFactory ### def createMenuItems(self, invocation): menuItems = list() selectedMsgs = invocation.getSelectedMessages() if selectedMsgs != None and len(selectedMsgs) >= 1: menuItems.append(JMenuItem("Add to ElasticSearch Index", actionPerformed=self.genAddToES(selectedMsgs, invocation.getInputEvent().getComponent()))) return menuItems def genAddToES(self, msgs, component): def menuAddToES(e): progress = ProgressMonitor(component, "Feeding ElasticSearch", "", 0, len(msgs)) i = 0 docs = list() for msg in msgs: if not Burp_onlyResponses or msg.getResponse(): docs.append(self.genESDoc(msg, timeStampFromResponse=True).to_dict(True)) i += 1 progress.setProgress(i) success, failed = bulk(self.es, docs, True, raise_on_error=False) progress.close() JOptionPane.showMessageDialog(self.panel, "<html><p style='width: 300px'>Successful imported %d messages, %d messages failed.</p></html>" % (success, failed), "Finished", JOptionPane.INFORMATION_MESSAGE) return menuAddToES ### Interface to ElasticSearch ### def genESDoc(self, msg, timeStampFromResponse=False): httpService = msg.getHttpService() doc = DocHTTPRequestResponse(protocol=httpService.getProtocol(), host=httpService.getHost(), port=httpService.getPort()) doc.meta.index = self.confESIndex request = msg.getRequest() response = msg.getResponse() if request: iRequest = self.helpers.analyzeRequest(msg) doc.request.method = iRequest.getMethod() doc.request.url = iRequest.getUrl().toString() headers = iRequest.getHeaders() for header in headers: try: doc.add_request_header(header) except: doc.request.requestline = header parameters = iRequest.getParameters() for parameter in parameters: ptype = parameter.getType() if ptype == IParameter.PARAM_URL: typename = "url" elif ptype == IParameter.PARAM_BODY: typename = "body" elif ptype == IParameter.PARAM_COOKIE: typename = "cookie" elif ptype == IParameter.PARAM_XML: typename = "xml" elif ptype == IParameter.PARAM_XML_ATTR: typename = "xmlattr" elif ptype == IParameter.PARAM_MULTIPART_ATTR: typename = "multipartattr" elif ptype == IParameter.PARAM_JSON: typename = "json" else: typename = "unknown" name = parameter.getName() value = parameter.getValue() doc.add_request_parameter(typename, name, value) ctype = iRequest.getContentType() if ctype == IRequestInfo.CONTENT_TYPE_NONE: doc.request.content_type = "none" elif ctype == IRequestInfo.CONTENT_TYPE_URL_ENCODED: doc.request.content_type = "urlencoded" elif ctype == IRequestInfo.CONTENT_TYPE_MULTIPART: doc.request.content_type = "multipart" elif ctype == IRequestInfo.CONTENT_TYPE_XML: doc.request.content_type = "xml" elif ctype == IRequestInfo.CONTENT_TYPE_JSON: doc.request.content_type = "json" elif ctype == IRequestInfo.CONTENT_TYPE_AMF: doc.request.content_type = "amf" else: doc.request.content_type = "unknown" bodyOffset = iRequest.getBodyOffset() doc.request.body = request[bodyOffset:].tostring().decode("ascii", "replace") if response: iResponse = self.helpers.analyzeResponse(response) doc.response.status = iResponse.getStatusCode() doc.response.content_type = iResponse.getStatedMimeType() doc.response.inferred_content_type = iResponse.getInferredMimeType() headers = iResponse.getHeaders() dateHeader = None for header in headers: try: doc.add_response_header(header) match = reDateHeader.match(header) if match: dateHeader = match.group(1) except: doc.response.responseline = header cookies = iResponse.getCookies() for cookie in cookies: expCookie = cookie.getExpiration() expiration = None if expCookie: try: expiration = str(datetime.fromtimestamp(expCookie.time / 1000)) except: pass doc.add_response_cookie(cookie.getName(), cookie.getValue(), cookie.getDomain(), cookie.getPath(), expiration) bodyOffset = iResponse.getBodyOffset() doc.response.body = response[bodyOffset:].tostring().decode("ascii", "replace") if timeStampFromResponse: if dateHeader: try: doc.timestamp = datetime.fromtimestamp(mktime_tz(parsedate_tz(dateHeader)), tz) # try to use date from response header "Date" self.lastTimestamp = doc.timestamp except: doc.timestamp = self.lastTimestamp # fallback: last stored timestamp. Else: now return doc
def getUiComponent(self): self.panel = JPanel() self.panel.setLayout(BoxLayout(self.panel, BoxLayout.PAGE_AXIS)) self.uiESHostLine = JPanel() self.uiESHostLine.setLayout(BoxLayout(self.uiESHostLine, BoxLayout.LINE_AXIS)) self.uiESHostLine.setAlignmentX(JPanel.LEFT_ALIGNMENT) self.uiESHostLine.add(JLabel("ElasticSearch Host: ")) self.uiESHost = JTextField(40) self.uiESHost.setMaximumSize(self.uiESHost.getPreferredSize()) self.uiESHostLine.add(self.uiESHost) self.panel.add(self.uiESHostLine) self.uiESIndexLine = JPanel() self.uiESIndexLine.setLayout(BoxLayout(self.uiESIndexLine, BoxLayout.LINE_AXIS)) self.uiESIndexLine.setAlignmentX(JPanel.LEFT_ALIGNMENT) self.uiESIndexLine.add(JLabel("ElasticSearch Index: ")) self.uiESIndex = JTextField(40) self.uiESIndex.setMaximumSize(self.uiESIndex.getPreferredSize()) self.uiESIndexLine.add(self.uiESIndex) self.panel.add(self.uiESIndexLine) uiToolsLine = JPanel() uiToolsLine.setLayout(BoxLayout(uiToolsLine, BoxLayout.LINE_AXIS)) uiToolsLine.setAlignmentX(JPanel.LEFT_ALIGNMENT) self.uiCBSuite = JCheckBox("Suite") uiToolsLine.add(self.uiCBSuite) uiToolsLine.add(Box.createRigidArea(Dimension(10, 0))) self.uiCBTarget = JCheckBox("Target") uiToolsLine.add(self.uiCBTarget) uiToolsLine.add(Box.createRigidArea(Dimension(10, 0))) self.uiCBProxy = JCheckBox("Proxy") uiToolsLine.add(self.uiCBProxy) uiToolsLine.add(Box.createRigidArea(Dimension(10, 0))) self.uiCBSpider = JCheckBox("Spider") uiToolsLine.add(self.uiCBSpider) uiToolsLine.add(Box.createRigidArea(Dimension(10, 0))) self.uiCBScanner = JCheckBox("Scanner") uiToolsLine.add(self.uiCBScanner) uiToolsLine.add(Box.createRigidArea(Dimension(10, 0))) self.uiCBIntruder = JCheckBox("Intruder") uiToolsLine.add(self.uiCBIntruder) uiToolsLine.add(Box.createRigidArea(Dimension(10, 0))) self.uiCBRepeater = JCheckBox("Repeater") uiToolsLine.add(self.uiCBRepeater) uiToolsLine.add(Box.createRigidArea(Dimension(10, 0))) self.uiCBSequencer = JCheckBox("Sequencer") uiToolsLine.add(self.uiCBSequencer) uiToolsLine.add(Box.createRigidArea(Dimension(10, 0))) self.uiCBExtender = JCheckBox("Extender") uiToolsLine.add(self.uiCBExtender) self.panel.add(uiToolsLine) self.panel.add(Box.createRigidArea(Dimension(0, 10))) uiOptionsLine = JPanel() uiOptionsLine.setLayout(BoxLayout(uiOptionsLine, BoxLayout.LINE_AXIS)) uiOptionsLine.setAlignmentX(JPanel.LEFT_ALIGNMENT) self.uiCBOptRespOnly = JCheckBox("Process only responses (include requests)") uiOptionsLine.add(self.uiCBOptRespOnly) self.panel.add(uiOptionsLine) self.panel.add(Box.createRigidArea(Dimension(0, 10))) uiButtonsLine = JPanel() uiButtonsLine.setLayout(BoxLayout(uiButtonsLine, BoxLayout.LINE_AXIS)) uiButtonsLine.setAlignmentX(JPanel.LEFT_ALIGNMENT) uiButtonsLine.add(JButton("Apply", actionPerformed=self.applyConfigUI)) uiButtonsLine.add(JButton("Reset", actionPerformed=self.resetConfigUI)) self.panel.add(uiButtonsLine) self.resetConfigUI(None) return self.panel
def getUiComponent(self): ui_panel = JPanel() ui_panel.setLayout(BoxLayout(ui_panel, BoxLayout.PAGE_AXIS)) ui_host_line = JPanel() ui_host_line.setLayout(BoxLayout(ui_host_line, BoxLayout.LINE_AXIS)) ui_host_line.setAlignmentX(JPanel.LEFT_ALIGNMENT) ui_host_line.add(JLabel("ElasticSearch Host: ")) self.ui_es_host = JTextField(40) self.ui_es_host.setMaximumSize(self.ui_es_host.getPreferredSize()) self.ui_es_host.setText(self.es_host) ui_host_line.add(self.ui_es_host) ui_panel.add(ui_host_line) ui_index_line = JPanel() ui_index_line.setLayout(BoxLayout(ui_index_line, BoxLayout.LINE_AXIS)) ui_index_line.setAlignmentX(JPanel.LEFT_ALIGNMENT) ui_index_line.add(JLabel("ElasticSearch Index: ")) self.ui_es_index = JTextField(40) self.ui_es_index.setText(self.es_index) self.ui_es_index.setMaximumSize(self.ui_es_index.getPreferredSize()) ui_index_line.add(self.ui_es_index) ui_panel.add(ui_index_line) ui_whitelist_line = JPanel() ui_whitelist_line.setLayout( BoxLayout(ui_whitelist_line, BoxLayout.LINE_AXIS)) ui_whitelist_line.setAlignmentX(JPanel.LEFT_ALIGNMENT) ui_whitelist_line.add(JLabel("Host whitelist: ")) self.ui_whitelist = JTextField(40) self.ui_whitelist.setText(self.whitelist) self.ui_whitelist.setMaximumSize(self.ui_whitelist.getPreferredSize()) ui_whitelist_line.add(self.ui_whitelist) ui_panel.add(ui_whitelist_line) ui_tools_panel = JPanel() ui_tools_panel.setLayout( BoxLayout(ui_tools_panel, BoxLayout.LINE_AXIS)) ui_tools_panel.setAlignmentX(JPanel.LEFT_ALIGNMENT) self.ui_tool_suite = JCheckBox( "Suite", self.tools & ECallbacks.TOOL_SUITE != 0) ui_tools_panel.add(self.ui_tool_suite) ui_tools_panel.add(Box.createRigidArea(Dimension(10, 0))) self.ui_tool_target = JCheckBox( "Target", self.tools & ECallbacks.TOOL_TARGET != 0) ui_tools_panel.add(self.ui_tool_target) ui_tools_panel.add(Box.createRigidArea(Dimension(10, 0))) self.ui_tool_proxy = JCheckBox( "Proxy", self.tools & ECallbacks.TOOL_PROXY != 0) ui_tools_panel.add(self.ui_tool_proxy) ui_tools_panel.add(Box.createRigidArea(Dimension(10, 0))) self.ui_tool_spider = JCheckBox( "Spider", self.tools & ECallbacks.TOOL_SPIDER != 0) ui_tools_panel.add(self.ui_tool_spider) ui_tools_panel.add(Box.createRigidArea(Dimension(10, 0))) self.ui_tool_scanner = JCheckBox( "Scanner", self.tools & ECallbacks.TOOL_SCANNER != 0) ui_tools_panel.add(self.ui_tool_scanner) ui_tools_panel.add(Box.createRigidArea(Dimension(10, 0))) self.ui_tool_intruder = JCheckBox( "Intruder", self.tools & ECallbacks.TOOL_INTRUDER != 0) ui_tools_panel.add(self.ui_tool_intruder) ui_tools_panel.add(Box.createRigidArea(Dimension(10, 0))) self.ui_tool_repeater = JCheckBox( "Repeater", self.tools & ECallbacks.TOOL_REPEATER != 0) ui_tools_panel.add(self.ui_tool_repeater) ui_tools_panel.add(Box.createRigidArea(Dimension(10, 0))) self.ui_tool_sequencer = JCheckBox( "Sequencer", self.tools & ECallbacks.TOOL_SEQUENCER != 0) ui_tools_panel.add(self.ui_tool_sequencer) ui_tools_panel.add(Box.createRigidArea(Dimension(10, 0))) self.ui_tool_extender = JCheckBox( "Extender", self.tools & ECallbacks.TOOL_EXTENDER != 0) ui_tools_panel.add(self.ui_tool_extender) ui_panel.add(ui_tools_panel) ui_panel.add(Box.createRigidArea(Dimension(0, 10))) ui_log_line = JPanel() ui_log_line.setLayout(BoxLayout(ui_log_line, BoxLayout.LINE_AXIS)) ui_log_line.setAlignmentX(JPanel.LEFT_ALIGNMENT) ui_debug = JRadioButton("DEBUG", self.log_level == 'DEBUG') ui_log_line.add(ui_debug) ui_log_line.add(Box.createRigidArea(Dimension(10, 0))) ui_info = JRadioButton("INFO", self.log_level == 'INFO') ui_log_line.add(ui_info) ui_log_line.add(Box.createRigidArea(Dimension(10, 0))) ui_warning = JRadioButton("WARNING", self.log_level == 'WARNING') ui_log_line.add(ui_warning) ui_log_line.add(Box.createRigidArea(Dimension(10, 0))) ui_error = JRadioButton("ERROR", self.log_level == 'ERROR') ui_log_line.add(ui_error) ui_log_line.add(Box.createRigidArea(Dimension(10, 0))) ui_critical = JRadioButton( "CRITICAL", self.log_level == 'CRITICAL') ui_log_line.add(ui_critical) ui_log_line.add(Box.createRigidArea(Dimension(10, 0))) ui_panel.add(ui_log_line) ui_panel.add(Box.createRigidArea(Dimension(0, 10))) self.ui_log_level = ButtonGroup() self.ui_log_level.add(ui_debug) self.ui_log_level.add(ui_info) self.ui_log_level.add(ui_warning) self.ui_log_level.add(ui_error) self.ui_log_level.add(ui_critical) ui_buttons_line = JPanel() ui_buttons_line.setLayout( BoxLayout(ui_buttons_line, BoxLayout.LINE_AXIS)) ui_buttons_line.setAlignmentX(JPanel.LEFT_ALIGNMENT) ui_buttons_line.add( JButton("Save config", actionPerformed=self.save_config)) ui_panel.add(ui_buttons_line) return ui_panel
letWidget.setAlignmentX(Component.LEFT_ALIGNMENT) eventWidget = EventWidget(file, amanda, amandaRef, maps.trackmap) widgetPanel = JPanel() widgetPanel.setLayout(BoxLayout(widgetPanel, BoxLayout.Y_AXIS)) widgetPanel.setMaximumSize(Dimension(400, 600)) widgetPanel.add(letWidget) widgetPanel.add(eventWidget) widgetPanel.add(Box.createHorizontalGlue()) displayPanel = display.getComponent() dim = Dimension(800, 800) displayPanel.setPreferredSize(dim) displayPanel.setMinimumSize(dim) # if widgetPanel alignment doesn't match # displayPanel alignment, BoxLayout will freak out widgetPanel.setAlignmentX(displayPanel.getAlignmentX()) widgetPanel.setAlignmentY(displayPanel.getAlignmentY()) # create JPanel in frame panel = JPanel() panel.setLayout(BoxLayout(panel, BoxLayout.X_AXIS)) panel.add(widgetPanel) panel.add(displayPanel) DisplayFrame("VisAD AMANDA Viewer", display, panel)
def __init__(self, parent, title, modal, app): from javax.swing import JTextArea border = BorderFactory.createEmptyBorder(5, 7, 7, 7) self.getContentPane().setBorder(border) self.setLayout(BoxLayout(self.getContentPane(), BoxLayout.Y_AXIS)) #Icon icon = ImageIcon(File.separator.join([app.SCRIPTDIR, "images", "icons", "logo.png"])) iconLbl = JLabel(icon) iconLbl.setAlignmentX(JLabel.CENTER_ALIGNMENT) #Name titleLbl = JLabel("Quality Assurance Tools script") titleLbl.setAlignmentX(JLabel.CENTER_ALIGNMENT) #Version p = JPanel() versionPanel = JPanel(GridLayout(2, 2)) versionPanel.add(JLabel("script: ")) versionPanel.add(JLabel(app.SCRIPTVERSION)) versionPanel.add(JLabel("tools: ")) self.toolsVersionLbl = JLabel(app.TOOLSVERSION) versionPanel.add(self.toolsVersionLbl) versionPanel.setAlignmentX(Component.CENTER_ALIGNMENT) p.add(versionPanel) #Wiki wikiLblPanel = JPanel(FlowLayout(FlowLayout.CENTER)) wikiLbl = UrlLabel(app.SCRIPTWEBSITE, "Wiki", 2) wikiLblPanel.add(wikiLbl) wikiLblPanel.setAlignmentX(JLabel.CENTER_ALIGNMENT) #Author, contributors and credits creditsTextArea = JTextArea(15, 35, editable=False) creditsTextArea.setBackground(None) contribFile = open(File.separator.join([app.SCRIPTDIR, "CONTRIBUTORS"]), "r") contribText = contribFile.read() contribFile.close() creditsTextArea.append(contribText) creditsTextArea.setCaretPosition(0) creditScrollPane = JScrollPane(creditsTextArea) #OK button okBtn = JButton("OK", ImageProvider.get("ok"), actionPerformed=self.on_okBtn_clicked) okBtn.setAlignmentX(JButton.CENTER_ALIGNMENT) #Layout self.add(Box.createRigidArea(Dimension(0, 7))) self.add(iconLbl) self.add(Box.createRigidArea(Dimension(0, 7))) self.add(titleLbl) self.add(Box.createRigidArea(Dimension(0, 7))) self.add(p) self.add(wikiLblPanel) self.add(Box.createRigidArea(Dimension(0, 7))) self.add(creditScrollPane) self.add(Box.createRigidArea(Dimension(0, 7))) self.add(okBtn) self.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE) self.pack()
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 + "<" + \ 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 __init__(self, parent, title, app): from javax.swing import JCheckBox, JRadioButton, ButtonGroup self.app = app border = BorderFactory.createEmptyBorder(5, 7, 5, 7) self.getContentPane().setBorder(border) self.getContentPane().setLayout(BorderLayout(0, 5)) self.tabbedPane = JTabbedPane() #1 Tab: general panel1 = JPanel() panel1.setBorder(BorderFactory.createEmptyBorder(7, 7, 7, 7)) panel1.setLayout(BoxLayout(panel1, BoxLayout.PAGE_AXIS)) #Checkbutton to enable/disable update check when script starts self.updateCBtn = JCheckBox(self.app.strings.getString("updateCBtn")) self.updateCBtn.setToolTipText( self.app.strings.getString("updateCBtn_tooltip")) #Download tools downloadBtn = JButton(self.app.strings.getString("updatesBtn"), ImageProvider.get("dialogs", "refresh"), actionPerformed=self.on_downloadBtn_clicked) downloadBtn.setToolTipText( self.app.strings.getString("updatesBtn_tooltip")) #Checkbuttons for enabling/disabling tools toolsPanel = JPanel(BorderLayout(0, 5)) title = self.app.strings.getString("enable_disable_tools") toolsPanel.setBorder(BorderFactory.createTitledBorder(title)) infoLbl = JLabel(self.app.strings.getString("JOSM_restart_warning")) infoLbl.setFont(infoLbl.getFont().deriveFont(Font.ITALIC)) toolsPanel.add(infoLbl, BorderLayout.PAGE_START) toolsStatusPane = JPanel(GridLayout(len(self.app.realTools), 0)) self.toolsCBtns = [] for tool in self.app.realTools: toolCBtn = JCheckBox() toolCBtn.addItemListener(self) toolLbl = JLabel(tool.title, tool.bigIcon, JLabel.LEFT) self.toolsCBtns.append(toolCBtn) toolPane = JPanel() toolPane.setLayout(BoxLayout(toolPane, BoxLayout.X_AXIS)) toolPane.add(toolCBtn) toolPane.add(toolLbl) toolsStatusPane.add(toolPane) toolsPanel.add(toolsStatusPane, BorderLayout.CENTER) #Radiobuttons for enabling/disabling layers when a new one #is added layersPanel = JPanel(GridLayout(0, 1)) title = self.app.strings.getString("errors_layers_manager") layersPanel.setBorder(BorderFactory.createTitledBorder(title)) errorLayersLbl = JLabel( self.app.strings.getString("errors_layers_info")) errorLayersLbl.setFont(errorLayersLbl.getFont().deriveFont( Font.ITALIC)) layersPanel.add(errorLayersLbl) self.layersRBtns = {} group = ButtonGroup() for mode in self.app.layersModes: layerRBtn = JRadioButton(self.app.strings.getString("%s" % mode)) group.add(layerRBtn) layersPanel.add(layerRBtn) self.layersRBtns[mode] = layerRBtn #Max number of errors text field self.maxErrorsNumberTextField = JTextField() self.maxErrorsNumberTextField.setToolTipText( self.app.strings.getString("maxErrorsNumberTextField_tooltip")) self.maxErrorsNumberTFieldDefaultBorder = self.maxErrorsNumberTextField.getBorder( ) self.maxErrorsNumberTextField.getDocument().addDocumentListener( ErrNumTextListener(self)) #layout self.updateCBtn.setAlignmentX(Component.LEFT_ALIGNMENT) panel1.add(self.updateCBtn) panel1.add(Box.createRigidArea(Dimension(0, 15))) downloadBtn.setAlignmentX(Component.LEFT_ALIGNMENT) panel1.add(downloadBtn) panel1.add(Box.createRigidArea(Dimension(0, 15))) toolsPanel.setAlignmentX(Component.LEFT_ALIGNMENT) panel1.add(toolsPanel) panel1.add(Box.createRigidArea(Dimension(0, 15))) layersPanel.setAlignmentX(Component.LEFT_ALIGNMENT) panel1.add(layersPanel) panel1.add(Box.createRigidArea(Dimension(0, 15))) maxErrP = JPanel(BorderLayout(5, 0)) maxErrP.add(JLabel(self.app.strings.getString("max_errors_number")), BorderLayout.LINE_START) maxErrP.add(self.maxErrorsNumberTextField, BorderLayout.CENTER) p = JPanel(BorderLayout()) p.add(maxErrP, BorderLayout.PAGE_START) p.setAlignmentX(Component.LEFT_ALIGNMENT) panel1.add(p) self.tabbedPane.addTab(self.app.strings.getString("tab_1_title"), None, panel1, None) #2 Tab: favourite zones panel2 = JPanel(BorderLayout(5, 15)) panel2.setBorder(BorderFactory.createEmptyBorder(7, 7, 7, 7)) #status topPanel = JPanel() topPanel.setLayout(BoxLayout(topPanel, BoxLayout.Y_AXIS)) infoPanel = HtmlPanel(self.app.strings.getString("fav_zones_info")) infoPanel.getEditorPane().addHyperlinkListener(self) infoPanel.setAlignmentX(Component.LEFT_ALIGNMENT) self.favZoneStatusCBtn = JCheckBox( self.app.strings.getString("activate_fav_area"), actionListener=self) self.favZoneStatusCBtn.setToolTipText( self.app.strings.getString("activate_fav_area_tooltip")) self.favZoneStatusCBtn.setAlignmentX(Component.LEFT_ALIGNMENT) topPanel.add(infoPanel) topPanel.add(Box.createRigidArea(Dimension(0, 10))) topPanel.add(self.favZoneStatusCBtn) #table self.zonesTable = JTable() tableSelectionModel = self.zonesTable.getSelectionModel() tableSelectionModel.addListSelectionListener(ZonesTableListener(self)) columns = [ "", self.app.strings.getString("Type"), self.app.strings.getString("Name") ] tableModel = ZonesTableModel([], columns) self.zonesTable.setModel(tableModel) self.scrollPane = JScrollPane(self.zonesTable) #map self.zonesMap = JMapViewer() self.zonesMap.setZoomContolsVisible(False) self.zonesMap.setMinimumSize(Dimension(100, 200)) #buttons self.removeBtn = JButton(self.app.strings.getString("Remove"), ImageProvider.get("dialogs", "delete"), actionPerformed=self.on_removeBtn_clicked) self.removeBtn.setToolTipText( self.app.strings.getString("remove_tooltip")) newBtn = JButton(self.app.strings.getString("New"), ImageProvider.get("dialogs", "add"), actionPerformed=self.on_newBtn_clicked) newBtn.setToolTipText(self.app.strings.getString("new_tooltip")) #layout panel2.add(topPanel, BorderLayout.PAGE_START) panel2.add(self.scrollPane, BorderLayout.LINE_START) panel2.add(self.zonesMap, BorderLayout.CENTER) self.buttonsPanel = JPanel() self.buttonsPanel.add(self.removeBtn) self.buttonsPanel.add(newBtn) panel2.add(self.buttonsPanel, BorderLayout.PAGE_END) self.tabbedPane.addTab(self.app.strings.getString("tab_2_title"), None, panel2, None) #3 Tab Tools options panel3 = JPanel() panel3.setLayout(BoxLayout(panel3, BoxLayout.Y_AXIS)) panel3.setBorder(BorderFactory.createEmptyBorder(7, 7, 7, 7)) for tool in self.app.realTools: if hasattr(tool, 'prefs'): p = JPanel(FlowLayout(FlowLayout.LEFT)) p.setBorder(BorderFactory.createTitledBorder(tool.title)) p.add(tool.prefsGui) panel3.add(p) self.tabbedPane.addTab(self.app.strings.getString("tab_3_title"), None, panel3, None) self.add(self.tabbedPane, BorderLayout.CENTER) exitPanel = JPanel() saveBtn = JButton(self.app.strings.getString("OK"), ImageProvider.get("ok"), actionPerformed=self.on_saveBtn_clicked) cancelBtn = JButton(self.app.strings.getString("cancel"), ImageProvider.get("cancel"), actionPerformed=self.on_cancelBtn_clicked) saveBtn.setToolTipText(self.app.strings.getString("save_preferences")) saveBtn.setAlignmentX(0.5) exitPanel.add(saveBtn) exitPanel.add(cancelBtn) self.add(exitPanel, BorderLayout.PAGE_END) self.addWindowListener(self) self.pack()
def getUiComponent(self): self.panel = JPanel() self.panel.setLayout(BoxLayout(self.panel, BoxLayout.PAGE_AXIS)) self.uiESHostLine = JPanel() self.uiESHostLine.setLayout( BoxLayout(self.uiESHostLine, BoxLayout.LINE_AXIS)) self.uiESHostLine.setAlignmentX(JPanel.LEFT_ALIGNMENT) self.uiESHostLine.add(JLabel("ElasticSearch Host: ")) self.uiESHost = JTextField(40) self.uiESHost.setMaximumSize(self.uiESHost.getPreferredSize()) self.uiESHostLine.add(self.uiESHost) self.panel.add(self.uiESHostLine) self.uiESIndexLine = JPanel() self.uiESIndexLine.setLayout( BoxLayout(self.uiESIndexLine, BoxLayout.LINE_AXIS)) self.uiESIndexLine.setAlignmentX(JPanel.LEFT_ALIGNMENT) self.uiESIndexLine.add(JLabel("ElasticSearch Index: ")) self.uiESIndex = JTextField(40) self.uiESIndex.setMaximumSize(self.uiESIndex.getPreferredSize()) self.uiESIndexLine.add(self.uiESIndex) self.panel.add(self.uiESIndexLine) uiToolsLine = JPanel() uiToolsLine.setLayout(BoxLayout(uiToolsLine, BoxLayout.LINE_AXIS)) uiToolsLine.setAlignmentX(JPanel.LEFT_ALIGNMENT) self.uiCBSuite = JCheckBox("Suite") uiToolsLine.add(self.uiCBSuite) uiToolsLine.add(Box.createRigidArea(Dimension(10, 0))) self.uiCBTarget = JCheckBox("Target") uiToolsLine.add(self.uiCBTarget) uiToolsLine.add(Box.createRigidArea(Dimension(10, 0))) self.uiCBProxy = JCheckBox("Proxy") uiToolsLine.add(self.uiCBProxy) uiToolsLine.add(Box.createRigidArea(Dimension(10, 0))) self.uiCBSpider = JCheckBox("Spider") uiToolsLine.add(self.uiCBSpider) uiToolsLine.add(Box.createRigidArea(Dimension(10, 0))) self.uiCBScanner = JCheckBox("Scanner") uiToolsLine.add(self.uiCBScanner) uiToolsLine.add(Box.createRigidArea(Dimension(10, 0))) self.uiCBIntruder = JCheckBox("Intruder") uiToolsLine.add(self.uiCBIntruder) uiToolsLine.add(Box.createRigidArea(Dimension(10, 0))) self.uiCBRepeater = JCheckBox("Repeater") uiToolsLine.add(self.uiCBRepeater) uiToolsLine.add(Box.createRigidArea(Dimension(10, 0))) self.uiCBSequencer = JCheckBox("Sequencer") uiToolsLine.add(self.uiCBSequencer) uiToolsLine.add(Box.createRigidArea(Dimension(10, 0))) self.uiCBExtender = JCheckBox("Extender") uiToolsLine.add(self.uiCBExtender) self.panel.add(uiToolsLine) self.panel.add(Box.createRigidArea(Dimension(0, 10))) uiOptionsLine = JPanel() uiOptionsLine.setLayout(BoxLayout(uiOptionsLine, BoxLayout.LINE_AXIS)) uiOptionsLine.setAlignmentX(JPanel.LEFT_ALIGNMENT) self.uiCBOptRespOnly = JCheckBox( "Process only responses (include requests)") uiOptionsLine.add(self.uiCBOptRespOnly) self.panel.add(uiOptionsLine) self.panel.add(Box.createRigidArea(Dimension(0, 10))) uiButtonsLine = JPanel() uiButtonsLine.setLayout(BoxLayout(uiButtonsLine, BoxLayout.LINE_AXIS)) uiButtonsLine.setAlignmentX(JPanel.LEFT_ALIGNMENT) uiButtonsLine.add(JButton("Apply", actionPerformed=self.applyConfigUI)) uiButtonsLine.add(JButton("Reset", actionPerformed=self.resetConfigUI)) self.panel.add(uiButtonsLine) self.resetConfigUI(None) return self.panel
class BurpExtender(IBurpExtender, IHttpListener, IContextMenuFactory, ITab): def registerExtenderCallbacks(self, callbacks): self.callbacks = callbacks self.helpers = callbacks.getHelpers() callbacks.setExtensionName( "Storing HTTP Requests/Responses into ElasticSearch") self.callbacks.registerHttpListener(self) self.callbacks.registerContextMenuFactory(self) self.out = callbacks.getStdout() self.lastTimestamp = None self.confESHost = self.callbacks.loadExtensionSetting( "elasticburp.host") or ES_host self.confESIndex = self.callbacks.loadExtensionSetting( "elasticburp.index") or ES_index self.confBurpTools = int( self.callbacks.loadExtensionSetting("elasticburp.tools") or Burp_Tools) saved_onlyresp = self.callbacks.loadExtensionSetting( "elasticburp.onlyresp") if saved_onlyresp == "True": self.confBurpOnlyResp = True elif saved_onlyresp == "False": self.confBurpOnlyResp = False else: self.confBurpOnlyResp = bool( int(saved_onlyresp or Burp_onlyResponses)) self.callbacks.addSuiteTab(self) self.applyConfig() def applyConfig(self): try: print("Connecting to '%s', index '%s'" % (self.confESHost, self.confESIndex)) self.es = connections.create_connection(hosts=[self.confESHost]) self.idx = Index(self.confESIndex) self.idx.doc_type(DocHTTPRequestResponse) if self.idx.exists(): self.idx.open() else: self.idx.create() self.callbacks.saveExtensionSetting("elasticburp.host", self.confESHost) self.callbacks.saveExtensionSetting("elasticburp.index", self.confESIndex) self.callbacks.saveExtensionSetting("elasticburp.tools", str(self.confBurpTools)) self.callbacks.saveExtensionSetting( "elasticburp.onlyresp", str(int(self.confBurpOnlyResp))) except Exception as e: JOptionPane.showMessageDialog( self.panel, "<html><p style='width: 300px'>Error while initializing ElasticSearch: %s</p></html>" % (str(e)), "Error", JOptionPane.ERROR_MESSAGE) ### ITab ### def getTabCaption(self): return "ElasticBurp" def applyConfigUI(self, event): #self.idx.close() self.confESHost = self.uiESHost.getText() self.confESIndex = self.uiESIndex.getText() self.confBurpTools = int( (self.uiCBSuite.isSelected() and IBurpExtenderCallbacks.TOOL_SUITE) | (self.uiCBTarget.isSelected() and IBurpExtenderCallbacks.TOOL_TARGET) | (self.uiCBProxy.isSelected() and IBurpExtenderCallbacks.TOOL_PROXY) | (self.uiCBSpider.isSelected() and IBurpExtenderCallbacks.TOOL_SPIDER) | (self.uiCBScanner.isSelected() and IBurpExtenderCallbacks.TOOL_SCANNER) | (self.uiCBIntruder.isSelected() and IBurpExtenderCallbacks.TOOL_INTRUDER) | (self.uiCBRepeater.isSelected() and IBurpExtenderCallbacks.TOOL_REPEATER) | (self.uiCBSequencer.isSelected() and IBurpExtenderCallbacks.TOOL_SEQUENCER) | (self.uiCBExtender.isSelected() and IBurpExtenderCallbacks.TOOL_EXTENDER)) self.confBurpOnlyResp = self.uiCBOptRespOnly.isSelected() self.applyConfig() def resetConfigUI(self, event): self.uiESHost.setText(self.confESHost) self.uiESIndex.setText(self.confESIndex) self.uiCBSuite.setSelected( bool(self.confBurpTools & IBurpExtenderCallbacks.TOOL_SUITE)) self.uiCBTarget.setSelected( bool(self.confBurpTools & IBurpExtenderCallbacks.TOOL_TARGET)) self.uiCBProxy.setSelected( bool(self.confBurpTools & IBurpExtenderCallbacks.TOOL_PROXY)) self.uiCBSpider.setSelected( bool(self.confBurpTools & IBurpExtenderCallbacks.TOOL_SPIDER)) self.uiCBScanner.setSelected( bool(self.confBurpTools & IBurpExtenderCallbacks.TOOL_SCANNER)) self.uiCBIntruder.setSelected( bool(self.confBurpTools & IBurpExtenderCallbacks.TOOL_INTRUDER)) self.uiCBRepeater.setSelected( bool(self.confBurpTools & IBurpExtenderCallbacks.TOOL_REPEATER)) self.uiCBSequencer.setSelected( bool(self.confBurpTools & IBurpExtenderCallbacks.TOOL_SEQUENCER)) self.uiCBExtender.setSelected( bool(self.confBurpTools & IBurpExtenderCallbacks.TOOL_EXTENDER)) self.uiCBOptRespOnly.setSelected(self.confBurpOnlyResp) def getUiComponent(self): self.panel = JPanel() self.panel.setLayout(BoxLayout(self.panel, BoxLayout.PAGE_AXIS)) self.uiESHostLine = JPanel() self.uiESHostLine.setLayout( BoxLayout(self.uiESHostLine, BoxLayout.LINE_AXIS)) self.uiESHostLine.setAlignmentX(JPanel.LEFT_ALIGNMENT) self.uiESHostLine.add(JLabel("ElasticSearch Host: ")) self.uiESHost = JTextField(40) self.uiESHost.setMaximumSize(self.uiESHost.getPreferredSize()) self.uiESHostLine.add(self.uiESHost) self.panel.add(self.uiESHostLine) self.uiESIndexLine = JPanel() self.uiESIndexLine.setLayout( BoxLayout(self.uiESIndexLine, BoxLayout.LINE_AXIS)) self.uiESIndexLine.setAlignmentX(JPanel.LEFT_ALIGNMENT) self.uiESIndexLine.add(JLabel("ElasticSearch Index: ")) self.uiESIndex = JTextField(40) self.uiESIndex.setMaximumSize(self.uiESIndex.getPreferredSize()) self.uiESIndexLine.add(self.uiESIndex) self.panel.add(self.uiESIndexLine) uiToolsLine = JPanel() uiToolsLine.setLayout(BoxLayout(uiToolsLine, BoxLayout.LINE_AXIS)) uiToolsLine.setAlignmentX(JPanel.LEFT_ALIGNMENT) self.uiCBSuite = JCheckBox("Suite") uiToolsLine.add(self.uiCBSuite) uiToolsLine.add(Box.createRigidArea(Dimension(10, 0))) self.uiCBTarget = JCheckBox("Target") uiToolsLine.add(self.uiCBTarget) uiToolsLine.add(Box.createRigidArea(Dimension(10, 0))) self.uiCBProxy = JCheckBox("Proxy") uiToolsLine.add(self.uiCBProxy) uiToolsLine.add(Box.createRigidArea(Dimension(10, 0))) self.uiCBSpider = JCheckBox("Spider") uiToolsLine.add(self.uiCBSpider) uiToolsLine.add(Box.createRigidArea(Dimension(10, 0))) self.uiCBScanner = JCheckBox("Scanner") uiToolsLine.add(self.uiCBScanner) uiToolsLine.add(Box.createRigidArea(Dimension(10, 0))) self.uiCBIntruder = JCheckBox("Intruder") uiToolsLine.add(self.uiCBIntruder) uiToolsLine.add(Box.createRigidArea(Dimension(10, 0))) self.uiCBRepeater = JCheckBox("Repeater") uiToolsLine.add(self.uiCBRepeater) uiToolsLine.add(Box.createRigidArea(Dimension(10, 0))) self.uiCBSequencer = JCheckBox("Sequencer") uiToolsLine.add(self.uiCBSequencer) uiToolsLine.add(Box.createRigidArea(Dimension(10, 0))) self.uiCBExtender = JCheckBox("Extender") uiToolsLine.add(self.uiCBExtender) self.panel.add(uiToolsLine) self.panel.add(Box.createRigidArea(Dimension(0, 10))) uiOptionsLine = JPanel() uiOptionsLine.setLayout(BoxLayout(uiOptionsLine, BoxLayout.LINE_AXIS)) uiOptionsLine.setAlignmentX(JPanel.LEFT_ALIGNMENT) self.uiCBOptRespOnly = JCheckBox( "Process only responses (include requests)") uiOptionsLine.add(self.uiCBOptRespOnly) self.panel.add(uiOptionsLine) self.panel.add(Box.createRigidArea(Dimension(0, 10))) uiButtonsLine = JPanel() uiButtonsLine.setLayout(BoxLayout(uiButtonsLine, BoxLayout.LINE_AXIS)) uiButtonsLine.setAlignmentX(JPanel.LEFT_ALIGNMENT) uiButtonsLine.add(JButton("Apply", actionPerformed=self.applyConfigUI)) uiButtonsLine.add(JButton("Reset", actionPerformed=self.resetConfigUI)) self.panel.add(uiButtonsLine) self.resetConfigUI(None) return self.panel ### IHttpListener ### def processHttpMessage(self, tool, isRequest, msg): if not tool & self.confBurpTools or isRequest and self.confBurpOnlyResp: return doc = self.genESDoc(msg) doc.save() ### IContextMenuFactory ### def createMenuItems(self, invocation): menuItems = list() selectedMsgs = invocation.getSelectedMessages() if selectedMsgs != None and len(selectedMsgs) >= 1: menuItems.append( JMenuItem("Add to ElasticSearch Index", actionPerformed=self.genAddToES( selectedMsgs, invocation.getInputEvent().getComponent()))) return menuItems def genAddToES(self, msgs, component): def menuAddToES(e): progress = ProgressMonitor(component, "Feeding ElasticSearch", "", 0, len(msgs)) i = 0 docs = list() for msg in msgs: if not Burp_onlyResponses or msg.getResponse(): docs.append( self.genESDoc( msg, timeStampFromResponse=True).to_dict(True)) i += 1 progress.setProgress(i) success, failed = bulk(self.es, docs, True, raise_on_error=False) progress.close() JOptionPane.showMessageDialog( self.panel, "<html><p style='width: 300px'>Successful imported %d messages, %d messages failed.</p></html>" % (success, failed), "Finished", JOptionPane.INFORMATION_MESSAGE) return menuAddToES ### Interface to ElasticSearch ### def genESDoc(self, msg, timeStampFromResponse=False): httpService = msg.getHttpService() doc = DocHTTPRequestResponse(protocol=httpService.getProtocol(), host=httpService.getHost(), port=httpService.getPort()) doc.meta.index = self.confESIndex request = msg.getRequest() response = msg.getResponse() if request: iRequest = self.helpers.analyzeRequest(msg) doc.request.method = iRequest.getMethod() doc.request.url = iRequest.getUrl().toString() headers = iRequest.getHeaders() for header in headers: try: doc.add_request_header(header) except: doc.request.requestline = header parameters = iRequest.getParameters() for parameter in parameters: ptype = parameter.getType() if ptype == IParameter.PARAM_URL: typename = "url" elif ptype == IParameter.PARAM_BODY: typename = "body" elif ptype == IParameter.PARAM_COOKIE: typename = "cookie" elif ptype == IParameter.PARAM_XML: typename = "xml" elif ptype == IParameter.PARAM_XML_ATTR: typename = "xmlattr" elif ptype == IParameter.PARAM_MULTIPART_ATTR: typename = "multipartattr" elif ptype == IParameter.PARAM_JSON: typename = "json" else: typename = "unknown" name = parameter.getName() value = parameter.getValue() doc.add_request_parameter(typename, name, value) ctype = iRequest.getContentType() if ctype == IRequestInfo.CONTENT_TYPE_NONE: doc.request.content_type = "none" elif ctype == IRequestInfo.CONTENT_TYPE_URL_ENCODED: doc.request.content_type = "urlencoded" elif ctype == IRequestInfo.CONTENT_TYPE_MULTIPART: doc.request.content_type = "multipart" elif ctype == IRequestInfo.CONTENT_TYPE_XML: doc.request.content_type = "xml" elif ctype == IRequestInfo.CONTENT_TYPE_JSON: doc.request.content_type = "json" elif ctype == IRequestInfo.CONTENT_TYPE_AMF: doc.request.content_type = "amf" else: doc.request.content_type = "unknown" bodyOffset = iRequest.getBodyOffset() doc.request.body = request[bodyOffset:].tostring().decode( "ascii", "replace") if response: iResponse = self.helpers.analyzeResponse(response) doc.response.status = iResponse.getStatusCode() doc.response.content_type = iResponse.getStatedMimeType() doc.response.inferred_content_type = iResponse.getInferredMimeType( ) headers = iResponse.getHeaders() dateHeader = None for header in headers: try: doc.add_response_header(header) match = reDateHeader.match(header) if match: dateHeader = match.group(1) except: doc.response.responseline = header cookies = iResponse.getCookies() for cookie in cookies: expCookie = cookie.getExpiration() expiration = None if expCookie: try: expiration = str( datetime.fromtimestamp(expCookie.time / 1000)) except: pass doc.add_response_cookie(cookie.getName(), cookie.getValue(), cookie.getDomain(), cookie.getPath(), expiration) bodyOffset = iResponse.getBodyOffset() doc.response.body = response[bodyOffset:].tostring().decode( "ascii", "replace") if timeStampFromResponse: if dateHeader: try: doc.timestamp = datetime.fromtimestamp( mktime_tz(parsedate_tz(dateHeader)), tz) # try to use date from response header "Date" self.lastTimestamp = doc.timestamp except: doc.timestamp = self.lastTimestamp # fallback: last stored timestamp. Else: now return doc
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")