Example usage for java.awt EventQueue invokeAndWait

List of usage examples for java.awt EventQueue invokeAndWait

Introduction

In this page you can find the example usage for java.awt EventQueue invokeAndWait.

Prototype

public static void invokeAndWait(Runnable runnable) throws InterruptedException, InvocationTargetException 

Source Link

Document

Causes runnable to have its run method called in the #isDispatchThread dispatch thread of Toolkit#getSystemEventQueue the system EventQueue .

Usage

From source file:org.parosproxy.paros.extension.scanner.ExtensionScanner.java

/**
 * This method initializes menuScanner   
 *    // w w  w  .jav a  2 s  .  c o  m
 * @return javax.swing.JMenu   
 */
//   private JMenu getMenuScanner() {
//      if (menuScanner == null) {
//         menuScanner = new JMenu();
//         menuScanner.setText("Scanner");
//         menuScanner.add(getMenuItemScanAll());
//         menuScanner.add(getMenuItemScan());
//         menuScanner.addSeparator();
//         menuScanner.add(getMenuItemPolicy());
//      }
//      return menuScanner;
//   }

public void scannerComplete() {
    try {
        Thread.sleep(1000);
    } catch (Exception e) {
    }

    final long scanTime = System.currentTimeMillis() - startTime;

    if (getView() != null) {
        getMenuItemScanAll().setEnabled(true);
        getMenuItemScan().setEnabled(true);
        getMenuItemPolicy().setEnabled(true);
        popupMenuScanHistory.setEnabled(true);

    }

    if (getView() != null && progressDialog != null) {
        if (EventQueue.isDispatchThread()) {
            progressDialog.dispose();
            progressDialog = null;
            getView().showMessageDialog("Scanning completed in " + scanTime / 1000
                    + "s.  The result can be obtained from Report>Last Scan Result.");
            return;
        }
        try {
            EventQueue.invokeAndWait(new Runnable() {
                public void run() {
                    progressDialog.dispose();
                    progressDialog = null;
                    getView().showMessageDialog("Scanning completed in " + scanTime / 1000
                            + "s.  The result can be obtained from Report>Last Scan Result.");
                }
            });
        } catch (Exception e) {
        }
    }

}

From source file:org.parosproxy.paros.extension.autoupdate.ExtensionAutoUpdate.java

public void download(final boolean silent) {

    if (newestVersionName == null) {
        return;//from   w  w  w  .  j a va  2  s .c o m
    }

    HttpMessage msg = new HttpMessage();
    try {
        msg.setRequestHeader(header);
        msg.setRequestBody(getBody(mirrorList[getRandom(mirrorList.length)], newestVersionName));

        getHttpSender().sendAndReceive(msg, true);

        if (msg.getResponseHeader().getStatusCode() != HttpStatusCode.OK) {
            throw new IOException();
        }

        if (silent && manualCheckStarted) {
            return;
        }

        File file = null;
        if (Constant.isWindows()) {
            file = new File("parosnew.exe");
        } else if (Constant.isLinux()) {
            file = new File("parosnew.zip");
        }

        FileOutputStream os = new FileOutputStream(file);
        os.write(msg.getResponseBody().getBytes());
        os.close();

        try {
            final File updateFile = file;
            EventQueue.invokeAndWait(new Runnable() {
                public void run() {

                    if (waitDialog != null) {
                        waitDialog.hide();
                    }

                    if (!silent) {
                        String s = "A newer verison has been downloaded.  It will be installed the \nnext time Paros is started.";
                        if (Constant.isLinux()) {
                            s = s + "  Note: Use startserver.sh to run Paros.";
                        }
                        getView().showMessageDialog(s);
                    } else {
                        String s = "A newer version is available.  Install the new version \nnext time Paros is started?";
                        if (Constant.isLinux()) {
                            s = s + "  Note: Use startserver.sh to run Paros.";
                        }
                        int result = getView().showConfirmDialog(s);
                        if (result != JOptionPane.OK_OPTION) {
                            updateFile.delete();
                        }
                    }
                }
            });
        } catch (Exception e) {
        }
    } catch (IOException e) {

        try {
            EventQueue.invokeAndWait(new Runnable() {
                public void run() {
                    if (waitDialog != null) {
                        waitDialog.hide();
                    }

                    if (!silent) {

                        getView().showWarningDialog("Error encountered.  Please download new updates manually");
                    }
                }
            });
        } catch (Exception e1) {
        }

        if (waitDialog != null) {
            waitDialog.hide();
        }
    } finally {
        httpSender.shutdown();
        httpSender = null;
    }
}

From source file:org.parosproxy.paros.extension.history.ManualRequestEditorDialog.java

private void send(final HttpMessage msg) {
    Thread t = new Thread(new Runnable() {
        public void run() {
            try {
                getHttpSender().sendAndReceive(msg, getChkFollowRedirect().isSelected());

                EventQueue.invokeAndWait(new Runnable() {
                    public void run() {
                        if (!msg.getResponseHeader().isEmpty()) {
                            getResponsePanel().setMessage(msg, false);

                            final int finalType = HistoryReference.TYPE_MANUAL;
                            Thread t = new Thread(new Runnable() {
                                public void run() {
                                    addHistory(msg, finalType);
                                }//from  www . j av  a 2s  .  com
                            });
                            t.start();

                        }
                        getPanelTab().setSelectedIndex(1);
                    }
                });

            } catch (NullPointerException npe) {
                getExtention().getView().showWarningDialog("Malformed header error.");
            } catch (HttpMalformedHeaderException mhe) {
                getExtention().getView().showWarningDialog("Malformed header error.");
            } catch (IOException ioe) {
                getExtention().getView().showWarningDialog("IO error in sending request.");
            } catch (Exception e) {
                // ZAP: Log exceptions
                log.warn(e.getMessage(), e);
            } finally {
                btnSend.setEnabled(true);
            }
        }
    });

    t.setPriority(Thread.NORM_PRIORITY);
    t.start();
}

From source file:org.zaproxy.zap.extension.customFire.ExtensionCustomFire.java

@Override
public void sessionChanged(final Session session) {
    if (EventQueue.isDispatchThread()) {
        sessionChangedEventHandler(session);

    } else {//w w w. j  a va  2  s  .  com
        try {
            EventQueue.invokeAndWait(new Runnable() {
                @Override
                public void run() {
                    sessionChangedEventHandler(session);
                }
            });

        } catch (InterruptedException | InvocationTargetException e) {
            //logger.error(e.getMessage(), e);
            e.printStackTrace();
        }
    }
}

From source file:org.parosproxy.paros.extension.spider.ExtensionSpider.java

public void spiderProgress(final URI uri, final int percentageComplete, final int numberCrawled,
        final int numberToCrawl) {
    String uriString = "";

    if (dialog != null) {
        if (EventQueue.isDispatchThread()) {
            dialog.getTxtNumCrawled().setText(Integer.toString(numberCrawled));
            dialog.getTxtOutstandingCrawl().setText(Integer.toString(numberToCrawl));

            dialog.getProgressBar().setValue(percentageComplete);
            uriString = "";
            if (uri != null) {
                uriString = uri.toString();
            }//from   w  ww  .  j a v  a2s  . c o  m
            dialog.getTxtDisplay().setText(uriString);
            //dialog.getTxtDisplay().setCaretPosition(0);

            return;
        }
        try {
            EventQueue.invokeAndWait(new Runnable() {
                public void run() {
                    String uriString = "";
                    dialog.getTxtNumCrawled().setText(Integer.toString(numberCrawled));
                    dialog.getTxtOutstandingCrawl().setText(Integer.toString(numberToCrawl));

                    dialog.getProgressBar().setValue(percentageComplete);
                    if (uri != null) {
                        uriString = uri.toString();
                    }
                    dialog.getTxtDisplay().setText(uriString);
                    //dialog.getTxtDisplay().setCaretPosition(0);

                }
            });
        } catch (Exception e) {
        }

    }

}

From source file:org.zaproxy.zap.extension.fuzz.httpfuzzer.ui.HttpFuzzResultsContentPanel.java

@Override
public void clear() {
    if (!EventQueue.isDispatchThread()) {
        try {//  w  ww .  j  a va2 s  .  c om
            EventQueue.invokeAndWait(new Runnable() {

                @Override
                public void run() {
                    clear();
                }
            });
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return;
    }

    currentFuzzer = null;
    fuzzResultTable.setModel(EMPTY_RESULTS_MODEL);
    errorsTable.setModel(EMPTY_ERRORS_MODEL);
}

From source file:org.parosproxy.paros.extension.history.ManualRequestEditorDialog.java

private void addHistoryInEventQueue(final HistoryReference ref) {
    if (EventQueue.isDispatchThread()) {
        historyList.addElement(ref);//from w w w .ja  v  a 2  s .  c o  m
    } else {
        try {
            EventQueue.invokeAndWait(new Runnable() {
                public void run() {
                    historyList.addElement(ref);
                }
            });
        } catch (Exception e) {
        }
    }
}

From source file:fur.shadowdrake.minecraft.InstallPanel.java

@Deprecated
private boolean registerRhaokarLightPack(File path) throws NetworkException {
    FileOutputStream fos;/*from  ww w.  j  a  v a  2  s.c o m*/

    try {
        fos = new FileOutputStream(new File(path, "modpack"));
        fos.write("rhaokar_light".getBytes());
        fos.close();
    } catch (FileNotFoundException ex) {
        return false;
    } catch (IOException ex) {
        return false;
    }
    if (new File(path, "resourcepacks/01.zip").isFile()) {
        downloadFile("manifest.json");
    } else if (new File(path, "resourcepacks/Soatex_Custom.zip").isFile()) {
        try {
            EventQueue.invokeAndWait(() -> {
                result = JOptionPane.showConfirmDialog(InstallPanel.this,
                        "An old version of the graphics pack was detected. Do you want to keep it?\nIf you choose no, your selection in addons will be downloaded.",
                        "Addons", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
            });
        } catch (InterruptedException | InvocationTargetException ex) {
            Logger.getLogger(InstallPanel.class.getName()).log(Level.SEVERE, null, ex);
        }
        switch (result) {
        case JOptionPane.YES_OPTION:
            downloadFile("manifest_old.json", "manifest.json");
            break;
        default:
            new File(path, "mods/ShadersModCore-v2.3.31-mc1.7.10-f.jar").delete();
            try {
                cleanDirectory(new File(path, "resourcepacks"));
            } catch (IOException ex) {
            }
            try {
                deleteDirectory(new File(path, "shaderpacks"));
            } catch (IOException ex) {
            }
            downloadAddons();
        }
    }
    return true;
}

From source file:org.parosproxy.paros.model.Session.java

protected void open(String fileName) throws DatabaseException, IOException, Exception {

    // TODO extract into db specific classes??
    if (Database.DB_TYPE_HSQLDB.equals(model.getDb().getType())) {
        configuration = new ZapXmlConfiguration(new File(fileName));
        sessionId = configuration.getLong(SESSION_ID);
        sessionName = configuration.getString(SESSION_NAME, "");
        sessionDesc = configuration.getString(SESSION_DESC, "");
    } else {/*from w w  w .  j a  va 2 s.co  m*/
        this.setSessionId(Long.parseLong(fileName));
    }
    model.getDb().close(false);
    model.getDb().open(fileName);
    this.fileName = fileName;

    //historyList.removeAllElements();

    if (!Constant.isLowMemoryOptionSet()) {
        SiteNode newRoot = new SiteNode(siteTree, -1, Constant.messages.getString("tab.sites"));
        siteTree.setRoot(newRoot);
    }

    // update history reference
    List<Integer> list = model.getDb().getTableHistory().getHistoryIdsOfHistType(getSessionId(),
            HistoryReference.TYPE_PROXIED, HistoryReference.TYPE_ZAP_USER);

    HistoryReference historyRef = null;

    discardContexts();

    // Load the session urls
    this.setExcludeFromProxyRegexs(sessionUrlListToStingList(
            model.getDb().getTableSessionUrl().getUrlsForType(RecordSessionUrl.TYPE_EXCLUDE_FROM_PROXY)));

    this.setExcludeFromScanRegexs(sessionUrlListToStingList(
            model.getDb().getTableSessionUrl().getUrlsForType(RecordSessionUrl.TYPE_EXCLUDE_FROM_SCAN)));

    this.setExcludeFromSpiderRegexs(sessionUrlListToStingList(
            model.getDb().getTableSessionUrl().getUrlsForType(RecordSessionUrl.TYPE_EXCLUDE_FROM_SPIDER)));

    for (int i = 0; i < list.size(); i++) {
        // ZAP: Removed unnecessary cast.
        int historyId = list.get(i).intValue();

        try {
            historyRef = new HistoryReference(historyId);

            if (View.isInitialised()) {
                final HistoryReference hRef = historyRef;
                final HttpMessage msg = historyRef.getHttpMessage();
                EventQueue.invokeAndWait(new Runnable() {

                    @Override
                    public void run() {
                        SiteNode sn = getSiteTree().addPath(hRef, msg);
                        if (sn != null) {
                            sn.setIncludedInScope(isIncludedInScope(sn), false);
                            sn.setExcludedFromScope(isExcludedFromScope(sn), false);
                        }
                    }
                });
            } else {
                SiteNode sn = getSiteTree().addPath(historyRef);
                if (sn != null) {
                    sn.setIncludedInScope(this.isIncludedInScope(sn), false);
                    sn.setExcludedFromScope(this.isExcludedFromScope(sn), false);
                }
            }
            // ZAP: Load alerts from db
            historyRef.loadAlerts();

            if (i % 100 == 99)
                Thread.yield();
        } catch (Exception e) {
            // ZAP: Log exceptions
            log.warn(e.getMessage(), e);
        }

    }

    // update siteTree reference
    list = model.getDb().getTableHistory().getHistoryIdsOfHistType(getSessionId(), HistoryReference.TYPE_SPIDER,
            HistoryReference.TYPE_BRUTE_FORCE, HistoryReference.TYPE_SPIDER_AJAX);

    for (int i = 0; i < list.size(); i++) {
        // ZAP: Removed unnecessary cast.
        int historyId = list.get(i).intValue();

        try {
            historyRef = new HistoryReference(historyId);

            if (View.isInitialised()) {
                final HistoryReference hRef = historyRef;
                final HttpMessage msg = historyRef.getHttpMessage();
                EventQueue.invokeAndWait(new Runnable() {

                    @Override
                    public void run() {
                        getSiteTree().addPath(hRef, msg);
                    }
                });
            } else {
                getSiteTree().addPath(historyRef);
            }

            if (i % 100 == 99)
                Thread.yield();

        } catch (Exception e) {
            // ZAP: Log exceptions
            log.warn(e.getMessage(), e);
        }

    }
    List<RecordContext> contextData = model.getDb().getTableContext().getAllData();
    for (RecordContext data : contextData) {
        Context ctx = this.getContext(data.getContextId());
        if (ctx == null) {
            ctx = new Context(this, data.getContextId());
            this.addContext(ctx);
            if (nextContextIndex <= data.getContextId()) {
                nextContextIndex = data.getContextId() + 1;
            }
        }
        switch (data.getType()) {
        case RecordContext.TYPE_NAME:
            ctx.setName(data.getData());
            if (View.isInitialised() && !ctx.getName().equals(String.valueOf(ctx.getIndex()))) {
                View.getSingleton().renameContext(ctx);
            }
            break;
        case RecordContext.TYPE_DESCRIPTION:
            ctx.setDescription(data.getData());
            break;
        case RecordContext.TYPE_INCLUDE:
            ctx.addIncludeInContextRegex(data.getData());
            break;
        case RecordContext.TYPE_EXCLUDE:
            ctx.addExcludeFromContextRegex(data.getData());
            break;
        case RecordContext.TYPE_IN_SCOPE:
            ctx.setInScope(Boolean.parseBoolean(data.getData()));
            break;
        case RecordContext.TYPE_INCLUDE_TECH:
            ctx.getTechSet().include(new Tech(data.getData()));
            break;
        case RecordContext.TYPE_EXCLUDE_TECH:
            ctx.getTechSet().exclude(new Tech(data.getData()));
            break;
        }
    }
    for (Context ctx : contexts) {
        try {
            // Set up the URL parameter parser
            List<String> strs = this.getContextDataStrings(ctx.getIndex(),
                    RecordContext.TYPE_URL_PARSER_CLASSNAME);
            if (strs.size() == 1) {
                Class<?> c = ExtensionFactory.getAddOnLoader().loadClass(strs.get(0));
                if (c == null) {
                    log.error("Failed to load URL parser for context " + ctx.getIndex() + " : " + strs.get(0));
                } else {
                    ParameterParser parser = (ParameterParser) c.getConstructor().newInstance();
                    strs = this.getContextDataStrings(ctx.getIndex(), RecordContext.TYPE_URL_PARSER_CONFIG);
                    if (strs.size() == 1) {
                        parser.init(strs.get(0));
                    }
                    parser.setContext(ctx);
                    ctx.setUrlParamParser(parser);
                }
            }
        } catch (Exception e) {
            log.error("Failed to load URL parser for context " + ctx.getIndex(), e);
        }
        try {
            // Set up the URL parameter parser
            List<String> strs = this.getContextDataStrings(ctx.getIndex(),
                    RecordContext.TYPE_POST_PARSER_CLASSNAME);
            if (strs.size() == 1) {
                Class<?> c = ExtensionFactory.getAddOnLoader().loadClass(strs.get(0));
                if (c == null) {
                    log.error("Failed to load POST parser for context " + ctx.getIndex() + " : " + strs.get(0));
                } else {
                    ParameterParser parser = (ParameterParser) c.getConstructor().newInstance();
                    strs = this.getContextDataStrings(ctx.getIndex(), RecordContext.TYPE_POST_PARSER_CONFIG);
                    if (strs.size() == 1) {
                        parser.init(strs.get(0));
                    }
                    parser.setContext(ctx);
                    ctx.setPostParamParser(parser);
                }
            }
        } catch (Exception e) {
            log.error("Failed to load POST parser for context " + ctx.getIndex(), e);
        }

        try {
            // Set up the Data Driven Nodes
            List<String> strs = this.getContextDataStrings(ctx.getIndex(),
                    RecordContext.TYPE_DATA_DRIVEN_NODES);
            for (String str : strs) {
                ctx.addDataDrivenNodes(new StructuralNodeModifier(str));
            }
        } catch (Exception e) {
            log.error("Failed to load data driven nodes for context " + ctx.getIndex(), e);
        }

        ctx.restructureSiteTree();
    }

    if (View.isInitialised()) {
        // ZAP: expand root
        View.getSingleton().getSiteTreePanel().expandRoot();
    }
    this.refreshScope();

    System.gc();
}

From source file:org.parosproxy.paros.extension.history.ExtensionHistory.java

private void addHistoryInEventQueue(final HistoryReference ref) {
    if (!View.isInitialised() || EventQueue.isDispatchThread()) {
        historyTableModel.addHistoryReference(ref);
    } else {//ww  w  .  j  ava2 s . co  m
        try {
            EventQueue.invokeAndWait(new Runnable() {
                @Override
                public void run() {
                    addHistoryInEventQueue(ref);
                }
            });
        } catch (final Exception e) {
            logger.error(e.getMessage(), e);
        }
    }
}