@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 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; }
/** * 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 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 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); // } } }
/** * 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); }
@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(); } }
/** * <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)); }
/** @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 ******* */ }
/** * Display of Java sources in a package structure rather than folder structure. * * @author Adam Sotona, Jesse Glick, Petr Hrebejk, Tomas Zezula */ final class PackageViewChildren extends Children.Keys /*<String>*/ implements FileChangeListener, ChangeListener, Runnable { private static final String NODE_NOT_CREATED = "NNC"; // NOI18N private static final String NODE_NOT_CREATED_EMPTY = "NNC_E"; // NOI18N private static final MessageFormat PACKAGE_FLAVOR = new MessageFormat( "application/x-java-org-netbeans-modules-java-project-packagenodednd; class=org.netbeans.spi.java.project.support.ui.PackageViewChildren$PackageNode; mask={0}"); // NOI18N static final String PRIMARY_TYPE = "application"; // NOI18N static final String SUBTYPE = "x-java-org-netbeans-modules-java-project-packagenodednd"; // NOI18N static final String MASK = "mask"; // NOI18N private java.util.Map /*<String,NODE_NOT_CREATED|NODE_NOT_CREATED_EMPTY|PackageNode>*/ names2nodes; private final FileObject root; private FileChangeListener wfcl; // Weak listener on the system filesystem private ChangeListener wvqcl; // Weak listener on the VisibilityQuery /** * Creates children based on a single source root. * * @param root the folder where sources start (must be a package root) */ public PackageViewChildren(FileObject root) { // Sem mas dat cache a bude to uplne nejrychlejsi na svete if (root == null) { throw new NullPointerException(); } this.root = root; } FileObject getRoot() { return root; // Used from PackageRootNode } protected Node[] createNodes(Object obj) { FileObject fo = root.getFileObject((String) obj); if (fo != null && fo.isValid()) { Object o = names2nodes.get(obj); PackageNode n; if (o == NODE_NOT_CREATED) { n = new PackageNode(root, DataFolder.findFolder(fo), false); } else if (o == NODE_NOT_CREATED_EMPTY) { n = new PackageNode(root, DataFolder.findFolder(fo), true); } else { n = new PackageNode(root, DataFolder.findFolder(fo)); } names2nodes.put(obj, n); return new Node[] {n}; } else { return new Node[0]; } } RequestProcessor.Task task = RequestProcessor.getDefault().create(this); protected void addNotify() { super.addNotify(); task.schedule(0); } public Node[] getNodes(boolean optimal) { if (optimal) { Node[] garbage = super.getNodes(false); task.waitFinished(); } return super.getNodes(false); } public Node findChild(String name) { getNodes(true); return super.findChild(name); } public void run() { computeKeys(); refreshKeys(); try { FileSystem fs = root.getFileSystem(); wfcl = (FileChangeListener) WeakListeners.create(FileChangeListener.class, this, fs); fs.addFileChangeListener(wfcl); } catch (FileStateInvalidException e) { ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, e); } wvqcl = WeakListeners.change(this, VisibilityQuery.getDefault()); VisibilityQuery.getDefault().addChangeListener(wvqcl); } protected void removeNotify() { VisibilityQuery.getDefault().removeChangeListener(wvqcl); try { root.getFileSystem().removeFileChangeListener(wfcl); } catch (FileStateInvalidException e) { ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, e); } setKeys(Collections.EMPTY_SET); names2nodes.clear(); super.removeNotify(); } // Private methods --------------------------------------------------------- private void refreshKeys() { setKeys(names2nodes.keySet()); } /* #70097: workaround of a javacore deadlock * See related issue: #61027 */ private void refreshKeysAsync() { SwingUtilities.invokeLater( new Runnable() { public void run() { refreshKeys(); } }); } private void computeKeys() { // XXX this is not going to perform too well for a huge source root... // However we have to go through the whole hierarchy in order to find // all packages (Hrebejk) names2nodes = new TreeMap(); findNonExcludedPackages(root); } /** Collect all recursive subfolders, except those which have subfolders but no files. */ private void findNonExcludedPackages(FileObject fo) { PackageView.findNonExcludedPackages(this, fo); } /** Finds all empty parents of given package and deletes them */ private void cleanEmptyKeys(FileObject fo) { FileObject parent = fo.getParent(); // Special case for default package if (root.equals(parent)) { PackageNode n = get(parent); // the default package is considered empty if it only contains folders, // regardless of the contents of these folders (empty or not) if (n != null && PackageDisplayUtils.isEmpty(root, false)) { remove(root); } return; } while (FileUtil.isParentOf(root, parent)) { PackageNode n = get(parent); if (n != null && n.isLeaf()) { remove(parent); } parent = parent.getParent(); } } // Non private only to be able to have the findNonExcludedPackages impl // in on place (PackageView) void add(FileObject fo, boolean empty) { String path = FileUtil.getRelativePath(root, fo); assert path != null : "Adding wrong folder " + fo + "(valid=" + fo.isValid() + ")" + "under root" + this.root + "(valid=" + this.root.isValid() + ")"; if (get(fo) == null) { names2nodes.put(path, empty ? NODE_NOT_CREATED_EMPTY : NODE_NOT_CREATED); } } private void remove(FileObject fo) { String path = FileUtil.getRelativePath(root, fo); assert path != null : "Removing wrong folder" + fo; names2nodes.remove(path); } private void removeSubTree(FileObject fo) { String path = FileUtil.getRelativePath(root, fo); assert path != null : "Removing wrong folder" + fo; Collection keys = new HashSet(names2nodes.keySet()); names2nodes.remove(path); path = path + '/'; // NOI18N for (Iterator it = keys.iterator(); it.hasNext(); ) { String key = (String) it.next(); if (key.startsWith(path)) { names2nodes.remove(key); } } } private PackageNode get(FileObject fo) { String path = FileUtil.getRelativePath(root, fo); assert path != null : "Asking for wrong folder" + fo; Object o = names2nodes.get(path); return !isNodeCreated(o) ? null : (PackageNode) o; } private boolean contains(FileObject fo) { String path = FileUtil.getRelativePath(root, fo); assert path != null : "Asking for wrong folder" + fo; Object o = names2nodes.get(path); return o != null; } private boolean exists(FileObject fo) { String path = FileUtil.getRelativePath(root, fo); return names2nodes.get(path) != null; } private boolean isNodeCreated(Object o) { return o instanceof Node; } private PackageNode updatePath(String oldPath, String newPath) { Object o = names2nodes.get(oldPath); if (o == null) { return null; } names2nodes.remove(oldPath); names2nodes.put(newPath, o); return !isNodeCreated(o) ? null : (PackageNode) o; } // Implementation of FileChangeListener ------------------------------------ public void fileAttributeChanged(FileAttributeEvent fe) {} public void fileChanged(FileEvent fe) {} public void fileFolderCreated(FileEvent fe) { FileObject fo = fe.getFile(); if (FileUtil.isParentOf(root, fo) && isVisible(root, fo)) { cleanEmptyKeys(fo); // add( fo, false); findNonExcludedPackages(fo); refreshKeys(); } } public void fileDataCreated(FileEvent fe) { FileObject fo = fe.getFile(); if (FileUtil.isParentOf(root, fo) && isVisible(root, fo)) { FileObject parent = fo.getParent(); if (!VisibilityQuery.getDefault().isVisible(parent)) { return; // Adding file into ignored directory } PackageNode n = get(parent); if (n == null && !contains(parent)) { add(parent, false); refreshKeys(); } else if (n != null) { n.updateChildren(); } } } public void fileDeleted(FileEvent fe) { FileObject fo = fe.getFile(); if (FileUtil.isParentOf(root, fo) && isVisible(root, fo)) { if (fo.isFolder() || get(fo) != null) { removeSubTree(fo); // Now add the parent if necessary FileObject parent = fo.getParent(); if ((FileUtil.isParentOf(root, parent) || root.equals(parent)) && get(parent) == null && parent.isValid()) { // Candidate for adding if (!toBeRemoved(parent)) { add(parent, true); } } refreshKeysAsync(); } else { FileObject parent = fo.getParent(); final PackageNode n = get(parent); if (n != null) { // #61027: workaround to a deadlock when the package is being changed from non-leaf to // leaf: boolean leaf = n.isLeaf(); DataFolder df = n.getDataFolder(); boolean empty = n.isEmpty(df); if (leaf != empty) { SwingUtilities.invokeLater( new Runnable() { public void run() { n.updateChildren(); } }); } else { n.updateChildren(); } } // If the parent folder only contains folders remove it if (toBeRemoved(parent)) { remove(parent); refreshKeysAsync(); } } } } /** * Returns true if the folder should be removed from the view i.e. it has some unignored children * and the children are folders only */ private boolean toBeRemoved(FileObject folder) { boolean ignoredOnly = true; boolean foldersOnly = true; FileObject kids[] = folder.getChildren(); for (int i = 0; i < kids.length; i++) { if (VisibilityQuery.getDefault().isVisible(kids[i])) { ignoredOnly = false; if (!kids[i].isFolder()) { foldersOnly = false; break; } } } if (ignoredOnly) { return false; // It is either empty or it only contains ignored files // thus is leaf and it means package } else { return foldersOnly; } } public void fileRenamed(FileRenameEvent fe) { FileObject fo = fe.getFile(); if (FileUtil.isParentOf(root, fo) && fo.isFolder()) { String rp = FileUtil.getRelativePath(root, fo.getParent()); String oldPath = rp + (rp.length() == 0 ? "" : "/") + fe.getName() + fe.getExt(); // NOI18N boolean visible = VisibilityQuery.getDefault().isVisible(fo); boolean doUpdate = false; // Find all entries which have to be updated ArrayList needsUpdate = new ArrayList(); for (Iterator it = names2nodes.keySet().iterator(); it.hasNext(); ) { String p = (String) it.next(); if (p.startsWith(oldPath)) { if (visible) { needsUpdate.add(p); } else { names2nodes.remove(p); doUpdate = true; } } } // If the node does not exists then there might have been update // from ignored to non ignored if (get(fo) == null && visible) { cleanEmptyKeys(fo); findNonExcludedPackages(fo); doUpdate = true; // force refresh } int oldPathLen = oldPath.length(); String newPath = FileUtil.getRelativePath(root, fo); for (Iterator it = needsUpdate.iterator(); it.hasNext(); ) { String p = (String) it.next(); StringBuffer np = new StringBuffer(p); np.replace(0, oldPathLen, newPath); PackageNode n = updatePath(p, np.toString()); // Replace entries in cache if (n != null) { n.updateDisplayName(); // Update nodes } } if (needsUpdate.size() > 1 || doUpdate) { // Sorting might change refreshKeys(); } } /* else if ( FileUtil.isParentOf( root, fo ) && fo.isFolder() ) { FileObject parent = fo.getParent(); PackageNode n = get( parent ); if ( n != null && VisibilityQuery.getDefault().isVisible( parent ) ) { n.updateChildren(); } } */ } /** Test whether file and all it's parent up to parent paremeter are visible */ private boolean isVisible(FileObject parent, FileObject file) { do { if (!VisibilityQuery.getDefault().isVisible(file)) { return false; } file = file.getParent(); } while (file != null && file != parent); return true; } // Implementation of ChangeListener ------------------------------------ public void stateChanged(ChangeEvent e) { computeKeys(); refreshKeys(); } /* private void debugKeySet() { for( Iterator it = names2nodes.keySet().iterator(); it.hasNext(); ) { String k = (String)it.next(); } } */ static final class PackageNode extends FilterNode { private static final DataFilter NO_FOLDERS_FILTER = new NoFoldersDataFilter(); private final FileObject root; private DataFolder dataFolder; private boolean isDefaultPackage; private static Action actions[]; public PackageNode(FileObject root, DataFolder dataFolder) { this(root, dataFolder, isEmpty(dataFolder)); } public PackageNode(FileObject root, DataFolder dataFolder, boolean empty) { super( dataFolder.getNodeDelegate(), empty ? Children.LEAF : dataFolder.createNodeChildren(NO_FOLDERS_FILTER), new ProxyLookup( new Lookup[] { Lookups.singleton(new NoFoldersContainer(dataFolder)), dataFolder.getNodeDelegate().getLookup(), Lookups.singleton( PackageRootNode.alwaysSearchableSearchInfo( SearchInfoFactory.createSearchInfo( dataFolder.getPrimaryFile(), false, // not recursive new FileObjectFilter[] {SearchInfoFactory.VISIBILITY_FILTER}))), })); this.root = root; this.dataFolder = dataFolder; this.isDefaultPackage = root.equals(dataFolder.getPrimaryFile()); } FileObject getRoot() { return root; // Used from PackageRootNode } public String getName() { String relativePath = FileUtil.getRelativePath(root, dataFolder.getPrimaryFile()); return relativePath == null ? null : relativePath.replace('/', '.'); // NOI18N } public Action[] getActions(boolean context) { if (!context) { if (actions == null) { // Copy actions and leave out the PropertiesAction and FileSystemAction. Action superActions[] = super.getActions(context); ArrayList actionList = new ArrayList(superActions.length); for (int i = 0; i < superActions.length; i++) { if (superActions[i] == null && superActions[i + 1] instanceof org.openide.actions.PropertiesAction) { i++; continue; } else if (superActions[i] instanceof org.openide.actions.PropertiesAction) { continue; } // This will disable the Refactor node! else if (superActions[i] != null && superActions[i] .getClass() .getName() .equals("org.netbeans.modules.refactoring.ui.RSMJavaDOAction")) { continue; } // else if ( superActions[i] instanceof // org.openide.actions.FileSystemAction ) { // actionList.add (null); // insert separator and new action // actionList.add // (FileSensitiveActions.fileCommandAction(ActionProvider.COMMAND_COMPILE_SINGLE, // NbBundle.getMessage( PackageViewChildren.class, // "LBL_CompilePackage_Action" ), // NOI18N // null )); // } actionList.add(superActions[i]); } actions = new Action[actionList.size()]; actionList.toArray(actions); } return actions; } else { return super.getActions(context); } } public boolean canRename() { if (isDefaultPackage) { return false; } else { return true; } } public boolean canCut() { return !isDefaultPackage; } /** Copy handling */ public Transferable clipboardCopy() throws IOException { try { return new PackageTransferable(this, DnDConstants.ACTION_COPY); } catch (ClassNotFoundException e) { throw new AssertionError(e); } } public Transferable clipboardCut() throws IOException { try { return new PackageTransferable(this, DnDConstants.ACTION_MOVE); } catch (ClassNotFoundException e) { throw new AssertionError(e); } } public /*@Override*/ Transferable drag() throws IOException { try { return new PackageTransferable(this, DnDConstants.ACTION_NONE); } catch (ClassNotFoundException e) { throw new AssertionError(e); } } public PasteType[] getPasteTypes(Transferable t) { if (t.isDataFlavorSupported(ExTransferable.multiFlavor)) { try { MultiTransferObject mto = (MultiTransferObject) t.getTransferData(ExTransferable.multiFlavor); boolean hasPackageFlavor = false; for (int i = 0; i < mto.getCount(); i++) { DataFlavor[] flavors = mto.getTransferDataFlavors(i); if (isPackageFlavor(flavors)) { hasPackageFlavor = true; } } return hasPackageFlavor ? new PasteType[0] : super.getPasteTypes(t); } catch (UnsupportedFlavorException e) { ErrorManager.getDefault().notify(e); return new PasteType[0]; } catch (IOException e) { ErrorManager.getDefault().notify(e); return new PasteType[0]; } } else { DataFlavor[] flavors = t.getTransferDataFlavors(); if (isPackageFlavor(flavors)) { return new PasteType[0]; } else { return super.getPasteTypes(t); } } } public /*@Override*/ PasteType getDropType(Transferable t, int action, int index) { if (t.isDataFlavorSupported(ExTransferable.multiFlavor)) { try { MultiTransferObject mto = (MultiTransferObject) t.getTransferData(ExTransferable.multiFlavor); boolean hasPackageFlavor = false; for (int i = 0; i < mto.getCount(); i++) { DataFlavor[] flavors = mto.getTransferDataFlavors(i); if (isPackageFlavor(flavors)) { hasPackageFlavor = true; } } return hasPackageFlavor ? null : super.getDropType(t, action, index); } catch (UnsupportedFlavorException e) { ErrorManager.getDefault().notify(e); return null; } catch (IOException e) { ErrorManager.getDefault().notify(e); return null; } } else { DataFlavor[] flavors = t.getTransferDataFlavors(); if (isPackageFlavor(flavors)) { return null; } else { return super.getDropType(t, action, index); } } } private boolean isPackageFlavor(DataFlavor[] flavors) { for (int i = 0; i < flavors.length; i++) { if (SUBTYPE.equals(flavors[i].getSubType()) && PRIMARY_TYPE.equals(flavors[i].getPrimaryType())) { return true; } } return false; } private static synchronized PackageRenameHandler getRenameHandler() { Lookup.Result renameImplementations = Lookup.getDefault().lookup(new Lookup.Template(PackageRenameHandler.class)); List handlers = (List) renameImplementations.allInstances(); if (handlers.size() == 0) return null; if (handlers.size() > 1) ErrorManager.getDefault() .log( ErrorManager.WARNING, "Multiple instances of PackageRenameHandler found in Lookup; only using first one: " + handlers); // NOI18N return (PackageRenameHandler) handlers.get(0); } public void setName(String name) { PackageRenameHandler handler = getRenameHandler(); if (handler != null) { handler.handleRename(this, name); return; } if (isDefaultPackage) { return; } String oldName = getName(); if (oldName.equals(name)) { return; } if (!isValidPackageName(name)) { DialogDisplayer.getDefault() .notify( new NotifyDescriptor.Message( NbBundle.getMessage(PackageViewChildren.class, "MSG_InvalidPackageName"), NotifyDescriptor.INFORMATION_MESSAGE)); return; } name = name.replace('.', '/') + '/'; // NOI18N oldName = oldName.replace('.', '/') + '/'; // NOI18N int i; for (i = 0; i < oldName.length() && i < name.length(); i++) { if (oldName.charAt(i) != name.charAt(i)) { break; } } i--; int index = oldName.lastIndexOf('/', i); // NOI18N String commonPrefix = index == -1 ? null : oldName.substring(0, index); String toCreate = (index + 1 == name.length()) ? "" : name.substring(index + 1); // NOI18N try { FileObject commonFolder = commonPrefix == null ? this.root : this.root.getFileObject(commonPrefix); FileObject destination = commonFolder; StringTokenizer dtk = new StringTokenizer(toCreate, "/"); // NOI18N while (dtk.hasMoreTokens()) { String pathElement = dtk.nextToken(); FileObject tmp = destination.getFileObject(pathElement); if (tmp == null) { tmp = destination.createFolder(pathElement); } destination = tmp; } FileObject source = this.dataFolder.getPrimaryFile(); DataFolder sourceFolder = DataFolder.findFolder(source); DataFolder destinationFolder = DataFolder.findFolder(destination); DataObject[] children = sourceFolder.getChildren(); for (int j = 0; j < children.length; j++) { if (children[j].getPrimaryFile().isData()) { children[j].move(destinationFolder); } } while (!commonFolder.equals(source)) { if (source.getChildren().length == 0) { FileObject tmp = source; source = source.getParent(); tmp.delete(); } else { break; } } } catch (IOException ioe) { ErrorManager.getDefault().notify(ioe); } } public boolean canDestroy() { if (isDefaultPackage) { return false; } else { return true; } } public void destroy() throws IOException { FileObject parent = dataFolder.getPrimaryFile().getParent(); // First; delete all files except packages DataObject ch[] = dataFolder.getChildren(); boolean empty = true; for (int i = 0; ch != null && i < ch.length; i++) { if (!ch[i].getPrimaryFile().isFolder()) { ch[i].delete(); } else { empty = false; } } // If empty delete itself if (empty) { super.destroy(); } // Second; delete empty super packages while (!parent.equals(root) && parent.getChildren().length == 0) { FileObject newParent = parent.getParent(); parent.delete(); parent = newParent; } } /** * Initially overridden to support CVS status labels in package nodes. * * @return annotated display name */ public String getHtmlDisplayName() { String name = getDisplayName(); try { FileObject fo = dataFolder.getPrimaryFile(); Set set = new NonResursiveFolderSet(fo); org.openide.filesystems.FileSystem.Status status = fo.getFileSystem().getStatus(); if (status instanceof org.openide.filesystems.FileSystem.HtmlStatus) { name = ((org.openide.filesystems.FileSystem.HtmlStatus) status).annotateNameHtml(name, set); } else { name = status.annotateName(name, set); } } catch (FileStateInvalidException e) { // no fs, do nothing } return name; } public String getDisplayName() { FileObject folder = dataFolder.getPrimaryFile(); String path = FileUtil.getRelativePath(root, folder); if (path == null) { // ??? return ""; } return PackageDisplayUtils.getDisplayLabel(path.replace('/', '.')); } public String getShortDescription() { FileObject folder = dataFolder.getPrimaryFile(); String path = FileUtil.getRelativePath(root, folder); if (path == null) { // ??? return ""; } return PackageDisplayUtils.getToolTip(folder, path.replace('/', '.')); } public java.awt.Image getIcon(int type) { java.awt.Image img = getMyIcon(type); try { FileObject fo = dataFolder.getPrimaryFile(); Set set = new NonResursiveFolderSet(fo); img = fo.getFileSystem().getStatus().annotateIcon(img, type, set); } catch (FileStateInvalidException e) { // no fs, do nothing } return img; } public java.awt.Image getOpenedIcon(int type) { java.awt.Image img = getMyOpenedIcon(type); try { FileObject fo = dataFolder.getPrimaryFile(); Set set = new NonResursiveFolderSet(fo); img = fo.getFileSystem().getStatus().annotateIcon(img, type, set); } catch (FileStateInvalidException e) { // no fs, do nothing } return img; } private Image getMyIcon(int type) { FileObject folder = dataFolder.getPrimaryFile(); String path = FileUtil.getRelativePath(root, folder); if (path == null) { // ??? return null; } return PackageDisplayUtils.getIcon(folder, path.replace('/', '.'), isLeaf()); } private Image getMyOpenedIcon(int type) { return getIcon(type); } public void update() { fireIconChange(); fireOpenedIconChange(); } public void updateDisplayName() { // fireNameChange(null, null); // fireDisplayNameChange(null, null); // fireShortDescriptionChange(null, null); } public void updateChildren() { boolean leaf = isLeaf(); DataFolder df = getDataFolder(); boolean empty = isEmpty(df); if (leaf != empty) { setChildren(empty ? Children.LEAF : df.createNodeChildren(NO_FOLDERS_FILTER)); update(); } } public /*@Override*/ Node.PropertySet[] getPropertySets() { Node.PropertySet[] properties = super.getPropertySets(); for (int i = 0; i < properties.length; i++) { if (Sheet.PROPERTIES.equals(properties[i].getName())) { // Replace the Sheet.PROPERTIES by the new one // having only the name property which does refactoring properties[i] = Sheet.createPropertiesSet(); ((Sheet.Set) properties[i]) .put( new PropertySupport.ReadWrite( DataObject.PROP_NAME, String.class, NbBundle.getMessage(PackageViewChildren.class, "PROP_name"), NbBundle.getMessage(PackageViewChildren.class, "HINT_name")) { public /*@Override*/ Object getValue() { return PackageViewChildren.PackageNode.this.getName(); } public /*@Override*/ void setValue(Object val) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException { if (!canRename()) throw new IllegalAccessException(); if (!(val instanceof String)) throw new IllegalArgumentException(); PackageViewChildren.PackageNode.this.setName((String) val); } public /*@Override*/ boolean canWrite() { return PackageViewChildren.PackageNode.this.canRename(); } }); } } return properties; } private DataFolder getDataFolder() { return (DataFolder) getCookie(DataFolder.class); } private static boolean isEmpty(DataFolder dataFolder) { if (dataFolder == null) { return true; } return PackageDisplayUtils.isEmpty(dataFolder.getPrimaryFile()); } private static boolean isValidPackageName(String name) { if (name.length() == 0) { // Fast check of default pkg return true; } StringTokenizer tk = new StringTokenizer(name, ".", true); // NOI18N boolean delimExpected = false; while (tk.hasMoreTokens()) { String namePart = tk.nextToken(); if (!delimExpected) { if (namePart.equals(".")) { // NOI18N return false; } for (int i = 0; i < namePart.length(); i++) { char c = namePart.charAt(i); if (i == 0) { if (!Character.isJavaIdentifierStart(c)) { return false; } } else { if (!Character.isJavaIdentifierPart(c)) { return false; } } } } else { if (!namePart.equals(".")) { // NOI18N return false; } } delimExpected = !delimExpected; } return delimExpected; } } private static final class NoFoldersContainer implements DataObject.Container, java.beans.PropertyChangeListener, NonRecursiveFolder { private DataFolder folder; private PropertyChangeSupport prop = new PropertyChangeSupport(this); public NoFoldersContainer(DataFolder folder) { this.folder = folder; } public FileObject getFolder() { return folder.getPrimaryFile(); } public DataObject[] getChildren() { DataObject[] arr = folder.getChildren(); ArrayList list = new ArrayList(arr.length); for (int i = 0; i < arr.length; i++) { if (arr[i] instanceof DataFolder) continue; list.add(arr[i]); } return list.size() == arr.length ? arr : (DataObject[]) list.toArray(new DataObject[0]); } public void addPropertyChangeListener(java.beans.PropertyChangeListener l) { prop.addPropertyChangeListener(l); } public void removePropertyChangeListener(java.beans.PropertyChangeListener l) { prop.removePropertyChangeListener(l); } public void propertyChange(java.beans.PropertyChangeEvent evt) { if (DataObject.Container.PROP_CHILDREN.equals(evt.getPropertyName())) { prop.firePropertyChange(PROP_CHILDREN, null, null); } } } static final class NoFoldersDataFilter implements ChangeListener, ChangeableDataFilter { EventListenerList ell = new EventListenerList(); public NoFoldersDataFilter() { VisibilityQuery.getDefault().addChangeListener(this); } public boolean acceptDataObject(DataObject obj) { FileObject fo = obj.getPrimaryFile(); return VisibilityQuery.getDefault().isVisible(fo) && !(obj instanceof DataFolder); } public void stateChanged(ChangeEvent e) { Object[] listeners = ell.getListenerList(); ChangeEvent event = null; for (int i = listeners.length - 2; i >= 0; i -= 2) { if (listeners[i] == ChangeListener.class) { if (event == null) { event = new ChangeEvent(this); } ((ChangeListener) listeners[i + 1]).stateChanged(event); } } } public void addChangeListener(ChangeListener listener) { ell.add(ChangeListener.class, listener); } public void removeChangeListener(ChangeListener listener) { ell.remove(ChangeListener.class, listener); } } static class PackageTransferable extends ExTransferable.Single { private PackageNode node; public PackageTransferable(PackageNode node, int operation) throws ClassNotFoundException { super( new DataFlavor( PACKAGE_FLAVOR.format(new Object[] {new Integer(operation)}), null, PackageNode.class.getClassLoader())); this.node = node; } protected Object getData() throws IOException, UnsupportedFlavorException { return this.node; } } static class PackagePasteType extends PasteType { private int op; private PackageNode[] nodes; private FileObject srcRoot; public PackagePasteType(FileObject srcRoot, PackageNode[] node, int op) { assert op == DnDConstants.ACTION_COPY || op == DnDConstants.ACTION_MOVE || op == DnDConstants.ACTION_NONE : "Invalid DnD operation"; // NOI18N this.nodes = node; this.op = op; this.srcRoot = srcRoot; } public void setOperation(int op) { this.op = op; } public Transferable paste() throws IOException { assert this.op != DnDConstants.ACTION_NONE; for (int ni = 0; ni < nodes.length; ni++) { FileObject fo = srcRoot; if (!nodes[ni].isDefaultPackage) { String pkgName = nodes[ni].getName(); StringTokenizer tk = new StringTokenizer(pkgName, "."); // NOI18N while (tk.hasMoreTokens()) { String name = tk.nextToken(); FileObject tmp = fo.getFileObject(name, null); if (tmp == null) { tmp = fo.createFolder(name); } fo = tmp; } } DataFolder dest = DataFolder.findFolder(fo); DataObject[] children = nodes[ni].dataFolder.getChildren(); boolean cantDelete = false; for (int i = 0; i < children.length; i++) { if (children[i].getPrimaryFile().isData() && VisibilityQuery.getDefault().isVisible(children[i].getPrimaryFile())) { // Copy only the package level children[i].copy(dest); if (this.op == DnDConstants.ACTION_MOVE) { try { children[i].delete(); } catch (IOException ioe) { cantDelete = true; } } } else { cantDelete = true; } } if (this.op == DnDConstants.ACTION_MOVE && !cantDelete) { try { FileObject tmpFo = nodes[ni].dataFolder.getPrimaryFile(); FileObject originalRoot = nodes[ni].root; assert tmpFo != null && originalRoot != null; while (!tmpFo.equals(originalRoot)) { if (tmpFo.getChildren().length == 0) { FileObject tmpFoParent = tmpFo.getParent(); tmpFo.delete(); tmpFo = tmpFoParent; } else { break; } } } catch (IOException ioe) { // Not important } } } return ExTransferable.EMPTY; } public String getName() { return NbBundle.getMessage(PackageViewChildren.class, "TXT_PastePackage"); } } /** * FileObject set that represents package. It means that it's content must not be processed * recursively. */ private static class NonResursiveFolderSet extends HashSet implements NonRecursiveFolder { private final FileObject folder; /** Creates set with one element, the folder. */ public NonResursiveFolderSet(FileObject folder) { this.folder = folder; add(folder); } public FileObject getFolder() { return folder; } } }
public void initValues( final Project project, final FileObject template, final FileObject preselectedFolder) { this.project = project; this.helper = project.getLookup().lookup(AntProjectHelper.class); final Object obj = template.getAttribute(IS_MIDLET_TEMPLATE_ATTRIBUTE); isMIDlet = false; if (obj instanceof Boolean) isMIDlet = ((Boolean) obj).booleanValue(); projectTextField.setText(ProjectUtils.getInformation(project).getDisplayName()); final Sources sources = ProjectUtils.getSources(project); final SourceGroup[] groups = sources.getSourceGroups(JavaProjectConstants.SOURCES_TYPE_JAVA); final SourceGroup preselectedGroup = getPreselectedGroup(groups, preselectedFolder); if (preselectedGroup != null) { final ModelItem groupItem = new ModelItem(preselectedGroup); final ModelItem[] nodes = groupItem.getChildren(); packageComboBox.setModel(new DefaultComboBoxModel(nodes)); final Object folderItem = getPreselectedPackage(groupItem, preselectedFolder); if (folderItem != null) packageComboBox.setSelectedItem(folderItem); } else { packageComboBox.setModel(new DefaultComboBoxModel()); } // Determine the extension final String ext = template == null ? "" : template.getExt(); // NOI18N expectedExtension = ext.length() == 0 ? "" : "." + ext; // NOI18N lName.setVisible(isMIDlet); tName.setVisible(isMIDlet); lIcon.setVisible(isMIDlet); cIcon.setVisible(isMIDlet); lNote.setVisible(isMIDlet); org.openide.awt.Mnemonics.setLocalizedText( lClassName, NbBundle.getMessage( MIDPTargetChooserPanelGUI.class, isMIDlet ? "LBL_File_MIDletClassName" : "LBL_File_MIDPClassName")); // NOI18N // Show name of the project if (isMIDlet) { tName.getDocument().removeDocumentListener(this); tName.setText(template.getName()); updateClassNameAndIcon(); if (testIfFileNameExists(preselectedGroup) && updateClassName) { String name = tName.getText(); int i = 1; for (; ; ) { tName.setText(name + "_" + i); // NOI18N updateClassNameAndIcon(); if (!testIfFileNameExists(preselectedGroup) || !updateClassName) break; i++; } } tName.getDocument().addDocumentListener(this); } else { tClassName.setText(template.getName()); if (testIfFileNameExists(preselectedGroup)) { String name = tClassName.getText(); int i = 1; for (; ; ) { tClassName.setText(name + "_" + i); // NOI18N if (!testIfFileNameExists(preselectedGroup)) break; i++; } } tClassName.getDocument().addDocumentListener(this); } updateText(); // Find all icons if (loadIcons) { loadIcons = false; final DefaultComboBoxModel icons = new DefaultComboBoxModel(); cIcon.setModel(icons); cIcon.setSelectedItem(""); // NOI18N RequestProcessor.getDefault() .post( new Runnable() { public void run() { final ArrayList<FileObject> roots = new ArrayList<FileObject>(); roots.add( helper.resolveFileObject( helper.getStandardPropertyEvaluator().getProperty("src.dir"))); // NOI18N final String libs = J2MEProjectUtils.evaluateProperty( helper, DefaultPropertiesDescriptor.LIBS_CLASSPATH); if (libs != null) { final String elements[] = PropertyUtils.tokenizePath(helper.resolvePath(libs)); for (int i = 0; i < elements.length; i++) try { final FileObject root = FileUtil.toFileObject(FileUtil.normalizeFile(new File(elements[i]))); if (root != null) roots.add( FileUtil.isArchiveFile(root) ? FileUtil.getArchiveRoot(root) : root); } catch (Exception e) { } } for (FileObject root : roots) { if (root != null) { final int rootLength = root.getPath().length(); final Enumeration en = root.getChildren(true); while (en.hasMoreElements()) { final FileObject fo = (FileObject) en.nextElement(); if (fo.isData()) { final String ext = fo.getExt().toLowerCase(); if ("png".equals(ext)) { // NOI18N String name = fo.getPath().substring(rootLength); if (!name.startsWith("/")) name = "/" + name; // NOI18N if (icons.getIndexOf(name) < 0) icons.addElement(name); } } } } } } }); } }
@Override public void actionPerformed(ActionEvent e) { JFileChooser fc = new JFileChooser(); fc.setFileFilter(ImportAction.getFileFilter()); fc.setCurrentDirectory( new File(Settings.get().get(Settings.DIRECTORY, Settings.DIRECTORY_DEFAULT))); fc.setMultiSelectionEnabled(true); if (fc.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) { for (final File file : fc.getSelectedFiles()) { File dir = file; if (!dir.isDirectory()) { dir = dir.getParentFile(); } Settings.get().put(Settings.DIRECTORY, dir.getAbsolutePath()); try { final FileChannel channel = FileChannel.open(file.toPath(), StandardOpenOption.READ); final ProgressHandle handle = ProgressHandleFactory.createHandle("Opening file " + file.getName()); handle.start(WORKUNITS); final long startTime = System.currentTimeMillis(); final long start = channel.size(); ParseMonitor monitor = new ParseMonitor() { @Override public void updateProgress() { try { int prog = (int) (WORKUNITS * (double) channel.position() / (double) start); handle.progress(prog); } catch (IOException ex) { } } @Override public void setState(String state) { updateProgress(); handle.progress(state); } }; final GraphParser parser; final OutlineTopComponent component = OutlineTopComponent.findInstance(); if (file.getName().endsWith(".xml")) { parser = new Parser(channel, monitor, null); } else if (file.getName().endsWith(".bgv")) { parser = new BinaryParser(channel, monitor, component.getDocument(), null); } else { parser = null; } RequestProcessor.getDefault() .post( new Runnable() { @Override public void run() { try { final GraphDocument document = parser.parse(); if (document != null) { SwingUtilities.invokeLater( new Runnable() { @Override public void run() { component.requestActive(); component.getDocument().addGraphDocument(document); } }); } } catch (IOException ex) { Exceptions.printStackTrace(ex); } handle.finish(); long stop = System.currentTimeMillis(); Logger.getLogger(getClass().getName()) .log( Level.INFO, "Loaded in " + file + " in " + ((stop - startTime) / 1000.0) + " seconds"); } }); } catch (FileNotFoundException ex) { Exceptions.printStackTrace(ex); } catch (IOException ex) { Exceptions.printStackTrace(ex); } } } }
public void actionPerformed(ActionEvent e) { final JButton source = (e.getSource() instanceof JButton) ? (JButton) e.getSource() : null; final TopComponent mainWindow = WindowManager.getDefault().findTopComponent("KenaiTopComponent"); // NOI18N mainWindow.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); final ProgressHandle progress = ProgressHandleFactory.createHandle( NbBundle.getMessage(CreateChatAction.class, "LBL_CheckPermissions")); progress.setInitialDelay(0); progress.start(); if (source != null) source.setEnabled(true); RequestProcessor.getDefault() .post( new Runnable() { public void run() { try { if (!project.getKenai().isAuthorized(project, KenaiActivity.PROJECTS_ADMIN)) { SwingUtilities.invokeLater( new Runnable() { public void run() { progress.finish(); JOptionPane.showMessageDialog( null, NbBundle.getMessage( CreateChatAction.class, "CTL_NotAuthorizedToCreateChat", getValue(NAME))); mainWindow.setCursor(Cursor.getDefaultCursor()); if (source != null) source.setEnabled(true); } }); return; } } catch (KenaiException ex) { Exceptions.printStackTrace(ex); } SwingUtilities.invokeLater( new Runnable() { public void run() { int value = JOptionPane.showOptionDialog( null, NbBundle.getMessage( CreateChatAction.class, "LBL_CreateChatQuestions"), NbBundle.getMessage(CreateChatAction.class, "LBL_CreateChatTitle"), JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, null, null); if (value == JOptionPane.YES_OPTION) { progress.setDisplayName( NbBundle.getMessage( CreateChatAction.class, "CTL_CreatingChatProgress")); RequestProcessor.getDefault() .post( new Runnable() { public void run() { try { final KenaiFeature f = project.createProjectFeature( project.getName(), NbBundle.getMessage( CreateChatAction.class, "CTL_ChatRoomName", project.getName()), NbBundle.getMessage( CreateChatAction.class, "CTL_ChatRoomDescription", project.getName()), KenaiService.Names.XMPP_CHAT, null, null, null); SwingUtilities.invokeLater( new Runnable() { public void run() { final ChatTopComponent chatTc = ChatTopComponent.findInstance(); chatTc.open(); chatTc.addChat( new ChatPanel( KenaiConnection.getDefault( project.getKenai()) .getChat(f))); mainWindow.setCursor(Cursor.getDefaultCursor()); progress.finish(); if (source != null) source.setEnabled(true); chatTc.requestActive(); } }); } catch (KenaiException kenaiException) { Exceptions.printStackTrace(kenaiException); mainWindow.setCursor(Cursor.getDefaultCursor()); progress.finish(); if (source != null) source.setEnabled(true); } } }); } else { mainWindow.setCursor(Cursor.getDefaultCursor()); progress.finish(); if (source != null) source.setEnabled(true); } } }); } }); }
private void refreshSetups() { if (dpt != null) { prepareTask.cancel(); } File[] files; switch (currentType) { case Setup.DIFFTYPE_LOCAL: displayStatuses = StatusInfo.STATUS_LOCAL_CHANGE; break; case Setup.DIFFTYPE_REMOTE: displayStatuses = StatusInfo.STATUS_REMOTE_CHANGE; break; case Setup.DIFFTYPE_ALL: displayStatuses = StatusInfo.STATUS_LOCAL_CHANGE | StatusInfo.STATUS_REMOTE_CHANGE; break; default: throw new IllegalStateException("Unknown DIFF type:" + currentType); // NOI18N } files = GitUtils.getModifiedFiles(context, displayStatuses); setups = computeSetups(files); boolean propertyColumnVisible = false; for (Setup setup : setups) { if (setup.getPropertyName() != null) { propertyColumnVisible = true; break; } } fileTable.setColumns( propertyColumnVisible ? new String[] { DiffNode.COLUMN_NAME_NAME, DiffNode.COLUMN_NAME_PROPERTY, DiffNode.COLUMN_NAME_STATUS, DiffNode.COLUMN_NAME_LOCATION } : new String[] { DiffNode.COLUMN_NAME_NAME, DiffNode.COLUMN_NAME_STATUS, DiffNode.COLUMN_NAME_LOCATION }); fileTable.setTableModel(setupToNodes(setups)); if (setups.length == 0) { String noContentLabel; switch (currentType) { case Setup.DIFFTYPE_LOCAL: noContentLabel = NbBundle.getMessage(MultiDiffPanel.class, "MSG_DiffPanel_NoLocalChanges"); break; case Setup.DIFFTYPE_REMOTE: noContentLabel = NbBundle.getMessage(MultiDiffPanel.class, "MSG_DiffPanel_NoRemoteChanges"); break; case Setup.DIFFTYPE_ALL: noContentLabel = NbBundle.getMessage(MultiDiffPanel.class, "MSG_DiffPanel_NoAllChanges"); break; default: throw new IllegalStateException("Unknown DIFF type:" + currentType); // NOI18N } setups = null; fileTable.setTableModel(new Node[0]); fileTable.getComponent().setEnabled(false); fileTable.getComponent().setPreferredSize(null); Dimension dim = fileTable.getComponent().getPreferredSize(); fileTable.getComponent().setPreferredSize(new Dimension(dim.width + 1, dim.height)); diffView = null; diffView = new NoContentPanel(noContentLabel); setBottomComponent(); nextAction.setEnabled(false); prevAction.setEnabled(false); revalidate(); repaint(); } else { fileTable.getComponent().setEnabled(true); fileTable.getComponent().setPreferredSize(null); Dimension dim = fileTable.getComponent().getPreferredSize(); fileTable.getComponent().setPreferredSize(new Dimension(dim.width + 1, dim.height)); setDiffIndex(0, 0); dpt = new DiffPrepareTask(setups); prepareTask = RequestProcessor.getDefault().post(dpt); } }
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; } }
public Task analyzePatterns() { checkState(0); task = RequestProcessor.getDefault().post(this); return task; }