@NbBundle.Messages({"GitHubIssueController.delete.comment.fail=Can't delete this issue."}) private void deleteComment() { final Comment deletedComment = getPanel().getDeletedComment(); if (deletedComment == null) { return; } RequestProcessor rp = GitHubIssues.getInstance().getRequestProcessor(); rp.post( new Runnable() { @Override public void run() { GitHubRepository repository = getPanel().getIssue().getRepository(); final boolean success = GitHubIssueSupport.deleteComment(repository, deletedComment); SwingUtilities.invokeLater( new Runnable() { @Override public void run() { if (success) { // remove comment panel getPanel().removeDeletedComment(); } else { // show error message UiUtils.showErrorDialog(Bundle.GitHubIssueController_delete_comment_fail()); } } }); } }); }
@Override public void actionPerformed(ActionEvent e) { final GitHubIssuePanel p = getPanel(); p.setNewCommentEnabled(false); GitHubIssues gitHubIssues = GitHubIssues.getInstance(); RequestProcessor rp = gitHubIssues.getRequestProcessor(); rp.post( new Runnable() { @Override public void run() { try { String comment = p.getNewComment(); if (StringUtils.isEmpty(comment)) { closeReopen(); } else { Comment newComment = comment(comment); if (newComment != null) { closeReopen(); } } SwingUtilities.invokeLater( new Runnable() { @Override public void run() { p.update(); } }); } finally { p.setNewCommentEnabled(true); } } }); }
@RandomlyFails // NB-Core-Build #8241 public void testTheStarvation37045() throws Exception { org.openide.util.Task task; synchronized (this) { org.openide.util.RequestProcessor.getDefault().post(support); // wait for the support (another thread) to try to open and block wait(); // now post there another task task = org.openide.util.RequestProcessor.getDefault().post(support); // wait for it to block, any amount of time is likely to do it Thread.sleep(500); // notify the first edit(), to continue (and throw exception) notify(); } // check for deadlock for (int i = 0; i < 5; i++) { if (task.isFinished()) break; Thread.sleep(500); } // uncomment the next line if you want to see real starvation threaddump // task.waitFinished (); assertTrue("Should be finished, but there is a starvation", task.isFinished()); }
public WSWebExtToolBarMVElement(WSWebExtDataObject dObj) { super(dObj); this.dObj = dObj; comp = new ToolBarDesignEditor(); factory = new PanelFactory(comp, dObj); addServletAction = new AddServletAction( NbBundle.getMessage(WSWebExtToolBarMVElement.class, "LBL_AddExtendedServlet")); removeServletAction = new RemoveServletAction( NbBundle.getMessage(WSWebExtToolBarMVElement.class, "LBL_RemoveExtendedServlet")); setVisualEditor(comp); repaintingTask = RequestProcessor.getDefault() .create( new Runnable() { public void run() { javax.swing.SwingUtilities.invokeLater( new Runnable() { public void run() { repaintView(); } }); } }); }
public void setupAutoRefresh() { if (refreshTask == null) { refreshTask = rp.create( new Runnable() { @Override public void run() { String selection = comp.getSelectedText(); if (selection != null && !isKeyword(selection)) { Pattern p = Pattern.compile(selection); Matcher m = p.matcher(comp.getText()); // for some reason the matcher skips the \n chars // so i am finding them all and subtracting them // from the resulting start and end offset. while (m.find() == true) { int startOffset = m.start(); int numberOfLineFeed = comp.getText().substring(0, startOffset).split("\n").length - 1; startOffset = startOffset - numberOfLineFeed; int endOffset = m.end() - numberOfLineFeed; bag.addHighlight(startOffset, endOffset, defaultColors); } } } }); refreshTask.setPriority(Thread.MIN_PRIORITY); } refreshTask.schedule(DELAY); }
public void displayError( final String errorText, final Throwable exception, final boolean setFocus) { if (errorText == null) throw new NullPointerException("errorText"); PROJECT_PROCESSOR.execute( new Runnable() { @Override public void run() { InputOutput io = IOProvider.getDefault().getIO(outputCaption, false); if (setFocus) { io.select(); } OutputWriter err = io.getErr(); outputLock.lock(); try { err.println(); err.println(errorText); if (exception != null) { exception.printStackTrace(err); } } finally { outputLock.unlock(); err.close(); } } }); }
public String getShortDescription() { // [TODO] hack for org.netbeans.modules.debugger.jpda.actions.MethodChooser that disables // tooltips if ("true" .equals( System.getProperty("org.netbeans.modules.debugger.jpda.doNotShowTooltips"))) { // NOI18N return null; } DebuggerEngine currentEngine = DebuggerManager.getDebuggerManager().getCurrentEngine(); if (currentEngine == null) return null; JPDADebugger d = currentEngine.lookupFirst(null, JPDADebugger.class); if (d == null) return null; Part lp = (Part) getAttachedAnnotatable(); if (lp == null) return null; Line line = lp.getLine(); DataObject dob = DataEditorSupport.findDataObject(line); if (dob == null) return null; EditorCookie ec = dob.getCookie(EditorCookie.class); if (ec == null) return null; // Only for editable dataobjects this.lp = lp; this.ec = ec; RequestProcessor.getDefault().post(this); return null; }
public void startModelValidating() { if (!isModelValid() && !validationStarted) { validationStarted = true; EventQueue.invokeLater( () -> { Scripts.LocalContext context = Scripts.getContext(); RP.execute( () -> { Scripts.setContext(context); try { validateModel(); } catch (Exception ex) { Logger.getLogger(PlatypusDataObject.class.getName()) .log(Level.WARNING, ex.getMessage(), ex); } finally { Scripts.setContext(null); EventQueue.invokeLater( () -> { validationStarted = false; setModelValid(true); }); } }); }); } }
/** * Restart the timer which starts the parser after the specified delay. * * @param onlyIfRunning Restarts the timer only if it is already running */ public void restartTimer() { if (parsingDocumentTask == null || parsingDocumentTask.isFinished() || parsingDocumentTask.cancel()) { dataObject.setDocumentDirty(true); Runnable r = new Runnable() { public void run() { dataObject.parsingDocument(); } }; if (parsingDocumentTask != null) parsingDocumentTask = RequestProcessor.getDefault().post(r, AUTO_PARSING_DELAY); else parsingDocumentTask = RequestProcessor.getDefault().post(r, 100); } }
public static ClassLoader getReferenceClassLoader() { if (referenceClassLoader != null) { return referenceClassLoader; } REFERENCE_RP .post( new Runnable() { @Override public void run() { if (referenceClassLoader != null) { return; } try { referenceLibrary = copyCompleteJarToTempDir(); referenceClassLoader = new URLClassLoader( new URL[] {Utilities.toURI(referenceLibrary).toURL()}, ClassLoader.getSystemClassLoader()); } catch (IOException ex) { Exceptions.printStackTrace(ex); } } }) .waitFinished(); return referenceClassLoader; }
static void save(final FileObject fo, final String content) { if (fo == null) throw new NullPointerException(); if (content == null) throw new NullPointerException(); requestProcessor.post( new Runnable() { public void run() { try { FileLock lock = fo.lock(); try { OutputStream os = fo.getOutputStream(lock); Writer writer = new OutputStreamWriter(os, "UTF-8"); // NOI18N try { writer.write(content); } finally { writer.close(); } } finally { lock.releaseLock(); } } catch (IOException ex) { ErrorManager.getDefault().notify(ex); } } }); }
public void propertyChange(PropertyChangeEvent evt) { String propertyName = evt.getPropertyName(); if (propertyName == null) return; if ((!JPDABreakpoint.PROP_ENABLED.equals(propertyName)) && (!JPDABreakpoint.PROP_VALIDITY.equals(propertyName)) && (!LineBreakpoint.PROP_CONDITION.equals(propertyName)) && (!LineBreakpoint.PROP_URL.equals(propertyName)) && (!LineBreakpoint.PROP_LINE_NUMBER.equals(propertyName)) // && // (!FieldBreakpoint.PROP_CLASS_NAME.equals( propertyName )) && // (!FieldBreakpoint.PROP_FIELD_NAME.equals( propertyName )) && // (!MethodBreakpoint.PROP_CLASS_FILTERS.equals( propertyName )) && // (!MethodBreakpoint.PROP_CLASS_EXCLUSION_FILTERS.equals( propertyName )) && // (!MethodBreakpoint.PROP_METHOD_NAME.equals( propertyName )) && // (!MethodBreakpoint.PROP_METHOD_SIGNATURE.equals( propertyName ) ) return; // JPDABreakpoint b = (JPDABreakpoint) evt.getSource(); VisageLineBreakpoint b = (VisageLineBreakpoint) evt.getSource(); DebuggerManager manager = DebuggerManager.getDebuggerManager(); Breakpoint[] bkpts = manager.getBreakpoints(); boolean found = false; for (int x = 0; x < bkpts.length; x++) { if (b == bkpts[x]) { found = true; break; } } if (!found) { // breakpoint has been removed return; } rp.post(new AnnotationRefresh(b, true, true)); }
@Override public void actionPerformed(ActionEvent ev) { // Start JSLintRunnable if (processor == null) { processor = new RequestProcessor("JSLintErrorCheck", 1, true); } processor.post(new JSLintRunnable(context, "-e")); }
public @Override void actionPerformed(ActionEvent e) { RP.post( new Runnable() { @Override public void run() { DDHelper.addJsfListener(serverProject, webProject); } }); } // class
public void dataRemoved(Application application) { RequestProcessor.getDefault() .post( new Runnable() { public void run() { client.markAsDead(); removedListener = null; } }); }
public void breakpointAdded(Breakpoint breakpoint) { if (isAnnotatable(breakpoint)) { VisageLineBreakpoint b = (VisageLineBreakpoint) breakpoint; // JPDABreakpoint b = (JPDABreakpoint) breakpoint; b.addPropertyChangeListener(this); RequestProcessor.getDefault().post(new AnnotationRefresh(b, false, true)); // if( b instanceof LineBreakpoint ) { VisageLineBreakpoint lb = (VisageLineBreakpoint) breakpoint; LineTranslations.getTranslations().registerForLineUpdates(lb); // } } }
/** * Creates a task that will execute the given command. * * @param cmd command to schedule * @param globalOptions options to use when running the command * @param mgr listener for command events * @return RequestProcessor.Task a task ready to execute the command * @throws IllegalCommandException if the command is not valid, e.g. it contains files that cannot * be processed by a single command (they do not have a common filesystem root OR their CVS * Roots differ) */ public RequestProcessor.Task createTask( Command cmd, GlobalOptions globalOptions, final ExecutorSupport mgr) throws IllegalCommandException { File[] files = getCommandFiles(cmd); if ((cmd instanceof CheckoutCommand) == false && !(cmd instanceof RlogCommand)) { // XXX ensureValidCommand(files); } if (globalOptions.getCVSRoot() == null) { globalOptions = (GlobalOptions) globalOptions.clone(); globalOptions.setCVSRoot(cvsRoot); } Client client = createClient(); if ((cmd instanceof RlogCommand)) { // XXX } else if ((cmd instanceof CheckoutCommand)) { // XXX BasicCommand bc = (BasicCommand) cmd; if (bc.getFiles() != null) { String path = bc.getFiles()[0].getAbsolutePath(); client.setLocalPath(path); } else { // #67315: use some default working dir client.setLocalPath(System.getProperty("user.dir")); // NOI18N } } else if (cmd instanceof ImportCommand) { client.setLocalPath(((ImportCommand) cmd).getImportDirectory()); } else { setLocalDirectory(client, files); } client.getEventManager().addCVSListener(mgr); final CommandRunnable cr = new CommandRunnable(client, globalOptions, cmd, mgr); mgr.commandEnqueued(cr); RequestProcessor.Task task = requestProcessor.create(cr); task.addTaskListener( new TaskListener() { public void taskFinished(Task task) { try { // There are times when 'commandTerminated()' is not the last method called, therefore // I introduced // this event that really marks the very end of a command (thread end) mgr.commandTerminated(new TerminationEvent(new Result(cr))); } catch (Throwable e) { ErrorManager.getDefault().notify(ErrorManager.WARNING, e); } finally { flushLog(); } } }); return task; }
/** * Construct diff component showing just one file. It hides All, Local, Remote toggles and file * chooser combo. */ public MultiDiffPanel(File file, String rev1, String rev2) { context = null; contextName = file.getName(); initComponents(); setupComponents(); fileTable.getComponent().setVisible(false); commitButton.setVisible(false); // mimics refreshSetups() setups = new Setup[] {new Setup(file, rev1, rev2)}; setDiffIndex(0, 0); dpt = new DiffPrepareTask(setups); prepareTask = RequestProcessor.getDefault().post(dpt); }
@NbBundle.Messages({ "GitHubIssueController.edit.comment.title=Edit Comment", "GitHubIssueController.edit.comment.fail=Can't edit this comment." }) private void editComment() { final Comment comment = getPanel().getEditedComment(); final String editedBody = CommentTabbedPanel.showDialog( Bundle.GitHubIssueController_edit_comment_title(), comment.getBody()); if (editedBody != null) { final GitHubIssue issue = getPanel().getIssue(); if (issue != null) { RequestProcessor rp = GitHubIssues.getInstance().getRequestProcessor(); rp.post( new Runnable() { @Override public void run() { Comment editedComment = issue.editComment(comment, editedBody); if (editedComment == null) { UiUtils.showErrorDialog(Bundle.GitHubIssueController_edit_comment_fail()); return; } SwingUtilities.invokeLater( new Runnable() { @Override public void run() { getPanel().loadComments(); } }); } }); } } }
@Override public void run() { if (!SwingUtilities.isEventDispatchThread()) { EventQueue.invokeLater(this); return; } currentToken = new Object(); TopComponent.Registry registry = TopComponent.getRegistry(); final TopComponent activeTc = registry.getActivated(); final Set<TopComponent> opened = new HashSet<>(registry.getOpened()); final LayoutScene existingLayers = currentLayers; final boolean isMaximized = isLayersMaximized(); final Object token = currentToken; RP.post( () -> { findNewLayers(existingLayers, activeTc, opened, isMaximized, token); }); }
@Override public void addNotify() { setKeys(new TaskResource[] {LOADINFG}); RequestProcessor.getDefault() .post( new Runnable() { public void run() { EventQueue.invokeLater( new Runnable() { public void run() { setKeys(resourceSet.getResources()); } }); } }); }
private void initListening(final int level) { CollabManager man = CollabManager.getDefault(); if (man == null) { // manager not yet registered. This is a transient condition during // module enablement because of manager registration mechanism. // Retry 5s later assert level < 10; RequestProcessor.getDefault() .post( new Runnable() { public void run() { initListening(level + 1); } }, level * 5000); } else { man.addPropertyChangeListener(helper); attachListeners(); updateStatus(); } }
public void setupAutoRefresh() { if (lastRefreshTask == null) { lastRefreshTask = rp.create( new Runnable() { @Override public void run() { String selection = comp.getSelectedText(); if (selection != null) { Pattern p = Pattern.compile(selection); Matcher m = p.matcher(comp.getText()); while (m.find() == true) { int startOffset = m.start(); int endOffset = m.end(); bag.addHighlight(startOffset, endOffset, defaultColors); } } } }); } lastRefreshTask.schedule(REFRESH_DELAY); }
@Override public void actionPerformed(ActionEvent ev) { Runnable runnable = new Runnable() { @Override public void run() { cssMinify(); } }; final RequestProcessor.Task theTask = RP.create(runnable); final ProgressHandle ph = ProgressHandleFactory.createHandle( "Minifying CSS " + context.getPrimaryFile().getName(), theTask); theTask.addTaskListener( new TaskListener() { @Override public void taskFinished(org.openide.util.Task task) { // JOptionPane.showMessageDialog(null, "Image Compressed Successfully"); ph.finish(); } }); ph.start(); theTask.schedule(0); }
/** @author suchys */ public class DocumentPreprocessor implements PropertyChangeListener { public static final String PREPROCESSOR_LINE_LIST = "preprocessor.line.list"; // NOI18N public static final String PREPROCESSOR_BLOCK_LIST = "preprocessor.block.list"; // NOI18N static final long serialVersionUID = 4863325941230276217L; static final Pattern BLOCK_HEADER_PATTERN = Pattern.compile("^\\s*/((/#)|(\\*[\\$#]))\\S"); // NOI18N /** preprocessor tag error annotations */ // protected ArrayList<PPLine> lineList = new ArrayList<PPLine>(); /** listens for document changes and updates blocks appropriately */ DocumentListener dl; /** Timer which countdowns the auto-reparsing of configuration blocks. */ final RequestProcessor.Task timerTask = RequestProcessor.getDefault() .create( new Runnable() { @Override public void run() { JTextComponent component = EditorRegistry.focusedComponent(); if (component != null) { DocumentPreprocessor.updateBlockChain( (NbEditorDocument) component.getDocument()); } } }); public DocumentPreprocessor() { dl = new DL(); JTextComponent component = EditorRegistry.focusedComponent(); if (component != null) { updateBlockChain((NbEditorDocument) component.getDocument()); final NbEditorDocument doc = (NbEditorDocument) component.getDocument(); doc.addDocumentListener(dl); doc.getDocumentProperties() .put( TextSwitcher.TEXT_SWITCH_SUPPORT, new ChangeListener() { public void stateChanged(@SuppressWarnings("unused") final ChangeEvent e) { updateBlockChain(doc); } }); } } public void propertyChange(PropertyChangeEvent evt) { JTextComponent last = EditorRegistry.lastFocusedComponent(); if (last != null) { final NbEditorDocument doc = (NbEditorDocument) last.getDocument(); doc.getDocumentProperties().remove(TextSwitcher.TEXT_SWITCH_SUPPORT); doc.removeDocumentListener(dl); } JTextComponent current = EditorRegistry.focusedComponent(); if (current != null) { final NbEditorDocument doc = (NbEditorDocument) current.getDocument(); doc.addDocumentListener(dl); doc.getDocumentProperties() .put( TextSwitcher.TEXT_SWITCH_SUPPORT, new ChangeListener() { public void stateChanged( @SuppressWarnings("unused") // NOI18N final ChangeEvent e) { restartTimer(); } }); restartTimer(); } } static final void setLineInfo( NbEditorDocument doc, List<PPLine> lineList, List<PPBlockInfo> blockList) { doc.putProperty(PREPROCESSOR_LINE_LIST, lineList); doc.putProperty(PREPROCESSOR_BLOCK_LIST, blockList); Highlighting headerLayer = (Highlighting) doc.getProperty(ConfigurationHighlightsLayerFactory.PROP_HIGLIGHT_HEADER_LAYER); if (headerLayer != null) { headerLayer.updateBags(); } Highlighting blockLayer = (Highlighting) doc.getProperty(ConfigurationHighlightsLayerFactory.PROP_HIGLIGHT_BLOCKS_LAYER); if (blockLayer != null) { blockLayer.updateBags(); } processAnnotations(doc, lineList); } /** Restart the timer which starts the parser after the specified delay. */ void restartTimer() { timerTask.schedule(200); } public static final void updateBlockChain(final NbEditorDocument doc) { if (doc == null) return; final Project p = J2MEProjectUtils.getProjectForDocument(doc); // TODO J2MEProject? if (p != null && p instanceof J2MEProject) { final ProjectConfigurationsHelper configHelper = p.getLookup().lookup(ProjectConfigurationsHelper.class); if (configHelper == null || !configHelper.isPreprocessorOn()) return; final HashMap<String, String> activeIdentifiers = new HashMap<String, String>(configHelper.getActiveAbilities()); activeIdentifiers.put(configHelper.getActiveConfiguration().getDisplayName(), null); try { J2MEProjectUtilitiesProvider utilProvider = Lookup.getDefault().lookup(J2MEProjectUtilitiesProvider.class); if (utilProvider == null) return; // we do not run in full NetBeans, but this should not happen here (no editor) final CommentingPreProcessor cpp = new CommentingPreProcessor( utilProvider.createPPDocumentSource((NbEditorDocument) doc), null, activeIdentifiers); cpp.run(); setLineInfo(doc, cpp.getLines(), cpp.getBlockList()); } catch (PreprocessorException e) { ErrorManager.getDefault().notify(e); } } } static String prefixPropertyName(final String configuration, final String propertyName) { return "configs." + configuration + '.' + propertyName; // NOI18N } class DL implements DocumentListener { public void changedUpdate(@SuppressWarnings("unused") final DocumentEvent arg0) {} public void insertUpdate(@SuppressWarnings("unused") final DocumentEvent evt) { DocumentPreprocessor.this.restartTimer(); } public void removeUpdate(@SuppressWarnings("unused") final DocumentEvent evt) { DocumentPreprocessor.this.restartTimer(); } } /** *** Annotation Stuff ******* */ static void processAnnotations( NbEditorDocument doc, List<PPLine> lineList) { // XXX needs to be split for errors and warnings final ArrayList<ErrorDescription> errs = new ArrayList(); DataObject dob = NbEditorUtilities.getDataObject(doc); FileObject fo = dob == null ? null : dob.getPrimaryFile(); for (PPLine line : lineList) { for (PPLine.Error err : line.getErrors()) { PPToken tok = err.token; int shift = (tok.getType() == LineParserTokens.END_OF_FILE || tok.getType() == LineParserTokens.END_OF_LINE || tok.getType() == LineParserTokens.OTHER_TEXT) ? Math.max(1, tok.getPadding().length()) : 0; int loff = NbDocument.findLineOffset(doc, line.getLineNumber() - 1); errs.add( ErrorDescriptionFactory.createErrorDescription( err.warning ? Severity.WARNING : Severity.ERROR, err.message, fo, loff + tok.getColumn() - shift, loff + tok.getColumn() + tok.getText().length())); } ArrayList<Fix> fixes = new ArrayList(); int start = Utilities.getRowStartFromLineOffset(doc, line.getLineNumber() - 1); if (line.getTokens().size() > 1 && "//#include".equals(line.getTokens().get(0).getText())) { // NOI18N fixes.add( new InlineIncludeHint( (NbEditorDocument) doc, start, line.getTokens().get(1).getText())); } else if (line.getType() == PPLine.OLDIF || line.getType() == PPLine.OLDENDIF) { PPBlockInfo b = line.getBlock(); while (b != null && b.getType() != PPLine.OLDIF) { b = b.getParent(); } if (b != null) fixes.add(new ReplaceOldSyntaxHint(doc, lineList, b)); } if (line.getType() == PPLine.UNKNOWN) fixes.add(new DisableHint((NbEditorDocument) doc, start)); if (fixes.size() > 0) errs.add( ErrorDescriptionFactory.createErrorDescription( Severity.HINT, NbBundle.getMessage(DocumentPreprocessor.class, "LBL_PreprocessorHint"), fixes, doc, line.getLineNumber())); // NOI18N } HintsController.setErrors(doc, "preprocessor-errors", errs); // NOI18N } /** *** End Annotation Stuff ******* */ }
public Task run() { ClassLoader targetLoader; if (target.contains("sharwell/optimized")) { targetLoader = Thread.currentThread().getContextClassLoader(); } else { targetLoader = getReferenceClassLoader(); } if (targetLoader == null) { return RequestProcessor.Task.EMPTY; } final ClassLoader loader = targetLoader; return REFERENCE_RP.post( new Runnable() { @Override public void run() { try { Class<?> toolClass = loader.loadClass(Tool.class.getName()); Constructor<?> ctor = toolClass.getConstructor(String[].class); Method processGrammarsOnCommandLine = toolClass.getMethod("processGrammarsOnCommandLine"); List<String> args = getCommandArguments(); for (FileObject grammarFile : grammarFiles) { args.add(FileUtil.toFile(grammarFile).getAbsolutePath()); } ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(loader); try { InputOutput inputOutput = IOProvider.getDefault() .getIO(String.format("ANTLR Codegen (%s)", target), false); inputOutput.select(); PrintStream originalOut = System.out; try (OutputWriter outputWriter = inputOutput.getOut()) { System.setOut(new PrintStream(new OutputWriterStream(outputWriter))); try { PrintStream originalErr = System.err; try (OutputWriter errorWriter = inputOutput.getErr()) { System.setErr(new PrintStream(new OutputWriterStream(errorWriter))); try { outputWriter.format("Arguments: %s%n", args); Object tool = ctor.newInstance((Object) args.toArray(new String[args.size()])); processGrammarsOnCommandLine.invoke(tool); } finally { System.setErr(originalErr); } } } finally { System.setOut(originalOut); } } } finally { Thread.currentThread().setContextClassLoader(contextClassLoader); } } catch (ClassNotFoundException | NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) { Exceptions.printStackTrace(ex); } } }); }
public FileObject render() throws IOException { if (EventQueue.isDispatchThread()) { throw new IllegalStateException("Tried to run povray from the " + "event thread"); } // Find the scene file pass to POV-Ray as a java.io.File File scene; try { scene = getFileToRender(); } catch (IOException ioe) { showMsg(ioe.getMessage()); return null; } // Get the POV-Ray executable File povray = getPovray(); if (povray == null) { // The user cancelled the file chooser w/o selecting showMsg(NbBundle.getMessage(Povray.class, "MSG_NoPovrayExe")); return null; } // Get the include dir, if it isn't under povray's home dir File includesDir = getStandardIncludeDir(povray); if (includesDir == null) { // The user cancelled the file chooser w/o selecting showMsg(NbBundle.getMessage(Povray.class, "MSG_NoPovrayInc")); return null; } // Find the image output directory for the project File imagesDir = getImagesDir(); // Assemble and format the line switches for the POV-Ray process based // on the contents of the Properties object String args = getCmdLineArgs(includesDir); String outFileName = stripExtension(scene) + ".png"; // Compute the name of the output image file File outFile = new File(imagesDir.getPath() + File.separator + outFileName); // Delete the image if it exists, so that any current tab viewing the file is // closed and the file will definitely be re-read when it is re-opened if (outFile.exists() && !outFile.delete()) { showMsg(NbBundle.getMessage(Povray.class, "LBL_CantDelete", outFile.getName())); return null; } // Append the input file and output file arguments to the command line String cmdline = povray.getPath() + ' ' + args + " +I" + scene.getPath() + " +O" + outFile.getPath(); System.err.println(cmdline); showMsg(NbBundle.getMessage(Povray.class, "MSG_Rendering", scene.getName())); final Process process = Runtime.getRuntime().exec(cmdline); // Get the standard out of the process InputStream out = new BufferedInputStream(process.getInputStream(), 8192); // Get the standard in of the process InputStream err = new BufferedInputStream(process.getErrorStream(), 8192); // Create readers for each final Reader outReader = new BufferedReader(new InputStreamReader(out)); final Reader errReader = new BufferedReader(new InputStreamReader(err)); // Get an InputOutput to write to the output window InputOutput io = IOProvider.getDefault().getIO(scene.getName(), false); // Force it to open the output window/activate our tab io.select(); // Print the command line we're calling for debug purposes io.getOut().println(cmdline); // Create runnables to poll each output stream OutHandler processSystemOut = new OutHandler(outReader, io.getOut()); OutHandler processSystemErr = new OutHandler(errReader, io.getErr()); // Get two different threads listening on the output & err // using the system-wide thread pool RequestProcessor.getDefault().post(processSystemOut); RequestProcessor.getDefault().post(processSystemErr); try { // Hang this thread until the process exits process.waitFor(); } catch (InterruptedException ex) { Exceptions.printStackTrace(ex); } // Close the output window's streams (title will become non-bold) processSystemOut.close(); processSystemErr.close(); if (outFile.exists() && process.exitValue() == 0) { // Try to find the new image file FileObject outFileObject = FileUtil.toFileObject(outFile); showMsg(NbBundle.getMessage(Povray.class, "MSG_Success", outFile.getPath())); return outFileObject; } else { showMsg(NbBundle.getMessage(Povray.class, "MSG_Failure", scene.getPath())); return null; } }
@NbBundle.Messages({ "SubmitIssueAction.message.pull.request.added.fail=The pull request has not been added.", "SubmitIssueAction.message.issue.added.fail=The issue has not been added.", "SubmitIssueAction.message.issue.updated.fail=The issue has not been updated." }) @Override public void actionPerformed(ActionEvent e) { final GitHubIssuePanel p = getPanel(); p.setSubmitButtonEnabled(false); RequestProcessor rp = GitHubIssues.getInstance().getRequestProcessor(); rp.post( new Runnable() { @Override public void run() { SwingUtilities.invokeLater( new Runnable() { @Override public void run() { GitHubIssue issue = p.getIssue(); CreateIssueParams issueParams = getCreateIssueParams(issue.isNew(), p); if (issue.isNew()) { if (p.isNewPullRequestSelected()) { // add pull request // can be added only title and body to a pull request // add other than those after the pull request was created PullRequest newPullRequest = p.getNewPullRequest(); if (newPullRequest != null) { newPullRequest .setTitle(issueParams.getTitle()) .setBody(issueParams.getBody()); try { PullRequest createdPullRequest = issue.createPullRequest(newPullRequest); if (createdPullRequest != null) { issue.editIssue(issueParams); p.update(); } else { // show dialog UiUtils.showErrorDialog( Bundle.SubmitIssueAction_message_pull_request_added_fail()); } } catch (IOException ex) { UiUtils.showErrorDialog(ex.getMessage()); } } } else { // add issue Issue newIssue = issue.submitNewIssue(issueParams); if (newIssue != null) { p.update(); } else { // show dialog UiUtils.showErrorDialog( Bundle.SubmitIssueAction_message_issue_added_fail()); } } } else { // edit issue Issue editIssue = issue.editIssue(issueParams); if (editIssue != null) { p.update(); } else { // show dialog UiUtils.showErrorDialog( Bundle.SubmitIssueAction_message_issue_updated_fail()); } } p.setSubmitButtonEnabled(true); } }); } }); }
@Override public void actionPerformed(ActionEvent e) { String actionCommand = e.getActionCommand(); final boolean isNewPullRequest = actionCommand.equals("New PR"); // NOI18N GitHubIssuePanel p = getPanel(); p.setCreatePullRequestButtonEnabled(false); final GitHubIssue issue = p.getIssue(); if (isNewPullRequest && !p.isNewPullRequestSelected()) { // remove the new pull request from the panle SwingUtilities.invokeLater( new Runnable() { @Override public void run() { getPanel().setNewPullRequest(null); } }); return; } RequestProcessor rp = GitHubIssues.getInstance().getRequestProcessor(); rp.post( new Runnable() { @Override public void run() { final GitHubRepository repository = issue.getRepository(); GitHubCache cache = GitHubCache.create(repository); final User mySelf = cache.getMySelf(); List<RepositoryBranch> baseBranches = cache.getBranches(true); final HashMap<Repository, List<RepositoryBranch>> baseRepositories = new HashMap<>(); baseRepositories.put(repository.getRepository(), baseBranches); final Map<Repository, List<RepositoryBranch>> headRepositories = getHeadRepositories(repository, baseBranches); SwingUtilities.invokeLater( new Runnable() { @Override public void run() { try { if (baseRepositories.isEmpty() || headRepositories.isEmpty()) { UiUtils.showErrorDialog( Bundle .CreatePullRequestAction_error_message_cannot_find_base_head_repositories()); return; } // create descriptor final CreatePullRequestPanel createPullRequestPanel = new CreatePullRequestPanel(baseRepositories, headRepositories); createPullRequestPanel.setMessage( Bundle.CreatePullRequestAction_confirmation_message()); final NotifyDescriptor.Confirmation descriptor = new NotifyDescriptor.Confirmation( createPullRequestPanel, Bundle.CreatePullRequestAction_descriptor_title(), NotifyDescriptor.OK_CANCEL_OPTION, NotifyDescriptor.QUESTION_MESSAGE); // add listeners ChangeListener changeListener = new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { descriptor.setValid(false); createPullRequestPanel.setErrorMessage(""); // NOI18N } }; createPullRequestPanel.addChangeListener(changeListener); ComparePullRequestPropertyChangeListener propertyChangeListener = new ComparePullRequestPropertyChangeListener( repository, createPullRequestPanel, descriptor); createPullRequestPanel.addPropertyChangeListener(propertyChangeListener); changeListener.stateChanged(null); // show dialog if (DialogDisplayer.getDefault().notify(descriptor) == NotifyDescriptor.OK_OPTION) { RepositoryBranch selectedBaseBranch = createPullRequestPanel.getSelectedBaseBranch(); RepositoryBranch selectedHeadBranch = createPullRequestPanel.getSelectedHeadBranch(); String baseBranch = selectedBaseBranch.getName(); String headBranch = mySelf.getLogin() + ":" + selectedHeadBranch.getName(); // NOI18N PullRequest pullRequest; try { if (isNewPullRequest) { // set new pull request to panel PullRequestMarker baseMarker = new PullRequestMarker(); baseMarker.setLabel(baseBranch); PullRequestMarker headMarker = new PullRequestMarker(); headMarker.setLabel(headBranch); PullRequest newPullRequest = new PullRequest().setBase(baseMarker).setHead(headMarker); getPanel().setNewPullRequest(newPullRequest); } else { pullRequest = issue.createPullRequest(headBranch, baseBranch); if (pullRequest != null) { getPanel().refresh(); } } } catch (IOException ex) { UiUtils.showErrorDialog( "Can't create a pull request:" + ex.getMessage()); // NOI18N } } else if (isNewPullRequest) { getPanel().setNewPullRequestSelected(false); } // remove listeners createPullRequestPanel.removeChangeListener(changeListener); createPullRequestPanel.removePropertyChangeListener(propertyChangeListener); } finally { getPanel().setCreatePullRequestButtonEnabled(true); } } }); } }); }
/** * <code>refreshResults</code> needs to be called after finding an instance of the <code> * ResultsTopComponent</code>. This is needed to run the specified query and fetch the results. */ public void refreshResults() { RequestProcessor.getDefault().post(new ShowQueryResultsRunnable(query)); }