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

The following examples show how to use org.openide.cookies.EditorCookie#saveDocument() . 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: PartialReparseTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private void doVerifyFullReparse(String code, String inject) 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();
    }, true);
    int startReplace = code.indexOf('^');
    int endReplace = code.indexOf('^', startReplace + 1) - 1;
    doc.remove(startReplace, endReplace - startReplace);
    doc.insertString(startReplace, inject, null);
    source.runUserActionTask(cc -> {
        cc.toPhase(Phase.RESOLVED);
        assertNotSame(topLevel[0], cc.getCompilationUnit());
    }, true);
    ec.saveDocument();
    ec.close();
}
 
Example 2
Source File: HintsPanel.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private void saveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveButtonActionPerformed
    final HintMetadata selectedHint = getSelectedHint();
    final String selectedHintId = selectedHint.id;
    DataObject dob = getDataObject(selectedHint);
    EditorCookie ec = dob.getCookie(EditorCookie.class);
    try {
        ec.saveDocument();
    } catch (IOException ex) {
        Exceptions.printStackTrace(ex);
    }
    RulesManager.getInstance().reload();
    cpBased.reset();
    errorTreeModel = constructTM(Utilities.getBatchSupportedHints(cpBased).keySet(), false);
    setModel(errorTreeModel);
    if (logic != null) {
        logic.errorTreeModel = errorTreeModel;
    }
    select(getHintByName(selectedHintId));
    customHintCodeBeforeEditing = null;
    cancelEditActionPerformed(evt);
    hasNewHints = true;
}
 
Example 3
Source File: DataEditorSupportEncodingTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testNationalCharactersSaved() throws Exception {
    DataObject d = DataObject.find(testFileObject);
    
    encodingName = "ISO-8859-2"; // NOI18N
    
    EditorCookie o = d.getLookup().lookup(EditorCookie.class);
    StyledDocument doc = o.openDocument();
    doc.insertString(0, CZECH_STRING_UTF, null);
    
    o.saveDocument();

    // try to open the file
    InputStream istm = testFileObject.getInputStream();
    try {
        BufferedReader r = new BufferedReader(new InputStreamReader(istm, "ISO-8859-2")); // NOI18N
        String line = r.readLine();

        assertEquals("Text differs", CZECH_STRING_UTF, line); // NOI18N
    } finally {
        istm.close();
    }
}
 
Example 4
Source File: DataEditorSupportTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/** Tests that charset of saving document is not removed from cache by
 * concurrent openDocument() call (see #160784). */
public void testSaveOpenConcurrent() throws Exception {
    obj = DataObject.find(fileObject);
    DES sup = support();
    assertFalse("It is closed now", sup.isDocumentLoaded());
    assertNotNull("DataObject found", obj);

    Document doc = sup.openDocument();
    assertTrue("It is open now", support().isDocumentLoaded());
    doc.insertString(0, "Ahoj", null);
    EditorCookie s = (EditorCookie) sup;
    assertNotNull("Modified, so it has cookie", s);
    assertEquals(sup, s);

    Logger.getLogger(DataEditorSupport.class.getName()).setLevel(Level.FINEST);
    Logger.getLogger(DataEditorSupport.class.getName()).addHandler(new OpeningHandler(sup));
    s.saveDocument();
    
    assertLockFree(obj.getPrimaryFile());
    s.close();
    CloseCookie c = (CloseCookie) sup;
    assertNotNull("Has close", c);
    assertTrue("Close ok", c.close());
    assertLockFree(obj.getPrimaryFile());
}
 
Example 5
Source File: LineSeparatorDataEditorSupportTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testLineSeparator() throws Exception {
    File file = File.createTempFile("lineSeparator", ".txt", getWorkDir());
    file.deleteOnExit();
    FileObject fileObject = FileUtil.toFileObject(file);
    fileObject.setAttribute(FileObject.DEFAULT_LINE_SEPARATOR_ATTR, "\r");
    DataObject dataObject = DataObject.find(fileObject);
    EditorCookie editor = dataObject.getLookup().lookup(org.openide.cookies.EditorCookie.class);
    final StyledDocument doc = editor.openDocument();
    SwingUtilities.invokeAndWait(new Runnable() {

        @Override
        public void run() {
            try {
                doc.insertString(doc.getLength(), ".\n", null);
            } catch (BadLocationException ex) {
                Exceptions.printStackTrace(ex);
            }
        }
    });
    
    editor.saveDocument();
    InputStream inputStream = fileObject.getInputStream();
    assertEquals('.',inputStream.read());
    assertEquals('\r',inputStream.read());
    inputStream.close();
}
 
Example 6
Source File: PUDataObject.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Saves the document.
 * @see EditorCookie#saveDocument
 */
public void save(){
    EditorCookie edit = (EditorCookie) getLookup().lookup(EditorCookie.class);
    if (edit != null){
        try {
            edit.saveDocument();
        } catch (IOException ex) {
            Exceptions.printStackTrace(ex);
        }
    }
}
 
Example 7
Source File: DataEditorSupportEncodingTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testIncompatibleCharacter() throws Exception {
    DataObject d = DataObject.find(testFileObject);
    
    encodingName = "ISO-8859-1"; // NOI18N
    
    EditorCookie o = d.getLookup().lookup(EditorCookie.class);
    StyledDocument doc = o.openDocument();
    doc.insertString(0, CZECH_STRING_UTF, null);
    
    try {
        o.saveDocument();
        
        // try to open the file
        InputStream istm = testFileObject.getInputStream();
        try {
            BufferedReader r = new BufferedReader(new InputStreamReader(istm, "ISO-8859-2")); // NOI18N
            String line = r.readLine();
            
            int questionMarkPos = line.indexOf('?'); // NOI18N
            
            assertTrue("Should save question marks", questionMarkPos != -1); // NOI18N
        } finally {
            istm.close();
        }
        //fail("Exception expected");
    } catch (UnmappableCharacterException ex) {
        // expected exceptiom
    }
}
 
Example 8
Source File: CatalogFileWrapperDOMImpl.java    From netbeans with Apache License 2.0 5 votes vote down vote up
void saveByDocumentEditorCookie(){
    try {
        DataObject dobj = DataObject.find(backendCatalogFileObj);
        EditorCookie thisDocumentEditorCookie = (EditorCookie)dobj.getCookie(EditorCookie.class);
        thisDocumentEditorCookie.saveDocument();
    } catch (IOException ex) {
    }
}
 
Example 9
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 10
Source File: CommentsTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public void testCommentPrinted195048() throws Exception {
    testFile = new File(getWorkDir(), "Test.java");
    TestUtilities.copyStringToFile(testFile,
        "package hierbas.del.litoral;\n" +
        "\n" +
        "public class Test {\n" +
        "}\n");
    String golden =
        "package hierbas.del.litoral;\n" +
        "\n" +
        "public class Test {\n\n" +
        "    /**test*/\n" +
        "    private String t() {\n" +
        "        String s;\n" +
        "    }\n" +
        "}\n";

    JavaSource src = getJavaSource(testFile);
    Task task = new Task<WorkingCopy>() {
        public void run(final WorkingCopy wc) throws IOException {
            wc.toPhase(JavaSource.Phase.RESOLVED);
            final TreeMaker tm = wc.getTreeMaker();
            MethodTree nue = tm.Method(tm.Modifiers(EnumSet.of(Modifier.PRIVATE)),
                                       "t",
                                       tm.MemberSelect(tm.MemberSelect(tm.Identifier("java"), "lang"), "String"),
                                       Collections.<TypeParameterTree>emptyList(),
                                       Collections.<VariableTree>emptyList(),
                                       Collections.<ExpressionTree>emptyList(),
                                       "{java.lang.String s;}",
                                       null);
            GeneratorUtilities gu = GeneratorUtilities.get(wc);

            tm.addComment(nue, Comment.create(Style.JAVADOC, -2, -2, -2, "/**test*/"), true);
            nue = gu.importFQNs(nue);

            ClassTree clazz = (ClassTree) wc.getCompilationUnit().getTypeDecls().get(0);

            wc.rewrite(clazz, gu.insertClassMember(clazz, nue));
        }

    };
    src.runModificationTask(task).commit();
    //GeneratorUtilities.insertClassMember opens the Document:
    DataObject d = DataObject.find(FileUtil.toFileObject(testFile));
    EditorCookie ec = d.getLookup().lookup(EditorCookie.class);
    ec.saveDocument();
    String res = TestUtilities.copyFileToString(testFile);
    //System.err.println(res);
    assertEquals(golden, res);
}
 
Example 11
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 12
Source File: GuardedBlockTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
/**
 * #90424: Guarded Exception
 */
public void testAddMethodAfterVariables() throws Exception {
    testFile = new File(getWorkDir(), "Test.java");
    TestUtilities.copyStringToFile(testFile, 
        "package javaapplication5;\n" +
        "\n" +
        "import java.awt.event.ActionEvent;\n" +
        "import java.awt.event.ActionListener;\n" +
        "\n" +
        "public class Guarded1 implements ActionListener {\n" +
        "    \n" +
        "    public Guarded1() {\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"
    );
    DataObject dataObject = DataObject.find(FileUtil.toFileObject(testFile));
    EditorCookie editorCookie = ((GuardedDataObject) dataObject).getCookie(EditorCookie.class);
    Document doc = editorCookie.openDocument();
    String golden = 
        "package javaapplication5;\n" +
        "\n" +
        "import java.awt.event.ActionEvent;\n" +
        "import java.awt.event.ActionListener;\n" +
        "\n" +
        "public class Guarded1 implements ActionListener {\n" +
        "    \n" +
        "    public Guarded1() {\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" +
        "    public void actionPerformed(ActionEvent e) {\n" +
        "    }\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)),
                    "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
            ); 
            ClassTree copy = make.addClassMember(clazz, newMethod);
            workingCopy.rewrite(clazz, copy);
        }
    };
    src.runModificationTask(task).commit();
    editorCookie.saveDocument();
    String res = TestUtilities.copyFileToString(testFile);
    //System.err.println(res);
    assertEquals(golden, res);
}
 
Example 13
Source File: GuardedBlockTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
/**
 * #119048: Guarded Exception
 */
public void test119048() throws Exception {
    testFile = new File(getWorkDir(), "Test.java");
    TestUtilities.copyStringToFile(testFile, 
        "package javaapplication5;\n" +
        "\n" +
        "public class NewJFrame extends javax.swing.JFrame {\n" +
        "\n" +
        "    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed\n" +
        "        // TODO add your handling code here:\n" +
        "        a = 3;\n" +
        "    }//GEN-LAST:event_jButton1ActionPerformed\n" +
        "\n" +
        "}"
    );
    DataObject dataObject = DataObject.find(FileUtil.toFileObject(testFile));
    EditorCookie editorCookie = ((GuardedDataObject) dataObject).getCookie(EditorCookie.class);
    Document doc = editorCookie.openDocument();
    String golden = 
        "package javaapplication5;\n" +
        "\n" +
        "public class NewJFrame extends javax.swing.JFrame {\n" +
        "\n" +
        "    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed\n" +
        "        int a;\n" +
        "        // TODO add your handling code here:\n" +
        "        a = 3;\n" +
        "    }//GEN-LAST:event_jButton1ActionPerformed\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 method = (MethodTree) clazz.getMembers().get(1);
            VariableTree var = make.Variable(
                    make.Modifiers(Collections.<Modifier>emptySet()),
                    "a",
                    make.PrimitiveType(TypeKind.INT),
                    null
                );
            BlockTree copy = make.insertBlockStatement(method.getBody(), 0, var);
            workingCopy.rewrite(method.getBody(), copy);
        }
    };
    src.runModificationTask(task).commit();
    editorCookie.saveDocument();
    String res = TestUtilities.copyFileToString(testFile);
    //System.err.println(res);
    assertEquals(golden, res);
}
 
Example 14
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 15
Source File: AbstractTestUtil.java    From netbeans with Apache License 2.0 4 votes vote down vote up
/**
     * Enbles <code>enable = true</code>  or disables <code>enable = false</code> the module.
     */
    public static void switchModule(String codeName, boolean enable) throws Exception {
        String statusFile = "Modules/" + codeName.replace('.', '-') + ".xml";
        ModuleInfo mi = getModuleInfo(codeName);
/*
        FileObject fo = findFileObject(statusFile);
        Document document = XMLUtil.parse(new InputSource(fo.getInputStream()), false, false, null, EntityCatalog.getDefault());
        //Document document = XMLUtil.parse(new InputSource(data.getPrimaryFile().getInputStream()), false, false, null, EntityCatalog.getDefault());
        NodeList list = document.getElementsByTagName("param");
 
        for (int i = 0; i < list.getLength(); i++) {
            Element ele = (Element) list.item(i);
            if (ele.getAttribute("name").equals("enabled")) {
                ele.getFirstChild().setNodeValue(enable ? "true" : "false");
                break;
            }
        }
 
        FileLock lock = fo.lock();
        OutputStream os = fo.getOutputStream(lock);
        XMLUtil.write(document, os, "UTF-8");
        lock.releaseLock();
        os.close();
 */
        
        // module is switched
        if (mi.isEnabled() == enable) {
            return;
        }
        
        DataObject data = findDataObject(statusFile);
        EditorCookie ec = (EditorCookie) data.getCookie(EditorCookie.class);
        StyledDocument doc = ec.openDocument();
        
        // Change parametr enabled
        String stag = "<param name=\"enabled\">";
        String etag = "</param>";
        String enabled = enable ? "true" : "false";
        String result;
        
        String str = doc.getText(0,doc.getLength());
        int sindex = str.indexOf(stag);
        int eindex = str.indexOf(etag, sindex);
        if (sindex > -1 && eindex > sindex) {
            result = str.substring(0, sindex + stag.length()) + enabled + str.substring(eindex);
            //System.err.println(result);
        } else {
            //throw new IllegalStateException("Invalid format of: " + statusFile + ", missing parametr 'enabled'");
            // Probably autoload module
            return;
        }
        
        // prepare synchronization and register listener
        final Waiter waiter = new Waiter();
        final PropertyChangeListener pcl = new PropertyChangeListener() {
            public void propertyChange(PropertyChangeEvent evt) {
                if (evt.getPropertyName().equals("enabled")) {
                    waiter.notifyFinished();
                }
            }
        };
        mi.addPropertyChangeListener(pcl);
        
        // save document
        doc.remove(0,doc.getLength());
        doc.insertString(0,result,null);
        ec.saveDocument();
        
        // wait for enabled propety change and remove listener
        waiter.waitFinished();
        mi.removePropertyChangeListener(pcl);
    }