Java Code Examples for org.openide.cookies.EditorCookie#openDocument()

The following examples show how to use org.openide.cookies.EditorCookie#openDocument() . 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: ErrorHintsProviderTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private void performTest(String name, boolean specialMacTreatment) throws Exception {
    prepareTest(name);
    
    DataObject testData = DataObject.find(testSource);
    EditorCookie ec = testData.getLookup().lookup(EditorCookie.class);
    Document doc = ec.openDocument();
    
    doc.putProperty(Language.class, JavaTokenId.language());
    
    for (ErrorDescription ed : new ErrorHintsProvider().computeErrors(info, doc, Utilities.JAVA_MIME_TYPE))
        ref(ed.toString().replaceAll("\\p{Space}*:\\p{Space}*", ":"));

    if (!org.openide.util.Utilities.isMac() && specialMacTreatment) {
        compareReferenceFiles(this.getName()+".ref",this.getName()+"-nonmac.pass",this.getName()+".diff");
    } else {
        compareReferenceFiles();
    }
}
 
Example 2
Source File: DocumentTitlePropertyTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/** Test updating document property Document.TitleProperty when dataobject is moved */
public void testMove () throws IOException {
    FileUtil.createData(FileUtil.getConfigRoot(), "someFolder/someFile.obj");
    FileUtil.createFolder(FileUtil.getConfigRoot(), "newFolder");

    DataObject obj = DataObject.find(FileUtil.getConfigFile("someFolder/someFile.obj"));
    DataFolder dFolder = (DataFolder) DataObject.find(FileUtil.getConfigFile("newFolder"));

    assertEquals( MyDataObject.class, obj.getClass());
    assertTrue( "we need UniFileLoader", obj.getLoader() instanceof UniFileLoader );

    EditorCookie ec = obj.getCookie(EditorCookie.class);

    StyledDocument doc = ec.openDocument();

    String val = (String) doc.getProperty(Document.TitleProperty);
    assertTrue("Test property value", val.startsWith("someFolder/someFile.obj"));

    obj.move(dFolder);

    val = (String) doc.getProperty(Document.TitleProperty);
    assertTrue("Test property value", val.startsWith("newFolder/someFile.obj"));
}
 
Example 3
Source File: AbstractTestUtil.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/** Converts DataObject to String.
 */
public static String dataObjectToString(DataObject dataObject) throws IOException, BadLocationException {
    EditorCookie editorCookie = (EditorCookie) dataObject.getCookie(EditorCookie.class);
    
    if (editorCookie != null) {
        StyledDocument document = editorCookie.openDocument();
        if (document != null) {
            return  document.getText(0, document.getLength());
        }
    }
    return null;
}
 
Example 4
Source File: SourceTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private Document openDocument(FileObject f) {
    try {
        DataObject dataObject = DataObject.find(f);
        EditorCookie ec = dataObject.getLookup().lookup(EditorCookie.class);
        return ec.openDocument();
    } catch (IOException ex) {
        throw new IllegalStateException(ex);
    }
}
 
Example 5
Source File: XMLDataObjectMimeTypeTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testForUnknownContent() throws Exception {
    XMLDataLoader l = XMLDataLoader.getLoader(XMLDataLoader.class);
    l.getExtensions().addExtension(getName());
    
    setUp("content/unknown");
    EditorCookie cook = obj.getCookie(EditorCookie.class);
    StyledDocument doc = cook.openDocument();
    assertEquals("text/plain+xml", doc.getProperty("mimeType"));
}
 
Example 6
Source File: DataEditorSupportMoveTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testModifiedMove() throws Exception {
    FileObject root = FileUtil.toFileObject(getWorkDir());
    FileObject data = FileUtil.createData(root, "someFolder/someFile.obj");
    
    DataObject obj = DataObject.find(data);
    assertEquals( MyDataObject.class, obj.getClass());
    assertEquals(MyLoader.class, obj.getLoader().getClass());
    
    EditorCookie ec = obj.getLookup().lookup(EditorCookie.class);
    assertNotNull("Editor cookie found", ec);
    ec.open();
    JEditorPane[] arr = openedPanes(ec);
    assertEquals("One pane is opened", 1, arr.length);
            
    StyledDocument doc = ec.openDocument();
    doc.insertString(0, "Ahoj", null);
    assertTrue("Modified", obj.isModified());
    Thread.sleep(100);
    
    FileObject newFolder = FileUtil.createFolder(root, "otherFolder");
    DataFolder df = DataFolder.findFolder(newFolder);
    
    obj.move(df);
    
    assertEquals(newFolder, obj.getPrimaryFile().getParent());
    
    assertEquals("Still one editor", 1, openedPanes(ec).length);
    DD.assertNoCalls();
}
 
Example 7
Source File: DataObjectSyncSupport.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private void loadTextRepresentation() {
    if ( getDO().isValid() ) { // because of remove modified document
        try {
            EditorCookie editor = getDO().getCookie(EditorCookie.class);
            editor.openDocument();
        } catch (IOException ex) {
            //??? ignore it just now
        }
    }
}
 
Example 8
Source File: I18nSupport.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/** Loads document if was not get in constructor should be called after creation if the
 * work on document is necessary. */
private void loadDocument() throws IOException {
    if (document == null) {
        EditorCookie editorCookie = sourceDataObject.getCookie(EditorCookie.class);

        if (editorCookie == null) {
            throw new IllegalArgumentException("I18N: Illegal data object type"+ sourceDataObject); // NOI18N
        }
        
        document = editorCookie.openDocument();
    }
}
 
Example 9
Source File: Util.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static Document getDocument(FileObject f) throws IOException {
    try {
        DataObject d = DataObject.find(f);
        EditorCookie ec = d.getCookie(EditorCookie.class);
        Document doc = ec.openDocument();
        if (doc == null) {
            throw new IOException("Document cannot be opened for : " + f.getPath());
        }
        return doc;
    } catch (DataObjectNotFoundException ex) {
        throw new IOException("DataObject does not exist for : " + f.getPath());
    }
}
 
Example 10
Source File: IndentCasesTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private EditorOperator openFile(String fileName) throws DataObjectNotFoundException, IOException {
    File file = new File(new File(projectDir, "web"), fileName);
    DataObject dataObj = DataObject.find(FileUtil.toFileObject(file));
    EditorCookie ed = dataObj.getCookie(EditorCookie.class);
    doc = (BaseDocument) ed.openDocument();
    ed.open();
    EditorOperator operator = new EditorOperator(file.getName());
    return operator;
}
 
Example 11
Source File: Utilities.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static String getAsString(String file) {
    String result;
    try {
        FileObject testFile = Repository.getDefault().findResource(file);
        DataObject DO = DataObject.find(testFile);
        
        EditorCookie ec=(EditorCookie)(DO.getCookie(EditorCookie.class));
        StyledDocument doc=ec.openDocument();
        result=doc.getText(0, doc.getLength());
        //            result=Common.unify(result);
    } catch (Exception e){
        throw new AssertionFailedErrorException(e);
    }
    return result;
}
 
Example 12
Source File: SemanticHighlightTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private void checkCurrentColorSettings() throws IOException {
String path  = "/projects/"+projectName+"/src/"+curPackage.replace('.','/')+"/"+testClass+".java";	
File testFile = new File(getDataDir(),path);
FileObject fo = FileUtil.toFileObject(testFile);
DataObject d = DataObject.find(fo);
final EditorCookie ec = (EditorCookie)d.getCookie(EditorCookie.class);
ec.open();
StyledDocument doc = ec.openDocument();
       //wait for semantic higlight initialization
       new org.netbeans.jemmy.EventTool().waitNoEvent(2000);
       dumpColorsForDocument(doc);

   }
 
Example 13
Source File: GuardedBlockTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
/**
 * #119962: Guarded Exception
 */
public void test119962() throws Exception {
    testFile = new File(getWorkDir(), "Test.java");
    TestUtilities.copyStringToFile(testFile, 
        "package test;\n" +
        "\n" +
        "public class NewJFrame extends javax.swing.JFrame {\n" +
        "    private String str;\n" +
        "    \n" +
        "    // <editor-fold defaultstate=\"collapsed\" desc=\"Generated Code\">//GEN-BEGIN:initComponents\n" +
        "    private void initComponents() {\n" +
        "\n" +
        "        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);\n" +
        "\n" +
        "        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());\n" +
        "        getContentPane().setLayout(layout);\n" +
        "        layout.setHorizontalGroup(\n" +
        "            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)\n" +
        "            .addGap(0, 400, Short.MAX_VALUE)\n" +
        "        );\n" +
        "        layout.setVerticalGroup(\n" +
        "            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)\n" +
        "            .addGap(0, 300, Short.MAX_VALUE)\n" +
        "        );\n" +
        "\n" +
        "        pack();\n" +
        "    }// </editor-fold>//GEN-END:initComponents\n" +
        "    // Variables declaration - do not modify//GEN-BEGIN:variables\n" +
        "    // End of variables declaration//GEN-END:variables\n" +
        "}"
    );
    DataObject dataObject = DataObject.find(FileUtil.toFileObject(testFile));
    EditorCookie editorCookie = ((GuardedDataObject) dataObject).getCookie(EditorCookie.class);
    Document doc = editorCookie.openDocument();
    String golden = 
        "package test;\n" +
        "\n" +
        "public class NewJFrame extends javax.swing.JFrame {\n" +
        "    private String str;\n" +
        "    \n" +
        "    // <editor-fold defaultstate=\"collapsed\" desc=\"Generated Code\">//GEN-BEGIN:initComponents\n" +
        "    private void initComponents() {\n" +
        "\n" +
        "        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);\n" +
        "\n" +
        "        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());\n" +
        "        getContentPane().setLayout(layout);\n" +
        "        layout.setHorizontalGroup(\n" +
        "            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)\n" +
        "            .addGap(0, 400, Short.MAX_VALUE)\n" +
        "        );\n" +
        "        layout.setVerticalGroup(\n" +
        "            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)\n" +
        "            .addGap(0, 300, Short.MAX_VALUE)\n" +
        "        );\n" +
        "\n" +
        "        pack();\n" +
        "    }// </editor-fold>//GEN-END:initComponents\n" +
        "\n" +
        "    public void actionPerformed(ActionEvent e) {\n" +
        "    }\n" +
        "    // Variables declaration - do not modify//GEN-BEGIN:variables\n" +
        "    // End of variables declaration//GEN-END:variables\n" +
        "}";
    
    JavaSource src = getJavaSource(testFile);
    Task<WorkingCopy> task = new Task<WorkingCopy>() {

        public void run(WorkingCopy workingCopy) throws IOException {
            workingCopy.toPhase(RESOLVED);
            CompilationUnitTree cut = workingCopy.getCompilationUnit();
            TreeMaker make = workingCopy.getTreeMaker();
            ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
            MethodTree newMethod = make.Method(
                    make.Modifiers(Collections.<Modifier>singleton(Modifier.PUBLIC)),
                    "actionPerformed",
                    make.PrimitiveType(TypeKind.VOID),
                    Collections.<TypeParameterTree>emptyList(),
                    Collections.<VariableTree>singletonList(
                        make.Variable(
                            make.Modifiers(Collections.<Modifier>emptySet()),
                            "e", 
                            make.Identifier("ActionEvent"), 
                        null)
                    ),
                    Collections.<ExpressionTree>emptyList(),
                    make.Block(Collections.<StatementTree>emptyList(), false),
                    null // default value - not applicable
            ); 
            workingCopy.rewrite(clazz, make.addClassMember(clazz, newMethod));
        }
    };
    src.runModificationTask(task).commit();
    editorCookie.saveDocument();
    String res = TestUtilities.copyFileToString(testFile);
    //System.err.println(res);
    assertEquals(golden, res);
}
 
Example 14
Source File: UtilsTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private void assertContent(String expectedContent, FileObject sourceFile) throws Exception {
    EditorCookie ec = sourceFile.getLookup().lookup(EditorCookie.class);
    StyledDocument doc = ec.openDocument();
    assertEquals(expectedContent,
                 doc.getText(0, doc.getLength()));
}
 
Example 15
Source File: GuardedBlockTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
/**
 * #177824: Guarded Exception
 */
public void testInsertMethodBeforeVariablesBug177824() throws Exception {

    String source =
        "package test;\n" +
        "\n" +
        "import java.awt.event.ActionEvent;\n" +
        "import java.awt.event.ActionListener;\n" +
        "\n" +
        "public class Guarded1 implements ActionListener {\n" +
        "    \n" +
        "    private void fooActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_fooActionPerformed\n" +
        "    }//GEN-LAST:event_fooActionPerformed\n" +
        "\n" +
        "    // Variables declaration - do not modify//GEN-BEGIN:variables\n" +
        "    private javax.swing.JButton jButton1;\n" +
        "    // End of variables declaration//GEN-END:variables\n" +
        "}\n";

    testFile = new File(getWorkDir(), "Test.java");
    TestUtilities.copyStringToFile(testFile, source);
    DataObject dataObject = DataObject.find(FileUtil.toFileObject(testFile));
    EditorCookie editorCookie = ((GuardedDataObject) dataObject).getCookie(EditorCookie.class);
    Document doc = editorCookie.openDocument();
    String golden =
        "package test;\n" +
        "\n" +
        "import java.awt.event.ActionEvent;\n" +
        "import java.awt.event.ActionListener;\n" +
        "\n" +
        "public class Guarded1 implements ActionListener {\n" +
        "    \n" +
        "    private void fooActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_fooActionPerformed\n" +
        "    }//GEN-LAST:event_fooActionPerformed\n" +
        "\n" +
        "    public String toString() {\n" +
        "    }\n" +
        "\n" +
        "    // Variables declaration - do not modify//GEN-BEGIN:variables\n" +
        "    private javax.swing.JButton jButton1;\n" +
        "    // End of variables declaration//GEN-END:variables\n" +
        "}\n";

    JavaSource src = getJavaSource(testFile);
    Task<WorkingCopy> task = new Task<WorkingCopy>() {

        public void run(WorkingCopy workingCopy) throws IOException {
            workingCopy.toPhase(RESOLVED);
            CompilationUnitTree cut = workingCopy.getCompilationUnit();
            TreeMaker make = workingCopy.getTreeMaker();
            ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
            MethodTree newMethod = make.Method(
                    make.Modifiers(Collections.<Modifier>singleton(Modifier.PUBLIC)),
                    "toString",
                    make.Type("java.lang.String"),
                    Collections.<TypeParameterTree>emptyList(),
                    Collections.<VariableTree>emptyList(),
                    Collections.<ExpressionTree>emptyList(),
                    make.Block(Collections.<StatementTree>emptyList(), false),
                    null // default value - not applicable
            );
            ClassTree copy = make.insertClassMember(clazz, 2, newMethod);
            workingCopy.rewrite(clazz, copy);
        }
    };
    src.runModificationTask(task).commit();
    editorCookie.saveDocument();
    String res = TestUtilities.copyFileToString(testFile);
    assertEquals(golden, res);
}
 
Example 16
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 17
Source File: HintTestBase.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private CompilationInfo parse(FileObject file) throws DataObjectNotFoundException, IllegalArgumentException, IOException {
    DataObject od = DataObject.find(file);
    EditorCookie ec = od.getLookup().lookup(EditorCookie.class);

    assertNotNull(ec);

    Document doc = ec.openDocument();

    doc.putProperty(Language.class, JavaTokenId.language());
    doc.putProperty("mimeType", "text/x-java");

    JavaSource js = JavaSource.create(ClasspathInfo.create(file), file);

    assertNotNull("found JavaSource for " + file, js);

    final DeadlockTask bt = new DeadlockTask(Phase.RESOLVED);

    js.runUserActionTask(bt, true);
    
    return bt.info;
}
 
Example 18
Source File: PartialReparseTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private void doRunTest(String code, String inject, Consumer<CompilationInfo> callback) throws Exception {
    FileObject srcDir = FileUtil.createMemoryFileSystem().getRoot();
    FileObject src = srcDir.createData("Test.java");
    try (Writer out = new OutputStreamWriter(src.getOutputStream())) {
        out.write(code.replaceFirst("^", "").replaceFirst("^", ""));
    }
    EditorCookie ec = src.getLookup().lookup(EditorCookie.class);
    Document doc = ec.openDocument();
    JavaSource source = JavaSource.forFileObject(src);
    Object[] topLevel = new Object[1];
    source.runUserActionTask(cc -> {
        cc.toPhase(Phase.RESOLVED);
        topLevel[0] = cc.getCompilationUnit();
        callback.accept(cc);
    }, true);
    int startReplace = code.indexOf('^');
    int endReplace = code.indexOf('^', startReplace + 1) + 1;
    doc.remove(startReplace, endReplace - startReplace);
    doc.insertString(startReplace, inject, null);
    AtomicReference<List<TreeDescription>> actualTree = new AtomicReference<>();
    AtomicReference<List<DiagnosticDescription>> actualDiagnostics = new AtomicReference<>();
    AtomicReference<List<Long>> actualLineMap = new AtomicReference<>();
    source.runUserActionTask(cc -> {
        cc.toPhase(Phase.RESOLVED);
        assertSame(topLevel[0], cc.getCompilationUnit());
        actualTree.set(dumpTree(cc));
        actualDiagnostics.set(dumpDiagnostics(cc));
        actualLineMap.set(dumpLineMap(cc));
        callback.accept(cc);
    }, true);
    ec.saveDocument();
    ec.close();
    AtomicReference<List<TreeDescription>> expectedTree = new AtomicReference<>();
    AtomicReference<List<DiagnosticDescription>> expectedDiagnostics = new AtomicReference<>();
    AtomicReference<List<Long>> expectedLineMap = new AtomicReference<>();
    source.runUserActionTask(cc -> {
        cc.toPhase(Phase.RESOLVED);
        assertNotSame(topLevel[0], cc.getCompilationUnit());
        expectedTree.set(dumpTree(cc));
        expectedDiagnostics.set(dumpDiagnostics(cc));
        expectedLineMap.set(dumpLineMap(cc));
        callback.accept(cc);
    }, true);
    assertEquals(expectedTree.get(), actualTree.get());
    assertEquals(expectedDiagnostics.get(), actualDiagnostics.get());
    assertEquals(expectedLineMap.get(), actualLineMap.get());
}
 
Example 19
Source File: ComputeImportsTest.java    From netbeans with Apache License 2.0 3 votes vote down vote up
private void doTest(String name, String sourceLevel, Iterable<FileData> files, String unfilteredPass, String filteredPass) throws Exception {
    prepareTest(name, sourceLevel, files);

    DataObject testDO = DataObject.find(testSource);
    EditorCookie ec = testDO.getCookie(EditorCookie.class);
    
    assertNotNull(ec);
    
    Document doc = ec.openDocument();
    
    Pair<Map<String, List<Element>>, Map<String, List<Element>>> candidates = new ComputeImports(info).computeCandidates();
    
    assertEquals(unfilteredPass, dump(candidates.b));
    assertEquals(filteredPass, dump(candidates.a));
}
 
Example 20
Source File: BulkSearchTestPerformer.java    From netbeans with Apache License 2.0 3 votes vote down vote up
private void prepareTest(String fileName, String code) throws Exception {
    clearWorkDir();

    FileUtil.refreshFor(File.listRoots());

    FileObject workFO = FileUtil.toFileObject(getWorkDir());

    assertNotNull(workFO);

    workFO.refresh();

    sourceRoot = workFO.createFolder("src");
    FileObject buildRoot  = workFO.createFolder("build");
    FileObject cache = workFO.createFolder("cache");

    FileObject data = FileUtil.createData(sourceRoot, fileName);
    File dataFile = FileUtil.toFile(data);

    assertNotNull(dataFile);

    TestUtilities.copyStringToFile(dataFile, code);

    SourceUtilsTestUtil.prepareTest(sourceRoot, buildRoot, cache);

    DataObject od = DataObject.find(data);
    EditorCookie ec = od.getLookup().lookup(EditorCookie.class);

    assertNotNull(ec);

    doc = ec.openDocument();
    doc.putProperty(Language.class, JavaTokenId.language());

    JavaSource js = JavaSource.forFileObject(data);

    assertNotNull(js);

    info = SourceUtilsTestUtil.getCompilationInfo(js, Phase.RESOLVED);

    assertNotNull(info);
}