org.netbeans.api.java.source.JavaSource.Phase Java Examples
The following examples show how to use
org.netbeans.api.java.source.JavaSource.Phase.
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: ImportAnalysisTest.java From netbeans with Apache License 2.0 | 6 votes |
public void test157566a() throws IOException { testFile = getFile(getSourceDir(), "org/netbeans/test/codegen/imports157566/b/Test.java"); JavaSource src = getJavaSource(testFile); Task<WorkingCopy> task = new Task<WorkingCopy>() { public void run(WorkingCopy workingCopy) throws IOException { workingCopy.toPhase(Phase.RESOLVED); CompilationUnitTree cut = workingCopy.getCompilationUnit(); TreeMaker make = workingCopy.getTreeMaker(); ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0); final TypeElement foo = workingCopy.getElements().getTypeElement("org.netbeans.test.codegen.imports157566.a.C"); assertNotNull(foo); Tree type = make.QualIdent(foo); VariableTree vt = make.Variable(make.Modifiers(EnumSet.noneOf(Modifier.class)), "test", type, null); workingCopy.rewrite(clazz, make.addClassMember(clazz, vt)); } }; src.runModificationTask(task).commit(); assertFiles("testImports157566a.pass"); }
Example #2
Source File: UseSuperTypeRefactoring.java From netbeans with Apache License 2.0 | 6 votes |
private void deriveSuperTypes(final TreePathHandle javaClassHandle) { JavaSource javaSrc = JavaSource.forFileObject(javaClassHandle. getFileObject()); try{ javaSrc.runUserActionTask(new CancellableTask<CompilationController>() { @Override public void cancel() { } @Override public void run(CompilationController complController) throws IOException { complController.toPhase(Phase.ELEMENTS_RESOLVED); TypeElement javaClassElement = (TypeElement) javaClassHandle.resolveElement(complController); candidateSuperTypes = deduceSuperTypes(javaClassElement, complController); } }, false); }catch(IOException ioex){ ioex.printStackTrace(); } }
Example #3
Source File: ImportFormatTest.java From netbeans with Apache License 2.0 | 6 votes |
public void testReplaceLine() throws IOException, FileStateInvalidException { JavaSource src = getJavaSource(testFile); Task<WorkingCopy> task = new Task<WorkingCopy>() { public void run(WorkingCopy workingCopy) throws IOException { workingCopy.toPhase(Phase.RESOLVED); CompilationUnitTree cut = workingCopy.getCompilationUnit(); TreeMaker make = workingCopy.getTreeMaker(); List<ImportTree> imports = new ArrayList<ImportTree>(cut.getImports()); ImportTree oneImport = imports.remove(4); imports.add(4, make.Import(make.Identifier("java.util.Collection"), false)); CompilationUnitTree unit = make.CompilationUnit( cut.getPackageName(), imports, cut.getTypeDecls(), cut.getSourceFile() ); workingCopy.rewrite(cut, unit); } }; src.runModificationTask(task).commit(); String res = TestUtilities.copyFileToString(testFile); //System.err.println(res); assertFiles("testReplaceLine_ImportFormatTest.pass"); }
Example #4
Source File: HintTestBase.java From netbeans with Apache License 2.0 | 6 votes |
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()); }
Example #5
Source File: GeneratorUtilitiesTest.java From netbeans with Apache License 2.0 | 6 votes |
public void run(WorkingCopy copy) throws Exception { copy.toPhase(JavaSource.Phase.RESOLVED); TreePath tp = copy.getTreeUtilities().pathFor(offset); assertTrue(TreeUtilities.CLASS_TREE_KINDS.contains(tp.getLeaf().getKind())); ClassTree ct = (ClassTree)tp.getLeaf(); TypeElement te = (TypeElement)copy.getTrees().getElement(tp); assertNotNull(te); List<? extends VariableElement> vars = ElementFilter.fieldsIn(te.getEnclosedElements()); assertEquals(1, vars.size()); GeneratorUtilities utilities = GeneratorUtilities.get(copy); assertNotNull(utilities); ClassTree newCt = utilities.insertClassMember(ct, getter ? utilities.createGetter(te, vars.get(0)) : utilities.createSetter(te, vars.get(0))); copy.rewrite(ct, newCt); }
Example #6
Source File: ImportAnalysisTest.java From netbeans with Apache License 2.0 | 6 votes |
public void testAddImport13() throws IOException { testFile = getFile(getSourceDir(), getSourcePckg() + "ImportsTest2.java"); JavaSource src = getJavaSource(testFile); Task<WorkingCopy> task = new Task<WorkingCopy>() { public void run(WorkingCopy workingCopy) throws IOException { workingCopy.toPhase(Phase.RESOLVED); CompilationUnitTree cut = workingCopy.getCompilationUnit(); TreeMaker make = workingCopy.getTreeMaker(); ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0); MethodTree node = (MethodTree) clazz.getMembers().get(0); BlockTree body = node.getBody(); List<StatementTree> stats = new ArrayList<StatementTree>(); for (StatementTree st : body.getStatements()) { stats.add(st); } TypeElement list = workingCopy.getElements().getTypeElement("java.util.Map.Entry"); Types types = workingCopy.getTypes(); TypeMirror tm = types.getArrayType(types.erasure(list.asType())); stats.add(make.Variable(make.Modifiers(Collections.<Modifier>emptySet()), "entry", make.Type(tm), null)); workingCopy.rewrite(body, make.Block(stats, false)); } }; src.runModificationTask(task).commit(); assertFiles("testAddImport13.pass"); }
Example #7
Source File: TypeMirrorHandleTest.java From netbeans with Apache License 2.0 | 6 votes |
public void testTypeMirrorHandleUnion() throws Exception { prepareTest(); writeIntoFile(testSource, "package test; public class Test { void t() { try { throw new Exception(); } catch (java.io.IOException | javax.swing.text.BadLocationException e) { } } }"); ClassPath empty = ClassPathSupport.createClassPath(new URL[0]); JavaSource js = JavaSource.create(ClasspathInfo.create(ClassPathSupport.createClassPath(SourceUtilsTestUtil.getBootClassPath().toArray(new URL[0])), empty, empty), testSource); js.runUserActionTask(new Task<CompilationController>() { public void run(final CompilationController info) throws Exception { info.toPhase(Phase.RESOLVED); new ErrorAwareTreePathScanner<Void, Void>() { @Override public Void visitVariable(VariableTree node, Void p) { if (node.getName().contentEquals("e")) { TypeMirror tm = info.getTrees().getTypeMirror(getCurrentPath()); assertEquals(TypeKind.UNION, tm.getKind()); assertTrue(info.getTypes().isSameType(tm, TypeMirrorHandle.create(tm).resolve(info))); } return super.visitVariable(node, p); } }.scan(info.getCompilationUnit(), null); } }, true); }
Example #8
Source File: ImportAnalysisTest.java From netbeans with Apache License 2.0 | 6 votes |
public void testAddImport18() throws IOException { testFile = getFile(getSourceDir(), getSourcePckg() + "ImportsTest6.java"); JavaSource src = getJavaSource(testFile); Task<WorkingCopy> task = new Task<WorkingCopy>() { public void run(WorkingCopy workingCopy) throws IOException { workingCopy.toPhase(Phase.RESOLVED); CompilationUnitTree node = workingCopy.getCompilationUnit(); TreeMaker make = workingCopy.getTreeMaker(); ExpressionTree pack = node.getPackageName(); PackageElement pe = workingCopy.getElements().getPackageElement("org.netbeans.test"); ExpressionTree nuePack = make.QualIdent(pe); workingCopy.rewrite(pack, nuePack); } }; src.runModificationTask(task).commit(); assertFiles("testAddImport18.pass"); }
Example #9
Source File: TreePathHandleTest.java From netbeans with Apache License 2.0 | 6 votes |
public void testHandleForMethodInvocation() throws Exception { FileObject file = FileUtil.createData(sourceRoot, "test/test.java"); writeIntoFile(file, "package test; public class test {public test() {aaa();} public void aaa() {}}"); JavaSource js = JavaSource.forFileObject(file); CompilationInfo info = SourceUtilsTestUtil.getCompilationInfo(js, Phase.RESOLVED); assertTrue(info.getDiagnostics().toString(), info.getDiagnostics().isEmpty()); TreePath tp = info.getTreeUtilities().pathFor(49); TreePathHandle handle = TreePathHandle.create(tp, info); TreePath resolved = handle.resolve(info); assertNotNull(resolved); assertTrue(tp.getLeaf() == resolved.getLeaf()); }
Example #10
Source File: JavaHintsPositionRefresher.java From netbeans with Apache License 2.0 | 6 votes |
public void run(CompilationController controller) throws Exception { if (controller.toPhase(JavaSource.Phase.RESOLVED).compareTo(Phase.RESOLVED) < 0) { return ; } Document doc = controller.getDocument(); if (doc == null) { return; } for (PositionRefresherHelper h : refreshers) { if (ctx.isCanceled()) { return; } List errors = h.getErrorDescriptionsAt(controller, ctx, doc); if (errors == null) continue; eds.put(h.getKey(), errors); } }
Example #11
Source File: TreePathHandleTest.java From netbeans with Apache License 2.0 | 6 votes |
public void test134457() throws Exception { FileObject file = FileUtil.createData(sourceRoot, "test/Test.java"); String code = "package test;\n" + "public class Test {\n" + " public static final String KONST = \"\";\n" + " public static void test() {\n" + " Test test = new Test();\n" + " test.KONST;\n" + " }\n" + "}"; writeIntoFile(file,code); JavaSource js = JavaSource.forFileObject(file); CompilationInfo info = SourceUtilsTestUtil.getCompilationInfo(js, Phase.RESOLVED); TreePath tp = info.getTreeUtilities().pathFor(code.indexOf("ONST;")); TreePathHandle handle = TreePathHandle.create(tp, info); TreePath resolved = handle.resolve(info); assertNotNull(resolved); assertTrue(tp.getLeaf() == resolved.getLeaf()); }
Example #12
Source File: ImportAnalysisTest.java From netbeans with Apache License 2.0 | 6 votes |
public void testImportGetterSetter() throws IOException { testFile = getFile(getSourceDir(), getSourcePckg() + "ImportsTest8.java"); JavaSource src = getJavaSource(testFile); Task<WorkingCopy> task = new Task<WorkingCopy>() { public void run(WorkingCopy workingCopy) throws IOException { workingCopy.toPhase(Phase.RESOLVED); CompilationUnitTree cut = workingCopy.getCompilationUnit(); TreeMaker make = workingCopy.getTreeMaker(); ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0); ExpressionTree type = make.QualIdent(workingCopy.getElements().getTypeElement("java.awt.geom.Point2D.Double")); VariableTree vt = make.Variable(make.Modifiers(EnumSet.noneOf(Modifier.class)), "test",type, null); workingCopy.rewrite(clazz, make.addClassMember(clazz, vt)); } }; src.runModificationTask(task).commit(); assertFiles("testImportGetterSetter.pass"); }
Example #13
Source File: JavaSourceHelper.java From netbeans with Apache License 2.0 | 6 votes |
/** * Finds the first public top-level type in the compilation unit given by the * given <code>CompilationController</code>. * * This method assumes the restriction that there is at most a public * top-level type declaration in a compilation unit, as described in the * section 7.6 of the JLS. */ public static ClassTree findPublicTopLevelClass(CompilationController controller) throws IOException { controller.toPhase(Phase.ELEMENTS_RESOLVED); final String mainElementName = controller.getFileObject().getName(); for (Tree tree : controller.getCompilationUnit().getTypeDecls()) { if (!TreeUtilities.CLASS_TREE_KINDS.contains(tree.getKind())) { continue; } ClassTree classTree = (ClassTree) tree; if (!classTree.getSimpleName().contentEquals(mainElementName)) { continue; } if (!classTree.getModifiers().getFlags().contains(Modifier.PUBLIC)) { continue; } return classTree; } return null; }
Example #14
Source File: TreeUtilitiesTest.java From netbeans with Apache License 2.0 | 6 votes |
public void testAttributingVar() throws Exception { ClassPath boot = ClassPathSupport.createClassPath(SourceUtilsTestUtil.getBootClassPath().toArray(new URL[0])); FileObject testFile = FileUtil.createData(FileUtil.createMemoryFileSystem().getRoot(), "Test.java"); try (Writer w = new OutputStreamWriter(testFile.getOutputStream())) { w.append("public class Test { private static int I; }"); } JavaSource js = JavaSource.create(ClasspathInfo.create(boot, ClassPath.EMPTY, ClassPath.EMPTY), testFile); js.runUserActionTask(new Task<CompilationController>() { @Override public void run(CompilationController parameter) throws Exception { parameter.toPhase(Phase.RESOLVED); TreePath clazzPath = new TreePath(new TreePath(new TreePath(parameter.getCompilationUnit()), parameter.getCompilationUnit().getTypeDecls().get(0)), ((ClassTree) parameter.getCompilationUnit().getTypeDecls().get(0)).getMembers().get(1)); Scope scope = parameter.getTrees().getScope(clazzPath); StatementTree st = parameter.getTreeUtilities().parseStatement("{ String s; }", new SourcePositions[1]); assertEquals(Kind.BLOCK, st.getKind()); StatementTree var = st.getKind() == Kind.BLOCK ? ((BlockTree) st).getStatements().get(0) : st; parameter.getTreeUtilities().attributeTree(st, scope); checkType(parameter, clazzPath, var); } }, true); }
Example #15
Source File: RenameConstructor.java From netbeans with Apache License 2.0 | 6 votes |
@Override public ChangeInfo implement() throws Exception { try { ModificationResult.runModificationTask(Collections.singleton(source), new UserTask() { @Override public void run(ResultIterator resultIterator) throws Exception { WorkingCopy wc = WorkingCopy.get(resultIterator.getParserResult(offset)); wc.toPhase(Phase.PARSED); TreePath path = pathHandle.resolve(wc); if (path != null && path.getLeaf().getKind() == Kind.METHOD) { MethodTree mt = (MethodTree) path.getLeaf(); wc.rewrite(mt, wc.getTreeMaker().setLabel(mt, newConstructorName)); } } }).commit(); } catch (IOException e) { Exceptions.printStackTrace(e); } return null; }
Example #16
Source File: ImportAnalysisTest.java From netbeans with Apache License 2.0 | 6 votes |
public void test157566d() throws IOException { testFile = getFile(getSourceDir(), "org/netbeans/test/codegen/imports157566/b/Testd.java"); JavaSource src = getJavaSource(testFile); Task<WorkingCopy> task = new Task<WorkingCopy>() { public void run(WorkingCopy workingCopy) throws IOException { workingCopy.toPhase(Phase.RESOLVED); CompilationUnitTree cut = workingCopy.getCompilationUnit(); TreeMaker make = workingCopy.getTreeMaker(); ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0); final TypeElement foo = workingCopy.getElements().getTypeElement("java.lang.String"); assertNotNull(foo); Tree type = make.QualIdent(foo); VariableTree vt = make.Variable(make.Modifiers(EnumSet.noneOf(Modifier.class)), "test", type, null); workingCopy.rewrite(clazz, make.addClassMember(clazz, vt)); } }; src.runModificationTask(task).commit(); assertFiles("testImports157566d.pass"); }
Example #17
Source File: JavaSourceHelper.java From netbeans with Apache License 2.0 | 6 votes |
public static List<? extends AnnotationMirror> getClassAnnotations(JavaSource source) { final List<? extends AnnotationMirror>[] classAnons = new List[1]; try { source.runUserActionTask(new AbstractTask<CompilationController>() { public void run(CompilationController controller) throws IOException { controller.toPhase(JavaSource.Phase.ELEMENTS_RESOLVED); TypeElement classElement = getTopLevelClassElement(controller); if (classElement == null) { return; } classAnons[0] = controller.getElements().getAllAnnotationMirrors(classElement); } }, true); } catch (IOException ex) { Exceptions.printStackTrace(ex); } return classAnons[0]; }
Example #18
Source File: WrappingTest.java From netbeans with Apache License 2.0 | 6 votes |
public void testWrapMethod1() throws Exception { String code = "package hierbas.del.litoral;\n\n" + "import java.util.concurrent.atomic.AtomicBoolean;\n\n" + "public class Test {\n" + "}\n"; runWrappingTest(code, new Task<WorkingCopy>() { public void run(WorkingCopy workingCopy) throws IOException { workingCopy.toPhase(Phase.RESOLVED); CompilationUnitTree cut = workingCopy.getCompilationUnit(); TreeMaker make = workingCopy.getTreeMaker(); ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0); ExpressionTree parsed = workingCopy.getTreeUtilities().parseExpression("new Object() { private void test(int a, int b, int c) throws java.io.FileNotFound, java.net.MalformedURLException { } }", new SourcePositions[1]); parsed = GeneratorUtilities.get(workingCopy).importFQNs(parsed); MethodTree method = (MethodTree) ((NewClassTree) parsed).getClassBody().getMembers().get(0); workingCopy.rewrite(clazz, make.addClassMember(clazz, method)); } }, FmtOptions.wrapMethodParams, WrapStyle.WRAP_IF_LONG.name(), FmtOptions.wrapThrowsKeyword, WrapStyle.WRAP_IF_LONG.name(), FmtOptions.wrapThrowsList, WrapStyle.WRAP_IF_LONG.name()); }
Example #19
Source File: TreePathHandleTest.java From netbeans with Apache License 2.0 | 6 votes |
public void testEmptyMod() throws Exception { FileObject file = FileUtil.createData(sourceRoot, "test/test.java"); writeIntoFile(file, "package test; public class test { String a; }"); JavaSource js = JavaSource.forFileObject(file); SourceUtilsTestUtil.compileRecursively(sourceRoot); js.runUserActionTask(new Task<CompilationController>() { public void run(CompilationController parameter) throws Exception { parameter.toPhase(Phase.RESOLVED); TypeElement test = parameter.getElements().getTypeElement("test.test"); TreePath path = parameter.getTrees().getPath(test); TreePath field = new TreePath(path, ((ClassTree) path.getLeaf()).getMembers().get(1)); TreePath mods = new TreePath(field, ((VariableTree) field.getLeaf()).getModifiers()); assertSame(mods.getLeaf(), TreePathHandle.create(mods, parameter).resolve(parameter).getLeaf()); } }, true); }
Example #20
Source File: ImportAnalysisTest.java From netbeans with Apache License 2.0 | 6 votes |
public void testAddImportThroughMethod3() throws IOException { 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(); ClassTree clazz = (ClassTree) workingCopy.getCompilationUnit().getTypeDecls().get(0); MethodTree node = (MethodTree) clazz.getMembers().get(0); int offset = (int) (workingCopy.getTrees().getSourcePositions().getStartPosition(workingCopy.getCompilationUnit(), node) + 1); TreePath context = workingCopy.getTreeUtilities().pathFor(offset); try { assertEquals("List", SourceUtils.resolveImport(workingCopy, context, "java.util.List")); assertEquals("Map", SourceUtils.resolveImport(workingCopy, context, "java.util.Map")); assertEquals("java.awt.List", SourceUtils.resolveImport(workingCopy, context, "java.awt.List")); } catch (IOException e) { throw new IllegalStateException(e); } } }; testSource.runModificationTask(task).commit(); String res = TestUtilities.copyFileToString(testFile); //System.err.println(res); assertFiles("testAddImportThroughMethod3.pass"); }
Example #21
Source File: ComputeOverridersTest.java From netbeans with Apache License 2.0 | 6 votes |
public void test234941() throws Exception { prepareSourceRoot("1"); prepareSource("1", "test/Object.java", "package test;" + "import java.lang.Object;" + "public class Object extends Object {" + "}"); FileObject file = sourceDirectories.getFileObject("1/test/Object.java"); CompilationInfo info = SourceUtilsTestUtil.getCompilationInfo(JavaSource.forFileObject(file), Phase.RESOLVED); URL r1 = sourceDirectories.getFileObject("1").getURL(); ComputeOverriders.reverseSourceRootsInOrderOverride = Arrays.asList(r1); ComputeOverriders.dependenciesOverride = new HashMap<URL, List<URL>>(); ComputeOverriders.dependenciesOverride.put(r1, Collections.<URL>emptyList()); //only checking the computation will end: new ComputeOverriders(new AtomicBoolean()).process(info, null, null, false); }
Example #22
Source File: JavaSourceHelper.java From netbeans with Apache License 2.0 | 5 votes |
public static boolean isEntity(JavaSource source) { final boolean[] isBoolean = new boolean[1]; try { source.runUserActionTask(new AbstractTask<CompilationController>() { public void run(CompilationController controller) throws IOException { controller.toPhase(JavaSource.Phase.ELEMENTS_RESOLVED); TypeElement classElement = getTopLevelClassElement(controller); if (classElement == null) { return; } List<? extends AnnotationMirror> annotations = controller.getElements().getAllAnnotationMirrors(classElement); for (AnnotationMirror annotation : annotations) { if (annotation.toString().equals("@javax.persistence.Entity")) { //NOI18N isBoolean[0] = true; break; } } } }, true); } catch (IOException ex) { Exceptions.printStackTrace(ex); } return isBoolean[0]; }
Example #23
Source File: LiteralTest.java From netbeans with Apache License 2.0 | 5 votes |
public void testNoExtraEscapesInStringLiteral() throws Exception { testFile = new File(getWorkDir(), "Test.java"); TestUtilities.copyStringToFile(testFile, "package hierbas.del.litoral;\n" + "\n" + "public class Test {\n" + " public static final String C;\n" + "}\n" ); String golden = "package hierbas.del.litoral;\n" + "\n" + "public class Test {\n" + " public static final String C = \"'\";\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(); ClassTree clazz = (ClassTree) workingCopy.getCompilationUnit().getTypeDecls().get(0); VariableTree var = (VariableTree) clazz.getMembers().get(1); LiteralTree val = make.Literal("'"); VariableTree nue = make.setInitialValue(var, val); workingCopy.rewrite(var, nue); } }; testSource.runModificationTask(task).commit(); String res = TestUtilities.copyFileToString(testFile); //System.err.println(res); assertEquals(golden, res); }
Example #24
Source File: SourceUtilsTestUtil.java From netbeans with Apache License 2.0 | 5 votes |
/** Blocking call for CompilationInfo after given phase is reached. * @param phase to be reached * @return CompilationInfo or null * XXX: REMOVE ME!!!!!!! */ public static CompilationInfo getCompilationInfo(JavaSource js, Phase phase ) throws IOException { if (phase == null || phase == Phase.MODIFIED) { throw new IllegalArgumentException (String.format("The %s is not a legal value of phase",phase)); //NOI18N } final DeadlockTask bt = new DeadlockTask(phase); js.runUserActionTask(bt,true); return bt.info; }
Example #25
Source File: JavaSourceHelper.java From netbeans with Apache License 2.0 | 5 votes |
public static long[] getPosition(JavaSource source, final String methodName) { final long[] position = {0, 0}; try { source.runUserActionTask(new AbstractTask<CompilationController>() { public void run(CompilationController controller) throws IOException { controller.toPhase(Phase.RESOLVED); TypeElement classElement = getTopLevelClassElement(controller); CompilationUnitTree tree = controller.getCompilationUnit(); Trees trees = controller.getTrees(); Tree elementTree; Element element = null; if (methodName == null) { element = classElement; } else { List<ExecutableElement> methods = ElementFilter.methodsIn(classElement.getEnclosedElements()); for (ExecutableElement method : methods) { if (method.getSimpleName().toString().equals(methodName)) { element = method; break; } } } if (element != null) { elementTree = trees.getTree(element); long pos = trees.getSourcePositions().getStartPosition(tree, elementTree); position[0] = tree.getLineMap().getLineNumber(pos) - 1; position[1] = tree.getLineMap().getColumnNumber(pos) - 1; } } }, true); } catch (IOException ex) { } return position; }
Example #26
Source File: ArraysTest.java From netbeans with Apache License 2.0 | 5 votes |
public void test162485b() throws Exception { testFile = new File(getWorkDir(), "Test.java"); TestUtilities.copyStringToFile(testFile, "package hierbas.del.litoral;\n" + "\n" + "public class Test {\n" + " Object test = new int[] {};\n" + "}\n" ); String golden = "package hierbas.del.litoral;\n" + "\n" + "public class Test {\n" + " Object test = {{1}};\n" + "}\n"; JavaSource src = getJavaSource(testFile); Task<WorkingCopy> task = new Task<WorkingCopy>() { public void run(WorkingCopy workingCopy) throws IOException { workingCopy.toPhase(Phase.RESOLVED); CompilationUnitTree cut = workingCopy.getCompilationUnit(); TreeMaker make = workingCopy.getTreeMaker(); ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0); VariableTree var = (VariableTree) clazz.getMembers().get(1); NewArrayTree nat = (NewArrayTree) var.getInitializer(); NewArrayTree dim2 = make.NewArray(null, Collections.<ExpressionTree>emptyList(), Collections.singletonList(make.Literal(Integer.valueOf(1)))); NewArrayTree newTree = make.NewArray(null, Collections.<ExpressionTree>emptyList(), Collections.<ExpressionTree>singletonList(dim2)); workingCopy.rewrite(nat, newTree); } }; src.runModificationTask(task).commit(); String res = TestUtilities.copyFileToString(testFile); //System.err.println(res); assertEquals(golden, res); }
Example #27
Source File: JavaClassCompletor.java From netbeans with Apache License 2.0 | 5 votes |
private void doSmartJavaCompletion(final JavaSource js, final String typedPrefix, final int substitutionOffset, final int queryType) throws IOException { js.runUserActionTask(new Task<CompilationController>() { public void run(CompilationController cc) throws Exception { if(isCancelled()) { return; } cc.toPhase(Phase.ELEMENTS_RESOLVED); ClassIndex ci = cc.getClasspathInfo().getClassIndex(); // add packages addPackages(ci, typedPrefix, substitutionOffset, CompletionProvider.COMPLETION_ALL_QUERY_TYPE); if(isCancelled()) { return; } // add classes Set<ElementHandle<TypeElement>> matchingTypes; if(queryType == CompletionProvider.COMPLETION_ALL_QUERY_TYPE) { matchingTypes = ci.getDeclaredTypes(typedPrefix, NameKind.CASE_INSENSITIVE_PREFIX, ALL); } else { matchingTypes = ci.getDeclaredTypes(typedPrefix, NameKind.CASE_INSENSITIVE_PREFIX, LOCAL); setAdditionalItems(true); } for (ElementHandle<TypeElement> eh : matchingTypes) { if(isCancelled()) { return; } if (eh.getKind() == ElementKind.CLASS) { LazyTypeCompletionItem item = LazyTypeCompletionItem.create(substitutionOffset, eh, js); addCacheItem(item); } } } }, true); }
Example #28
Source File: AnnotationTest.java From netbeans with Apache License 2.0 | 5 votes |
public void testAnnotationRename1() throws Exception { testFile = new File(getWorkDir(), "Test.java"); TestUtilities.copyStringToFile(testFile, "package hierbas.del.litoral;\n" + "\n" + "public @interface Test {\n" + "}\n" ); String golden = "package hierbas.del.litoral;\n" + "\n" + "public @interface Foo {\n" + "}\n"; JavaSource src = getJavaSource(testFile); Task task = new Task<WorkingCopy>() { public void run(WorkingCopy workingCopy) throws IOException { workingCopy.toPhase(Phase.RESOLVED); CompilationUnitTree cut = workingCopy.getCompilationUnit(); TreeMaker make = workingCopy.getTreeMaker(); for (Tree typeDecl : cut.getTypeDecls()) { // ensure that it is correct type declaration, i.e. class if (TreeUtilities.CLASS_TREE_KINDS.contains(typeDecl.getKind())) { ClassTree copy = make.setLabel((ClassTree) typeDecl, "Foo"); workingCopy.rewrite(typeDecl, copy); } } } }; src.runModificationTask(task).commit(); String res = TestUtilities.copyFileToString(testFile); //System.err.println(res); assertEquals(golden, res); }
Example #29
Source File: JavaSourceTaskFactory.java From netbeans with Apache License 2.0 | 5 votes |
/**Construct the JavaSourceTaskFactory with given {@link Phase} and {@link Priority}. * * @param phase phase to use for tasks created by {@link #createTask} * @param priority priority to use for tasks created by {@link #createTask} */ protected JavaSourceTaskFactory(@NonNull Phase phase, @NonNull Priority priority) { this.phase = phase; this.priority = priority; this.taskIndexingMode = TaskIndexingMode.DISALLOWED_DURING_SCAN; this.file2Task = new HashMap<FileObject, CancellableTask<CompilationInfo>>(); this.file2JS = new HashMap<FileObject, JavaSource>(); }
Example #30
Source File: SourceUtilsTest.java From netbeans with Apache License 2.0 | 5 votes |
private static void runUserActionTask(FileObject javaFile, final Task<CompilationController> taskToTest) throws Exception { JavaSource javaSource = JavaSource.forFileObject(javaFile); javaSource.runUserActionTask(new Task<CompilationController>() { public void run(CompilationController controller) throws Exception { controller.toPhase(Phase.RESOLVED); taskToTest.run(controller); } }, true); }