class BurpExtender(IBurpExtender, IExtensionStateListener, IHttpListener, ITab, FocusListener, ActionListener, MouseAdapter): _version = "0.2" _name = "PyRules" _varsStorage = _name + "_vars" _scriptStorage = _name + "_script" _enabled = 0 _vars = {} def registerExtenderCallbacks(self, callbacks): print "Load:" + self._name + " " + self._version self.callbacks = callbacks self.helpers = callbacks.helpers #Create Tab layout self.jVarsPane = JTextPane() self.jVarsPane.setFont(Font('Monospaced', Font.PLAIN, 11)) self.jVarsPane.addFocusListener(self) self.jMenuPanel = JPanel() self.jLeftUpPanel = JPanel() self.jEnable = JCheckBox() self.jEnable.setFont(Font('Monospaced', Font.BOLD, 11)) self.jEnable.setForeground(Color(0, 0, 204)) self.jEnable.setText(self._name) self.jEnable.addActionListener(self) self.jDocs = JLabel() self.jDocs.setFont(Font('Monospaced', Font.PLAIN, 11)) self.jDocs.setForeground(Color(51, 102, 255)) self.jDocs.setText(Strings.docs_titel) self.jDocs.setToolTipText(Strings.docs_tooltip) self.jDocs.addMouseListener(self) self.jConsoleText = JTextArea() self.jConsoleText.setFont(Font('Monospaced', Font.PLAIN, 10)) self.jConsoleText.setBackground(Color(244, 246, 247)) self.jConsoleText.setEditable(0) self.jConsoleText.setWrapStyleWord(1) self.jConsoleText.setRows(10) self.jScrollConsolePane = JScrollPane() self.jScrollConsolePane.setViewportView(self.jConsoleText) #set initial text self.jConsoleText.setText(Strings.console_disable) self.jMenuPanelLayout = GroupLayout(self.jMenuPanel) self.jMenuPanel.setLayout(self.jMenuPanelLayout) self.jMenuPanelLayout.setHorizontalGroup( self.jMenuPanelLayout.createParallelGroup( GroupLayout.Alignment.LEADING).addGroup( self.jMenuPanelLayout.createSequentialGroup().addComponent( self.jEnable).addPreferredGap( LayoutStyle.ComponentPlacement.RELATED, 205, 32767).addComponent(self.jDocs))) self.jMenuPanelLayout.setVerticalGroup( self.jMenuPanelLayout.createParallelGroup( GroupLayout.Alignment.LEADING).addGroup( self.jMenuPanelLayout.createSequentialGroup().addGroup( self.jMenuPanelLayout.createParallelGroup( GroupLayout.Alignment.BASELINE).addComponent( self.jEnable).addComponent(self.jDocs)).addGap( 0, 7, 32767))) self.jConsolePane = JPanel() self.jConsoleLayout = GroupLayout(self.jConsolePane) self.jConsolePane.setLayout(self.jConsoleLayout) self.jConsoleLayout.setHorizontalGroup( self.jConsoleLayout.createParallelGroup( GroupLayout.Alignment.LEADING).addComponent( self.jScrollConsolePane)) self.jConsoleLayout.setVerticalGroup( self.jConsoleLayout.createParallelGroup( GroupLayout.Alignment.LEADING).addGroup( GroupLayout.Alignment.TRAILING, self.jConsoleLayout.createSequentialGroup().addComponent( self.jScrollConsolePane, GroupLayout.DEFAULT_SIZE, 154, 32767).addContainerGap())) self.jLeftUpPanelLayout = GroupLayout(self.jLeftUpPanel) self.jLeftUpPanel.setLayout(self.jLeftUpPanelLayout) self.jLeftUpPanelLayout.setHorizontalGroup( self.jLeftUpPanelLayout.createParallelGroup( GroupLayout.Alignment.LEADING).addComponent( self.jConsolePane, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, 32767).addComponent(self.jMenuPanel, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)) self.jLeftUpPanelLayout.setVerticalGroup( self.jLeftUpPanelLayout. createParallelGroup(GroupLayout.Alignment.LEADING).addGroup( GroupLayout.Alignment.TRAILING, self.jLeftUpPanelLayout.createSequentialGroup().addComponent( self.jMenuPanel, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE).addPreferredGap( LayoutStyle.ComponentPlacement.RELATED).addComponent( self.jConsolePane, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, 32767))) self.jScrollpaneLeftDown = JScrollPane() self.jScrollpaneLeftDown.setViewportView(self.jVarsPane) self.jSplitPaneLeft = JSplitPane(JSplitPane.VERTICAL_SPLIT, self.jLeftUpPanel, self.jScrollpaneLeftDown) self.jSplitPaneLeft.setDividerLocation(300) self.jScriptPane = JTextPane() self.jScriptPane.setFont(Font('Monospaced', Font.PLAIN, 11)) self.jScriptPane.addMouseListener(self) self.JScrollPaneRight = JScrollPane() self.JScrollPaneRight.setViewportView(self.jScriptPane) self.jSplitPane = JSplitPane(JSplitPane.HORIZONTAL_SPLIT, self.jSplitPaneLeft, self.JScrollPaneRight) self.jSplitPane.setDividerLocation(400) #Load saved saved settings ##Load vars vars = callbacks.loadExtensionSetting(self._varsStorage) if vars: vars = base64.b64decode(vars) else: # try to load the example try: with open("examples/Simple-CSRF-vars.py") as fvars: vars = fvars.read() # load the default text except: vars = Strings.vars ## initiate the persistant variables locals_ = {} try: exec(vars, {}, locals_) except Exception as e: print e self._vars = locals_ ## update the vars screen self.jVarsPane.document.insertString(self.jVarsPane.document.length, vars, SimpleAttributeSet()) ##Load script script = callbacks.loadExtensionSetting(self._scriptStorage) if script: script = base64.b64decode(script) else: # try to load the example try: with open("examples/Simple-CSRF-script.py") as fscript: script = fscript.read() # load the default text except: script = Strings.script ## compile the rules self._script = script self._code = '' try: self._code = compile(script, '<string>', 'exec') except Exception as e: print( '{}\nReload extension after you correct the error.'.format(e)) ## update the rules screen self.jScriptPane.document.insertString( self.jScriptPane.document.length, script, SimpleAttributeSet()) #Register Extension callbacks.customizeUiComponent(self.getUiComponent()) callbacks.addSuiteTab(self) callbacks.registerExtensionStateListener(self) callbacks.registerHttpListener(self) self.jScriptPane.requestFocus() def getUiComponent(self): return self.jSplitPane def getTabCaption(self): return self._name def actionPerformed(self, event): #Check box was clicked if self.jEnable == event.getSource(): if self._enabled == 1: self._enabled = 0 # console content shows help self.jConsoleText.setText(Strings.console_disable) else: self._enabled = 1 # console content displays the current persistent variable state self.jConsoleText.setText(Strings.console_state) self.jConsoleText.append(pformat(self._vars)) self.jConsoleText.append(Strings.extra_line) self.jConsoleText.append(Strings.console_log) return def mouseClicked(self, event): if event.source == self.jDocs: uri = URI.create("https://github.com/DanNegrea/PyRules") if uri and Desktop.isDesktopSupported() and Desktop.getDesktop( ).isSupported(Desktop.Action.BROWSE): Desktop.getDesktop().browse(uri) return def focusGained(self, event): if self.jConsolePane == event.getSource(): pass #print "Status pane gained focus" #debug return def focusLost(self, event): #Reinitialize the persistent values if self.jVarsPane == event.getSource(): # get the text from the pane end = self.jVarsPane.document.length vars = self.jVarsPane.document.getText(0, end) # compute the new values locals_ = {} exec(vars, {}, locals_) self._vars = locals_ # display the new result in console self.jConsoleText.append(Strings.console_state) self.jConsoleText.append(pformat(self._vars)) self.jConsoleText.append(Strings.extra_line) self.jConsoleText.append(Strings.console_log) # scroll to bottom verticalScrollBar = self.jScrollConsolePane.getVerticalScrollBar() verticalScrollBar.setValue(verticalScrollBar.getMaximum()) return def extensionUnloaded(self): try: #Save the latestest vars and script text ## save vars end = self.jVarsPane.document.length vars = self.jVarsPane.document.getText(0, end) vars = base64.b64encode(vars) self.callbacks.saveExtensionSetting(self._varsStorage, vars) ## save script/rules end = self.jScriptPane.document.length script = self.jScriptPane.document.getText(0, end) script = base64.b64encode(script) self.callbacks.saveExtensionSetting(self._scriptStorage, script) except Exception: traceback.print_exc(file=self.callbacks.getStderr()) print "Unloaded" #debug return def processHttpMessage(self, toolFlag, messageIsRequest, messageInfo): if self._enabled == 0: return try: locals_ = { 'extender': self, 'callbacks': self.callbacks, 'helpers': self.helpers, 'toolFlag': toolFlag, 'messageIsRequest': messageIsRequest, 'messageInfo': messageInfo, 'log': self.log } # add the _vars as gloval variables locals_ = dict(locals_, **self._vars) # execute the script/rules try: exec(self.getCode, {}, locals_) # catch exit() call inside the rule except SystemExit: pass # update the persistant variables by searching the local variables with the same name for key in self._vars: # assumption self._vars dictionary is smaller than locals_ if key in locals_: self._vars[key] = locals_[key] except Exception: traceback.print_exc(file=self.callbacks.getStderr()) return #Returns the compiled script @property def getCode(self): end = self.jScriptPane.document.length script = self.jScriptPane.document.getText(0, end) # if the script hasn't changed return the already compile text if script == self._script: return self._code self._script = script # compile, store and return the result self._code = compile(script, '<string>', 'exec') return self._code #Log the information into the console screen def log(self, obj): # if string just append. else use pformat from pprint if isinstance(obj, str): self.jConsoleText.append(obj + "\n") else: self.jConsoleText.append(pformat(obj) + "\n") # scroll to bottom verticalScrollBar = self.jScrollConsolePane.getVerticalScrollBar() verticalScrollBar.setValue(verticalScrollBar.getMaximum()) return
class PluginUI(): def __init__(self, extender): self.extender = extender self.initComponents() def showMessage(self, msg): JOptionPane.showMessageDialog(self.mainPanel, msg) def getProcessorTechName(self): return self.comboProcessorTech.getSelectedItem() def getGeneratorTechsName(self): techList = [] if self.chkGeneral.isSelected(): techList.append('General') if self.chkMAXDB.isSelected(): techList.append('SAP_MaxDB') if self.chkMSSQL.isSelected(): techList.append('MSSQL') if self.chkMSAccess.isSelected(): techList.append('MSAccess') if self.chkPostgres.isSelected(): techList.append('PostgreSQL') if self.chkOracle.isSelected(): techList.append('Oracle') if self.chkSqlite.isSelected(): techList.append('SQLite') if self.chkMysql.isSelected(): techList.append('MySQL') return techList def pastePayloadButtonAction(self, event): clpbrd = Toolkit.getDefaultToolkit().getSystemClipboard() content = clpbrd.getContents(None) if content and content.isDataFlavorSupported(DataFlavor.stringFlavor): items = content.getTransferData(DataFlavor.stringFlavor) items = items.splitlines() for item in items: self.extender.PayloadList.append(item) self.listPayloads.setListData(self.extender.PayloadList) self.writePayloadsListFile() def loadPayloadButtonAction(self, event): fileChooser = JFileChooser() fileChooser.dialogTitle = 'Choose Payload List' fileChooser.fileSelectionMode = JFileChooser.FILES_ONLY if (fileChooser.showOpenDialog( self.mainPanel) == JFileChooser.APPROVE_OPTION): file = fileChooser.getSelectedFile() with open(file.getAbsolutePath(), 'r') as reader: for line in reader.readlines(): self.extender.PayloadList.append(line.strip('\n')) self.listPayloads.setListData(self.extender.PayloadList) self.showMessage('{} payloads loaded'.format( len(self.extender.PayloadList))) self.writePayloadsListFile() def removePayloadButtonAction(self, event): for item in self.listPayloads.getSelectedValuesList(): self.extender.PayloadList.remove(item) self.listPayloads.setListData(self.extender.PayloadList) self.writePayloadsListFile() def clearPayloadButtonAction(self, event): self.extender.PayloadList[:] = [] self.listPayloads.setListData(self.extender.PayloadList) self.writePayloadsListFile() def addPayloadButtonAction(self, event): if str(self.textNewPayload.text).strip(): self.extender.PayloadList.append(self.textNewPayload.text) self.textNewPayload.text = '' self.listPayloads.setListData(self.extender.PayloadList) self.writePayloadsListFile() def toClipboardButtonAction(self, event): self.extender.generatePayloads() result = '\n'.join(self.extender.tamperedPayloads) result = StringSelection(result) clpbrd = Toolkit.getDefaultToolkit().getSystemClipboard() clpbrd.setContents(result, None) self.showMessage('{} url encoded payload copied to clipboard'.format( len(self.extender.tamperedPayloads))) def toFileButtonAction(self, event): fileChooser = JFileChooser() fileChooser.dialogTitle = 'Save Payloads' fileChooser.fileSelectionMode = JFileChooser.FILES_ONLY if (fileChooser.showSaveDialog( self.mainPanel) == JFileChooser.APPROVE_OPTION): file = fileChooser.getSelectedFile() self.extender.generatePayloads() result = '\n' result = result.join(self.extender.tamperedPayloads) with open(file.getAbsolutePath(), 'w') as writer: writer.writelines(result) self.showMessage('{} url encoded payload written to file'.format( len(self.extender.tamperedPayloads))) def tamperPayloadButtonAction(self, event): tamperedPayloads = [] tamperFunction = self.comboProcessorTech.getSelectedItem() payloads = self.textPlainPayload.text payloads = payloads.splitlines() for payload in payloads: tamperedPayloads.append( self.extender.tamperSinglePayload(tamperFunction, payload)) result = '\n'.join(tamperedPayloads) self.textTamperedPayload.text = result def comboProcessorTechAction(self, event): varName = 'SQLiQueryTampering_comboProcessorTech' state = str(self.comboProcessorTech.getSelectedIndex()) self.extender.callbacks.saveExtensionSetting(varName, state) def OnCheck(self, event): chk = event.getSource() varName = 'SQLiQueryTampering_{}'.format(chk.text) state = str(1 if chk.isSelected() else 0) self.extender.callbacks.saveExtensionSetting(varName, state) def writePayloadsListFile(self): payloads = '\n'.join(self.extender.PayloadList) payloads = payloads.encode('utf-8') with open('payloads.lst', 'w') as writer: writer.write(payloads) def readPayloadsListFile(self): result = [] with open('payloads.lst', 'r') as reader: for line in reader.readlines(): result.append(line.strip('\n')) return result def initComponents(self): TabbedPane1 = JTabbedPane() GeneratorScrollPane = JScrollPane() GeneratorPanel = JPanel() jlbl1 = JLabel() jlbl2 = JLabel() spanePayloadList = JScrollPane() self.listPayloads = JList() pastePayloadButton = JButton( actionPerformed=self.pastePayloadButtonAction) loadPayloadButton = JButton( actionPerformed=self.loadPayloadButtonAction) removePayloadButton = JButton( actionPerformed=self.removePayloadButtonAction) clearPayloadButton = JButton( actionPerformed=self.clearPayloadButtonAction) self.textNewPayload = JTextField() addPayloadButton = JButton(actionPerformed=self.addPayloadButtonAction) jSeparator1 = JSeparator() jlbl3 = JLabel() jlbl4 = JLabel() self.chkGeneral = JCheckBox(actionPerformed=self.OnCheck) self.chkMAXDB = JCheckBox(actionPerformed=self.OnCheck) self.chkMSSQL = JCheckBox(actionPerformed=self.OnCheck) self.chkMSAccess = JCheckBox(actionPerformed=self.OnCheck) self.chkPostgres = JCheckBox(actionPerformed=self.OnCheck) self.chkOracle = JCheckBox(actionPerformed=self.OnCheck) self.chkSqlite = JCheckBox(actionPerformed=self.OnCheck) self.chkMysql = JCheckBox(actionPerformed=self.OnCheck) jlbl5 = JLabel() toClipboardButton = JButton( actionPerformed=self.toClipboardButtonAction) toFileButton = JButton(actionPerformed=self.toFileButtonAction) ProcessorScrollPane = JScrollPane() ProcessorPanel = JPanel() jLabel1 = JLabel() self.comboProcessorTech = JComboBox( itemStateChanged=self.comboProcessorTechAction) jSeparator2 = JSeparator() jLabel2 = JLabel() jLabel3 = JLabel() jScrollPane1 = JScrollPane() self.textPlainPayload = JTextArea() jLabel4 = JLabel() jScrollPane2 = JScrollPane() self.textTamperedPayload = JTextArea() tamperPayloadButton = JButton( actionPerformed=self.tamperPayloadButtonAction) jlbl1.setForeground(Color(255, 102, 51)) jlbl1.setFont(Font(jlbl1.getFont().toString(), 1, 14)) jlbl1.setText("User-Defiend Payloads") jlbl2.setText( "This payload type lets you configure a simple list of strings that are used as payloads." ) spanePayloadList.setViewportView(self.listPayloads) self.extender.PayloadList = self.readPayloadsListFile() self.listPayloads.setListData(self.extender.PayloadList) pastePayloadButton.setText("Paste") loadPayloadButton.setText("Load") removePayloadButton.setText("Remove") clearPayloadButton.setText("Clear") self.textNewPayload.setToolTipText("") addPayloadButton.setText("Add") jlbl3.setForeground(Color(255, 102, 51)) jlbl3.setFont(Font(jlbl3.getFont().toString(), 1, 14)) jlbl3.setText("Tamper Techniques") jlbl4.setText( "You can select the techniques that you want to perform processing tasks on each user-defined payload" ) self.chkGeneral.setText("General") varName = 'SQLiQueryTampering_{}'.format(self.chkGeneral.text) state = self.extender.callbacks.loadExtensionSetting(varName) if state: self.chkGeneral.setSelected(int(state)) self.chkMAXDB.setText("SAP MAX DB") varName = 'SQLiQueryTampering_{}'.format(self.chkMAXDB.text) state = self.extender.callbacks.loadExtensionSetting(varName) if state: self.chkMAXDB.setSelected(int(state)) self.chkMSSQL.setText("MS SQL Server") varName = 'SQLiQueryTampering_{}'.format(self.chkMSSQL.text) state = self.extender.callbacks.loadExtensionSetting(varName) if state: self.chkMSSQL.setSelected(int(state)) self.chkMSAccess.setText("MS Access") varName = 'SQLiQueryTampering_{}'.format(self.chkMSAccess.text) state = self.extender.callbacks.loadExtensionSetting(varName) if state: self.chkMSAccess.setSelected(int(state)) self.chkPostgres.setText("Postgres SQL") varName = 'SQLiQueryTampering_{}'.format(self.chkPostgres.text) state = self.extender.callbacks.loadExtensionSetting(varName) if state: self.chkPostgres.setSelected(int(state)) self.chkOracle.setText("Oracle") varName = 'SQLiQueryTampering_{}'.format(self.chkOracle.text) state = self.extender.callbacks.loadExtensionSetting(varName) if state: self.chkOracle.setSelected(int(state)) self.chkSqlite.setText("Sqlite") varName = 'SQLiQueryTampering_{}'.format(self.chkSqlite.text) state = self.extender.callbacks.loadExtensionSetting(varName) if state: self.chkSqlite.setSelected(int(state)) self.chkMysql.setText("MySql") varName = 'SQLiQueryTampering_{}'.format(self.chkMysql.text) state = self.extender.callbacks.loadExtensionSetting(varName) if state: self.chkMysql.setSelected(int(state)) jlbl5.setText("[?] Save the Generated/Tampered Payloads to :") toClipboardButton.setText("Clipboard") toFileButton.setText("File") GeneratorPanelLayout = GroupLayout(GeneratorPanel) GeneratorPanel.setLayout(GeneratorPanelLayout) GeneratorPanelLayout.setHorizontalGroup( GeneratorPanelLayout.createParallelGroup( GroupLayout.Alignment.LEADING). addGroup(GeneratorPanelLayout.createSequentialGroup( ).addContainerGap().addGroup( GeneratorPanelLayout.createParallelGroup( GroupLayout.Alignment.TRAILING).addComponent( jlbl2, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE).addComponent( jlbl4, GroupLayout.Alignment.LEADING, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE).addComponent( jSeparator1, GroupLayout.Alignment.LEADING). addGroup(GeneratorPanelLayout.createSequentialGroup().addGap( 6, 6, 6).addGroup( GeneratorPanelLayout.createParallelGroup( GroupLayout.Alignment.LEADING).addGroup( GeneratorPanelLayout.createSequentialGroup( ).addGroup( GeneratorPanelLayout.createParallelGroup( GroupLayout.Alignment.LEADING, False).addComponent( removePayloadButton, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE).addComponent( clearPayloadButton, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE).addComponent( loadPayloadButton, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE). addComponent(pastePayloadButton, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE).addComponent( addPayloadButton, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)). addGap(21, 21, 21).addGroup( GeneratorPanelLayout.createParallelGroup( GroupLayout.Alignment.LEADING). addComponent( self.textNewPayload).addComponent( spanePayloadList))).addComponent( jlbl1).addComponent(jlbl3). addGroup(GeneratorPanelLayout.createSequentialGroup( ).addGroup( GeneratorPanelLayout.createParallelGroup( GroupLayout.Alignment.LEADING).addComponent( self.chkGeneral).addComponent( self.chkMSSQL) ).addGap(18, 18, 18).addGroup( GeneratorPanelLayout.createParallelGroup( GroupLayout.Alignment.LEADING).addComponent( self.chkPostgres).addComponent( self.chkMAXDB) ).addGap(18, 18, 18).addGroup( GeneratorPanelLayout.createParallelGroup( GroupLayout.Alignment.LEADING).addComponent( self.chkMSAccess).addComponent( self.chkOracle) ).addGap(18, 18, 18).addGroup( GeneratorPanelLayout.createParallelGroup( GroupLayout.Alignment.LEADING).addComponent( self.chkSqlite).addComponent(self.chkMysql) )).addGroup(GeneratorPanelLayout.createSequentialGroup( ).addComponent(jlbl5).addPreferredGap( LayoutStyle.ComponentPlacement. UNRELATED).addComponent(toClipboardButton).addGap( 18, 18, 18).addComponent(toFileButton, GroupLayout.PREFERRED_SIZE, 97, GroupLayout.PREFERRED_SIZE ))))).addContainerGap())) GeneratorPanelLayout.setVerticalGroup( GeneratorPanelLayout.createParallelGroup( GroupLayout.Alignment.LEADING). addGroup(GeneratorPanelLayout.createSequentialGroup( ).addContainerGap().addComponent(jlbl1).addPreferredGap( LayoutStyle.ComponentPlacement.RELATED).addComponent( jlbl2, GroupLayout.PREFERRED_SIZE, 21, GroupLayout.PREFERRED_SIZE).addGap(18, 18, 18).addGroup( GeneratorPanelLayout.createParallelGroup( GroupLayout.Alignment.LEADING).addComponent( spanePayloadList, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE). addGroup(GeneratorPanelLayout.createSequentialGroup( ).addComponent(pastePayloadButton).addPreferredGap( LayoutStyle.ComponentPlacement.RELATED ).addComponent(loadPayloadButton).addPreferredGap( LayoutStyle.ComponentPlacement.RELATED ).addComponent(removePayloadButton).addPreferredGap( LayoutStyle.ComponentPlacement.RELATED). addComponent(clearPayloadButton))). addPreferredGap( LayoutStyle.ComponentPlacement.RELATED).addGroup( GeneratorPanelLayout.createParallelGroup( GroupLayout.Alignment.BASELINE).addComponent( self.textNewPayload, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE). addComponent(addPayloadButton)).addPreferredGap( LayoutStyle.ComponentPlacement.UNRELATED). addComponent(jSeparator1, GroupLayout.PREFERRED_SIZE, 10, GroupLayout.PREFERRED_SIZE).addPreferredGap( LayoutStyle.ComponentPlacement.RELATED). addComponent(jlbl3).addPreferredGap( LayoutStyle.ComponentPlacement.UNRELATED ).addComponent(jlbl4).addPreferredGap( LayoutStyle.ComponentPlacement.UNRELATED).addGroup( GeneratorPanelLayout.createParallelGroup( GroupLayout.Alignment.BASELINE).addComponent( self.chkGeneral).addComponent( self.chkMAXDB).addComponent( self.chkOracle).addComponent( self.chkSqlite)). addPreferredGap( LayoutStyle.ComponentPlacement.UNRELATED).addGroup( GeneratorPanelLayout.createParallelGroup( GroupLayout.Alignment.BASELINE).addComponent( self.chkMSSQL).addComponent( self.chkPostgres).addComponent( self.chkMSAccess).addComponent( self.chkMysql) ).addGap(18, 18, 18).addGroup( GeneratorPanelLayout.createParallelGroup( GroupLayout.Alignment.BASELINE).addComponent( jlbl5).addComponent(toClipboardButton). addComponent(toFileButton)).addGap(20, 20, 20))) GeneratorScrollPane.setViewportView(GeneratorPanel) TabbedPane1.addTab("Generator", GeneratorScrollPane) varName = 'SQLiQueryTampering_comboProcessorTech' state = self.extender.callbacks.loadExtensionSetting(varName) for item in self.extender.getTamperFuncsName(): self.comboProcessorTech.addItem(item) if state: self.comboProcessorTech.setSelectedIndex(int(state)) jLabel1.setText("Processor Technique :") jLabel2.setText( "Modify Plain Payloads based on the selected Processor Technique. Write one payload per line." ) jLabel3.setText("Plain Payloads:") self.textPlainPayload.setColumns(20) self.textPlainPayload.setRows(5) jScrollPane1.setViewportView(self.textPlainPayload) jLabel4.setText("Tampered Payloads:") self.textTamperedPayload.setColumns(20) self.textTamperedPayload.setRows(5) jScrollPane2.setViewportView(self.textTamperedPayload) tamperPayloadButton.setText("Tamper Payloads") ProcessorPanelLayout = GroupLayout(ProcessorPanel) ProcessorPanel.setLayout(ProcessorPanelLayout) ProcessorPanelLayout.setHorizontalGroup( ProcessorPanelLayout. createParallelGroup(GroupLayout.Alignment.LEADING).addGroup( GroupLayout.Alignment.TRAILING, ProcessorPanelLayout.createSequentialGroup().addContainerGap( GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE).addComponent( tamperPayloadButton).addContainerGap( GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ).addGroup(ProcessorPanelLayout.createSequentialGroup( ).addContainerGap().addGroup( ProcessorPanelLayout.createParallelGroup( GroupLayout.Alignment.LEADING).addComponent(jSeparator2). addComponent(jScrollPane1).addComponent(jScrollPane2).addGroup( ProcessorPanelLayout.createSequentialGroup().addGroup( ProcessorPanelLayout.createParallelGroup( GroupLayout.Alignment.LEADING).addComponent( jLabel3).addComponent(jLabel4).addGroup( ProcessorPanelLayout.createSequentialGroup( ).addComponent(jLabel1).addPreferredGap( LayoutStyle.ComponentPlacement. UNRELATED).addComponent( self.comboProcessorTech, GroupLayout.PREFERRED_SIZE, 286, GroupLayout.PREFERRED_SIZE)). addComponent(jLabel2)).addGap( 0, 78, Short.MAX_VALUE))).addContainerGap())) ProcessorPanelLayout.setVerticalGroup( ProcessorPanelLayout.createParallelGroup( GroupLayout.Alignment.LEADING).addGroup( ProcessorPanelLayout.createSequentialGroup().addGap( 33, 33, 33).addGroup( ProcessorPanelLayout.createParallelGroup( GroupLayout.Alignment.BASELINE). addComponent(jLabel1).addComponent( self.comboProcessorTech, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)).addGap( 18, 18, 18).addComponent( jSeparator2, GroupLayout.PREFERRED_SIZE, 10, GroupLayout.PREFERRED_SIZE).addGap( 12, 12, 12).addComponent(jLabel2).addGap( 18, 18, 18). addComponent(jLabel3).addPreferredGap( LayoutStyle.ComponentPlacement.UNRELATED).addComponent( jScrollPane1, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE).addPreferredGap( LayoutStyle.ComponentPlacement.UNRELATED). addComponent(jLabel4).addPreferredGap( LayoutStyle.ComponentPlacement.UNRELATED).addComponent( jScrollPane2, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE).addPreferredGap( LayoutStyle.ComponentPlacement.UNRELATED). addComponent(tamperPayloadButton).addGap(36, 36, 36))) ProcessorScrollPane.setViewportView(ProcessorPanel) TabbedPane1.addTab("Processor", ProcessorScrollPane) self.mainPanel = JPanel() layout = GroupLayout(self.mainPanel) self.mainPanel.setLayout(layout) layout.setHorizontalGroup( layout.createParallelGroup( GroupLayout.Alignment.LEADING).addComponent( TabbedPane1, GroupLayout.DEFAULT_SIZE, 701, Short.MAX_VALUE)) layout.setVerticalGroup( layout.createParallelGroup( GroupLayout.Alignment.LEADING).addComponent(TabbedPane1)) TabbedPane1.getAccessibleContext().setAccessibleName("Generator")
class extender(): def __init__(self): self.jLabel1 = JLabel() self.jCheckBox1 = JCheckBox() self.jScrollPane1 = JScrollPane() self.jTable1 = JTable() self.jTabbedPane1 = JTabbedPane() self.jPanel1 = JPanel() self.jButton1 = JButton("Add") self.jButton2 = JButton("Remove") self.jLabel2 = JLabel() self.jLabel3 = JLabel() self.jLabel4 = JLabel() self.jLabel5 = JLabel() self.jLabel6 = JLabel() self.jTextField1 = JTextField() self.jTextField2 = JTextField() self.jTextField3 = JTextField() method = ["http", "https"] self.jComboBox1 = JComboBox(method) self.jLabel7 = JLabel() self.jLabel8 = JLabel() self.jTextField4 = JTextField() self.jButton3 = JButton() self.jPanel2 = JPanel() self.jScrollPane3 = JScrollPane() self.jTextArea2 = JTextArea() self.jLabel1.setFont(Font("굴림", 1, 12)) self.jLabel1.setText("Use local files to serve remote locations.") self.jCheckBox1.setText("Enable Map Local") self.jScrollPane1.setViewportView(self.jTable1) self.jLabel2.setText("Protocol:") self.jLabel3.setText("Host:") self.jLabel4.setText("Path:") self.jLabel5.setText("Query:") self.jLabel6.setText("Map From") self.jLabel7.setText("Map To") self.jLabel8.setText("Local Path:") self.jButton3.setText("Choose") jPanel1Layout = GroupLayout(self.jPanel1) self.jPanel1.setLayout(jPanel1Layout) from java.lang import Short jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(GroupLayout.Alignment.TRAILING) .addComponent(self.jLabel3) .addComponent(self.jLabel2) .addComponent(self.jLabel4) .addComponent(self.jLabel5) .addComponent(self.jLabel6)) .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(GroupLayout.Alignment.LEADING) .addComponent(self.jTextField1) .addComponent(self.jTextField2) .addComponent(self.jTextField3) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(self.jComboBox1, GroupLayout.PREFERRED_SIZE, 86, GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE)))) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addComponent(self.jLabel7)) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(30, 30, 30) .addComponent(self.jLabel8) .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED) .addComponent(self.jTextField4, GroupLayout.DEFAULT_SIZE, 2000, Short.MAX_VALUE) .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED) .addComponent(self.jButton3, GroupLayout.PREFERRED_SIZE, 95, GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(self.jButton1, GroupLayout.PREFERRED_SIZE, 79, GroupLayout.PREFERRED_SIZE) .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED) .addComponent(self.jButton2, GroupLayout.PREFERRED_SIZE, 79, GroupLayout.PREFERRED_SIZE))) .addGap(0, 18, Short.MAX_VALUE))) .addContainerGap()) ) jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(GroupLayout.Alignment.LEADING) .addGroup(GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addContainerGap() .addComponent(self.jLabel6) .addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel1Layout.createParallelGroup(GroupLayout.Alignment.BASELINE) .addComponent(self.jLabel2) .addComponent(self.jComboBox1, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)) .addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel1Layout.createParallelGroup(GroupLayout.Alignment.BASELINE) .addComponent(self.jLabel3) .addComponent(self.jTextField1, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)) .addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel1Layout.createParallelGroup(GroupLayout.Alignment.BASELINE) .addComponent(self.jLabel4) .addComponent(self.jTextField2, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)) .addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel1Layout.createParallelGroup(GroupLayout.Alignment.BASELINE) .addComponent(self.jLabel5) .addComponent(self.jTextField3, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addComponent(self.jLabel7) .addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel1Layout.createParallelGroup(GroupLayout.Alignment.BASELINE) .addComponent(self.jLabel8) .addComponent(self.jTextField4, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addComponent(self.jButton3)) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(GroupLayout.Alignment.BASELINE) .addComponent(self.jButton1) .addComponent(self.jButton2)) .addContainerGap(19, Short.MAX_VALUE)) ) self.jTabbedPane1.addTab("Edit Mapping", self.jPanel1) self.jTextArea2.setColumns(20) self.jTextArea2.setRows(5) self.jScrollPane3.setViewportView(self.jTextArea2) jPanel2Layout = GroupLayout(self.jPanel2) self.jPanel2.setLayout(jPanel2Layout) jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addComponent(self.jScrollPane3, GroupLayout.DEFAULT_SIZE, 729, Short.MAX_VALUE) .addContainerGap()) ) jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addComponent(self.jScrollPane3, GroupLayout.DEFAULT_SIZE, 255, Short.MAX_VALUE) .addContainerGap()) ) self.jTabbedPane1.addTab("Viewer", self.jPanel2) self.panel = JPanel() layout = GroupLayout(self.panel) self.panel.setLayout(layout) layout.setHorizontalGroup( layout.createParallelGroup(GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING) .addComponent(self.jScrollPane1) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING) .addComponent(self.jCheckBox1) .addComponent(self.jLabel1, GroupLayout.PREFERRED_SIZE, 285, GroupLayout.PREFERRED_SIZE)) .addGap(0, 0, Short.MAX_VALUE)) .addComponent(self.jTabbedPane1)) .addContainerGap()) ) layout.setVerticalGroup( layout.createParallelGroup(GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(self.jLabel1) .addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(self.jCheckBox1) .addGap(18, 18, 18) .addComponent(self.jScrollPane1, GroupLayout.PREFERRED_SIZE, 140, GroupLayout.PREFERRED_SIZE) .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED) .addComponent(self.jTabbedPane1) .addContainerGap()) )
class CumulusUI(JFrame): '''Java Swing used to create a JFrame UI. On init the objects will be populated with information derived from URL requests to CUMULUS and the open CWMS watershed. ''' def __init__(self, arg_dict): super(CumulusUI, self).__init__() # Load argument from the command line self.start_time = arg_dict['start_time'] self.end_time = arg_dict['end_time'] self.dss_path = arg_dict['dss_path'] self.cwms_home = arg_dict['cwms_home'] self.config = arg_dict['config'] # Get the DSS Path if one was saved in the "cumulus.config" file if os.path.isfile(self.config): with open(os.path.join(APPDATA, "cumulus.config")) as f: self.dss_path = f.read() # Get the basins and products, load JSON, create lists for JList, and create dictionaries self.basin_download = json.loads(self.http_get(url_basins)) self.jlist_basins = ["{}:{}".format(b['office_symbol'], b['name']) for b in self.basin_download] self.basin_meta = dict(zip(self.jlist_basins, self.basin_download)) self.jlist_basins.sort() self.product_download = json.loads(self.http_get(url_products)) self.jlist_products = ["{}".format(p['name'].replace("_", " ").title()) for p in self.product_download] self.product_meta = dict(zip(self.jlist_products, self.product_download)) self.jlist_products.sort() btn_submit = JButton() lbl_start_date = JLabel() lbl_end_date = JLabel() self.txt_select_file = JTextField() btn_select_file = JButton() lbl_origin = JLabel() lbl_extent = JLabel() lbl_select_file = JLabel() self.txt_start_time = JTextField() self.txt_end_time = JTextField() jScrollPane1 = JScrollPane() self.lst_product = JList() self.lst_product = JList(self.jlist_products, valueChanged = self.choose_product) jScrollPane2 = JScrollPane() self.lst_watershed = JList() self.lst_watershed = JList(self.jlist_basins, valueChanged = self.choose_watershed) self.cwms_dssname = JCheckBox() self.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE) self.setTitle("Cumulus CAVI UI") self.setLocation(Point(10, 10)) self.setLocationByPlatform(True) self.setName("CumulusCaviUi") self.setResizable(False) btn_submit.setFont(Font("Tahoma", 0, 18)) btn_submit.setText("Submit") btn_submit.actionPerformed = self.submit lbl_start_date.setText("Start Date/Time") lbl_end_date.setText("End Date/Time") self.txt_select_file.setToolTipText("FQPN to output file (.dss)") btn_select_file.setText("...") btn_select_file.setToolTipText("Select File...") btn_select_file.actionPerformed = self.select_file lbl_origin.setText("Minimum (x,y):") lbl_extent.setText("Maximum (x,y):") lbl_select_file.setText("Output File Location") self.txt_start_time.setToolTipText("Start Time") self.txt_end_time.setToolTipText("End Time") self.lst_product.setBorder(BorderFactory.createTitledBorder(None, "Available Products", TitledBorder.CENTER, TitledBorder.TOP, Font("Tahoma", 0, 14))) self.lst_product.setFont(Font("Tahoma", 0, 14)) jScrollPane1.setViewportView(self.lst_product) self.lst_product.getAccessibleContext().setAccessibleName("Available Products") self.lst_product.getAccessibleContext().setAccessibleParent(jScrollPane2) self.lst_watershed.setBorder(BorderFactory.createTitledBorder(None, "Available Watersheds", TitledBorder.CENTER, TitledBorder.TOP, Font("Tahoma", 0, 14))) self.lst_watershed.setFont(Font("Tahoma", 0, 14)) self.lst_watershed.setSelectionMode(ListSelectionModel.SINGLE_SELECTION) jScrollPane2.setViewportView(self.lst_watershed) self.cwms_dssname.setText("CWMS DSS filename") self.cwms_dssname.setToolTipText("Parameter.yyyy.mm.dss") self.cwms_dssname.setVisible(False) layout = GroupLayout(self.getContentPane()); self.getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING, False) .addComponent(lbl_select_file) .addComponent(jScrollPane1) .addComponent(jScrollPane2) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(GroupLayout.Alignment.TRAILING) .addComponent(btn_submit) .addComponent(self.txt_select_file, GroupLayout.PREFERRED_SIZE, 377, GroupLayout.PREFERRED_SIZE)) .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED) .addComponent(btn_select_file)) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING) .addComponent(lbl_start_date) .addComponent(self.txt_start_time, GroupLayout.PREFERRED_SIZE, 170, GroupLayout.PREFERRED_SIZE)) .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING) .addComponent(self.txt_end_time, GroupLayout.PREFERRED_SIZE, 170, GroupLayout.PREFERRED_SIZE) .addComponent(lbl_end_date)))) .addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ) layout.setVerticalGroup( layout.createParallelGroup(GroupLayout.Alignment.LEADING) .addGroup(GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGap(25, 25, 25) .addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE) .addComponent(lbl_start_date) .addComponent(lbl_end_date)) .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING) .addComponent(self.txt_start_time, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addComponent(self.txt_end_time, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addComponent(jScrollPane2, GroupLayout.PREFERRED_SIZE, 201, GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jScrollPane1, GroupLayout.PREFERRED_SIZE, 201, GroupLayout.PREFERRED_SIZE) .addGap(18, 18, Short.MAX_VALUE) .addComponent(lbl_select_file) .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE) .addComponent(self.txt_select_file, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addComponent(btn_select_file)) .addGap(18, 18, 18) .addComponent(btn_submit) .addContainerGap()) ) self.txt_select_file.setText(self.dss_path) self.txt_start_time.setText(self.start_time) self.txt_end_time.setText(self.end_time) self.pack() self.setLocationRelativeTo(None) def http_get(self, url): '''Return java.lang.String JSON Input: java.lang.String URL ''' start_timer = System.currentTimeMillis() try: url = URL(url) urlconnect = url.openConnection() br = BufferedReader( InputStreamReader( urlconnect.getInputStream(), "UTF-8" ) ) s = br.readLine() br.close() except MalformedURLException() as ex: cumulus_logger.error(str(ex)) MessageBox.showError(str(ex), "Exception") raise except IOException as ex: cumulus_logger.error(str(ex)) MessageBox.showError(str(ex), "Exception") raise end_timer = System.currentTimeMillis() cumulus_logger.debug( "HTTP GET (milliseconds): {}".format( (end_timer - start_timer) ) ) return s def http_post(self, json_string, url): '''Return java.lang.String JSON Input: java.lang.String JSON, java.lang.String URL ''' start_timer = System.currentTimeMillis() try: # Get a connection and set the request properties url = URL(url) urlconnect = url.openConnection() urlconnect.setDoOutput(True) urlconnect.setRequestMethod("POST") urlconnect.setRequestProperty("Content-Type", "application/json; UTF-8") urlconnect.setRequestProperty("Accept", "application/json") # Write to the body bw = BufferedWriter( OutputStreamWriter( urlconnect.getOutputStream() ) ) bw.write(json_string) bw.flush() bw.close() # Read the result from the POST br = BufferedReader( InputStreamReader( urlconnect.getInputStream(), "UTF-8" ) ) s = br.readLine() br.close() except MalformedURLException() as ex: cumulus_logger.error(str(ex)) MessageBox.showError(str(ex), "Exception") raise Exception(ex) except IOException as ex: cumulus_logger.error(str(ex)) MessageBox.showError(str(ex), "Exception") raise Exception(ex) end_timer = System.currentTimeMillis() cumulus_logger.debug( "HTTP GET (milliseconds): {}".format( (end_timer - start_timer) ) ) return s def json_build(self): '''Return JSON string or 'None' if failed The returning JSON string is from the UI and used when POSTing to the Cumulus API. ''' conf = { 'datetime_start': None, 'datetime_end': None, 'watershed_id': None, 'product_id': None, } try: tf = TimeFormatter() tz = tf.zid st = tf.parse_zoned_date_time(self.txt_start_time.getText(), tz) et = tf.parse_zoned_date_time(self.txt_end_time.getText(), tz) conf['datetime_start'] = st.format(tf.iso_instant()) conf['datetime_end'] = et.format(tf.iso_instant()) except DateTimeParseException as ex: MessageBox.showWarning(ex, "Exception") selected_watershed = self.lst_watershed.getSelectedValue() selected_products = self.lst_product.getSelectedValues() if selected_watershed is not None: watershed_id = self.basin_meta[selected_watershed]['id'] conf['watershed_id'] = watershed_id else: MessageBox.showWarning( "No Watershed Selected", "Exception" ) return None product_ids = list() if len(selected_products) > 0: for p in selected_products: product_ids.append(self.product_meta[p]['id']) conf['product_id'] = product_ids else: MessageBox.showWarning( "No Products Selected", "Exception" ) return None return json.dumps(conf) def choose_product(self, event): '''The event here is a javax.swing.event.ListSelectionEvent because it comes from a Jlist. Use getValueIsAdjusting() to only get the mouse up value. ''' output_str = '''{name} After: {after} Before: {before} Parameter: {para} Unit: {u} ''' index = self.lst_product.selectedIndex if not event.getValueIsAdjusting(): pnames = self.lst_product.getSelectedValues() for pname in pnames: cumulus_logger.info("~" * 50) cumulus_logger.info("Product: {}".format(pname)) cumulus_logger.info( "After time: {}".format(self.product_meta[pname]['after'])) cumulus_logger.info( "Before time: {}".format(self.product_meta[pname]['before'])) cumulus_logger.info( "Parameter: {}".format(self.product_meta[pname]['parameter'])) cumulus_logger.info( "unit: {}".format(self.product_meta[pname]['unit'])) def choose_watershed(self, event): '''The event here is a javax.swing.event.ListSelectionEvent because it comes from a Jlist. Use getValueIsAdjusting() to only get the mouse up value. ''' index = self.lst_watershed.selectedIndex if not event.getValueIsAdjusting(): _dict = self.basin_meta[self.lst_watershed.getSelectedValue()] def select_file(self, event): '''Provide the user a JFileChooser to select the DSS file data is to download to. Event is a java.awt.event.ActionEvent ''' fc = FileChooser(self.txt_select_file) fc.title = "Select Output DSS File" _dir = os.path.dirname(self.dss_path) fc.set_current_dir(File(_dir)) fc.show() def submit(self, event): '''Collect user inputs and initiate download of DSS files to process. Event is a java.awt.event.ActionEvent ''' start_timer = end_timer = System.currentTimeMillis() # Build the JSON from the UI inputs and POST if we have JSON json_string = self.json_build() cumulus_logger.debug("JSON String Builder: {}".format(json_string)) if json_string is not None: cumulus_logger.info("*" * 50) cumulus_logger.info("Initiated Cumulus Product Request") cumulus_logger.info("*" * 50) post_result = self.http_post(json_string, url_downloads) json_post_result = json.loads(post_result) id = json_post_result['id'] max_timeout = 180 while max_timeout > 0: get_result = self.http_get("/".join([url_downloads, id])) if get_result is not None: json_get_result = json.loads(get_result) progress = json_get_result['progress'] #100% stat = json_get_result['status'] #SUCCESS fname = json_get_result['file'] # not null cumulus_logger.info("Status: {:>10}; Progress: {:>4.1f}%; Timeout: {:>4}".format(stat, progress, max_timeout)) if stat == 'FAILED': cumulus_logger.error("Failed to load grid products.") MessageBox.showError( "Failed to load grid products.", "Failed Download" ) break if int(progress) == 100 and stat == 'SUCCESS' and fname is not None: dest_dssfile = self.txt_select_file.getText() cumulus_logger.debug("DSS Download Filname: {}".format(fname)) downloaded_dssfile = download_dss(fname) if downloaded_dssfile is not None: cumulus_logger.info("DSS file downloaded.") merged_dssfiles = merge_dss(downloaded_dssfile, dest_dssfile) if len(merged_dssfiles) > 0: end_timer = System.currentTimeMillis() msg = "DSS file downloaded and merged to: {}".format( '\n'.join([f for f in merged_dssfiles]) ) cumulus_logger.info(msg) MessageBox.showInformation(msg, "Successful Processing" ) else: msg = "DSS file merge unsuccessful" cumulus_logger.warning(msg) MessageBox.showWarning(msg, "Unsuccessful Merge" ) else: msg = "Downloading and processing the DSS file failed!" cumulus_logger.error(msg) MessageBox.showError(msg, "Failed Processing" ) break else: Thread.sleep(2000) max_timeout -= 1 cumulus_logger. info( "Submit time duration (milliseconds): {}".format( (end_timer - start_timer) ) ) # Try to clean up any dss6 and dss7 files in the temp try: tempdir = tempfile.gettempdir() dss_temp_files = os.listdir(tempdir) for f in dss_temp_files: if (f.endswith(".dss") or f.endswith(".dss")): os.remove(os.path.join(tempdir, f)) except OSError as ex: cumulus_logger.warning(str(ex))