当前位置: 首页>>代码示例>>Java>>正文


Java JavaSource.runModificationTask方法代码示例

本文整理汇总了Java中org.netbeans.api.java.source.JavaSource.runModificationTask方法的典型用法代码示例。如果您正苦于以下问题:Java JavaSource.runModificationTask方法的具体用法?Java JavaSource.runModificationTask怎么用?Java JavaSource.runModificationTask使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在org.netbeans.api.java.source.JavaSource的用法示例。


在下文中一共展示了JavaSource.runModificationTask方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: addInputParamFields

import org.netbeans.api.java.source.JavaSource; //导入方法依赖的package包/类
public static void addInputParamFields(JavaSource source,
        final List<ParameterInfo> params,
        final javax.lang.model.element.Modifier[] modifier) throws IOException {
    ModificationResult result = source.runModificationTask(new AbstractTask<WorkingCopy>() {

        public void run(WorkingCopy copy) throws IOException {
            copy.toPhase(JavaSource.Phase.ELEMENTS_RESOLVED);
            List<ParameterInfo> addList = new ArrayList<ParameterInfo>();
            for (ParameterInfo p : params) {
                if (JavaSourceHelper.getField(copy, Util.getParameterName(p, true, true, true)) == null) {
                    addList.add(p);
                }
            }
            JavaSourceHelper.addFields(copy, Util.getParamNames(addList),
                    Util.getParamTypeNames(addList), Util.getParamValues(addList), modifier);
        }
    });
    result.commit();
}
 
开发者ID:apache,项目名称:incubator-netbeans,代码行数:20,代码来源:JavaUtil.java

示例2: assertField

import org.netbeans.api.java.source.JavaSource; //导入方法依赖的package包/类
/**
 * Asserts that a field specified by the given parameters exists / doesn't exist in the given file.
 * @param testFile the 
 * @param field the FQN of the field 
 * @param fieldName the name of the field. May be null in which the name isn't checked.
 * @param expectSuccess specifies whether the field with the given parameters is expected to exist
 * in the given file.
 */ 
private void assertField(File testFile, final String field, final String fieldName, final boolean expectSuccess) throws Exception {
    JavaSource targetSource = JavaSource.forFileObject(FileUtil.toFileObject(testFile));
    
    Task task = new TaskSupport() {
        void doAsserts(EntityManagerGenerationStrategySupport strategy) {
            VariableTree result = strategy.getField(field);
            if (expectSuccess){
                assertNotNull(result);
                TreePath path = strategy.getWorkingCopy().getTrees().getPath(strategy.getWorkingCopy().getCompilationUnit(), result);
                TypeMirror variableType = strategy.getWorkingCopy().getTrees().getTypeMirror(path);
                assertEquals(field, variableType.toString());
                // check that field name matches if was provided
                if (fieldName != null){
                    assertEquals(fieldName, result.getName().toString());
                }
            } else {
                assertNull(result);
            }
        }
    };
    
    targetSource.runModificationTask(task);
}
 
开发者ID:apache,项目名称:incubator-netbeans,代码行数:32,代码来源:EntityManagerGenerationStrategySupportTest.java

示例3: runJavaFix

import org.netbeans.api.java.source.JavaSource; //导入方法依赖的package包/类
private ModificationResult runJavaFix(final JavaFix jf) throws IOException {
    FileObject file = Accessor.INSTANCE.getFile(jf);
    JavaSource js = JavaSource.forFileObject(file);
    final Map<FileObject, List<Difference>> changes = new HashMap<FileObject, List<Difference>>();

    ModificationResult mr = js.runModificationTask(new Task<WorkingCopy>() {
        public void run(WorkingCopy wc) throws Exception {
            if (wc.toPhase(Phase.RESOLVED).compareTo(Phase.RESOLVED) < 0) {
                return;
            }

            Map<FileObject, byte[]> resourceContentChanges = new HashMap<FileObject, byte[]>();
            Accessor.INSTANCE.process(jf, wc, true, resourceContentChanges, /*Ignored for now:*/new ArrayList<RefactoringElementImplementation>());
            BatchUtilities.addResourceContentChanges(resourceContentChanges, changes);
            
        }
    });
    
    changes.putAll(JavaSourceAccessor.getINSTANCE().getDiffsFromModificationResult(mr));
    
    return JavaSourceAccessor.getINSTANCE().createModificationResult(changes, Collections.<Object, int[]>emptyMap());
}
 
开发者ID:apache,项目名称:incubator-netbeans,代码行数:23,代码来源:HintTest.java

示例4: perform

import org.netbeans.api.java.source.JavaSource; //导入方法依赖的package包/类
public void perform(FileObject file, JTextComponent pane, final AddFxPropertyConfig config, final Scope scope) {
    final int caretOffset = component.getCaretPosition();
    JavaSource js = JavaSource.forDocument(component.getDocument());
    if (js != null) {
        try {
            ModificationResult mr = js.runModificationTask(new Task<WorkingCopy>() {
                @Override
                public void run(WorkingCopy javac) throws IOException {
                    javac.toPhase(JavaSource.Phase.ELEMENTS_RESOLVED);
                    Element e = handle.resolve(javac);
                    TreePath path = e != null ? javac.getTrees().getPath(e) : javac.getTreeUtilities().pathFor(caretOffset);
                    path = getPathElementOfKind(TreeUtilities.CLASS_TREE_KINDS, path);
                    if (path == null) {
                        org.netbeans.editor.Utilities.setStatusBoldText(component, ERR_CannotFindOriginalClass());
                    } else {
                        ClassTree cls = (ClassTree) path.getLeaf();
                        AddJavaFXPropertyMaker maker = new AddJavaFXPropertyMaker(javac, scope, javac.getTreeMaker(), config);
                        List<Tree> members = maker.createMembers();
                        if(members != null) {
                            javac.rewrite(cls, GeneratorUtils.insertClassMembers(javac, cls, members, caretOffset));
                        }
                    }
                }
            });
            GeneratorUtils.guardedCommit(component, mr);
        } catch (IOException ex) {
            Exceptions.printStackTrace(ex);
        }
    }
}
 
开发者ID:apache,项目名称:incubator-netbeans,代码行数:31,代码来源:AddJavaFXPropertyCodeGenerator.java

示例5: addImportsToSource

import org.netbeans.api.java.source.JavaSource; //导入方法依赖的package包/类
public static void addImportsToSource(JavaSource source, List<String> imports) throws IOException {
    for (final String imp : imports) {
        ModificationResult result = source.runModificationTask(new AbstractTask<WorkingCopy>() {

            public void run(WorkingCopy copy) throws IOException {
                copy.toPhase(JavaSource.Phase.RESOLVED);
                JavaSourceHelper.addImports(copy, new String[]{imp});
            }
        });
        result.commit();
    }
}
 
开发者ID:apache,项目名称:incubator-netbeans,代码行数:13,代码来源:JavaUtil.java

示例6: testObjectEditing2

import org.netbeans.api.java.source.JavaSource; //导入方法依赖的package包/类
public void testObjectEditing2() throws Exception {
    FileObject java = FileUtil.createData(fo, "X.java");
    final String what1 = "package java.lang; public class Object {\n" +
                         "  public int hashCode() {return 0;}" +
                         "  public int hashCode() {return 0;}" +
                         "  public boolean equals(Object o) {return false;}" +
                         "  public boolean equals(Object o) {return false;}" +
                         "  \n";

    String what2 =
        "}\n";
    String what = what1 + what2;
    GeneratorUtilsTest.writeIntoFile(java, what);

    JavaSource js = JavaSource.forFileObject(java);
    assertNotNull("Created", js);

    class TaskImpl implements Task<WorkingCopy> {
        public void run(WorkingCopy copy) throws Exception {
            copy.toPhase(JavaSource.Phase.RESOLVED);
            ClassTree clazzTree = (ClassTree) copy.getCompilationUnit().getTypeDecls().get(0);
            TreePath clazz = new TreePath(new TreePath(copy.getCompilationUnit()), clazzTree);
            List<VariableElement> vars = new LinkedList<VariableElement>();

            for (Tree m : clazzTree.getMembers()) {
                if (m.getKind() == Kind.VARIABLE) {
                    vars.add((VariableElement) copy.getTrees().getElement(new TreePath(clazz, m)));
                }
            }

            EqualsHashCodeGenerator.overridesHashCodeAndEquals(copy, copy.getTrees().getElement(clazz), null);
        }
    }

    TaskImpl t = new TaskImpl();

    js.runModificationTask(t);
}
 
开发者ID:apache,项目名称:incubator-netbeans,代码行数:39,代码来源:EqualsHashCodeGeneratorTest.java

示例7: test157760b

import org.netbeans.api.java.source.JavaSource; //导入方法依赖的package包/类
public void test157760b() throws Exception {
    testFile = new File(getWorkDir(), "package-info.java");
    TestUtilities.copyStringToFile(testFile, "@AA\[email protected]\[email protected]\npackage foo;");

    FileObject testSourceFO = FileUtil.toFileObject(testFile);
    assertNotNull(testSourceFO);
    ClassPath sourcePath = ClassPath.getClassPath(testSourceFO, ClassPath.SOURCE);
    assertNotNull(sourcePath);
    FileObject[] roots = sourcePath.getRoots();
    assertEquals(1, roots.length);
    final FileObject sourceRoot = roots[0];
    assertNotNull(sourceRoot);
    ClassPath compilePath = ClassPath.getClassPath(testSourceFO, ClassPath.COMPILE);
    assertNotNull(compilePath);
    ClassPath bootPath = ClassPath.getClassPath(testSourceFO, ClassPath.BOOT);
    assertNotNull(bootPath);
    ClasspathInfo cpInfo = ClasspathInfo.create(bootPath, compilePath, sourcePath);

    String golden = "@EE\[email protected]\[email protected]\npackage foo;";

    JavaSource javaSource = JavaSource.create(cpInfo, FileUtil.toFileObject(testFile));

    Task<WorkingCopy> task = new Task<WorkingCopy>() {
        public void run(WorkingCopy workingCopy) throws Exception {
            workingCopy.toPhase(JavaSource.Phase.RESOLVED);
            TreeMaker make = workingCopy.getTreeMaker();
            CompilationUnitTree nue = make.addPackageAnnotation(workingCopy.getCompilationUnit(), make.Annotation(make.Identifier("DD"), Collections.<ExpressionTree>emptyList()));
            nue = make.insertPackageAnnotation(nue, 0, make.Annotation(make.Identifier("EE"), Collections.<ExpressionTree>emptyList()));
            nue = make.removePackageAnnotation(nue, 1);
            nue = make.removePackageAnnotation(nue, workingCopy.getCompilationUnit().getPackageAnnotations().get(1));
            workingCopy.rewrite(workingCopy.getCompilationUnit(), nue);
        }
    };
    ModificationResult result = javaSource.runModificationTask(task);
    result.commit();
    String res = TestUtilities.copyFileToString(testFile);
    System.err.println(res);
    assertEquals(golden, res);
}
 
开发者ID:apache,项目名称:incubator-netbeans,代码行数:40,代码来源:CompilationUnitTest.java

示例8: test157760c

import org.netbeans.api.java.source.JavaSource; //导入方法依赖的package包/类
public void test157760c() throws Exception {
    testFile = new File(getWorkDir(), "package-info.java");
    TestUtilities.copyStringToFile(testFile, "/*\n a\n */\npackage foo;");

    FileObject testSourceFO = FileUtil.toFileObject(testFile);
    assertNotNull(testSourceFO);
    ClassPath sourcePath = ClassPath.getClassPath(testSourceFO, ClassPath.SOURCE);
    assertNotNull(sourcePath);
    FileObject[] roots = sourcePath.getRoots();
    assertEquals(1, roots.length);
    final FileObject sourceRoot = roots[0];
    assertNotNull(sourceRoot);
    ClassPath compilePath = ClassPath.getClassPath(testSourceFO, ClassPath.COMPILE);
    assertNotNull(compilePath);
    ClassPath bootPath = ClassPath.getClassPath(testSourceFO, ClassPath.BOOT);
    assertNotNull(bootPath);
    ClasspathInfo cpInfo = ClasspathInfo.create(bootPath, compilePath, sourcePath);

    String golden = "/*\n a\n */\[email protected]\npackage foo;";

    JavaSource javaSource = JavaSource.create(cpInfo, FileUtil.toFileObject(testFile));

    Task<WorkingCopy> task = new Task<WorkingCopy>() {
        public void run(WorkingCopy workingCopy) throws Exception {
            workingCopy.toPhase(JavaSource.Phase.RESOLVED);
            TreeMaker make = workingCopy.getTreeMaker();
            CompilationUnitTree nue = make.addPackageAnnotation(workingCopy.getCompilationUnit(), make.Annotation(make.Identifier("AA"), Collections.<ExpressionTree>emptyList()));
            workingCopy.rewrite(workingCopy.getCompilationUnit(), nue);
        }
    };
    ModificationResult result = javaSource.runModificationTask(task);
    result.commit();
    String res = TestUtilities.copyFileToString(testFile);
    System.err.println(res);
    assertEquals(golden, res);
}
 
开发者ID:apache,项目名称:incubator-netbeans,代码行数:37,代码来源:CompilationUnitTest.java

示例9: implement

import org.netbeans.api.java.source.JavaSource; //导入方法依赖的package包/类
public ChangeInfo implement() throws Exception {
    //use the original cp-info so it is "sure" that the target can be resolved:
    JavaSource js = JavaSource.create(cpInfo, targetFile);
    
    ModificationResult diff = js.runModificationTask(new Task<WorkingCopy>() {

        public void run(final WorkingCopy working) throws IOException {
            working.toPhase(Phase.RESOLVED);
            TypeElement targetType = target.resolve(working);
            
            if (targetType == null) {
                ErrorHintsProvider.LOG.log(Level.INFO, "Cannot resolve target."); // NOI18N
                return;
            }
            
            TreePath targetTree = working.getTrees().getPath(targetType);
            
            if (targetTree == null) {
                ErrorHintsProvider.LOG.log(Level.INFO, "Cannot resolve target tree: " + targetType.getQualifiedName() + "."); // NOI18N
                return;
            }
            
            TreeMaker make = working.getTreeMaker();
            MethodTree constr = make.Method(make.Modifiers(EnumSet.of(Modifier.PUBLIC)), "<init>", null, Collections.<TypeParameterTree>emptyList(), Collections.<VariableTree>emptyList(), Collections.<ExpressionTree>emptyList(), "{}" /*XXX*/, null); // NOI18N
            ClassTree innerClass = make.Class(make.Modifiers(modifiers), name, Collections.<TypeParameterTree>emptyList(), null, Collections.<Tree>emptyList(), Collections.<Tree>singletonList(constr));
            
            innerClass = createConstructor(working, new TreePath(targetTree, innerClass));
            
            working.rewrite(targetTree.getLeaf(), GeneratorUtilities.get(working).insertClassMember((ClassTree)targetTree.getLeaf(), innerClass));
        }
    });
    
    return Utilities.commitAndComputeChangeInfo(targetFile, diff, null);
}
 
开发者ID:apache,项目名称:incubator-netbeans,代码行数:35,代码来源:CreateClassFix.java

示例10: doTest197097

import org.netbeans.api.java.source.JavaSource; //导入方法依赖的package包/类
public void doTest197097() throws Exception {
    testFile = new File(getWorkDir(), "Test.java");
    TestUtilities.copyStringToFile(testFile,
        "package zoo;\n" +
        "\n" +
        "public class A {\n" +
        "    public class I extends java.util.ArrayList {\n" +
        "        public I(java.util.Collection c) {\n" +
        "            super(c);\n" +
        "        }\n" +
        "    }\n" +
        "}\n"
    );

    FileObject emptyJava = FileUtil.createData(FileUtil.getConfigRoot(), "Templates/Classes/Empty.java");
    emptyJava.setAttribute("template", Boolean.TRUE);
    FileObject classJava = FileUtil.createData(FileUtil.getConfigRoot(), "Templates/Classes/Class.java");
    classJava.setAttribute("template", Boolean.TRUE);
    Writer w = new OutputStreamWriter(classJava.getOutputStream(), "UTF-8");
    w.write("package zoo;\npublic class Template {\n  \n}");
    w.close();
    FileObject testSourceFO = FileUtil.toFileObject(testFile);
    assertNotNull(testSourceFO);
    ClassPath sourcePath = ClassPath.getClassPath(testSourceFO, ClassPath.SOURCE);
    assertNotNull(sourcePath);
    FileObject[] roots = sourcePath.getRoots();
    assertEquals(1, roots.length);
    final FileObject sourceRoot = roots[0];
    assertNotNull(sourceRoot);
    ClassPath compilePath = ClassPath.getClassPath(testSourceFO, ClassPath.COMPILE);
    assertNotNull(compilePath);
    ClassPath bootPath = ClassPath.getClassPath(testSourceFO, ClassPath.BOOT);
    assertNotNull(bootPath);
    ClasspathInfo cpInfo = ClasspathInfo.create(bootPath, compilePath, sourcePath);

    String golden1 =
        "package zoo;\n" +
        "\n" +
        "\n" + //XXX
        "public class I extends java.util.ArrayList {\n\n" +
        "    public I(java.util.Collection c) {\n" +
        "        super(c);\n" +
        "    }\n" +
        "  \n" +//XXX
        "}\n";

    JavaSource javaSource = JavaSource.create(cpInfo, FileUtil.toFileObject(testFile));

    Task<WorkingCopy> task = new Task<WorkingCopy>() {

        public void cancel() {
        }

        public void run(WorkingCopy workingCopy) throws Exception {
            workingCopy.toPhase(JavaSource.Phase.RESOLVED);
            TreeMaker make = workingCopy.getTreeMaker();
            Tree classDecl = ((ClassTree) workingCopy.getCompilationUnit().getTypeDecls().get(0)).getMembers().get(1);
            CompilationUnitTree newTree = make.CompilationUnit(
                    sourceRoot,
                    "zoo/I.java",
                    Collections.<ImportTree>emptyList(),
                    Collections.<Tree>singletonList(classDecl)
            );
            workingCopy.rewrite(null, newTree);
            MethodTree constructor = (MethodTree) ((ClassTree) classDecl).getMembers().get(0);
            workingCopy.rewrite(constructor, make.setLabel(constructor, "I"));
        }
    };
    ModificationResult result = javaSource.runModificationTask(task);
    result.commit();
    String res = TestUtilities.copyFileToString(new File(getDataDir().getAbsolutePath() + "/zoo/I.java"));
    System.err.println(res);
    assertEquals(res, golden1);
}
 
开发者ID:apache,项目名称:incubator-netbeans,代码行数:75,代码来源:CompilationUnitTest.java

示例11: testTaggingOfGeneratedMethodBodyInInnerClass

import org.netbeans.api.java.source.JavaSource; //导入方法依赖的package包/类
/**
 * Adds 'System.err.println(true);' statement to the method body,
 * tags the tree and checks the marks are valid inside an inner class
 */
public void testTaggingOfGeneratedMethodBodyInInnerClass() throws Exception {

    // the tag
    final String methodBodyTag = "mbody"; //NOI18N

    testFile = new File(getWorkDir(), "Test.java");
    TestUtilities.copyStringToFile(testFile,
        "package hierbas.del.litoral;\n\n" +
        "import java.io.*;\n\n" +
        "public class Test {\n" +
        "    class foo {\n" +
        "        public void taragui() {\n" +
        "            ;\n" +
        "        }\n" +
        "    }\n" +
        "}\n"
        );

    JavaSource testSource = JavaSource.forFileObject(FileUtil.toFileObject(testFile));
    Task<WorkingCopy> task = new Task<WorkingCopy>() {

        public void run(WorkingCopy workingCopy) throws java.io.IOException {
            workingCopy.toPhase(Phase.RESOLVED);
            TreeMaker make = workingCopy.getTreeMaker();

            // finally, find the correct body and rewrite it.
            ClassTree topClazz = (ClassTree) workingCopy.getCompilationUnit().getTypeDecls().get(0);
            ClassTree clazz = (ClassTree) topClazz.getMembers().get(1);
            MethodTree method = (MethodTree) clazz.getMembers().get(1);
            ExpressionStatementTree statement = make.ExpressionStatement(
                make.MethodInvocation(
                    Collections.<ExpressionTree>emptyList(),
                    make.MemberSelect(
                        make.MemberSelect(
                            make.Identifier("System"),
                            "err"
                        ),
                        "println"
                    ),
                    Collections.singletonList(
                        make.Literal(Boolean.TRUE)
                    )
                )
            );
            //tag
            workingCopy.tag(statement, methodBodyTag);

            BlockTree copy = make.addBlockStatement(method.getBody(), statement);
            workingCopy.rewrite(method.getBody(), copy);
        }

    };
    ModificationResult diff = testSource.runModificationTask(task);
    diff.commit();
    int[] span = diff.getSpan(methodBodyTag);
    int delta = span[1] - span[0];
    //lenghth of added statement has to be the same as the length of span
    assertEquals(delta, new String("System.err.println(true);").length());
    //absolute position of span beginning
    assertEquals(143, span[0]);

    assertEquals("System.err.println(true);", diff.getResultingSource(FileUtil.toFileObject(testFile)).substring(span[0], span[1]));
}
 
开发者ID:apache,项目名称:incubator-netbeans,代码行数:68,代码来源:TreeTaggingTest.java

示例12: testTaggingOfGeneratedMethodBodyInAnnonymousClass

import org.netbeans.api.java.source.JavaSource; //导入方法依赖的package包/类
/**
 * Adds 'System.err.println(true);' statement to the method body,
 * tags the tree and checks the marks are valid inside an annonymous class
 */
public void testTaggingOfGeneratedMethodBodyInAnnonymousClass() throws Exception {

    // the tag
    final String methodBodyTag = "mbody"; //NOI18N

    testFile = new File(getWorkDir(), "Test.java");
    TestUtilities.copyStringToFile(testFile,
        "package hierbas.del.litoral;\n\n" +
        "import java.io.*;\n\n" +
        "public class Test {\n" +
        "    public void foo() {\n" +
        "        new Runnable() {\n" +
        "            public void run() {\n" +
        "                ;\n" +
        "            }\n" +
        "        };\n" +
        "    }" +
        "}\n"
        );

    JavaSource testSource = JavaSource.forFileObject(FileUtil.toFileObject(testFile));
    Task<WorkingCopy> task = new Task<WorkingCopy>() {

        public void run(WorkingCopy workingCopy) throws java.io.IOException {
            workingCopy.toPhase(Phase.RESOLVED);
            TreeMaker make = workingCopy.getTreeMaker();

            // finally, find the correct body and rewrite it.
            ClassTree topClazz = (ClassTree) workingCopy.getCompilationUnit().getTypeDecls().get(0);
            
            MethodTree meth = (MethodTree) topClazz.getMembers().get(1);
            NewClassTree clazz = (NewClassTree) ((ExpressionStatementTree) meth.getBody().getStatements().get(0)).getExpression();
            MethodTree method = (MethodTree) clazz.getClassBody().getMembers().get(1);
            ExpressionStatementTree statement = make.ExpressionStatement(
                make.MethodInvocation(
                    Collections.<ExpressionTree>emptyList(),
                    make.MemberSelect(
                        make.MemberSelect(
                            make.Identifier("System"),
                            "err"
                        ),
                        "println"
                    ),
                    Collections.singletonList(
                        make.Literal(Boolean.TRUE)
                    )
                )
            );
            //tag
            workingCopy.tag(statement, methodBodyTag);

            BlockTree copy = make.addBlockStatement(method.getBody(), statement);
            workingCopy.rewrite(method.getBody(), copy);
        }

    };
    ModificationResult diff = testSource.runModificationTask(task);
    diff.commit();
    int[] span = diff.getSpan(methodBodyTag);
    int delta = span[1] - span[0];
    //lenghth of added statement has to be the same as the length of span
    assertEquals(delta, new String("System.err.println(true);").length());
    //absolute position of span beginning
    assertEquals(184, span[0]);

    assertEquals("System.err.println(true);", diff.getResultingSource(FileUtil.toFileObject(testFile)).substring(span[0], span[1]));
}
 
开发者ID:apache,项目名称:incubator-netbeans,代码行数:72,代码来源:TreeTaggingTest.java

示例13: testTaggingOfSuperCall

import org.netbeans.api.java.source.JavaSource; //导入方法依赖的package包/类
public void testTaggingOfSuperCall() throws Exception {

        // the tag
        final String methodBodyTag = "mbody"; //NOI18N

        testFile = new File(getWorkDir(), "Test.java");
        TestUtilities.copyStringToFile(testFile,
            "/**/" +
            "package hierbas.del.litoral;\n\n" +
            "import java.io.*;\n\n" +
            "public class Test {\n" +
            "    public void taragui() {\n" +
            "        ;\n" +
            "    }\n" +
            "}\n"
            );

        JavaSource testSource = JavaSource.forFileObject(FileUtil.toFileObject(testFile));
        Task<WorkingCopy> task = new Task<WorkingCopy>() {

            public void run(WorkingCopy workingCopy) throws java.io.IOException {
                workingCopy.toPhase(Phase.RESOLVED);
                TreeMaker make = workingCopy.getTreeMaker();

                // finally, find the correct body and rewrite it.
                ClassTree clazz = (ClassTree) workingCopy.getCompilationUnit().getTypeDecls().get(0);
                MethodTree method = (MethodTree) clazz.getMembers().get(1);

                MethodInvocationTree inv = make.MethodInvocation(Collections.<ExpressionTree>emptyList(), make.MemberSelect(make.Identifier("super"), "print"), Collections.<ExpressionTree>emptyList()); //NOI18N
                ReturnTree ret = make.Return(inv);

                //tag
                workingCopy.tag(ret, methodBodyTag);

                BlockTree copy = make.addBlockStatement(method.getBody(), ret);
                workingCopy.rewrite(method.getBody(), copy);
            }

        };
        ModificationResult diff = testSource.runModificationTask(task);
        diff.commit();

        int[] span = diff.getSpan(methodBodyTag);
        int delta = span[1] - span[0];
        //lenghth of added statement has to be the same as the length of span
        assertEquals(delta, new String("return super.print();").length());
        //absolute position of span beginning
        assertEquals(119, span[0]);

        assertEquals("return super.print();", diff.getResultingSource(FileUtil.toFileObject(testFile)).substring(span[0], span[1]));
    }
 
开发者ID:apache,项目名称:incubator-netbeans,代码行数:52,代码来源:TreeTaggingTest.java

示例14: test204638

import org.netbeans.api.java.source.JavaSource; //导入方法依赖的package包/类
public void test204638() throws Exception {
    setupJavaTemplates();
    FileObject testSourceFO = FileUtil.toFileObject(testFile);
    assertNotNull(testSourceFO);
    DataObject created = DataObject.find(classJava).createFromTemplate(DataFolder.findFolder(testSourceFO.getParent()));
    assertEquals(template, created.getPrimaryFile().asText());
    ClassPath sourcePath = ClassPath.getClassPath(testSourceFO, ClassPath.SOURCE);
    assertNotNull(sourcePath);
    FileObject[] roots = sourcePath.getRoots();
    assertEquals(1, roots.length);
    final FileObject sourceRoot = roots[0];
    assertNotNull(sourceRoot);
    ClassPath compilePath = ClassPath.getClassPath(testSourceFO, ClassPath.COMPILE);
    assertNotNull(compilePath);
    ClassPath bootPath = ClassPath.getClassPath(testSourceFO, ClassPath.BOOT);
    assertNotNull(bootPath);
    ClasspathInfo cpInfo = ClasspathInfo.create(bootPath, compilePath, sourcePath);

    String golden1 =
        "/*\n" +
        "initial\n" +
        "comment\n" +
        "*/\n" +
        "package zoo;\n" +
        "public class Krtek {\n" +
        "    public Krtek() {}\n" +
        "}\n";

    JavaSource javaSource = JavaSource.create(cpInfo, FileUtil.toFileObject(testFile));

    Task<WorkingCopy> task = new Task<WorkingCopy>() {

        public void cancel() {
        }

        public void run(WorkingCopy workingCopy) throws Exception {
            workingCopy.toPhase(JavaSource.Phase.RESOLVED);
            TreeMaker make = workingCopy.getTreeMaker();
            CompilationUnitTree newTree = make.CompilationUnit(
                    sourceRoot,
                    "zoo/Krtek.java",
                    Collections.<ImportTree>emptyList(),
                    Collections.<Tree>emptyList()
            );
            MethodTree constr = make.Method(make.Modifiers(EnumSet.of(Modifier.PUBLIC)), "Krtek", null, Collections.<TypeParameterTree>emptyList(), Collections.<VariableTree>emptyList(), Collections.<ExpressionTree>emptyList(), "{}", null);
            newTree = make.addCompUnitTypeDecl(newTree, make.Class(make.Modifiers(EnumSet.of(Modifier.PUBLIC)), "Krtek", Collections.<TypeParameterTree>emptyList(), null, Collections.<Tree>emptyList(), Collections.<Tree>singletonList(constr)));
            workingCopy.rewrite(null, newTree);
        }
    };
    ModificationResult result = javaSource.runModificationTask(task);
    result.commit();
    String res = TestUtilities.copyFileToString(new File(getDataDir().getAbsolutePath() + "/zoo/Krtek.java"));
    System.err.println(res);
    assertEquals(res, golden1);
}
 
开发者ID:apache,项目名称:incubator-netbeans,代码行数:56,代码来源:CompilationUnitTest.java

示例15: invoke

import org.netbeans.api.java.source.JavaSource; //导入方法依赖的package包/类
@Override
public void invoke() {
    final int caretOffset = component.getCaretPosition();
    final ToStringPanel panel = new ToStringPanel(description);
    DialogDescriptor dialogDescriptor = GeneratorUtils.createDialogDescriptor(panel, NbBundle.getMessage(ToStringGenerator.class, "LBL_generate_tostring")); //NOI18N
    Dialog dialog = DialogDisplayer.getDefault().createDialog(dialogDescriptor);
    dialog.setVisible(true);
    if (dialogDescriptor.getValue() != dialogDescriptor.getDefaultValue()) {
        return;
    }
    JavaSource js = JavaSource.forDocument(component.getDocument());
    if (js != null) {
        try {
            ModificationResult mr = js.runModificationTask(new Task<WorkingCopy>() {

                @Override
                public void run(WorkingCopy copy) throws IOException {
                    copy.toPhase(JavaSource.Phase.ELEMENTS_RESOLVED);
                    Element e = description.getElementHandle().resolve(copy);
                    TreePath path = e != null ? copy.getTrees().getPath(e) : copy.getTreeUtilities().pathFor(caretOffset);
                    path = copy.getTreeUtilities().getPathElementOfKind(TreeUtilities.CLASS_TREE_KINDS, path);
                    if (path == null) {
                        String message = NbBundle.getMessage(ToStringGenerator.class, "ERR_CannotFindOriginalClass"); //NOI18N
                        org.netbeans.editor.Utilities.setStatusBoldText(component, message);
                    } else {
                        ClassTree cls = (ClassTree) path.getLeaf();
                        ArrayList<VariableElement> fields = new ArrayList<>();
                        for (ElementHandle<? extends Element> elementHandle : panel.getVariables()) {
                            VariableElement field = (VariableElement) elementHandle.resolve(copy);
                            if (field == null) {
                                return;
                            }
                            fields.add(field);
                        }
                        MethodTree mth = createToStringMethod(copy, fields, cls.getSimpleName().toString());
                        copy.rewrite(cls, GeneratorUtils.insertClassMembers(copy, cls, Collections.singletonList(mth), caretOffset));
                    }
                }
            });
            GeneratorUtils.guardedCommit(component, mr);
        } catch (IOException ex) {
            Exceptions.printStackTrace(ex);
        }
    }
}
 
开发者ID:apache,项目名称:incubator-netbeans,代码行数:46,代码来源:ToStringGenerator.java


注:本文中的org.netbeans.api.java.source.JavaSource.runModificationTask方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。