Esempio n. 1
0
 def openFile(self, fileext, filedesc, fileparm):
     myFilePath = ''
     chooseFile = JFileChooser()
     myFilter = FileNameExtensionFilter(filedesc, [fileext])
     chooseFile.setFileFilter(myFilter)
     ret = chooseFile.showOpenDialog(self.tab)
     if ret == JFileChooser.APPROVE_OPTION:
         file = chooseFile.getSelectedFile()
         myFilePath = str(file.getCanonicalPath()).lower()
         if not myFilePath.endswith(fileext):
             myFilePath += '.' + fileext
         okWrite = JOptionPane.YES_OPTION
         if os.path.isfile(myFilePath):
             okWrite = JOptionPane.showConfirmDialog(
                 self.tab, 'File already exists. Ok to over-write?', '',
                 JOptionPane.YES_NO_OPTION)
             if okWrite == JOptionPane.NO_OPTION:
                 return
         j = True
         while j:
             try:
                 f = open(myFilePath, mode=fileparm)
                 j = False
             except IOError:
                 okWrite = JOptionPane.showConfirmDialog(
                     self.tab, 'File cannot be opened. Correct and retry?',
                     '', JOptionPane.YES_NO_OPTION)
                 if okWrite == JOptionPane.NO_OPTION:
                     return None, False
         return f, True
 def showDialog(self, event):
     msg = self.message.getText()
     title = self.title.getText()
     opt = self.optionDict[self.optType.getSelectedItem()]
     kind = self.msgDict[self.msgType.getSelectedItem()]
     if msg:
         if title:
             if kind:
                 result = JOptionPane.showConfirmDialog(
                     self.frame, msg, title, opt, kind)
             else:
                 result = JOptionPane.showConfirmDialog(
                     self.frame, msg, title, opt)
         else:
             result = JOptionPane.showConfirmDialog(
                 self.frame,
                 msg,
             )
         self.statusUpdate('result = %d' % result)
     else:
         JOptionPane.showMessageDialog(self.frame,
                                       'A message value is required!',
                                       'Required value not specified',
                                       JOptionPane.ERROR_MESSAGE)
         self.statusUpdate('Enter a message, and try again.')
Esempio n. 3
0
    def OnRegularReloadOfModule(self, event):
        if jython:
            moduleName = self.fileNamesList.getSelectedValue()
        else:
            moduleName = GetListSelection(self.fileNamesList)
        print "Module to reload:", moduleName
        if moduleName:
            warning = """You are about to do a regular reload of module %s.
If you do this, any currently open windows defined in that specific module
will no longer respond to special reloads until the entire program is restarted.
Any other module will not neccessarily use the reloaded code unless it too is reloaded.
Any subsequently opened windows will only use the new code regularly reloaded in this module
if the calling module does an explicit import of the reloaded module before referencing the window and
if the code snippet opening the new window explicitely accesses the reloaded module's window class
as a "module.className()" reference, as opposed to "from module import name" and "className()"
(where the classname would then still point to the previous version).
Confusing? Yes! I'm still not sure I understand it thoroughly myself. :-)
Proceed anyway?""" % moduleName
            title = "Confirm regular reload"
            if jython:
                result = JOptionPane.showConfirmDialog(self, warning, title, JOptionPane.YES_NO_CANCEL_OPTION)
                proceed = (result == JOptionPane.YES_OPTION)
            else:
                proceed = AskYesNoDialog(self.window, warning, title)
            if proceed:
                print "==== starting regular reload of module", moduleName
                reload(sys.modules[moduleName])
                print "== done with regular reload\n"
            else:
                print "reload cancelled"
Esempio n. 4
0
def run(mode):
    selected = None
    if mode == 'b':
        selected = Application.getInstance().getMainFrame().getBrowser(
        ).getActiveTree().getSelectedNode().getUserObject()
    if mode == 'd':
        selected = Application.getInstance().getProject().getActiveDiagram(
        ).getSelected().get(0).getElement()
    if not isinstance(selected, Class):
        gl.log("You must select a block!!!")
        return

    try:
        SessionManager.getInstance().createSession("generalize")
        choice = JOptionPane.showConfirmDialog(
            None,
            "If you undo specializations you may lose default values on blocks since they'll be deleted, continue?",
            "Continue?", JOptionPane.YES_NO_OPTION)
        if choice == JOptionPane.YES_OPTION:
            undo(selected)

        SessionManager.getInstance().closeSession()
    except:
        SessionManager.getInstance().cancelSession()
        exceptionType, exceptionValue, exceptionTraceback = sys.exc_info()
        messages = traceback.format_exception(exceptionType, exceptionValue,
                                              exceptionTraceback)
        for message in messages:
            gl.log(message)
Esempio n. 5
0
def yesNo(frame, message):
    n = JOptionPane.showConfirmDialog(frame,
        message, "Question", JOptionPane.YES_NO_OPTION)
    if n == JOptionPane.YES_OPTION:
        return True
    else:
        return False
Esempio n. 6
0
    def __buffer(self):
        """
			Returns the current buffer ready for run/import, checking if it is
			a python buffer and whether has been saved
		"""
        from javax.swing import JOptionPane
        buf = self.view.editPane.buffer
        if buf.mode.name != "python":
            if buf.getProperty("jython.originator"):
                buf = buf.getProperty("jython.originator")

        if buf.mode.name == "python":
            if buf.dirty:
                if not jEdit.getBooleanProperty("options.jython.autosave"):
                    if jEdit.getBooleanProperty("options.jython.saveask"):
                        result = JOptionPane.showConfirmDialog(
                            self.panel, "Do you want to save before running",
                            "Confirm", JOptionPane.YES_NO_CANCEL_OPTION)
                        if result == JOptionPane.CANCEL_OPTION:
                            return None
                        if result == JOptionPane.YES_OPTION:
                            buf.save(self.view, None)
                else:
                    buf.save(self.view, None)
            return buf

        return None
Esempio n. 7
0
 def edit_filter(event):
     # TODO Set the properties on the edit filter based on the passed event
     result = JOptionPane.showConfirmDialog(
         self, edit_filter_panel, "Edit Filter",
         JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE)
     if result == 0:
         print "Will save filter"
Esempio n. 8
0
def dispQuestion(msg, title):
    result = JOptionPane.showConfirmDialog(None, msg, title,
                                           JOptionPane.YES_NO_OPTION,
                                           JOptionPane.QUESTION_MESSAGE)
    if result == JOptionPane.YES_OPTION:
        return True
    return False
Esempio n. 9
0
    def _button_demo_pressed(self, msg):
        if JOptionPane.showConfirmDialog(
            msg.getSource().getParent().getParent(),
            "This will clear all session handling rules in Burp's \n" +
            "\"Project options -> Sessions\"\n" +
            "tab, even rules not produced by this extension. They\n" +
            "will be replaced with a sample/demo rule containing an\n" +
            "invoke extension session handler action.\n\n" +
            "A request which can be used for the demo will be sent\n" +
            "to the Repeater tab.\n\n" +
            "The demo URL will be placed in the settings, and the\n" +
            "contents of the \"Cookies to obtain\" list will be\n"+
            "replaced with a single demo cookie named\n" +
            "\"ClientSideCookie\"\n\n" +
            "Please check the PhantomJS settings, then click on\n" +
            "\'Add a new \"Get Cookies\" session handler\'.\n\n" +
            "Are you sure you want to remove any existing session\n" +
            "handling rules?",
            "Burp Suite / WAF Cookie Fetcher",
            JOptionPane.YES_NO_OPTION
        ) == JOptionPane.YES_OPTION:
            panel_update_cookies = self.getParent().panel_update_cookies
            for field in \
                    panel_update_cookies.fields:
                if "getText" in dir(field) and "getName" in dir(field):
                    field_name = field.getName()
                    if field_name == "url":
                        field.setText(cb.demo_url)
                    if field_name == "domain":
                        field.setText(cb.demo_domain)
            panel_update_cookies._rowpanel2.removeAllElements()
            panel_update_cookies._rowpanel2.addelement(cb.demo_cookie)

            cb.callbacks.loadConfigFromJson(cb.demo_json)
            cb.send_url_to_repeater(cb.demo_url)
Esempio n. 10
0
 def clearClick(self,e):
     result = JOptionPane.showConfirmDialog(self._splitpane, "Clear AuthMatrix Configuration?", "Clear Config", JOptionPane.YES_NO_OPTION)
     if result == JOptionPane.YES_OPTION:
         self._db.clear()
         self._tabs.removeAll()
         self._userTable.redrawTable()
         self._messageTable.redrawTable()
Esempio n. 11
0
def check_directory(path):

    if (os.path.lexists(path)):
        contents = os.listdir(path)

        if (contents.count("install-birch") == 0):
            print_console("The selected directory " + path +
                          " does NOT contain a BIRCH installation!")
            message = "The selected path does NOT contain a BIRCH installation.\nPlease select the base directory of the installation that you wish to update,\nOr click \"no\" to cancel update."
            reload = JOptionPane.showConfirmDialog(None, message, "Input",
                                                   JOptionPane.YES_NO_OPTION)

            if (reload == JOptionPane.NO_OPTION):
                print_console("User aborted install.")
                commonlib.shutdown()

            fc = JFileChooser()
            fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY)
            fc.showOpenDialog(None)
            path = fc.getSelectedFile().getPath()

            check_directory(path)

        else:
            ARGS.install_dir = path
            print_console("The selected directory " + path +
                          " contains a BIRCH installation, it will be updated")
Esempio n. 12
0
    def OnRegularReloadOfModule(self, event):
        if jython:
            moduleName = self.fileNamesList.getSelectedValue()
        else:
            moduleName = GetListSelection(self.fileNamesList)
        print "Module to reload:", moduleName
        if moduleName:
            warning = """You are about to do a regular reload of module %s.
If you do this, any currently open windows defined in that specific module
will no longer respond to special reloads until the entire program is restarted.
Any other module will not neccessarily use the reloaded code unless it too is reloaded.
Any subsequently opened windows will only use the new code regularly reloaded in this module
if the calling module does an explicit import of the reloaded module before referencing the window and
if the code snippet opening the new window explicitely accesses the reloaded module's window class
as a "module.className()" reference, as opposed to "from module import name" and "className()"
(where the classname would then still point to the previous version).
Confusing? Yes! I'm still not sure I understand it thoroughly myself. :-)
Proceed anyway?""" % moduleName
            title = "Confirm regular reload"
            if jython:
                result = JOptionPane.showConfirmDialog(
                    self, warning, title, JOptionPane.YES_NO_CANCEL_OPTION)
                proceed = (result == JOptionPane.YES_OPTION)
            else:
                proceed = AskYesNoDialog(self.window, warning, title)
            if proceed:
                print "==== starting regular reload of module", moduleName
                reload(sys.modules[moduleName])
                print "== done with regular reload\n"
            else:
                print "reload cancelled"
Esempio n. 13
0
    def deleteSession(self, evt):
        """Listener for the Delete Session button."""

        if JOptionPane.showConfirmDialog(None, "Are you sure?", "", JOptionPane.YES_NO_OPTION) == JOptionPane.OK_OPTION:
            self._extender.sm.remove_session()
            self.refresh_sessions()
            self.update_table()
            self.parse_message()
Esempio n. 14
0
 def restart(self, event):
     """ Reinitializes the interpreter """
     from javax.swing import JOptionPane
     result = JOptionPane.showConfirmDialog(self.panel, \
      jEdit.getProperty("jython.console.clean-confirm"), "Confirm", JOptionPane.YES_NO_CANCEL_OPTION)
     if result == JOptionPane.YES_OPTION:
         JythonExecutor.getExecutor().interrupt()
         self.__inittext()
Esempio n. 15
0
 def windowClosing(self, event):
     answer = JOptionPane.showConfirmDialog(
         event.getSource(), "Are you sure you want to close?",
         "Confirm closing", JOptionPane.YES_NO_OPTION)
     if JOptionPane.NO_OPTION == answer:
         event.consume()  # Prevent closing
     else:
         Roi.removeRoiListener(self.roilistener)
         event.getSource().dispose()  # close the JFrame
Esempio n. 16
0
 def tabClose(self, event):
     result = JOptionPane.showConfirmDialog(
         None, 'Are you sure you want to close \'{}\' ?'.format(
             event.source.text), "Close Tab", JOptionPane.YES_NO_OPTION,
         JOptionPane.QUESTION_MESSAGE)
     if result == JOptionPane.YES_OPTION:
         idx = self.tabbed_pane.indexOfTabComponent(event.source)
         self.tabbed_pane.remove(idx)
         self.scripts.remove(self.script)
Esempio n. 17
0
 def generateReport(self,event):
     if self.reportType.getSelectedItem() == "HTML":
         path = self.reportToHTML()
     if self.reportType.getSelectedItem() == "XLSX":
         path = self.reportToXLS()
     if self.reportType.getSelectedItem() == "DOCX":
         path = self.generateReportFromDocxTemplate('template.docx',"newfile.docx", 'word/document.xml')
     n = JOptionPane.showConfirmDialog(None, "Report generated successfuly:\n%s\nWould you like to open it?" % (path), "PT Manager", JOptionPane.YES_NO_OPTION)
     if n == JOptionPane.YES_OPTION:
         os.system('"' + path + '"') # Bug! stucking burp until the file get closed
Esempio n. 18
0
 def create_autologic_and_sections(self):
     self.msg = "About to create all signal logic and sections\nrequired for dispatcher operation"
     self.msg = self.msg + "\n***********************\n Do you wish to continue\n***********************"
     myAnswer = JOptionPane.showConfirmDialog(None, self.msg)
     self.set_layout_editor()
     self.delete_transits()
     self.delete_sections()
     self.delete_signal_mast_logic()
     self.create_auto_signal_mast_logic()
     self.create_sections()
Esempio n. 19
0
def confirmWindowClosing(event):
    """ event: the WindowEvent that tells us what was done to the window. """
    answer = JOptionPane.showConfirmDialog(event.getSource(),
                                           "Are you sure you want to close?",
                                           "Confirm closing",
                                           JOptionPane.YES_NO_OPTION)
    if JOptionPane.NO_OPTION == answer:
        event.consume()  # prevent closing the window by cancelling the event
    else:
        event.getSource().dispose()  # close the JFrame
Esempio n. 20
0
 def promptOptionPane(self, question):
     '''
     1. Show popup with given question text
     2. Give Yes No Cancel options
     3. Return chosen option
     '''
     option = JOptionPane.YES_NO_CANCEL_OPTION
     result = JOptionPane.showConfirmDialog(self.view.getContentPane(),
                                            question, "Question", option)
     return result
Esempio n. 21
0
    def deleteSession(self, evt):
        """Listener for the Delete Session button."""

        if JOptionPane.showConfirmDialog(
                None, "Are you sure?", "",
                JOptionPane.YES_NO_OPTION) == JOptionPane.OK_OPTION:
            self._extender.sm.remove_session()
            self.refresh_sessions()
            self.update_table()
            self.parse_message()
Esempio n. 22
0
 def promptOptionPane(self, question):
     '''
     1. Show popup with given question text
     2. Give Yes No Cancel options
     3. Return chosen option
     '''
     result = JOptionPane.showConfirmDialog( \
             self.view.getContentPane(), question, "Question", \
             JOptionPane.YES_NO_CANCEL_OPTION)
     return result
Esempio n. 23
0
    def _cookie_fetch_test(self, msg):

        test_values = {}  # next few lines are similar to update_values()
        for field in self.fields:
            if "getText" in dir(field) and "getName" in dir(field):
                value = field.getText()
                test_values[field.getName()] = value

        cookies_from_phantom = PhantomJS.read(
                                              test_values["phantomJS_path"],
                                              test_values["phantomJS_args"],
                                              test_values["url"],
                                              test_values["duration"]
                                            )[0]
        cookie_count = len(cookies_from_phantom)

        cb.callbacks.printOutput(
                                    "Cookie Fetch Test results: " +
                                    str(cookie_count) +
                                    " cookies received."
                                )

        add_to_list = False
        if cookie_count > 0:
            result_text = (
                        "Cookie Fetch Test results:\n\n" +
                        str(cookie_count) +
                        " cookies received.\n\n" +
                        "See extender stdout log for names and values.\n\n" +
                        "Would you like to add all of the fetched cookie " +
                        "names to the \"Cookies to obtain\" list?"
                    )
            if JOptionPane.showConfirmDialog(
                            self,
                            result_text,
                            "Burp Suite / WAF Cookie Fetcher",
                            JOptionPane.YES_NO_OPTION
                        ) == JOptionPane.YES_OPTION:
                add_to_list = True
        else:
            JOptionPane.showMessageDialog(
                self,
                "Cookie Fetch Test results:\n\n" +
                "No cookies received"
            )

        for cookie in cookies_from_phantom:
            cookie_name = cookie[u"name"]
            cookie_value = cookie[u"value"]
            if add_to_list: self._rowpanel2.addelement(cookie_name)
            cb.callbacks.printOutput(
                                cookie_name +
                                ": " +
                                cookie_value
                            )
Esempio n. 24
0
    def buildAddEditPrompt(self,
                           typeValue=None,
                           searchValue=None,
                           replacementValue=None):
        """
        Builds the replacement rules add/edit prompt.

        Args:
            typeValue: the value that will be set on the type JLabel.
            searchValue: the value that will be set on the search JLabel.
            replacementValue: the value that will be set on the replacement JLabel.

        Return:
            tuple: (type, search, replacement) as input by user.
        """
        panel = Box.createVerticalBox()

        typeLabel = JLabel("Replacement type")
        type = JComboBox([REPLACE_HEADER_NAME])
        searchLabel = JLabel("Header Name / Search String")
        search = JTextField()
        replaceLabel = JLabel("Replacement Value")
        replacement = JTextField()

        panel.add(typeLabel)
        panel.add(type)
        panel.add(searchLabel)
        panel.add(search)
        panel.add(replaceLabel)
        panel.add(replacement)

        if typeValue:
            type.setSelectedItem(typeValue)

        if searchValue:
            search.text = searchValue

        if replacementValue:
            replacement.text = replacementValue

        title = "Add Replacement Rule" if type == None else "Edit Replacement Rule"

        result = JOptionPane.showConfirmDialog(None, panel,
                                               "Add Replacement Rule",
                                               JOptionPane.PLAIN_MESSAGE)

        if result == JOptionPane.OK_OPTION:
            if search.text.strip() == "":
                self.messageDialog("Header name must be non-blank.")
                raise InvalidInputException()
            else:
                return type.selectedItem, search.text, replacement.text
        else:
            raise InvalidInputException()
Esempio n. 25
0
 def saveClick(self, e):
     returnVal = self._fc.showSaveDialog(self._splitpane)
     if returnVal == JFileChooser.APPROVE_OPTION:
         f = self._fc.getSelectedFile()
         if f.exists():
             result = JOptionPane.showConfirmDialog(self._splitpane, "The file exists, overwrite?", "Existing File", JOptionPane.YES_NO_OPTION)
             if result != JOptionPane.YES_OPTION:
                 return
         fileName = f.getPath()
         outs = ObjectOutputStream(FileOutputStream(fileName))
         outs.writeObject(self._db.getSaveableObject())
         outs.close()
Esempio n. 26
0
 def windowClosing(self, event):
     if JOptionPane.NO_OPTION == JOptionPane.showConfirmDialog(
             event.getSource(), "Are you sure you want to close?",
             "Confirm closing", JOptionPane.YES_NO_OPTION):
         # Prevent closing
         event.consume()
     else:
         for d in self.destroyables:
             d.destroy()
         event.getSource().dispose()
         self.destroyables = set()
         event.getSource().removeWindowListener(self)
Esempio n. 27
0
 def confirmLocoDirection(self, loc):
     if loc.reversible() is False and loc.inReverseLoop() is False:
         # check it's pointing the right way
         self.debug("getting direction from user")
         b = JOptionPane.showConfirmDialog(None, "Loco " + str(loc.nameAndAddress()) + " is facing the right way?",
                                           "Confirm Loco direction", JOptionPane.YES_NO_OPTION)
         if b == JOptionPane.YES_OPTION:
             loc.wrongway = False
         else:
             loc.wrongway = True
     else:
         # can't be facing the wrong way, since reversible is true
         loc.wrongway = False
Esempio n. 28
0
    def new_session(self, evt):
        """Listener for New Session button."""

        name = JOptionPane.showInputDialog(None, "Name the new session:", "Session name")
        if name != None:
            from_request = JOptionPane.showConfirmDialog(None, "Create session from current request?", "From current request?", JOptionPane.YES_NO_OPTION)
            self._extender.sm.new_session(name)
            self.refresh_sessions()

            # let user select parameters for new session
            if from_request == JOptionPane.OK_OPTION:
                dialog = SessionFromRequestDialog(self)
                dialog.setVisible(True)
Esempio n. 29
0
 def saveClick(self, e):
     returnVal = self._fc.showSaveDialog(self._splitpane)
     if returnVal == JFileChooser.APPROVE_OPTION:
         f = self._fc.getSelectedFile()
         if f.exists():
             result = JOptionPane.showConfirmDialog(
                 self._splitpane, "The file exists, overwrite?",
                 "Existing File", JOptionPane.YES_NO_OPTION)
             if result != JOptionPane.YES_OPTION:
                 return
         fileName = f.getPath()
         outs = io.ObjectOutputStream(io.FileOutputStream(fileName))
         outs.writeObject(self._db.getSaveableObject())
         outs.close()
Esempio n. 30
0
    def listSubmit(self, event):
        """Submit highlighted to csv file to automation folder of spectrometer
        """

        # Ask for starting carousel position and submit experimets to topspin
        # obtain file name of CSV file
        selected = self.list.selectedIndex
        csvName = self.data[selected]

        # if no selected file and table is empty just return
        if self.label.text == "Selected File":
            return

        # Create check dialog before submitting data to automation
        self.dataTableModel.dataVector
        #        submitString = "submit " + csvName + " starting at carousel position " + self.carouselStartingPosition.text
        submitString = "submit " + csvName + " starting at carousel position " + str(
            (self.dataTableModel.dataVector)[0][1])
        result = JOptionPane.showConfirmDialog(self.frame, submitString)

        # if submission confirmed
        if result == 0:
            # submit csv file to automation
            ret = readcsv243A.submitNMRexpts([
                self.dataTableModel.dataVector, csvName,
                self.carouselStartingPosition.text
            ])
            # if successful or not update status string
            if ret == 0:
                self.statusLabel.text = "File " + csvName + " Submitted to TOPSPIN  Starting at Carousel Position " + str(
                    (self.dataTableModel.dataVector)[0][1])
                self.panelStatusLabel.setBackground(Color.GREEN)
            elif ret == 1:
                self.statusLabel.text = "Carousel Position not a number"
                self.panelStatusLabel.setBackground(Color.RED)
            elif ret == 2:
                self.statusLabel.text = "Incompatible experiment chosen for spectrometer"
                self.panelStatusLabel.setBackground(Color.RED)
            elif ret == 3:
                self.statusLabel.text = "A holder starting position is not between 1 and 60 inclusive"
                self.panelStatusLabel.setBackground(Color.RED)
            elif ret == 4:
                self.statusLabel.text = "Too many samples for starting position chosen"
                self.panelStatusLabel.setBackground(Color.RED)

            # if an error occured display error message also in a warning dialog too.
            if ret in [1, 2, 3, 4]:
                JOptionPane.showMessageDialog(self.frame,
                                              self.statusLabel.text)
Esempio n. 31
0
    def new_session(self, evt):
        """Listener for New Session button."""

        name = JOptionPane.showInputDialog(None, "Name the new session:",
                                           "Session name")
        if name != None:
            from_request = JOptionPane.showConfirmDialog(
                None, "Create session from current request?",
                "From current request?", JOptionPane.YES_NO_OPTION)
            self._extender.sm.new_session(name)
            self.refresh_sessions()

            # let user select parameters for new session
            if from_request == JOptionPane.OK_OPTION:
                dialog = SessionFromRequestDialog(self)
                dialog.setVisible(True)
Esempio n. 32
0
def compress_old_birch():

    print_label("Archiving old BIRCH")
    filename = "birch_backup" + str(datetime.datetime.now()).replace(
        " ", "") + ".tar"
    filename = filename.replace(":", "")
    filename = filename.replace("-", "")
    print_console("Saving old BIRCH in " + filename)
    tar = tarfile.open(filename, "w")

    os.chdir(ARGS.install_dir)

    for each in birch_files:
        if (os.path.lexists(ARGS.install_dir + "/" + each)):
            print_console("Archiving old birch directory " + each)

            try:
                tar.add(each)
            except IOError:
                print_console("Could not add file: \"" + each +
                              "\" to archive:")
                ioerr = traceback.format_exc()
                print_console(str(ioerr))
                message = "An IO error occurred, the file \"" + each + "\"could not be added to the archive, do you still wish to proceed?"
                cont = JOptionPane.showConfirmDialog(None, message, "Input",
                                                     JOptionPane.YES_NO_OPTION)

                if (cont == JOptionPane.NO_OPTION):
                    print_console("User aborted installation")
                    JOptionPane.showMessageDialog(
                        "It is recommended that you archive manually archive your previous BIRCH installation before you proceed with the update."
                    )
                    commonlib.shutdown()

            except:
                err = traceback.format_exc()
                print_console(err)
                print_console(
                    "Unhandled exception occurred, this is a bug. For safety reasons, the update has been aborted"
                )
                JOptionPane.showMessageDialog(
                    None,
                    "Unhandled exception occurred, this is a bug. For safety reasons, the update has been aborted"
                )
                commonlib.shutdown()

    tar.close()
Esempio n. 33
0
 def clickhere(self, event):
     self.lst.selectionMode = (
         ListSelectionModel.MULTIPLE_INTERVAL_SELECTION)
     print "clicked"
     self.itemSelected = list(sorted(self.lst.selectedValues[:]))
     print "item selected:", self.itemSelected
     if self.radiobutton1.isSelected():
         self.saveState = "Y"
         print "Save MIPs!"
     if self.radiobutton2.isSelected():
         self.saveState = "N"
         print "Don't save MIPs!"
     self.exeunt = JOptionPane.showConfirmDialog(
         None,
         "You have chosen to make MIPs out of \n {} \n proceed?".format(
             str(self.itemSelected)), "Proceed?", JOptionPane.YES_NO_OPTION)
     self.clickEx()
Esempio n. 34
0
    def menuItemClicked(self, menuItemCaption, messageInfo):
        if menuItemCaption == 'Save PoC':

            if self.dir:
                fc = JFileChooser(self.dir)
            else:
                fc = JFileChooser()

            returnVal = fc.showSaveDialog(None)

            if returnVal == JFileChooser.APPROVE_OPTION:
                file = fc.getSelectedFile()

                try:
                    mode = 'w'
                    if file.exists():
                        res = JOptionPane.showConfirmDialog(
                            None, "File exists. Append?")
                        mode = {
                            JOptionPane.YES_OPTION: 'a',
                            JOptionPane.NO_OPTION: 'w',
                            JOptionPane.CANCEL_OPTION: None,
                        }[res]

                    if not mode:
                        return
                    fp = open(str(file.getAbsolutePath()), mode)
                    for req_resp in messageInfo:
                        req = req_resp.getRequest()
                        resp = req_resp.getResponse()
                        fp.write(req.tostring())
                        fp.write('\r\n\r\n')
                        fp.write(resp.tostring())
                        fp.write('\r\n\r\n')
                    fp.close()
                except Exception, e:
                    JOptionPane.showMessageDialog(
                        None, "Error during save: " + str(e), "Error",
                        JOptionPane.ERROR_MESSAGE)
                    raise

                JOptionPane.showMessageDialog(None,
                                              "File was successfully saved",
                                              "Ok",
                                              JOptionPane.INFORMATION_MESSAGE)
                self.dir = fc.getCurrentDirectory()
Esempio n. 35
0
    def approveSelection(self):
        filePath = self.getSelectedFile().getPath()
        fileName = String(self.getSelectedFile().getName())

        if fileName.matches('[_a-zA-Z0-9()~#.]+'):
            if os.path.exists(filePath):
                message = 'File "' + str(fileName) + ' exists. Overwrite?'
                result = JOptionPane.showConfirmDialog(self, message,
                                                       'Confirm Overwrite',
                                                       JOptionPane.YES_NO_OPTION)
                if result == JOptionPane.YES_OPTION:
                    JFileChooser.approveSelection(self)
            else:
                JFileChooser.approveSelection(self)
        else:
            message = 'The file name contains illegal characters. Please rename.'
            JOptionPane.showMessageDialog(self, message, 'Error', JOptionPane.ERROR_MESSAGE)
Esempio n. 36
0
    def menuItemClicked(self, menuItemCaption, messageInfo):
        if menuItemCaption == 'Save PoC':

            if self.dir:
                fc = JFileChooser(self.dir)
            else:
                fc = JFileChooser()

            returnVal = fc.showSaveDialog(None)

            if returnVal == JFileChooser.APPROVE_OPTION:
                file = fc.getSelectedFile()

                try:
                    mode = 'w'
                    if file.exists():
                        res = JOptionPane.showConfirmDialog(None, 
                                "File exists. Append?")
                        mode = {
                                JOptionPane.YES_OPTION : 'a',
                                JOptionPane.NO_OPTION : 'w',
                                JOptionPane.CANCEL_OPTION : None,
                                }[res]

                    if not mode:
                        return
                    fp = open(str(file.getAbsolutePath()), mode)
                    for req_resp in messageInfo:
                        req = req_resp.getRequest()
                        resp = req_resp.getResponse()
                        fp.write(req.tostring())
                        fp.write('\r\n\r\n')
                        fp.write(resp.tostring())
                        fp.write('\r\n\r\n')
                    fp.close()
                except Exception, e:
                    JOptionPane.showMessageDialog(None, 
                            "Error during save: " + str(e), "Error",  
                            JOptionPane.ERROR_MESSAGE)
                    raise

                JOptionPane.showMessageDialog(None, 
                            "File was successfully saved", "Ok",  
                            JOptionPane.INFORMATION_MESSAGE)
                self.dir = fc.getCurrentDirectory()
Esempio n. 37
0
    def approveSelection(self):
        filePath = self.getSelectedFile().getPath()
        fileName = String(self.getSelectedFile().getName())

        if fileName.matches('[_a-zA-Z0-9()~#.]+'):
            if os.path.exists(filePath):
                message = 'File "' + str(fileName) + ' exists. Overwrite?'
                result = JOptionPane.showConfirmDialog(
                    self, message, 'Confirm Overwrite',
                    JOptionPane.YES_NO_OPTION)
                if result == JOptionPane.YES_OPTION:
                    JFileChooser.approveSelection(self)
            else:
                JFileChooser.approveSelection(self)
        else:
            message = 'The file name contains illegal characters. Please rename.'
            JOptionPane.showMessageDialog(self, message, 'Error',
                                          JOptionPane.ERROR_MESSAGE)
Esempio n. 38
0
    def saveFile(self, event=None):
        '''
        If file being edited has a path, then overwrite with latest changes.
        If file was created from scratch and has no path, prompt JFileChooser
        to save in desired location.
        Also checks for project name, and if found, makes it default.
        '''
        atfText = self.atfAreaController.getAtfAreaText()
        if not self.currentFilename:
            fileChooser = JFileChooser(self.get_working_dir())
            file_filter = FileNameExtensionFilter("ATF files", ["atf"])
            fileChooser.setFileFilter(file_filter)
            status = fileChooser.showSaveDialog(self.view)
            if status == JFileChooser.APPROVE_OPTION:
                atfFile = fileChooser.getSelectedFile()
                filename = atfFile.getCanonicalPath()
                # Make sure users check before lightly overwriting a file
                # No need to ask if they choose to save on the file they are
                # currently and knowingly editing.
                if os.path.isfile(filename) and \
                   filename != self.currentFilename:
                    reply = JOptionPane.showConfirmDialog(
                        None, "Are you sure you want to overwrite that file?",
                        "Confirm replace file", JOptionPane.YES_NO_OPTION)
                    if reply == JOptionPane.NO_OPTION:
                        return
                filename = self.force_atf_extension(filename)
                self.currentFilename = filename
                self.view.setTitle(os.path.basename(filename))
            else:
                return
        try:
            self.writeTextFile(self.currentFilename, atfText)
        except:
            self.logger.error("There was an error trying to save %s.",
                              self.currentFilename)
        else:
            self.logger.info("File %s successfully saved.",
                             self.currentFilename)

        # Find project and language and add to settings.yaml as default
        self.update_config()
Esempio n. 39
0
    def _generate_model(self, e):
        if len(self._messages) <= 0:
            frame = JFrame("Error")
            JOptionPane.showMessageDialog(frame, "No messages!", "Error",
                                          JOptionPane.ERROR_MESSAGE)
            return
        if self._sql_file == None:
            frame = JFrame("Error")
            replay = JOptionPane.showConfirmDialog(
                frame, "No SQL file selected!\nDo you want to continue?",
                "Info", JOptionPane.YES_NO_OPTION)
            if replay == JOptionPane.NO_OPTION:
                return

        # create a new AslanppModel
        model = AslanppModel()
        # save _sql_file
        model._sql_file = self._sql_file

        for c in self._messages:
            # from byte to char Request and Response
            # for some reason b can be a negative value causing a crash
            # so I put a check to ensure b is in the right range
            msg = c[0]
            if msg.getRequest() == None or msg.getResponse() == None:
                # do not convert empty messages
                continue
            http_request = "".join(
                chr(b) for b in msg.getRequest() if b >= 0 and b <= 256)
            http_response = "".join(
                chr(b) for b in msg.getResponse() if b >= 0 and b <= 256)
            protocol = msg.getHttpService().getProtocol()
            # save the tag number generate by _parseHttpRequestResponse in the _messages array
            c[1] = converter._parseHttpRequestResponse(model, http_request,
                                                       http_response, protocol)

        # generate the ASLan++ code
        self._model, self._concrete = converter._generateWAFExModel(model)
        Platform.runLater(
            UpdateEditor(self._jfxp_aslanpp._editor,
                         self._jfxp_concretization._editor, self._model,
                         self._concrete))
Esempio n. 40
0
    def changeDomainPopup(self, oldDomain, index):
        hostField = JTextField(25)
        checkbox = JCheckBox()
        domainPanel = JPanel(GridLayout(0,1))
        domainPanel.add(JLabel("Request %s: Domain %s inaccessible. Enter new domain." % (str(index),oldDomain)))

        firstline = JPanel()
        firstline.add(JLabel("Host:"))
        firstline.add(hostField)
        domainPanel.add(firstline)
        secondline = JPanel()
        secondline.add(JLabel("Replace domain for all requests?"))
        secondline.add(checkbox)
        domainPanel.add(secondline)
        result = JOptionPane.showConfirmDialog(
            self._splitpane,domainPanel, "Domain Inaccessible", JOptionPane.OK_CANCEL_OPTION)
        cancelled = (result == JOptionPane.CANCEL_OPTION)
        if cancelled:
            return (False, None, False)
        return (True, hostField.getText(), checkbox.isSelected())
Esempio n. 41
0
    def continueAfterSaving(self, prompt):
        if self.filename is None or self.editor.modified:
            promptResult = JOptionPane.showConfirmDialog(self.parentWindow,
                prompt + '\n' + PROMPT_SAVE_REQUIRED,
                PROMPT_SAVE_CAPTION, JOptionPane.YES_NO_OPTION
            )

            if promptResult == JOptionPane.YES_OPTION:
                isSaved = self.saveAction()
                if isSaved:
                    # The file saved, keep going.
                    return True
                else:
                    # The file _isn't_ saved, bail out.
                    return False
            else:
                # The user decided to cancel, bail out.
                return False
        else:
            return True
Esempio n. 42
0
 def dialog(self, message, options=None,
                   default=0, title="GeoGebra", message_type='question'):
     message_type = message_types[message_type]
     if options is None:
         return JOptionPane.showMessageDialog(
             self.api.appFrame,
             message, title, message_type
         )
     if isinstance(options, basestring):
         if options in option_types:
             option_type = option_types[options]
             return JOptionPane.showConfirmDialog(
                 self.api.appFrame,
                 message, title, option_type, message_type
             )
         options = options.split("/")
     default = options[default]
     return JOptionPane.showOptionDialog(
         self.api.appFrame,
         message, title, 0, message_type, None, options, default
     )
Esempio n. 43
0
def compress_old_birch():
	
	print_label("Archiving old BIRCH")	
	filename="birch_backup"+str(datetime.datetime.now()).replace(" ","")+".tar"
	filename=filename.replace(":","")
	filename=filename.replace("-","")
	print_console("Saving old BIRCH in "+filename)
	tar = tarfile.open(filename, "w")
	
	os.chdir(ARGS.install_dir)
	
	for each in birch_files:
		if (os.path.lexists(ARGS.install_dir+"/"+each)):
			print_console("Archiving old birch directory "+ each)
			
			
			try:
				tar.add(each)
			except IOError:
				print_console("Could not add file: \""+each+"\" to archive:")
				ioerr=traceback.format_exc()
				print_console(str(ioerr))
				message="An IO error occurred, the file \""+each+"\"could not be added to the archive, do you still wish to proceed?"
				cont=JOptionPane.showConfirmDialog(None,message, "Input",JOptionPane.YES_NO_OPTION);
				
				if (cont==JOptionPane.NO_OPTION):
					print_console("User aborted installation")
					JOptionPane.showMessageDialog("It is recommended that you archive manually archive your previous BIRCH installation before you proceed with the update.")
					commonlib.shutdown()
				
			except:
				err=traceback.format_exc()
				print_console(err)
				print_console("Unhandled exception occurred, this is a bug. For safety reasons, the update has been aborted")
				JOptionPane.showMessageDialog(None,"Unhandled exception occurred, this is a bug. For safety reasons, the update has been aborted")
				commonlib.shutdown()
			
	tar.close()
Esempio n. 44
0
    def continueAfterSavingOrDiscarding(self, prompt):
        if self.editor.modified:
            promptResult = JOptionPane.showConfirmDialog(self.parentWindow,
                prompt + '\n' + PROMPT_SAVE_OR_DISCARD,
                PROMPT_SAVE_CAPTION, JOptionPane.YES_NO_CANCEL_OPTION
            )

            if promptResult == JOptionPane.YES_OPTION:
                isSaved = self.saveAction()
                if isSaved:
                    # The file saved, keep going.
                    return True
                else:
                    # The file _isn't_ saved, bail out.
                    return False
            elif promptResult == JOptionPane.NO_OPTION:
                # The user elected not to save it, so keep going.
                return True
            else:
                # The user decided to cancel, bail out.
                return False
        else:
            return True
Esempio n. 45
0
def check_directory(path):

	if (os.path.lexists(path)):
		contents=os.listdir(path)
		
		if (contents.count("install-birch")==0):
			print_console("The selected directory "+path+" does NOT contain a BIRCH installation!")
			message="The selected path does NOT contain a BIRCH installation.\nPlease select the base directory of the installation that you wish to update,\nOr click \"no\" to cancel update."
			reload = JOptionPane.showConfirmDialog(None,message, "Input",JOptionPane.YES_NO_OPTION);
		
			if (reload==JOptionPane.NO_OPTION):
				print_console("User aborted install.")
				commonlib.shutdown()
			
			fc = JFileChooser();
			fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
			fc.showOpenDialog(None);
			path = fc.getSelectedFile().getPath();
			
			check_directory(path)
			
		else:
			ARGS.install_dir=path
			print_console("The selected directory "+path+" contains a BIRCH installation, it will be updated")
Esempio n. 46
0
    def doInBackground(self):
        #print "\n- Checking for the latest version..."
        try:
            url = URL(self.app.scriptVersionUrl)
            uc = url.openConnection()
            ins = uc.getInputStream()
            p = Properties()
            p.load(ins)
            latestScriptVersion = p.getProperty("script")
            self.app.latestToolsVersion = p.getProperty("tools")
        except (UnknownHostException, SocketException):
            print "I can't connect to:\n%s" % url
            ins.close()
            return

        if latestScriptVersion == self.app.SCRIPTVERSION:
            #using latest script
            print "  already using the latest script version:", self.app.SCRIPTVERSION
            if self.app.latestToolsVersion == self.app.TOOLSVERSION:
                #using latest tools
                print "  already using the latest tools version:", self.app.TOOLSVERSION
                if self.mode != "auto":
                    JOptionPane.showMessageDialog(self.app.preferencesFrame,
                                                  self.app.strings.getString("using_latest"))
                    return
            else:
                #not using latest tools
                print "  tools can be updated: %s -> %s" % (self.app.TOOLSVERSION,
                                                           self.app.latestToolsVersion)
                answer = JOptionPane.showConfirmDialog(Main.parent,
                    self.app.strings.getString("update_tools_question"),
                    self.app.strings.getString("updates_available"),
                    JOptionPane.YES_NO_OPTION)
                if answer == 0:
                    #Download the updated tools data
                    print "\n- Update tools data"
                    try:
                        self.app.toolsProgressDialog
                    except AttributeError:
                        from java.awt import Dialog
                        self.app.toolsProgressDialog = ToolsProgressDialog(Main.parent,
                                                           self.app.strings.getString("download_tools_updates"),
                                                           Dialog.ModalityType.APPLICATION_MODAL,
                                                           self.app)
                    self.app.toolsProgressDialog.show()
        else:
            #not using latest script
            print "a new script version is available:\n%s -> %s" % (self.app.SCRIPTVERSION,
                                                                    latestScriptVersion)
            messageArguments = array([self.app.SCRIPTVERSION, latestScriptVersion], String)
            formatter = MessageFormat("")
            formatter.applyPattern(self.app.strings.getString("updates_warning"))
            msg = formatter.format(messageArguments)
            options = [
                self.app.strings.getString("Do_not_check_for_updates"),
                self.app.strings.getString("Visit_Wiki"),
                self.app.strings.getString("cancel")]
            answer = JOptionPane.showOptionDialog(Main.parent,
                msg,
                self.app.strings.getString("updates_available"),
                JOptionPane.YES_NO_CANCEL_OPTION,
                JOptionPane.QUESTION_MESSAGE,
                None,
                options,
                options[1])
            if answer == 0:
                self.app.properties.setProperty("check_for_update", "off")
                self.app.save_config(self)
            elif answer == 1:
                OpenBrowser.displayUrl(self.app.SCRIPTWEBSITE)
Esempio n. 47
0
    def handle(self):

        self.debug("Jack Starting")

        if self.getJackStatus() != STOPPED:
            # maybe still running?
            b = JOptionPane.showConfirmDialog(None, "Jack might already be running, continue?",
                                              "JackStatus: " + str(self.getJackStatus()), JOptionPane.YES_NO_OPTION)
            if b == JOptionPane.NO_OPTION:
                self.debug("Quitting on user command")
                return False

        # set status memory variable
        self.setStatus()

        # rotate logs
        if os.path.exists(LOGFILE):
            if os.path.exists(LOGFILE + '.6'):
                os.remove(LOGFILE + '.6')
            for i in range(5,0,-1):
                fn = LOGFILE + '.' + str(i)
                if os.path.exists(fn):
                    os.rename(fn, LOGFILE + '.' + str(i+1))
            os.rename(LOGFILE, LOGFILE + '.1')

        # turn layout power on
        self.powerState = powermanager.getPower()
        if self.powerState != jmri.PowerManager.ON:
            poweredOn = True
            self.debug("turning power on")
            powermanager.setPower(jmri.PowerManager.ON)
        else:
            poweredOn = False
            self.debug("power is on")

        # clear locks
        for lock in ['North Link Lock', 'South Link Lock', 'IMLOCKNORTHSIDINGS', 'IMLOCKNORTHTRACKLINK', 'IMLOCKSOUTHSIDINGS', 'IMLOCKSOUTHTRACKLINK']:
            self.debug('unlocking ' + lock)
            mem = memories.getMemory(lock)
            if mem is not None:
                mem.setValue(None)

        # unselect all sidings
        loco.Loco.unselectSidings(NORTH_SIDINGS + SOUTH_SIDINGS)
        loco.Loco.unselectReverseLoops([NORTH_REVERSE_LOOP, SOUTH_REVERSE_LOOP])

        # clear display memories
        for i in range(1,7):
            m = memories.provideMemory("IMTRACK" + str(i) + "LOCO")
            m.setValue(None)
            m = memories.provideMemory("IMTRACK" + str(i) + "SPEED")
            m.setValue(None)

        # set sensors to inactive
        for s in ["Add Loco", "Stop", "Estop"]:
            sen = sensors.getSensor(s)
            sen.setKnownState(INACTIVE)

        # reset memories
        for m in ["IMNEWLOCO", "IMRETIRELOCO", "IMRETIREDLOCO"]:
            mem = memories.getMemory(m)
            if mem is not None:
                mem.setValue(None)

        # Initialise tracks
        self.initTracks()

        # check these sensors are not active, they control lock release
        for s in ["LS60", "LS64"]:
            sen = sensors.getSensor(s)
            if sen.knownState == ACTIVE:
                raise RuntimeError("sensor " + s + " is active")

        # Initialise locomotives and get their location.
        cont = self.initLocos()
        if cont is False:
            # User cancelled
            print "Jack exiting on user cancel"
            self.status = STOPPED
            self.setStatus()
            return False

        # give the sensors time to wake up if we just turned power on
        if poweredOn:
            time.sleep(5)

        # log sensor status
        for n in sensors.getSystemNameList():
            s = sensors.getSensor(n)
            self.log("sensor: " + str(s.getDisplayName()) + " state: " + str(s.state))

        # clear block values in unoccupied blocks
        for name in blocks.getSystemNameList():
            self.log("checking block " + name)
            b = blocks.getBlock(name)
            if b.getState() != OCCUPIED:
                self.log("setting value of block " + name + " to None")
                b.setValue(None)
                if b.getUserName() is not None:
                    m = memories.getMemory(b.getUserName())
                    if m is not None:
                        m.setValue(None)


        # final status check before we hit main loop
        if self.checkStatus() != NORMAL:
            self.status = STOPPED
            self.setStatus()
            self.debug("exiting on non-normal status")
            return False


        print "Jack entering main loop."

        # ------------- Main Loop -------------------
        maxloops = 10000
        loopcount = 0
        while True:
            loopcount += 1
            if loopcount % 100 == 0:
                self.debug("loop " + str(loopcount))
            self.checkStatus() # see if we should be stopping
            if self.status == ESTOP:
                # Stop everything immediately
                self.eStop() # stops all locos
                self.debug("Jack waiting to exit on eStop")
                # give other processes time to read the estop
                time.sleep(30)
                self.debug("Jack exits on ESTOP")
                self.status = STOPPED
                self.setStatus()
                return False
            # check for journeys that have completed
            self.checkJourneys()
            if self.status == STOPPING:
                if len(self.memories) == 0:
                    print "Jack: All done - exiting"
                    self.status = STOPPED
                    self.setStatus()
                    return False
                elif loopcount % 20 == 0:
                    self.debug("waiting for " + str(len(self.memories)) + " journeys to complete")
                    for m in self.memories:
                        self.debug('  ' + m)
            # kick off new journeys, if appropriate
            self.startNewJourneys()
            # check for new locos
            self.checkForNewLocos()
            # check for locos to retire
            self.checkForRetiringLocos()
            # check to see if track status has changed
            self.checkTrackStatus()
            # bow out if there's a limit
            if maxloops is not None and loopcount > maxloops:
                self.debug('exiting after ' + str(maxloops) + ' loops')
                self.status = STOPPED
                self.setStatus()
                return False # stop the loop for the moment

            time.sleep(1)
Esempio n. 48
0
print "\n---- Find Bundle References :: {}".format(bundleArg)
searchFiles(bundleArg, jmriPath, "References")
searchFiles(bundleArg, join(FileUtil.getProgramPath(), "jython"), "References")

print "Final notUsedList size = {}".format(len(notUsedList))
endTime = time()

print "\nTiming"
print ("  Phase 1: {}").format(midTime-startTime)
print ("  Phase 2: {}").format(endTime-midTime)
print ("    Total: {}").format(endTime-startTime)

##
# Provide the option to export the unused key list to an external file.
##
saveResp = JOptionPane.showConfirmDialog(None, "Do you want to save the unused key list?", dialogTitle, JOptionPane.YES_NO_OPTION)
if saveResp == 0:
    fo = JFileChooser(FileUtil.getUserFilesPath())
    fo.setDialogTitle(dialogTitle)
    ret = fo.showSaveDialog(None)
    if ret == JFileChooser.APPROVE_OPTION:
        keyFile = fo.getSelectedFile().toString()
        with io.open(keyFile, "w", encoding="utf-8") as outputFile:
            outputFile.write("\n".join(notUsedList))

##
# Provide the option to update the property files.
#   All of the files for the current bundle name will be updated.
#   A backup will be created for each file before it is updated.  4 copies of the backup will be retained.
#   The unused keys will be converted to comments with the NotUsed tag.
# Note:  If the Java tree is managed by Git, the backups will create new file entries.
Esempio n. 49
0
 def confirmSave(self, message):
     return JOptionPane.showConfirmDialog(
         self.parentWindow, message,
         "Confirm Save", JOptionPane.YES_NO_OPTION
     ) == JOptionPane.YES_OPTION
Esempio n. 50
0
 def popUpAreYouSure(self):
     dialogResult = JOptionPane.showConfirmDialog(None,"Are you sure?","Warning",JOptionPane.YES_NO_OPTION)
     if dialogResult == 0:
         return 0
     return 1
from javax.swing import JOptionPane
option = JOptionPane.showConfirmDialog(getMainFrame(), 'Auto import sample data?', 'Auto import', JOptionPane.YES_NO_OPTION)
if option == JOptionPane.YES_OPTION:
    addMovie('300');
    addMovie('Prometheus');
    addMovie('Alien');
    addMovie('Superman');
    addMovie('Spiderman');
    addMovie('Defiance');
    addMovie('Taken');
    addMovie('Chronicle');
    addMovie('Brave');
    addMovie('Hellboy');
Esempio n. 52
0
 def confirm(self, message):
     confirm = JOptionPane.showConfirmDialog(
         self.parentWindow, message, TITLE, JOptionPane.YES_NO_OPTION
     )
     return confirm == JOptionPane.YES_OPTION
 def confirmImport(self, event):
     result = JOptionPane.showConfirmDialog(None, "You are about to make requests to potentially sensitive resources.\nRemove any sensitive resources from your listing file.\nProceed to import to Burp Site Map?", "Careful!", JOptionPane.WARNING_MESSAGE)
     if result == 0:
         self.importList()
Esempio n. 54
0
import javax.swing.JOptionPane as JOptionPane
import javax.swing.JPasswordField as JPasswordField

# ask user input his vpn password
jPasswordField = JPasswordField()
switchApp("Sikuli IDE")
result = JOptionPane.showConfirmDialog(None, jPasswordField, "Please input vpn password", JOptionPane.OK_CANCEL_OPTION);

if result == 0:
    # open app
    vpnapp = App("NetExtender")
    vpnapp.open()
    wait("SONICWALL.png", 60)
    type("Password.png", jPasswordField.text)
    click("Connect.png")

    sparrowApp = App("Sparrow")
    sparrowApp.open()

    wait("swnotlcSonic.png", 90)
    doubleClick("swnotlcSonic.png")
    wait("Sonlcwall.png", 90)
    re = find("OneTimePassw.png").offset(Location(100, 0)).nearby(5)
    doubleClick(re)
    type("c", KeyModifier.CMD)

    vpnapp.focus()
      
   

    click("AEmpOfHlYPHS.png")
Esempio n. 55
0
        if len(keyRow) == 1:
            csvFile.write("")
            csvFile.write("")
            csvFile.write("")
            csvFile.write("")
            csvFile.write(keyRow[0])
        else:
            csvFile.write('{}'.format(keyRow[0]))
            csvFile.write(keyRow[1])
            csvFile.write(keyRow[2])
            csvFile.write(keyRow[3])
            csvFile.write(keyRow[4])
        csvFile.endRecord()

# Provide the option to export the full class key list to an external file.
saveResp = JOptionPane.showConfirmDialog(None, "Do you want to export the full class key list to a CSV file?", dialogTitle, JOptionPane.YES_NO_OPTION)
if saveResp == 0:
    fo = JFileChooser(FileUtil.getUserFilesPath())
    fo.setDialogTitle(dialogTitle)
    fo.setFileFilter(FileNameExtensionFilter("CSV", ["csv"]));
    ret = fo.showSaveDialog(None)
    if ret == JFileChooser.APPROVE_OPTION:
        keyFile = fo.getSelectedFile().toString()
        csvFile = com.csvreader.CsvWriter(java.io.BufferedOutputStream(java.io.FileOutputStream(keyFile)),',',java.nio.charset.Charset.defaultCharset())
        writeHeader(csvFile)
        writeDetails(csvFile)
        csvFile.flush()
        csvFile.close()
        JOptionPane.showMessageDialog(None,"Class keys export completed",dialogTitle,JOptionPane.INFORMATION_MESSAGE)

print '\n   {} Done'.format(dialogTitle)