all = JPanel() layout = GridLayout(4, 1) all.setLayout(layout) all.add( JLabel(" ") ) all.add( button ) all.add( JLabel("Min") ) all.add( minField ) all.add( JLabel("Max") ) all.add(maxField ) all.add( JLabel("Score :") ) all.add(scoreField) frame = JFrame("CCM scoring") frame.getContentPane().add(JScrollPane(all)) frame.pack() frame.addWindowListener( Closing() ) scoreField.requestFocusInWindow() # Get the grid files chooser = JFileChooser() chooser.setDialogTitle("Choose plate grids") chooser.setMultiSelectionEnabled(True) chooser.setCurrentDirectory( File(os.path.expanduser("~"))) chooser.showOpenDialog(JPanel()) # This is a hack to get a file path from the # sun.awt.shell.DefaultShellFolder object returned by the chooser fp = [str(i) for i in chooser.getSelectedFiles()] if len(fp) != 0: gd = GenericDialog("Name your output file") gd.addStringField("Score file name", "scores.csv")
class BurpExtender(IBurpExtender, ITab, IScannerCheck, IContextMenuFactory, IParameter, IIntruderPayloadGeneratorFactory): def registerExtenderCallbacks(self, callbacks): self.callbacks = callbacks self.helpers = callbacks.getHelpers() callbacks.setExtensionName("Session Authentication Tool") self.out = callbacks.getStdout() # definition of suite tab self.tab = JPanel(GridBagLayout()) self.tabledata = MappingTableModel(callbacks) self.table = JTable(self.tabledata) #self.table.getColumnModel().getColumn(0).setPreferredWidth(50); #self.table.getColumnModel().getColumn(1).setPreferredWidth(100); self.tablecont = JScrollPane(self.table) c = GridBagConstraints() c.fill = GridBagConstraints.HORIZONTAL c.anchor = GridBagConstraints.FIRST_LINE_START c.gridx = 0 c.gridy = 0 c.gridheight = 6 c.weightx = 0.3 c.weighty = 0.5 self.tab.add(self.tablecont, c) c = GridBagConstraints() c.weightx = 0.1 c.anchor = GridBagConstraints.FIRST_LINE_START c.gridx = 1 c.gridy = 0 label_id = JLabel("Identifier:") self.tab.add(label_id, c) self.input_id = JTextField(20) self.input_id.setToolTipText("Enter the identifier which is used by the application to identifiy a particular test user account, e.g. a numerical user id or a user name.") c.gridy = 1 self.tab.add(self.input_id, c) c.gridy = 2 label_content = JLabel("Content:") self.tab.add(label_content, c) self.input_content = JTextField(20, actionPerformed=self.btn_add_id) self.input_content.setToolTipText("Enter some content which is displayed in responses of the application and shows that the current session belongs to a particular user, e.g. the full name of the user.") c.gridy = 3 self.tab.add(self.input_content, c) self.btn_add = JButton("Add/Edit Identity", actionPerformed=self.btn_add_id) c.gridy = 4 self.tab.add(self.btn_add, c) self.btn_del = JButton("Delete Identity", actionPerformed=self.btn_del_id) c.gridy = 5 self.tab.add(self.btn_del, c) callbacks.customizeUiComponent(self.tab) callbacks.customizeUiComponent(self.table) callbacks.customizeUiComponent(self.tablecont) callbacks.customizeUiComponent(self.btn_add) callbacks.customizeUiComponent(self.btn_del) callbacks.customizeUiComponent(label_id) callbacks.customizeUiComponent(self.input_id) callbacks.addSuiteTab(self) callbacks.registerScannerCheck(self) callbacks.registerIntruderPayloadGeneratorFactory(self) callbacks.registerContextMenuFactory(self) def btn_add_id(self, e): ident = self.input_id.text self.input_id.text = "" content = self.input_content.text self.input_content.text = "" self.tabledata.add_mapping(ident, content) self.input_id.requestFocusInWindow() def btn_del_id(self, e): rows = self.table.getSelectedRows().tolist() self.tabledata.del_rows(rows) ### ITab ### def getTabCaption(self): return("SessionAuth") def getUiComponent(self): return self.tab ### IContextMenuFactory ### def createMenuItems(self, invocation): menuitems = list() msgs = invocation.getSelectedMessages() if msgs != None: if len(msgs) == 1: # "add as object id/as content to last id" context menu items bounds = invocation.getSelectionBounds() if bounds != None and bounds[0] != bounds[1]: msg = None if invocation.getInvocationContext() == IContextMenuInvocation.CONTEXT_MESSAGE_EDITOR_REQUEST or invocation.getInvocationContext() == IContextMenuInvocation.CONTEXT_MESSAGE_VIEWER_REQUEST: msg = msgs[0].getRequest().tostring() if invocation.getInvocationContext() == IContextMenuInvocation.CONTEXT_MESSAGE_EDITOR_RESPONSE or invocation.getInvocationContext() == IContextMenuInvocation.CONTEXT_MESSAGE_VIEWER_RESPONSE: msg = msgs[0].getResponse().tostring() if msg != None: selection = msg[bounds[0]:bounds[1]] shortSelection = selection[:20] if len(selection) > len(shortSelection): shortSelection += "..." menuitems.append(JMenuItem("Add '" + shortSelection + "' as object id", actionPerformed=self.gen_menu_add_id(selection))) if self.tabledata.lastadded != None: menuitems.append(JMenuItem("Add '" + shortSelection + "' as content to last added id", actionPerformed=self.gen_menu_add_content(selection))) if len(msgs) > 0: # "Send to Intruder" context menu items requestsWithIds = list() for msg in msgs: if isinstance(msg.getRequest(), array) and self.tabledata.containsId(msg.getRequest().tostring()): requestsWithIds.append(msg) if len(requestsWithIds) > 0: menuitems.append(JMenuItem("Send to Intruder and preconfigure id injection points", actionPerformed=self.gen_menu_send_intruder(requestsWithIds))) return menuitems def gen_menu_add_id(self, ident): def menu_add_id(e): self.tabledata.add_mapping(ident, "") return menu_add_id def gen_menu_add_content(self, content): def menu_add_content(e): self.tabledata.set_lastadded_content(content) return menu_add_content def gen_menu_send_intruder(self, requestResponses): def menu_send_intruder(e): for requestResponse in requestResponses: httpService = requestResponse.getHttpService() request = requestResponse.getRequest() injectionPoints = list() for ident in self.tabledata.getIds(): newInjectionPoints = findAll(request.tostring(), ident) if newInjectionPoints != None: injectionPoints += newInjectionPoints if len(injectionPoints) > 0: self.callbacks.sendToIntruder(httpService.getHost(), httpService.getPort(), httpService.getProtocol() == "https", request, injectionPoints) return menu_send_intruder ### IIntruderPayloadGeneratorFactory ### def getGeneratorName(self): return "SessionAuth Identifiers" def createNewInstance(self, attack): return IdentifiersPayloadGenerator(self.tabledata) ### IScannerCheck ### def doPassiveScan(self, baseRequestResponse): analyzedRequest = self.helpers.analyzeRequest(baseRequestResponse) params = analyzedRequest.getParameters() ids = self.tabledata.getIds() issues = list() for param in params: value = param.getValue() for ident in ids: if value == ident: issues.append(SessionAuthPassiveScanIssue( analyzedRequest.getUrl(), baseRequestResponse, param, ident, self.tabledata.getValue(ident), SessionAuthPassiveScanIssue.foundEqual, self.callbacks )) elif value.find(ident) >= 0: issues.append(SessionAuthPassiveScanIssue( analyzedRequest.getUrl(), baseRequestResponse, param, ident, self.tabledata.getValue(ident), SessionAuthPassiveScanIssue.foundInside, self.callbacks )) if len(issues) > 0: return issues else: return None def doActiveScan(self, baseRequestResponse, insertionPoint): ids = self.tabledata.getIds() if len(ids) <= 1: # active check only possible if multiple ids were given return None baseVal = insertionPoint.getBaseValue() url = baseRequestResponse.getUrl() idFound = list() for ident in ids: # find all identifiers in base value if baseVal.find(ident) >= 0: idFound.append(ident) if len(idFound) == 0: # no given identifier found, nothing to do return None baseResponse = baseRequestResponse.getResponse().tostring() baseResponseBody = baseResponse[self.helpers.analyzeResponse(baseResponse).getBodyOffset():] issues = list() scannedCombos = list() for replaceId in idFound: # scanner checks: replace found id by other given ids for scanId in ids: if replaceId == scanId or set([replaceId, scanId]) in scannedCombos: continue scannedCombos.append(set([replaceId, scanId])) scanPayload = baseVal.replace(replaceId, scanId) scanRequest = insertionPoint.buildRequest(scanPayload) scanRequestResponse = self.callbacks.makeHttpRequest(baseRequestResponse.getHttpService(), scanRequest) scanResponse = scanRequestResponse.getResponse().tostring() scanResponseBody = scanResponse[self.helpers.analyzeResponse(scanResponse).getBodyOffset():] if baseResponseBody == scanResponseBody: # response hasn't changed - no issue continue # Analyze responses replaceValue = self.tabledata.getValue(replaceId) scanValue = self.tabledata.getValue(scanId) # naming convention: # first word: base || scan (response) # second word: Replace || Scan (value) if replaceValue != "": baseReplaceValueCount = len(baseResponseBody.split(replaceValue)) - 1 scanReplaceValueCount = len(scanResponseBody.split(replaceValue)) - 1 else: baseReplaceValueCount = 0 scanReplaceValueCount = 0 if scanValue != "": baseScanValueCount = len(baseResponseBody.split(scanValue)) - 1 scanScanValueCount = len(scanResponseBody.split(scanValue)) - 1 else: baseScanValueCount = 0 scanScanValueCount = 0 if scanScanValueCount == 0: # Scan identifier content value doesn't appears, but responses differ issueCase = SessionAuthActiveScanIssue.caseScanValueNotFound elif baseReplaceValueCount > 0 and baseScanValueCount == 0 and scanReplaceValueCount == 0 and scanScanValueCount == baseReplaceValueCount: # Scan identifier replaces all occurrences of the original identifier in the response issueCase = SessionAuthActiveScanIssue.caseScanValueAppearsExactly elif baseReplaceValueCount > 0 and baseScanValueCount == 0 and scanReplaceValueCount == 0 and scanScanValueCount > 0: # Scan identfiers value appears, replaced ids value disappears issueCase = SessionAuthActiveScanIssue.caseScanValueAppearsFuzzy elif baseReplaceValueCount > scanReplaceValueCount and baseScanValueCount < scanScanValueCount: # Occurence count of replaced id value decreases, scan id value increases issueCase = SessionAuthActiveScanIssue.caseDecreaseIncrease elif baseScanValueCount < scanScanValueCount: # Occurence count of scan id value increases issueCase = SessionAuthActiveScanIssue.caseScanValueIncrease else: # Remainingg cases issueCase = SessionAuthActiveScanIssue.caseOther issues.append(SessionAuthActiveScanIssue( url, baseRequestResponse, insertionPoint, scanPayload, scanRequestResponse, replaceId, replaceValue, scanId, scanValue, issueCase, self.callbacks )) if len(issues) > 0: return issues else: return None def consolidateDuplicateIssues(self, existingIssue, newIssue): if existingIssue.getIssueDetail() == newIssue.getIssueDetail(): return 1 else: return 0
class BurpExtender(IBurpExtender, ITab, IScannerCheck, IContextMenuFactory, IParameter, IIntruderPayloadGeneratorFactory): def registerExtenderCallbacks(self, callbacks): self.callbacks = callbacks self.helpers = callbacks.getHelpers() callbacks.setExtensionName("Session Authentication Tool") self.out = callbacks.getStdout() # definition of suite tab self.tab = JPanel(GridBagLayout()) self.tabledata = MappingTableModel(callbacks) self.table = JTable(self.tabledata) #self.table.getColumnModel().getColumn(0).setPreferredWidth(50); #self.table.getColumnModel().getColumn(1).setPreferredWidth(100); self.tablecont = JScrollPane(self.table) c = GridBagConstraints() c.fill = GridBagConstraints.HORIZONTAL c.anchor = GridBagConstraints.FIRST_LINE_START c.gridx = 0 c.gridy = 0 c.gridheight = 6 c.weightx = 0.3 c.weighty = 0.5 self.tab.add(self.tablecont, c) c = GridBagConstraints() c.weightx = 0.1 c.anchor = GridBagConstraints.FIRST_LINE_START c.gridx = 1 c.gridy = 0 label_id = JLabel("Identifier:") self.tab.add(label_id, c) self.input_id = JTextField(20) self.input_id.setToolTipText( "Enter the identifier which is used by the application to identifiy a particular test user account, e.g. a numerical user id or a user name." ) c.gridy = 1 self.tab.add(self.input_id, c) c.gridy = 2 label_content = JLabel("Content:") self.tab.add(label_content, c) self.input_content = JTextField(20, actionPerformed=self.btn_add_id) self.input_content.setToolTipText( "Enter some content which is displayed in responses of the application and shows that the current session belongs to a particular user, e.g. the full name of the user." ) c.gridy = 3 self.tab.add(self.input_content, c) self.btn_add = JButton("Add/Edit Identity", actionPerformed=self.btn_add_id) c.gridy = 4 self.tab.add(self.btn_add, c) self.btn_del = JButton("Delete Identity", actionPerformed=self.btn_del_id) c.gridy = 5 self.tab.add(self.btn_del, c) callbacks.customizeUiComponent(self.tab) callbacks.customizeUiComponent(self.table) callbacks.customizeUiComponent(self.tablecont) callbacks.customizeUiComponent(self.btn_add) callbacks.customizeUiComponent(self.btn_del) callbacks.customizeUiComponent(label_id) callbacks.customizeUiComponent(self.input_id) callbacks.addSuiteTab(self) callbacks.registerScannerCheck(self) callbacks.registerIntruderPayloadGeneratorFactory(self) callbacks.registerContextMenuFactory(self) def btn_add_id(self, e): ident = self.input_id.text self.input_id.text = "" content = self.input_content.text self.input_content.text = "" self.tabledata.add_mapping(ident, content) self.input_id.requestFocusInWindow() def btn_del_id(self, e): rows = self.table.getSelectedRows().tolist() self.tabledata.del_rows(rows) ### ITab ### def getTabCaption(self): return ("SessionAuth") def getUiComponent(self): return self.tab ### IContextMenuFactory ### def createMenuItems(self, invocation): menuitems = list() msgs = invocation.getSelectedMessages() if msgs != None: if len( msgs ) == 1: # "add as object id/as content to last id" context menu items bounds = invocation.getSelectionBounds() if bounds != None and bounds[0] != bounds[1]: msg = None if invocation.getInvocationContext( ) == IContextMenuInvocation.CONTEXT_MESSAGE_EDITOR_REQUEST or invocation.getInvocationContext( ) == IContextMenuInvocation.CONTEXT_MESSAGE_VIEWER_REQUEST: msg = msgs[0].getRequest().tostring() if invocation.getInvocationContext( ) == IContextMenuInvocation.CONTEXT_MESSAGE_EDITOR_RESPONSE or invocation.getInvocationContext( ) == IContextMenuInvocation.CONTEXT_MESSAGE_VIEWER_RESPONSE: msg = msgs[0].getResponse().tostring() if msg != None: selection = msg[bounds[0]:bounds[1]] shortSelection = selection[:20] if len(selection) > len(shortSelection): shortSelection += "..." menuitems.append( JMenuItem("Add '" + shortSelection + "' as object id", actionPerformed=self.gen_menu_add_id( selection))) if self.tabledata.lastadded != None: menuitems.append( JMenuItem( "Add '" + shortSelection + "' as content to last added id", actionPerformed=self.gen_menu_add_content( selection))) if len(msgs) > 0: # "Send to Intruder" context menu items requestsWithIds = list() for msg in msgs: if isinstance(msg.getRequest(), array) and self.tabledata.containsId( msg.getRequest().tostring()): requestsWithIds.append(msg) if len(requestsWithIds) > 0: menuitems.append( JMenuItem( "Send to Intruder and preconfigure id injection points", actionPerformed=self.gen_menu_send_intruder( requestsWithIds))) return menuitems def gen_menu_add_id(self, ident): def menu_add_id(e): self.tabledata.add_mapping(ident, "") return menu_add_id def gen_menu_add_content(self, content): def menu_add_content(e): self.tabledata.set_lastadded_content(content) return menu_add_content def gen_menu_send_intruder(self, requestResponses): def menu_send_intruder(e): for requestResponse in requestResponses: httpService = requestResponse.getHttpService() request = requestResponse.getRequest() injectionPoints = list() for ident in self.tabledata.getIds(): newInjectionPoints = findAll(request.tostring(), ident) if newInjectionPoints != None: injectionPoints += newInjectionPoints if len(injectionPoints) > 0: self.callbacks.sendToIntruder( httpService.getHost(), httpService.getPort(), httpService.getProtocol() == "https", request, injectionPoints) return menu_send_intruder ### IIntruderPayloadGeneratorFactory ### def getGeneratorName(self): return "SessionAuth Identifiers" def createNewInstance(self, attack): return IdentifiersPayloadGenerator(self.tabledata) ### IScannerCheck ### def doPassiveScan(self, baseRequestResponse): analyzedRequest = self.helpers.analyzeRequest(baseRequestResponse) params = analyzedRequest.getParameters() ids = self.tabledata.getIds() issues = list() for param in params: value = param.getValue() for ident in ids: if value == ident: issues.append( SessionAuthPassiveScanIssue( analyzedRequest.getUrl(), baseRequestResponse, param, ident, self.tabledata.getValue(ident), SessionAuthPassiveScanIssue.foundEqual, self.callbacks)) elif value.find(ident) >= 0: issues.append( SessionAuthPassiveScanIssue( analyzedRequest.getUrl(), baseRequestResponse, param, ident, self.tabledata.getValue(ident), SessionAuthPassiveScanIssue.foundInside, self.callbacks)) if len(issues) > 0: return issues else: return None def doActiveScan(self, baseRequestResponse, insertionPoint): ids = self.tabledata.getIds() if len(ids ) <= 1: # active check only possible if multiple ids were given return None baseVal = insertionPoint.getBaseValue() url = baseRequestResponse.getUrl() idFound = list() for ident in ids: # find all identifiers in base value if baseVal.find(ident) >= 0: idFound.append(ident) if len(idFound) == 0: # no given identifier found, nothing to do return None baseResponse = baseRequestResponse.getResponse().tostring() baseResponseBody = baseResponse[ self.helpers.analyzeResponse(baseResponse).getBodyOffset():] issues = list() scannedCombos = list() for replaceId in idFound: # scanner checks: replace found id by other given ids for scanId in ids: if replaceId == scanId or set([replaceId, scanId ]) in scannedCombos: continue scannedCombos.append(set([replaceId, scanId])) scanPayload = baseVal.replace(replaceId, scanId) scanRequest = insertionPoint.buildRequest(scanPayload) scanRequestResponse = self.callbacks.makeHttpRequest( baseRequestResponse.getHttpService(), scanRequest) scanResponse = scanRequestResponse.getResponse().tostring() scanResponseBody = scanResponse[self.helpers.analyzeResponse( scanResponse).getBodyOffset():] if baseResponseBody == scanResponseBody: # response hasn't changed - no issue continue # Analyze responses replaceValue = self.tabledata.getValue(replaceId) scanValue = self.tabledata.getValue(scanId) # naming convention: # first word: base || scan (response) # second word: Replace || Scan (value) if replaceValue != "": baseReplaceValueCount = len( baseResponseBody.split(replaceValue)) - 1 scanReplaceValueCount = len( scanResponseBody.split(replaceValue)) - 1 else: baseReplaceValueCount = 0 scanReplaceValueCount = 0 if scanValue != "": baseScanValueCount = len( baseResponseBody.split(scanValue)) - 1 scanScanValueCount = len( scanResponseBody.split(scanValue)) - 1 else: baseScanValueCount = 0 scanScanValueCount = 0 if scanScanValueCount == 0: # Scan identifier content value doesn't appears, but responses differ issueCase = SessionAuthActiveScanIssue.caseScanValueNotFound elif baseReplaceValueCount > 0 and baseScanValueCount == 0 and scanReplaceValueCount == 0 and scanScanValueCount == baseReplaceValueCount: # Scan identifier replaces all occurrences of the original identifier in the response issueCase = SessionAuthActiveScanIssue.caseScanValueAppearsExactly elif baseReplaceValueCount > 0 and baseScanValueCount == 0 and scanReplaceValueCount == 0 and scanScanValueCount > 0: # Scan identfiers value appears, replaced ids value disappears issueCase = SessionAuthActiveScanIssue.caseScanValueAppearsFuzzy elif baseReplaceValueCount > scanReplaceValueCount and baseScanValueCount < scanScanValueCount: # Occurence count of replaced id value decreases, scan id value increases issueCase = SessionAuthActiveScanIssue.caseDecreaseIncrease elif baseScanValueCount < scanScanValueCount: # Occurence count of scan id value increases issueCase = SessionAuthActiveScanIssue.caseScanValueIncrease else: # Remainingg cases issueCase = SessionAuthActiveScanIssue.caseOther issues.append( SessionAuthActiveScanIssue(url, baseRequestResponse, insertionPoint, scanPayload, scanRequestResponse, replaceId, replaceValue, scanId, scanValue, issueCase, self.callbacks)) if len(issues) > 0: return issues else: return None def consolidateDuplicateIssues(self, existingIssue, newIssue): if existingIssue.getIssueDetail() == newIssue.getIssueDetail(): return 1 else: return 0
class WSAShelp_08(java.lang.Runnable): #--------------------------------------------------------------------------- # Name: __init__() # Role: Class constructor #--------------------------------------------------------------------------- def __init__(self): #----------------------------------------------------------------------- # Painter instance used to highlight text # Note: See hilight() #----------------------------------------------------------------------- self.painter = DefaultHighlighter.DefaultHighlightPainter(Color.YELLOW) #--------------------------------------------------------------------------- # Name: center() # Role: Position the frame in the center of the screen # Note: The frame isn't allowed to be wider than 1/2 the screen width, or # more than 1/2 the screen height. It is resized, if necessary. # Note: The value of 640 is used to keep the AdminTask.help() text from # wrapping #--------------------------------------------------------------------------- def center(self, frame): screenSize = Toolkit.getDefaultToolkit().getScreenSize() frameSize = frame.getSize() frameSize.width = min(frameSize.width, screenSize.width >> 1) frameSize.width = max(frameSize.width, 640) frameSize.height = min(frameSize.height, screenSize.height >> 1) if frameSize != frame.getSize(): frame.setSize(frameSize) frame.setLocation((screenSize.width - frameSize.width) >> 1, (screenSize.height - frameSize.height) >> 1) #--------------------------------------------------------------------------- # Name: frameResized() # Role: Component Listener event handler for the componentResized event #--------------------------------------------------------------------------- def frameResized(self, ce): index = self.tabs.getSelectedIndex() name = self.tabs.getTitleAt(index) if len(self.tPanes[name]) > 1: table, rowHeight, w0, w1 = self.tPanes[name][1:] width = table.getParent().getExtentSize().getWidth() tcm = table.getColumnModel() # Table Column Model margin = tcm.getColumnMargin() # gap between columns if w0 + w1 + 2 * margin > width: table.setRowHeight(rowHeight * 3) c0 = int(round(width * .23)) c1 = int(width - c0 - margin) else: table.setRowHeight(rowHeight) c0 = w0 + margin c1 = int(width - c0 - margin) tcr = table.getCellRenderer(0, 0) tcr.setWidths(c0, c1) tcr.setHiText(self.textField.getText()) tcm.getColumn(0).setPreferredWidth(c0) tcm.getColumn(1).setPreferredWidth(c1) #------------------------------------------------------------------- # Redraw the table using the new column widths and row heights #------------------------------------------------------------------- table.repaint() #--------------------------------------------------------------------------- # Name: hilight() # Role: Find, and highlight every occurrance of text on specified JTextPane #--------------------------------------------------------------------------- def hilight(self, tPane, text): hiliter = tPane.getHighlighter() hiliter.removeAllHighlights() if text: doc = tPane.getDocument() info = doc.getText(0, doc.getLength()) start = 0 here = info.find(text, start) while here > -1: hiliter.addHighlight(here, here + len(text), self.painter) start = here + len(text) here = info.find(text, start) #--------------------------------------------------------------------------- # Name: lookFor() # Role: ActionListener event handler called when user press <Enter> #--------------------------------------------------------------------------- def lookFor(self, event): text = event.getSource().getText() index = self.tabs.getSelectedIndex() name = self.tabs.getTitleAt(index) self.hilight(self.tPanes[name][0], text) if len(self.tPanes[name]) > 1: table = self.tPanes[name][1] table.getCellRenderer(0, 0).setHiText(text) table.repaint() #--------------------------------------------------------------------------- # Name: run() # Role: Instantiate the user class # Note: Invoked by the Swing Event Dispatch Thread #--------------------------------------------------------------------------- def run(self): frame = JFrame('WSAShelp_08', layout=BorderLayout(), componentResized=self.frameResized, defaultCloseOperation=JFrame.EXIT_ON_CLOSE) #----------------------------------------------------------------------- # RegExp used to locate method names #----------------------------------------------------------------------- methRE = re.compile(r'^(\w+)(?:\s+.*)$', re.MULTILINE) #----------------------------------------------------------------------- # Create & Populate the JTabbedPane #----------------------------------------------------------------------- WASobjs = [ ('wsadmin', None), # Special case ('Help', Help), ('AdminApp', AdminApp), ('AdminConfig', AdminConfig), ('AdminControl', AdminControl), ('AdminTask', AdminTask) ] self.tPanes = {} highlighters = {} self.tabs = tabs = JTabbedPane(stateChanged=self.tabPicked) for name, WASobj in WASobjs: #------------------------------------------------------------------- # Use a single ScrollPane for the AdminTask help #------------------------------------------------------------------- if name in ['wsadmin', 'AdminTask']: if WASobj: data = WASobj.help().expandtabs() else: data = Help.wsadmin().expandtabs() pane = JTextPane(text=data, editable=0, font=monoFont) #--------------------------------------------------------------- # Move the caret to ensure that the starting text is shown #--------------------------------------------------------------- pane.moveCaretPosition(0) tabs.addTab(name, JScrollPane(pane)) self.tPanes[name] = [pane] else: #--------------------------------------------------------------- # Use a RegExp to identify where the 1st method starts. #--------------------------------------------------------------- text = WASobj.help().expandtabs() mo = re.search(methRE, text) # Match Object desc = text[:mo.start(1)].strip() meth = text[mo.start(1):].strip() #--------------------------------------------------------------- # The description section is before the 1st method #--------------------------------------------------------------- topPane = JTextPane(text=desc, editable=0, font=monoFont) topPane.moveCaretPosition(0) top = JScrollPane(topPane) #--------------------------------------------------------------- # For the other scripting objects, use a vertically split pane # with the top containing the description section, and the # bottom (eventually) containing the method details. #--------------------------------------------------------------- splitPane = JSplitPane( JSplitPane.VERTICAL_SPLIT, top, JLabel('One moment please...'), resizeWeight=0.5, # divider position = 50% oneTouchExpandable=1) #--------------------------------------------------------------- # Start a separate thread to parse the method text and build a # a JTable to be put into the bottom part of this splitPane #--------------------------------------------------------------- self.tPanes[name] = [topPane] tableTask( meth, # Help text to be parsed / processed splitPane, # SplitPane to be updated self.tPanes[name], # tPanes entry to be updated WASobj # WAS scripting object ).execute() tabs.addTab(name, splitPane) #----------------------------------------------------------------------- # Add the tabbed pane to the frame & show the result #----------------------------------------------------------------------- frame.add(tabs, 'Center') #----------------------------------------------------------------------- # Label & input field for user input #----------------------------------------------------------------------- info = JPanel(BorderLayout()) info.add(JLabel('Highlight text:'), 'West') self.textField = JTextField(actionPerformed=self.lookFor) info.add(self.textField, 'Center') frame.add(info, 'South') frame.pack() self.center(frame) frame.setVisible(1) self.textField.requestFocusInWindow() #--------------------------------------------------------------------------- # Name: tabPicked() # Role: ChangeListener event handler - called when a tab is selected #--------------------------------------------------------------------------- def tabPicked(self, event): pane = event.getSource() index = pane.getSelectedIndex() name = pane.getTitleAt(index) try: tPane = self.tPanes[name][0] tPane.select(0, 0) hiText = self.textField.getText() self.hilight(tPane, hiText) if len(self.tPanes[name]) > 1: table, rowHeight, w0, w1 = self.tPanes[name][1:] #--------------------------------------------------------------- # Viewport width & preferred width for column 0 #--------------------------------------------------------------- width = table.getParent().getExtentSize().getWidth() tcm = table.getColumnModel() # Table Column Model margin = tcm.getColumnMargin() # gap between columns if w0 + w1 + 2 * margin > width: table.setRowHeight(rowHeight * 3) c0 = int(round(width * .23)) c1 = int(width - c0 - margin) else: table.setRowHeight(rowHeight) c0 = w0 + margin c1 = int(width - c0 - margin) tcr = table.getCellRenderer(0, 0) tcr.setWidths(c0, c1) tcr.setHiText(hiText) tcm.getColumn(0).setPreferredWidth(c0) tcm.getColumn(1).setPreferredWidth(c1) except: # Type, value = sys.exc_info()[ :2 ] # print 'Error: %s\nvalue: %s' % ( Type, value ) pass
class ChatApp(JFrame): ## Constructor function, initiate the base classes and call the GUI def __init__(self): '''Calls the base class and main UI ''' # Call to the super class, initiates associated base classes super(ChatApp, self).__init__() # Call the Initial UI self.initUI() ## Build the GUI for login, uses GroupLayout Manager for component positioning def initUI(self): '''Initial UI and Widget creation takes place here! ''' self.setContentPane = JPanel() #self.setDefaultLookAndFeelDecorated(True) # Borders foreground_colour = Color(30,57,68) background_colour = Color(247,246,242) window_background = Color(145,190,210) self.border = BorderFactory.createLoweredBevelBorder() self.border2 = BorderFactory.createLineBorder(foreground_colour, 1, True) # Fonts self.entry_font= Font("Ubuntu Light", Font.BOLD, 20) self.label_font= Font("Ubuntu Light", Font.BOLD, 17) self.btn_font=Font("Ubuntu Light", Font.BOLD, 15) # Layout start layout=GroupLayout(self.getContentPane()) self.getContentPane().setLayout(layout) layout.setAutoCreateGaps(True) layout.setAutoCreateContainerGaps(True) self.setPreferredSize(Dimension(300, 150)) # Create the labels user_label= JLabel(" Username : "******" Server : ", JLabel.LEFT, font=self.label_font) # Colours user_label.setForeground(foreground_colour) server_label.setForeground(foreground_colour) # Create the text entries self.username=JTextField(actionPerformed=self.continueEvent, border=self.border2, font = self.entry_font) self.server=JTextField(actionPerformed=self.continueEvent, border=self.border2, font = self.entry_font) # Colours self.username.setBackground(background_colour) self.server.setBackground(background_colour) self.username.setForeground(foreground_colour) self.server.setForeground(foreground_colour) # Allow editable self.username.setEditable(True) self.server.setEditable(True) # Create the buttons quit_btn=JButton(" Quit! ", actionPerformed=self.closeEvent, border=self.border2, font=self.btn_font) go_btn=JButton(" Go! ", actionPerformed=self.continueEvent, border=self.border2, font=self.btn_font) # Colours quit_btn.setBackground(background_colour) go_btn.setBackground(background_colour) quit_btn.setForeground(foreground_colour) go_btn.setForeground(foreground_colour) # Setting up the horizontal groups parameters layout.setHorizontalGroup(layout.createSequentialGroup() # Left side .addGroup(layout.createParallelGroup(GroupLayout.Alignment.TRAILING) .addComponent(user_label) .addComponent(server_label)) # Right side .addGroup(layout.createParallelGroup(GroupLayout.Alignment.CENTER) .addComponent(self.username) .addComponent(self.server) .addGroup(layout.createSequentialGroup() .addComponent(quit_btn) .addComponent(go_btn))) ) # Setting up Vertical Groups layout.setVerticalGroup(layout.createSequentialGroup() # Top group .addGroup(layout.createParallelGroup(GroupLayout.Alignment.CENTER) .addComponent(user_label) .addComponent(self.username)) # Middle group .addGroup(layout.createParallelGroup(GroupLayout.Alignment.CENTER) .addComponent(server_label) .addComponent(self.server)) # Bottom group .addGroup(layout.createParallelGroup() .addComponent(quit_btn) .addComponent(go_btn)) ) # Finalise the GUI layout.linkSize(SwingConstants.HORIZONTAL, [quit_btn,go_btn]) self.getContentPane().setBackground(window_background) self.pack() self.setTitle('Chat Login') self.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) self.setLocationRelativeTo(None) self.setVisible(True) ## Event driven funtion to respond to quit button click def closeEvent(self,event): '''Function to close the login window ''' print("Goodbye!") exit() ## Event driven function to respond to send button click, grabs text and sends it down the wire def continueEvent(self,event): '''Function that retreives the login details for sending to the server ''' # Grab the text that has been entered user = self.username.getText() Host = self.server.getText() # Default port Port=60001 connected=False while not connected: # Try make a connection except when there isn't one available, then quit program' try: tn=telnetlib.Telnet(Host, Port) connected=True continue except: JOptionPane.showMessageDialog(self,'Connection Error, No Server Available!') self.username.setText('') self.server.setText('') self.username.requestFocusInWindow() return # Listen for a response response = tn.read_until('<<<') print(response) # Acknowledge with the username tn.write(user+'\r\n') # Receive validation of name, present dialog if not valid valid_name = tn.read_until('<') valid_name.strip() v_name, delim = valid_name.split('<') if v_name.strip() != 'OK': JOptionPane.showMessageDialog(self,'Bad Username, please choose another') self.username.setText('') self.username.requestFocusInWindow() return # Set the login GUI to hidden self.setVisible(False) ## <<<<<< I have no idea why this doesn't work but I suspect it's something to do with either inheritance or having 2 class instances # Call the main program, pass the connection as a parameter ChatClient(user,response , tn)
class WSAShelp_05(java.lang.Runnable): #--------------------------------------------------------------------------- # Name: __init__() # Role: Class constructor #--------------------------------------------------------------------------- def __init__(self): #----------------------------------------------------------------------- # Painter instance used to highlight text #----------------------------------------------------------------------- self.painter = DefaultHighlighter.DefaultHighlightPainter(Color.YELLOW) #--------------------------------------------------------------------------- # Name: center() # Role: Position the frame in the center of the screen # Note: The frame isn't allowed to be wider than 1/2 the screen width, or # more than 1/2 the screen height. It is resized, if necessary. #--------------------------------------------------------------------------- def center(self, frame): screenSize = Toolkit.getDefaultToolkit().getScreenSize() frameSize = frame.getSize() frameSize.width = min(frameSize.width, screenSize.width >> 1) frameSize.height = min(frameSize.height, screenSize.height >> 1) if frameSize != frame.getSize(): frame.setSize(frameSize) frame.setLocation((screenSize.width - frameSize.width) >> 1, (screenSize.height - frameSize.height) >> 1) #--------------------------------------------------------------------------- # Name: hilight() # Role: Find, and highlight every occurrance of text on specified JTextPane #--------------------------------------------------------------------------- def hilight(self, tPane, text): hiliter = tPane.getHighlighter() hiliter.removeAllHighlights() if text: doc = tPane.getDocument() info = doc.getText(0, doc.getLength()) start = 0 here = info.find(text, start) while here > -1: hiliter.addHighlight(here, here + len(text), self.painter) start = here + len(text) here = info.find(text, start) #--------------------------------------------------------------------------- # Name: lookFor() # Role: ActionListener event handler called when user press <Enter> #--------------------------------------------------------------------------- def lookFor(self, event): text = event.getSource().getText() index = self.tabs.getSelectedIndex() name = self.tabs.getTitleAt(index) for tPane in self.tPanes[name]: self.hilight(tPane, text) #--------------------------------------------------------------------------- # Name: run() # Role: Instantiate the user class # Note: Invoked by the Swing Event Dispatch Thread #--------------------------------------------------------------------------- def run(self): frame = JFrame('WSAShelp_05', layout=BorderLayout(), defaultCloseOperation=JFrame.EXIT_ON_CLOSE) #----------------------------------------------------------------------- # RegExp used to locate the method name portion of the help text #----------------------------------------------------------------------- methRE = re.compile(r'^(\w+)(?:\s+.*)$', re.MULTILINE) monoFont = Font('Courier', Font.PLAIN, 12) #----------------------------------------------------------------------- # Create & Populate the JTabbedPane #----------------------------------------------------------------------- objs = [ ('wsadmin', None), # Special case ('Help', Help), ('AdminApp', AdminApp), ('AdminConfig', AdminConfig), ('AdminControl', AdminControl), ('AdminTask', AdminTask) ] self.tPanes = {} highlighters = {} self.tabs = tabs = JTabbedPane(stateChanged=self.tabPicked) for name, obj in objs: #------------------------------------------------------------------- # Use a single ScrollPane for the AdminTask help #------------------------------------------------------------------- if name in ['wsadmin', 'AdminTask']: if obj: data = obj.help().expandtabs() else: data = Help.wsadmin().expandtabs() pane = JTextPane(text=data, editable=0, font=monoFont) pane.moveCaretPosition(0) tabs.addTab(name, JScrollPane(pane)) self.tPanes[name] = [pane] # print 'tPanes[ "%s" ]' % name else: #--------------------------------------------------------------- # Use a RegExp to identify where the 1st method starts. #--------------------------------------------------------------- text = obj.help().expandtabs() mo = re.search(methRE, text) # Match Object desc = text[:mo.start(1)].strip() meth = text[mo.start(1):].strip() #--------------------------------------------------------------- # The description section is before the 1st method #--------------------------------------------------------------- topPane = JTextPane(text=desc, editable=0, font=monoFont) topPane.moveCaretPosition(0) top = JScrollPane(topPane) #--------------------------------------------------------------- # The method section starts at the 1st method #--------------------------------------------------------------- botPane = JTextPane(text=meth, editable=0, font=monoFont) botPane.moveCaretPosition(0) bot = JScrollPane(botPane) #--------------------------------------------------------------- # For the other scripting objects, use a vertically split pane # with the top containing the description section, and the # bottom containing the method details. #--------------------------------------------------------------- tabs.addTab( name, JSplitPane( JSplitPane.VERTICAL_SPLIT, top, bot, resizeWeight=0.5, # divider position = 50% oneTouchExpandable=1)) self.tPanes[name] = [topPane, botPane] # print 'tPanes[ "%s" ]' % name #----------------------------------------------------------------------- # Add the tabbed pane to the frame & show the result #----------------------------------------------------------------------- frame.add(tabs, 'Center') #----------------------------------------------------------------------- # Label & input field for user input #----------------------------------------------------------------------- info = JPanel(BorderLayout()) info.add(JLabel('Highlight text:'), 'West') self.textField = JTextField(actionPerformed=self.lookFor) info.add(self.textField, 'Center') frame.add(info, 'South') frame.pack() self.center(frame) frame.setVisible(1) self.textField.requestFocusInWindow() #--------------------------------------------------------------------------- # Name: tabPicked() # Role: ChangeListener event handler - called when a tab is selected #--------------------------------------------------------------------------- def tabPicked(self, event): pane = event.getSource() index = pane.getSelectedIndex() name = pane.getTitleAt(index) try: for tPane in self.tPanes[name]: self.hilight(tPane, self.textField.getText()) except: pass