Java Code Examples for org.openide.text.NbDocument#runAtomic()

The following examples show how to use org.openide.text.NbDocument#runAtomic() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ResourceConfigurationHelper.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * Replace the content of the document by the graph.
 */
public static void replaceDocument(final StyledDocument doc, BaseBean graph) {
    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    try {
        graph.write(out);
    } catch (IOException ioe) {
        LOGGER.log(Level.WARNING, null, ioe);
    }
    NbDocument.runAtomic(doc, new Runnable() {
        public void run() {
            try {
                doc.remove(0, doc.getLength());
                doc.insertString(0, out.toString(), null);
            } catch (BadLocationException ble) {
                LOGGER.log(Level.WARNING, null, ble);
            }
        }
    });
}
 
Example 2
Source File: SearchCompletionItem.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public void defaultAction(final JTextComponent component) {
    Completion.get().hideCompletion();
    Completion.get().hideDocumentation();
    NbDocument.runAtomic((StyledDocument) component.getDocument(), new Runnable() {
        @Override
        public void run() {
            Document doc = component.getDocument();

            try {
                doc.remove(0, doc.getLength());
                doc.insertString(0, getText(), null);
            } catch (BadLocationException e) {
                Logger.getLogger(SearchCompletionItem.class.getName()).log(Level.FINE, null, e);
            }
        }
    });
}
 
Example 3
Source File: WordCompletionItem.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void defaultAction(final JTextComponent component) {
    Completion.get().hideCompletion();
    Completion.get().hideDocumentation();
    NbDocument.runAtomic((StyledDocument) component.getDocument(), new Runnable() {
        public void run() {
            Document doc = component.getDocument();
            
            try {
                doc.remove(substituteOffset, component.getCaretPosition() - substituteOffset);
                doc.insertString(substituteOffset, getText(), null);
            } catch (BadLocationException e) {
                ErrorManager.getDefault().notify(e);
            }
        }
    });
}
 
Example 4
Source File: ResourceConfigurationHelper.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * Replace the content of the document by the graph.
 */
public static void replaceDocument(final StyledDocument doc, BaseBean graph) {
    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    try {
        graph.write(out);
    } catch (IOException ioe) {
        Exceptions.printStackTrace(ioe);
    }
    NbDocument.runAtomic(doc, new Runnable() {
        public void run() {
            try {
                doc.remove(0, doc.getLength());
                doc.insertString(0, out.toString(), null);
            } catch (BadLocationException ble) {
                Exceptions.printStackTrace(ble);
            }
        }
    });
}
 
Example 5
Source File: FXMLCompletionItem.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public void defaultAction(final JTextComponent component) {
    Completion.get().hideCompletion();
    Completion.get().hideDocumentation();
    NbDocument.runAtomic((StyledDocument) component.getDocument(), new Runnable() {
        @Override
        public void run() {
            Document doc = component.getDocument();
            
            try {
                doc.remove(substituteOffset, component.getCaretPosition() - substituteOffset);
                doc.insertString(substituteOffset, getText(), null);
            } catch (BadLocationException e) {
                Logger.getLogger(FXMLCompletionItem.class.getName()).log(Level.FINE, null, e);
            }
        }
    });
}
 
Example 6
Source File: TomcatModuleConfiguration.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * Replace the content of the document by the graph.
 */
private static void replaceDocument(final StyledDocument doc, BaseBean graph) {
    final StringWriter out = new StringWriter();
    try {
        graph.write(out);
    } catch (Schema2BeansException ex) {
        Logger.getLogger(TomcatModuleConfiguration.class.getName()).log(Level.INFO, null, ex);
    } catch (IOException ioe) {
        Logger.getLogger(TomcatModuleConfiguration.class.getName()).log(Level.INFO, null, ioe);
    }
    NbDocument.runAtomic(doc, new Runnable() {

        public void run() {
            try {
                doc.remove(0, doc.getLength());
                doc.insertString(0, out.toString(), null);
            } catch (BadLocationException ble) {
                Exceptions.printStackTrace(ble);
            }
        }
    });
}
 
Example 7
Source File: SourceFileObject.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public synchronized @Override void close() throws IOException {
    try {
        NbDocument.runAtomic(this.doc,
            new Runnable () {
                @Override
                public void run () {
                    try {
                        doc.remove(0,doc.getLength());
                        doc.insertString(0,new String(
                            data,
                            0,
                            pos,
                            FileEncodingQuery.getEncoding(getHandle().resolveFileObject(false))),
                        null);
                    } catch (BadLocationException e) {
                        if (LOG.isLoggable(Level.SEVERE))
                            LOG.log(Level.SEVERE, e.getMessage(), e);
                    }
                }
            });
    } finally {
        resetCaches();
    }
}
 
Example 8
Source File: TextDocumentServiceImpl.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public void didChange(DidChangeTextDocumentParams params) {
    Document doc = openedDocuments.get(params.getTextDocument().getUri());
    NbDocument.runAtomic((StyledDocument) doc, () -> {
        for (TextDocumentContentChangeEvent change : params.getContentChanges()) {
            try {
                int start = getOffset(doc, change.getRange().getStart());
                int end   = getOffset(doc, change.getRange().getEnd());
                doc.remove(start, end - start);
                doc.insertString(start, change.getText(), null);
            } catch (BadLocationException ex) {
                throw new IllegalStateException(ex);
            }
        }
    });
    runDiagnoticTasks(params.getTextDocument().getUri());
}
 
Example 9
Source File: BiAnalyser.java    From netbeans with Apache License 2.0 6 votes vote down vote up
void regenerateSourceImpl(StyledDocument doc) {
    NbDocument.runAtomic(doc, new Runnable() {
            public void run()  {
                regenerateBeanDescriptor();
                regenerateProperties();
                regenerateEvents();
                if (!olderVersion) {
                    regenerateMethods();
                }
                regenerateIcons();
                regenerateDefaultIdx();
                regenerateSuperclass();
                isModified = false;
                isIconModified = false;
            }
    } );
}
 
Example 10
Source File: EditorTestPerformer.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public ChangeInfo implement() throws Exception {
    NbDocument.runAtomic(doc, new Runnable() {
        public void run() {
            try {
                doc.remove(start, end - start);
                doc.insertString(start, text, null);
            } catch (BadLocationException ex) {
                throw new IllegalStateException(ex);
            }
        }
    });
    
    return null;
}
 
Example 11
Source File: EditableDiffView.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private void replace(final StyledDocument doc, final int start, final int length, final String text) {
    NbDocument.runAtomic(doc, new Runnable() {
        @Override    
        public void run() {
            try {
                doc.remove(start, length);
                doc.insertString(start, text, null);
            } catch (BadLocationException e) {
                Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, e.getMessage(), e);
            }
        }
    });
}
 
Example 12
Source File: Utils.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static void applyEdits(String uri, List<TextEdit> edits) {
    try {
        FileObject file = URLMapper.findFileObject(new URI(uri).toURL());
        EditorCookie ec = file.getLookup().lookup(EditorCookie.class);
        Document doc = ec != null ? ec.openDocument() : null;
        if (doc == null) {
            return ;
        }
        NbDocument.runAtomic((StyledDocument) doc, () -> {
            applyEditsNoLock(doc, edits);
        });
    } catch (URISyntaxException | IOException ex) {
        Exceptions.printStackTrace(ex);
    }
}
 
Example 13
Source File: Formatter.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private void applyTextEdits(List<TextEdit> edits) {
    if (ctx.document() instanceof StyledDocument) {
        NbDocument.runAtomic((StyledDocument) ctx.document(), () -> {
            Utils.applyEditsNoLock(ctx.document(), edits, ctx.startOffset(), ctx.endOffset());
        });
    } else {
        Utils.applyEditsNoLock(ctx.document(), edits, ctx.startOffset(), ctx.endOffset());
    }
}
 
Example 14
Source File: XmlMultiViewEditorSupport.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private void doSaveDocument() throws IOException {
        // code below is basically a copy-paste from XmlJ2eeEditorSupport
        
        final StyledDocument doc = getDocument();
        // dependency on xml/core
        String enc = EncodingUtil.detectEncoding(doc);
        if (enc == null) enc = "UTF8"; //!!! // NOI18N
        
        try {
            //test encoding on dummy stream
            new OutputStreamWriter(new ByteArrayOutputStream(1), enc);
            if (!checkCharsetConversion(enc)) {
                return;
            }
            super.saveDocument();
            //moved from Env.save()
// DataObject.setModified() already called as part of super.saveDocument(). The save action is now asynchronous
// in the IDE and super.saveDocument() checks for possible extra document modifications performed during save
// and sets the DO.modified flag accordingly.
//            getDataObject().setModified(false);
        } catch (UnsupportedEncodingException ex) {
            // ask user what next?
            String message = NbBundle.getMessage(XmlMultiViewEditorSupport.class,"TEXT_SAVE_AS_UTF", enc);
            NotifyDescriptor descriptor = new NotifyDescriptor.Confirmation(message);
            Object res = DialogDisplayer.getDefault().notify(descriptor);
            
            if (res.equals(NotifyDescriptor.YES_OPTION)) {
                
                // update prolog to new valid encoding
                
                try {
                    final int MAX_PROLOG = 1000;
                    int maxPrologLen = Math.min(MAX_PROLOG, doc.getLength());
                    final char prolog[] = doc.getText(0, maxPrologLen).toCharArray();
                    int prologLen = 0;  // actual prolog length
                    
                    //parse prolog and get prolog end
                    if (prolog[0] == '<' && prolog[1] == '?' && prolog[2] == 'x') {
                        
                        // look for delimitting ?>
                        for (int i = 3; i<maxPrologLen; i++) {
                            if (prolog[i] == '?' && prolog[i+1] == '>') {
                                prologLen = i + 1;
                                break;
                            }
                        }
                    }
                    
                    final int passPrologLen = prologLen;
                    
                    Runnable edit = new Runnable() {
                        public void run() {
                            try {
                                
                                doc.remove(0, passPrologLen + 1); // +1 it removes exclusive
                                doc.insertString(0, "<?xml version='1.0' encoding='UTF-8' ?> \n<!-- was: " + new String(prolog, 0, passPrologLen + 1) + " -->", null); // NOI18N
                                
                            } catch (BadLocationException e) {
                                if (System.getProperty("netbeans.debug.exceptions") != null) // NOI18N
                                    e.printStackTrace();
                            }
                        }
                    };
                    
                    NbDocument.runAtomic(doc, edit);
                    
                    super.saveDocument();
                    //moved from Env.save()
// DataObject.setModified() already called as part of super.saveDocument(). The save action is now asynchronous
// in the IDE and super.saveDocument() checks for possible extra document modifications performed during save
// and sets the DO.modified flag accordingly.
//                    getDataObject().setModified(false);
                    // need to force reloading
                    ((XmlMultiViewDataObject) getDataObject()).getDataCache().reloadData();
                    
                    
                } catch (BadLocationException lex) {
                    ErrorManager.getDefault().notify(lex);
                }
                
            } else { // NotifyDescriptor != YES_OPTION
                return;
            }
        }
    }
 
Example 15
Source File: XMLJ2eeEditorSupport.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public void saveDocument () throws IOException {
        final StyledDocument doc = getDocument();
        // dependency on xml/core
        String enc = EncodingUtil.detectEncoding(doc);
        if (enc == null) enc = "UTF8"; //!!! // NOI18N
        
        try {
            //test encoding on dummy stream
            new OutputStreamWriter(new ByteArrayOutputStream(1), enc);
            if (!checkCharsetConversion(enc)) {
                return;
            }
            super.saveDocument();
            //moved from Env.save()
// DataObject.setModified() already called as part of super.saveDocument(). The save action is now asynchronous
// in the IDE and super.saveDocument() checks for possible extra document modifications performed during save
// and sets the DO.modified flag accordingly.
//            getDataObject().setModified (false);
        } catch (UnsupportedEncodingException ex) {
            // ask user what next?
            String message = NbBundle.getMessage(XMLJ2eeEditorSupport.class,"TEXT_SAVE_AS_UTF", enc);
            NotifyDescriptor descriptor = new NotifyDescriptor.Confirmation(message);
            Object res = DialogDisplayer.getDefault().notify(descriptor);

            if (res.equals(NotifyDescriptor.YES_OPTION)) {

                // update prolog to new valid encoding                

                try {
                    final int MAX_PROLOG = 1000;                
                    int maxPrologLen = Math.min(MAX_PROLOG, doc.getLength());                
                    final char prolog[] = doc.getText(0, maxPrologLen).toCharArray();
                    int prologLen = 0;  // actual prolog length

                    //parse prolog and get prolog end                
                    if (prolog[0] == '<' && prolog[1] == '?' && prolog[2] == 'x') {

                        // look for delimitting ?>
                        for (int i = 3; i<maxPrologLen; i++) {
                            if (prolog[i] == '?' && prolog[i+1] == '>') {
                                prologLen = i + 1;
                                break;
                            }
                        }                                        
                    }

                    final int passPrologLen = prologLen;

                    Runnable edit = new Runnable() {
                         public void run() {
                             try {

                                doc.remove(0, passPrologLen + 1); // +1 it removes exclusive
                                doc.insertString(0, "<?xml version='1.0' encoding='UTF-8' ?> \n<!-- was: " + new String(prolog, 0, passPrologLen + 1) + " -->", null); // NOI18N

                             } catch (BadLocationException e) {
                                 if (System.getProperty("netbeans.debug.exceptions") != null) // NOI18N
                                     e.printStackTrace();
                             }
                         }
                    };

                    NbDocument.runAtomic(doc, edit);

                    super.saveDocument();
                    //moved from Env.save()
// DataObject.setModified() already called as part of super.saveDocument(). The save action is now asynchronous
// and super.saveDocument() checks for possible extra document modifications performed during save
// and sets the DO.modified flag accordingly.
//                    getDataObject().setModified (false);

                } catch (BadLocationException lex) {
                    Exceptions.printStackTrace(lex);
                }

            } else { // NotifyDescriptor != YES_OPTION
                return;
            }
        }
    }
 
Example 16
Source File: JavaSourceTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public void testParsingDelay() throws MalformedURLException, InterruptedException, IOException, BadLocationException {
    FileObject test = createTestFile ("Test1");
    ClassPath bootPath = createBootPath ();
    ClassPath compilePath = createCompilePath ();
    ClassPath sourcePath = createSourcePath();
    JavaSource js = JavaSource.create(ClasspathInfo.create(bootPath, compilePath, sourcePath), test);
    DataObject dobj = DataObject.find(test);
    EditorCookie ec = (EditorCookie) dobj.getCookie(EditorCookie.class);
    final StyledDocument doc = ec.openDocument();
    doc.putProperty(Language.class, JavaTokenId.language());
    TokenHierarchy h = TokenHierarchy.get(doc);
    TokenSequence ts = h.tokenSequence(JavaTokenId.language());
    Thread.sleep(500);  //It may happen that the js is invalidated before the dispatch of task is done and the test of timers may fail
    CountDownLatch[] latches = new CountDownLatch[] {
        new CountDownLatch (1),
        new CountDownLatch (1)
    };
    long[] timers = new long[2];
    AtomicInteger counter = new AtomicInteger (0);
    CancellableTask<CompilationInfo> task = new DiagnosticTask(latches, timers, counter, Phase.PARSED);
    JavaSourceAccessor.getINSTANCE().addPhaseCompletionTask (js,task,Phase.PARSED, Priority.HIGH, TaskIndexingMode.ALLOWED_DURING_SCAN);
    assertTrue ("Time out",waitForMultipleObjects(new CountDownLatch[] {latches[0]}, 15000));
    assertEquals ("Called more times than expected",1,counter.getAndSet(0));
    long start = System.currentTimeMillis();
    Thread.sleep(500);  //Making test a more deterministic, when the task is cancelled by DocListener, it's hard for test to recover from it
    NbDocument.runAtomic (doc,
        new Runnable () {
            public void run () {
                try {
                    String text = doc.getText(0,doc.getLength());
                    int index = text.indexOf(REPLACE_PATTERN);
                    assertTrue (index != -1);
                    doc.remove(index,REPLACE_PATTERN.length());
                    doc.insertString(index,"System.out.println();",null);
                } catch (BadLocationException ble) {
                    ble.printStackTrace(System.out);
                }
            }
    });
    assertTrue ("Time out",waitForMultipleObjects(new CountDownLatch[] {latches[1]}, 15000));
    assertEquals ("Called more times than expected",1,counter.getAndSet(0));
    assertTrue("Took less time than expected time=" + (timers[1] - start), (timers[1] - start) >= TestUtil.getReparseDelay());
    JavaSourceAccessor.getINSTANCE().removePhaseCompletionTask (js,task);
}
 
Example 17
Source File: EmbeddedIndexerTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public void testEmbeddingIndexerQueryOnInnerOnly() throws Exception {
    RepositoryUpdater ru = RepositoryUpdater.getDefault();
    assertEquals(0, ru.getScannedBinaries().size());
    assertEquals(0, ru.getScannedBinaries().size());
    assertEquals(0, ru.getScannedUnknowns().size());

    final RepositoryUpdaterTest.TestHandler handler = new RepositoryUpdaterTest.TestHandler();
    final Logger logger = Logger.getLogger(RepositoryUpdater.class.getName()+".tests");
    logger.setLevel (Level.FINEST);
    logger.addHandler(handler);

    srcCp = ClassPath.getClassPath(srcRoot, PATH_TOP_SOURCES);
    assertNotNull(srcCp);
    assertEquals(1, srcCp.getRoots().length);
    assertEquals(srcRoot, srcCp.getRoots()[0]);
    globalPathRegistry_register(PATH_TOP_SOURCES, srcCp);
    assertTrue (handler.await());
    assertEquals(0, handler.getBinaries().size());
    assertEquals(1, handler.getSources().size());
    assertEquals(srcRoot.toURL(), handler.getSources().get(0));

    QuerySupport sup;
    Collection<? extends IndexResult> res;
    Map<? extends Integer,? extends Integer> count;

    //Symulate EditorRegistry
    final Source src = Source.create(srcFile);
    ParserManager.parse(Collections.<Source>singleton(src), new UserTask() {
        @Override
        public void run(ResultIterator resultIterator) throws Exception {
        }
    });
    final DataObject dobj = DataObject.find(srcFile);
    final EditorCookie ec = dobj.getLookup().lookup(EditorCookie.class);
    final StyledDocument doc = ec.openDocument();
    SwingUtilities.invokeAndWait(new Runnable() {
        @Override
        public void run() {
            final JEditorPane jp = new JEditorPane() {
                @Override
                public boolean isFocusOwner() {
                    return true;
                }
            };
            jp.setDocument(doc);
            EditorApiPackageAccessor.get().register(jp);
        }
    });

    //Do modification
    NbDocument.runAtomic(doc, new Runnable() {
        @Override
        public void run() {
            try {
                doc.insertString(doc.getLength(), "<C>", null); //NOI18N
            } catch (Exception e) {
                Exceptions.printStackTrace(e);
            }
        }
    });

    //Query should be updated
    sup = QuerySupport.forRoots(InnerIndexer.NAME, InnerIndexer.VERSION, srcRoot);
    res = sup.query("_sn", srcFile.getNameExt(), QuerySupport.Kind.EXACT, (String[]) null);
    assertEquals(5,res.size());
    count = countModes(res);
    assertEquals(Integer.valueOf(1), count.get(0));
    assertEquals(Integer.valueOf(2), count.get(1));
    assertEquals(Integer.valueOf(1), count.get(2));
    assertEquals(Integer.valueOf(1), count.get(3));
}
 
Example 18
Source File: TaskProcessorTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public void testDeadlock() throws Exception {
    FileUtil.setMIMEType("foo", "text/foo");
    MockMimeLookup.setInstances(MimePath.parse("text/foo"), new FooParserFactory(), new PlainKit());
    MockMimeLookup.setInstances(MimePath.parse("text/plain"), new FooParserFactory(), new PlainKit());
    final File workingDir = getWorkDir();        
    final FileObject file = FileUtil.createData(new File(workingDir,"test.foo"));
    final Source src = Source.create(file);
    final DataObject dobj = DataObject.find(file);
    final EditorCookie ec = dobj.getLookup().lookup(EditorCookie.class);
    final StyledDocument doc = ec.openDocument();
    final CountDownLatch start_a = new CountDownLatch(1);
    final CountDownLatch start_b = new CountDownLatch(1);
    final CountDownLatch end = new CountDownLatch(1);
    final CountDownLatch taskEnded = new CountDownLatch(1);
    final Collection<Pair<SchedulerTask,Class<? extends Scheduler>>> tasks = Collections.<Pair<SchedulerTask,Class<? extends Scheduler>>>singleton(
            Pair.<SchedulerTask,Class<? extends Scheduler>>of(
        new ParserResultTask<Parser.Result>() {
            @Override
            public void run(Result result, SchedulerEvent event) {
                taskEnded.countDown();
            }

            @Override
            public int getPriority() {
                return 1000;
            }

            @Override
            public Class<? extends Scheduler> getSchedulerClass() {
                return null;
            }

            @Override
            public void cancel() {
            }                    
        }, null));
    TaskProcessor.addPhaseCompletionTasks(
            tasks,
            SourceAccessor.getINSTANCE().getCache(src),
            true);
    taskEnded.await();
    final Thread t = new Thread () {
        @Override
        public void run() {
            NbDocument.runAtomic(doc, new Runnable() {
                @Override
                public void run() {
                    start_a.countDown();
                    try {
                        start_b.await();
                        synchronized(TaskProcessor.INTERNAL_LOCK) {
                            end.await();
                        }
                    } catch (InterruptedException ex) {
                        Exceptions.printStackTrace(ex);
                    }
                }
            });                    
        }
    };
    t.start();        
    synchronized(TaskProcessor.INTERNAL_LOCK) {
        start_b.countDown();
        start_a.await();
        SourceAccessor.getINSTANCE().getCache(src).invalidate();
        TaskProcessor.removePhaseCompletionTasks(Collections.<SchedulerTask>singleton(tasks.iterator().next().first()), src);
    }
    end.countDown();
}
 
Example 19
Source File: JavaSourceTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public void testDocumentChanges () throws Exception {
    FileObject testFile1 = createTestFile ("Test1");
    ClassPath bootPath = createBootPath ();
    ClassPath compilePath = createCompilePath ();
    ClassPath srcPath = createSourcePath();
    JavaSource js1 = JavaSource.create(ClasspathInfo.create(bootPath, compilePath, srcPath), testFile1);

    final CountDownLatch start = new CountDownLatch (1);
    final CountDownLatch stop =  new CountDownLatch (1);
    final AtomicBoolean last = new AtomicBoolean (false);
    final AtomicInteger counter = new AtomicInteger (0);

    CancellableTask<CompilationInfo> task = new CancellableTask<CompilationInfo>() {

        private int state = 0;

        public void cancel() {
        }

        public void run(CompilationInfo ci) throws Exception {
            switch (state) {
                case 0:
                    state = 1;
                    start.countDown();
                    break;
                case 1:
                    counter.incrementAndGet();
                    if (last.get()) {
                        stop.countDown();
                    }
                    break;
            }
        }
    };
    JavaSourceAccessor.getINSTANCE().addPhaseCompletionTask(js1,task,Phase.PARSED,Priority.HIGH, TaskIndexingMode.ALLOWED_DURING_SCAN);
    start.await();
    Thread.sleep(500);
    final DataObject dobj = DataObject.find(testFile1);
    final EditorCookie ec = (EditorCookie) dobj.getCookie(EditorCookie.class);
    final StyledDocument doc = ec.openDocument();
    doc.putProperty(Language.class, JavaTokenId.language());
    TokenHierarchy h = TokenHierarchy.get(doc);
    TokenSequence ts = h.tokenSequence(JavaTokenId.language());
    for (int i=0; i<10; i++) {
        if (i == 9) {
            last.set(true);
        }
        NbDocument.runAtomic (doc,
            new Runnable () {
                public void run () {
                    try {
                        doc.insertString(0," ",null);
                    } catch (BadLocationException ble) {
                        ble.printStackTrace(System.out);
                    }
                }
        });
        Thread.sleep(100);
    }
    assertTrue ("Time out",stop.await(15000, TimeUnit.MILLISECONDS));
    assertEquals("Called more time than expected",1,counter.get());
    JavaSourceAccessor.getINSTANCE().removePhaseCompletionTask(js1,task);
}
 
Example 20
Source File: JavaSourceTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public void testInterference () throws MalformedURLException, IOException, InterruptedException {
    FileObject testFile1 = createTestFile ("Test1");
    FileObject testFile2 = createTestFile ("Test2");
    ClassPath bootPath = createBootPath ();
    ClassPath compilePath = createCompilePath ();
    ClassPath srcPath = createSourcePath();
    JavaSource js1 = JavaSource.create(ClasspathInfo.create(bootPath, compilePath, srcPath), testFile1);
    JavaSource js2 = JavaSource.create(ClasspathInfo.create(bootPath, compilePath, srcPath), testFile2);
    DataObject dobj = DataObject.find(testFile1);
    EditorCookie ec = (EditorCookie) dobj.getCookie(EditorCookie.class);
    final StyledDocument doc = ec.openDocument();
    doc.putProperty(Language.class, JavaTokenId.language());
    TokenHierarchy h = TokenHierarchy.get(doc);
    TokenSequence ts = h.tokenSequence(JavaTokenId.language());
    Thread.sleep(500);
    CountDownLatch[] latches1 = new CountDownLatch[] {
        new CountDownLatch (1),
        new CountDownLatch (1),
    };
    CountDownLatch[] latches2 = new CountDownLatch[] {
        new CountDownLatch (1),
    };
    CountDownLatch latch3 = new CountDownLatch (1);
    AtomicInteger counter = new AtomicInteger (0);

    DiagnosticTask task1 = new DiagnosticTask(latches1, counter, Phase.RESOLVED);
    CancellableTask<CompilationInfo> task2 = new DiagnosticTask(latches2, counter, Phase.RESOLVED);

    JavaSourceAccessor.getINSTANCE().addPhaseCompletionTask(js1,task1,Phase.RESOLVED,Priority.HIGH, TaskIndexingMode.ALLOWED_DURING_SCAN);
    Thread.sleep(500);  //Making test a more deterministic, when the task is cancelled by DocListener, it's hard for test to recover from it
    js2.runUserActionTask(new CompileControlJob(latch3),true);
    JavaSourceAccessor.getINSTANCE().addPhaseCompletionTask(js2,task2,Phase.RESOLVED,Priority.MAX, TaskIndexingMode.ALLOWED_DURING_SCAN);
    boolean result = waitForMultipleObjects (new CountDownLatch[] {latches1[0], latches2[0], latch3}, 15000);
    if (!result) {
        assertTrue (String.format("Time out, latches1[0]: %d latches2[0]: %d latches3: %d",latches1[0].getCount(), latches2[0].getCount(), latch3.getCount()), false);
    }
    assertEquals ("Called more times than expected",2,counter.getAndSet(0));

    Thread.sleep(500);  //Making test a more deterministic, when the task is cancelled by DocListener, it's hard for test to recover from it
    NbDocument.runAtomic (doc,
        new Runnable () {
            public void run () {
                try {
                    String text = doc.getText(0,doc.getLength());
                    int index = text.indexOf(REPLACE_PATTERN);
                    assertTrue (index != -1);
                    doc.remove(index,REPLACE_PATTERN.length());
                    doc.insertString(index,"System.out.println();",null);
                } catch (BadLocationException ble) {
                    ble.printStackTrace(System.out);
                }
            }
    });
    assertTrue ("Time out",waitForMultipleObjects(new CountDownLatch[] {latches1[1]}, 15000));
    assertEquals ("Called more times than expected",1,counter.getAndSet(0));
    JavaSourceAccessor.getINSTANCE().removePhaseCompletionTask(js1,task1);
    JavaSourceAccessor.getINSTANCE().removePhaseCompletionTask(js2,task2);
}