Java Code Examples for javax.swing.text.StyledDocument#putProperty()

The following examples show how to use javax.swing.text.StyledDocument#putProperty() . 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: DataEditorSupport.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/** Let's the super method create the document and also annotates it
* with Title and StreamDescription properties.
*
* @param kit kit to user to create the document
* @return the document annotated by the properties
*/
@Override
protected StyledDocument createStyledDocument (EditorKit kit) {
    StyledDocument doc = super.createStyledDocument (kit);
        
    // set document name property
    doc.putProperty(Document.TitleProperty,
        FileUtil.getFileDisplayName(obj.getPrimaryFile())
    );
    // set dataobject to stream desc property
    doc.putProperty(Document.StreamDescriptionProperty,
        obj
    );
    
    //Report the document into the Timers&Counters window:
    Logger.getLogger("TIMER").log(Level.FINE, "Document", new Object[] {obj.getPrimaryFile(), doc});
    
    return doc;
}
 
Example 2
Source File: DataEditorSupport.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Called from the <code>EnvListener</code>.
 */
final void updateDocumentProperty () {
    //Update document TitleProperty
    EditorCookie ec = getDataObject().getCookie(EditorCookie.class);
    if (ec != null) {
        StyledDocument doc = ec.getDocument();
        if (doc != null) {
            doc.putProperty(Document.TitleProperty,
            FileUtil.getFileDisplayName(getDataObject().getPrimaryFile()));
        }
    }
}
 
Example 3
Source File: GsfDataObject.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
protected StyledDocument createStyledDocument (EditorKit kit) {
    StyledDocument doc = super.createStyledDocument(kit);
    // Enter the file object in to InputAtrributes. It can be used by lexer.
    InputAttributes attributes = new InputAttributes();
    FileObject fileObject = NbEditorUtilities.getFileObject(doc);
    final GsfLanguage lng = language.getGsfLanguage();
    if (lng != null) {
        attributes.setValue(lng.getLexerLanguage(), FileObject.class, fileObject, false);
    }
    doc.putProperty(InputAttributes.class, attributes);
    return doc;
}
 
Example 4
Source File: PropertiesEditorSupport.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Called from the <code>EnvironmentListener</code>.
 */
final void updateDocumentProperty () {
    //Update document TitleProperty
    EditorCookie ec = getDataObject().getCookie(EditorCookie.class);
    if (ec != null) {
        StyledDocument doc = ec.getDocument();
        if (doc != null) {
            doc.putProperty(Document.TitleProperty,
            FileUtil.getFileDisplayName(getDataObject().getPrimaryFile()));
        }
    }
}
 
Example 5
Source File: JavaSourceTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public void testPhaseCompletionTask () throws MalformedURLException, InterruptedException, IOException {
    FileObject test = createTestFile ("Test1");
    ClassPath bootPath = createBootPath ();
    ClassPath compilePath = createCompilePath ();
    ClassPath srcPath = createSourcePath ();
    JavaSource js = JavaSource.create(ClasspathInfo.create(bootPath, compilePath, srcPath), 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);
    CountDownLatch[] latches1 = new CountDownLatch[] {
        new CountDownLatch (1),
        new CountDownLatch (1)
    };
    CountDownLatch[] latches2 = new CountDownLatch[] {
        new CountDownLatch (1),
        new CountDownLatch (1)
    };
    AtomicInteger counter = new AtomicInteger (0);
    CancellableTask<CompilationInfo> task1 = new DiagnosticTask(latches1, counter, Phase.RESOLVED);
    CancellableTask<CompilationInfo> task2 =  new DiagnosticTask(latches2, counter, Phase.PARSED);
    JavaSourceAccessor.getINSTANCE().addPhaseCompletionTask(js,task1,Phase.RESOLVED,Priority.HIGH, TaskIndexingMode.ALLOWED_DURING_SCAN);
    JavaSourceAccessor.getINSTANCE().addPhaseCompletionTask(js,task2,Phase.PARSED,Priority.LOW, TaskIndexingMode.ALLOWED_DURING_SCAN);
    assertTrue ("Time out",waitForMultipleObjects(new CountDownLatch[] {latches1[0], latches2[0]}, 150000));
    assertEquals ("Called more times than expected",2,counter.getAndSet(0));
    Thread.sleep(1000);  //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], latches2[1]}, 15000));
    assertEquals ("Called more times than expected",2,counter.getAndSet(0));
    JavaSourceAccessor.getINSTANCE().removePhaseCompletionTask (js,task1);
    JavaSourceAccessor.getINSTANCE().removePhaseCompletionTask (js,task2);
}
 
Example 6
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);
}
 
Example 7
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 8
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 9
Source File: JavaSourceTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public void testIndexCancel2() throws Exception {
    final IndexFactory oldFactory = IndexManagerTestUtilities.getIndexFactory();
    final TestIndexFactory factory = new TestIndexFactory();
    IndexManagerTestUtilities.setIndexFactory(factory);
    try {
        FileObject test = createTestFile ("Test1");
        final ClassPath bootPath = createBootPath ();
        final ClassPath compilePath = createCompilePath ();
        final ClassPath sourcePath = createSourcePath ();
        final GlobalPathRegistry regs = GlobalPathRegistry.getDefault();
        regs.register(ClassPath.SOURCE, new ClassPath[]{sourcePath});
        try {
            ClassLoader l = JavaSourceTest.class.getClassLoader();
            Lkp.DEFAULT.setLookupsWrapper(
                Lookups.metaInfServices(l),
                Lookups.singleton(l),
                Lookups.singleton(new ClassPathProvider() {
                @Override
                public ClassPath findClassPath(FileObject file, String type) {
                    if (ClassPath.BOOT == type) {
                        return bootPath;
                    }

                    if (ClassPath.SOURCE == type) {
                        return sourcePath;
                    }

                    if (ClassPath.COMPILE == type) {
                        return compilePath;
                    }
                    return null;
                }
            }));


            JavaSource js = JavaSource.create(ClasspathInfo.create(bootPath, compilePath, sourcePath), test);
            IndexingManager.getDefault().refreshIndexAndWait(sourcePath.getRoots()[0].getURL(), null);
            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

            final CountDownLatch ready = new CountDownLatch(1);
            final CountDownLatch change = new CountDownLatch(1);
            final CountDownLatch end = new CountDownLatch (1);
            final AtomicReference<Set<String>> result = new AtomicReference<Set<String>>(Collections.<String>emptySet());
            final ThreadLocal<Boolean> me = new ThreadLocal<Boolean>();

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

                @Override
                public void cancel() {
                    if (me.get() == Boolean.TRUE) {
                        change.countDown();
                    }
                }

                @Override
                public void run(CompilationInfo p) throws Exception {
                    ready.countDown();
                    change.await();
                    ClassIndex index = p.getClasspathInfo().getClassIndex();
                    result.set(index.getPackageNames("javax", true, EnumSet.allOf(ClassIndex.SearchScope.class)));
                    end.countDown();
                }

            };
            factory.instance.active=true;
            JavaSourceAccessor.getINSTANCE().addPhaseCompletionTask (js,task,Phase.PARSED, Priority.HIGH, TaskIndexingMode.ALLOWED_DURING_SCAN);
            assertTrue(ready.await(5, TimeUnit.SECONDS));
            me.set(Boolean.TRUE);
            try {
                js.runUserActionTask( new Task<CompilationController>() {
                        @Override
                        public void run (final CompilationController info) {                            
                        }
                }, true);
            } finally {
                me.remove();
            }
            assertTrue(end.await(5, TimeUnit.SECONDS));
            assertNull(result.get());
            JavaSourceAccessor.getINSTANCE().removePhaseCompletionTask (js,task);
        } finally {
            regs.unregister(ClassPath.SOURCE, new ClassPath[]{sourcePath});
        }
    } finally {
        IndexManagerTestUtilities.setIndexFactory(oldFactory);
    }
}
 
Example 10
Source File: EditToBeUndoneRedoneTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public void testUndoRedoUndoEdits() throws Exception {

        final StyledDocument d = support.openDocument();

        UndoRedo.Manager ur = support.getUndoRedo();
        UndoRedoManager urMgr = null;

        if (ur instanceof UndoRedoManager) {
            urMgr = (UndoRedoManager) ur;
        }

        d.insertString(d.getLength(), "a", null);
        final CompoundEdit bigEdit = new CompoundEdit();
        d.insertString(d.getLength(), "b", null);
        bigEdit.end();
        support.saveDocument();

        // setting the property to populate urMgr.onSaveTasksEdit field
        d.putProperty("beforeSaveRunnable", new Runnable() {

            public void run() {
                Runnable beforeSaveStart = (Runnable) d.getProperty("beforeSaveStart");
                if (beforeSaveStart != null) {
                    beforeSaveStart.run();
                    support.getUndoRedo().undoableEditHappened(new UndoableEditEvent(d, bigEdit));
                }
            }
        });

        urMgr.undo();
        support.saveDocument();
        d.putProperty("beforeSaveRunnable", null);
        assertEquals("after undo data", "a", d.getText(0, d.getLength()));

        urMgr.redo();
        support.saveDocument();
        assertEquals("after redo data", "ab", d.getText(0, d.getLength()));

        urMgr.undo();
        assertEquals("after redo data", "a", d.getText(0, d.getLength()));
    }
 
Example 11
Source File: ParsinApiInteractionTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public void testRunWhenScanFinishGetCalledUnderCCLock() throws Exception {
    final File wd = getWorkDir();
    final File srcDir = new File (wd,"src");
    srcDir.mkdirs();
    final File file = new File (srcDir,"test.foo");
    file.createNewFile();
    FileUtil.setMIMEType("foo", "text/foo");
    MockMimeLookup.setInstances(MimePath.parse("text/foo"), new FooParserFactory(), new PlainKit());
    final FileObject fo = FileUtil.toFileObject(file);
    final DataObject dobj = DataObject.find(fo);
    final EditorCookie ec = dobj.getLookup().lookup(EditorCookie.class);
    final StyledDocument doc = ec.openDocument();
    final Source src = Source.create(doc);
    final CountDownLatch ruRunning = new CountDownLatch(1);
    final CountDownLatch rwsfCalled = new CountDownLatch(1);
    final AtomicReference<Set<RepositoryUpdater.IndexingState>> indexing = new AtomicReference<Set<RepositoryUpdater.IndexingState>>();
    final IndexingUtils.IndexingStatus is = new IndexingUtils.IndexingStatus() {
        @Override
        public Set<? extends RepositoryUpdater.IndexingState> getIndexingState() {
            return indexing.get();
        }
    };
    IndexingUtils.setIndexingStatus(is);
    RepositoryUpdaterTestSupport.runAsWork(
            new Runnable(){
                @Override
                public void run() {
                    indexing.set(EnumSet.of(RepositoryUpdater.IndexingState.WORKING));
                    try {
                        ruRunning.countDown();
                        rwsfCalled.await();
                    } catch (InterruptedException ie) {
                    } finally {
                        indexing.set(EnumSet.noneOf(RepositoryUpdater.IndexingState.class));
                    }
                }
            });
    ruRunning.await();
    doc.putProperty("completion-active", Boolean.TRUE);
    try {
        final Future<Void> done = ParserManager.parseWhenScanFinished(Collections.<Source>singleton(src),new UserTask() {
            @Override
            public void run(ResultIterator resultIterator) throws Exception {                    
            }
    });
    assertFalse(done.isDone());
    assertFalse(done.isCancelled());
    rwsfCalled.countDown();
    try {
        done.get(5, TimeUnit.SECONDS);
    } catch (TimeoutException te) {
        assertTrue("Deadlock",false);
    }
    } finally {
        doc.putProperty("completion-active", null);
    }
}