Java Code Examples for org.netbeans.api.java.source.JavaSource#runUserActionTask()

The following examples show how to use org.netbeans.api.java.source.JavaSource#runUserActionTask() . 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: CtSymArchiveTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testIssue247469() throws IOException {
    final JavaPlatform jp = JavaPlatformManager.getDefault().getDefaultPlatform();
    assertNotNull(jp);
    final ClasspathInfo cpInfo = ClasspathInfo.create(jp.getBootstrapLibraries(), ClassPath.EMPTY, ClassPath.EMPTY);
    assertNotNull(cpInfo);
    final JavaSource js = JavaSource.create(cpInfo);
    js.runUserActionTask(new Task<CompilationController>() {
        @Override
        public void run(final CompilationController cc) throws Exception {
            final PackageElement packageElement = cc.getElements().getPackageElement("java.lang"); // NOI18N
            for (Element elem : packageElement.getEnclosedElements()) {
                if ("ProcessBuilder$1".equals(elem.getSimpleName().toString())) { // NOI18N
                    TypeElement te = (TypeElement) elem;
                    assertEquals(NestingKind.ANONYMOUS, te.getNestingKind());
                    break;
                }
            }
        }
    }, true);
}
 
Example 2
Source File: JavaSourceHelper.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public static String getPackageName(JavaSource source) {
    if(source == null) return "";

    final String[] packageName = new String[1];
    try {
        source.runUserActionTask(new AbstractTask<CompilationController>() {

            public void run(CompilationController controller) throws IOException {
                controller.toPhase(JavaSource.Phase.ELEMENTS_RESOLVED);
                ExpressionTree packageTree = controller.getCompilationUnit().getPackageName();
                if (packageTree != null) {
                    packageName[0] = packageTree.toString();
                }
            }
        }, true);
    } catch (IOException ex) {
    }

    return packageName[0];
}
 
Example 3
Source File: MethodNode.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private boolean isEntityBeanMethod() throws IOException {
    
    final boolean[] result = new boolean[] { false };
        JavaSource javaSource = JavaSource.create(cpInfo);
    javaSource.runUserActionTask(new Task<CompilationController>() {
        public void run(CompilationController controller) throws IOException {
            controller.toPhase(JavaSource.Phase.ELEMENTS_RESOLVED);
            Elements elements = controller.getElements();
            TypeElement entityBean = elements.getTypeElement("javax.ejb.EntityBean"); // NOI18N
            TypeElement implBeanElement = elements.getTypeElement(implBean);
            if (implBeanElement != null && entityBean != null) {
                result[0] = controller.getTypes().isSubtype(implBeanElement.asType(), entityBean.asType());
            }
        }
    }, true);
    return result[0];
    
}
 
Example 4
Source File: JavaSourceHelper.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public static List<MethodTree> getAllMethods(JavaSource source) {
    final List<MethodTree> allMethods = new ArrayList<MethodTree>();

    try {
        source.runUserActionTask(new AbstractTask<CompilationController>() {

            public void run(CompilationController controller) throws IOException {
                controller.toPhase(JavaSource.Phase.ELEMENTS_RESOLVED);
                TypeElement classElement = getTopLevelClassElement(controller);
                List<ExecutableElement> methods = ElementFilter.methodsIn(classElement.getEnclosedElements());

                for (ExecutableElement method : methods) {
                    allMethods.add(controller.getTrees().getTree(method));
                }
            }
        }, true);
    } catch (IOException ex) {
    }
    return allMethods;
}
 
Example 5
Source File: JavaSourceHelper.java    From netbeans with Apache License 2.0 5 votes vote down vote up
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 6
Source File: GenerationUtilsTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
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);
}
 
Example 7
Source File: WebActionProvider.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private boolean isWebService(JavaSource js) {
    final boolean[] foundWebServiceAnnotation = {false};
    if (js != null) {
        try {
            js.runUserActionTask(new org.netbeans.api.java.source.Task<CompilationController>() {
                @Override
                public void run(CompilationController ci) throws Exception {
                    ci.toPhase(JavaSource.Phase.ELEMENTS_RESOLVED);
                    TypeElement classEl = org.netbeans.modules.j2ee.core.api.support.java.SourceUtils.getPublicTopLevelElement(ci);
                    if (classEl != null) {
                        TypeElement wsElement = ci.getElements().getTypeElement("javax.jws.WebService"); //NOI18N
                        if (wsElement != null) {
                            List<? extends AnnotationMirror> annotations = classEl.getAnnotationMirrors();
                            for (AnnotationMirror anMirror : annotations) {
                                if (ci.getTypes().isSameType(wsElement.asType(), anMirror.getAnnotationType())) {
                                    foundWebServiceAnnotation[0] = true;
                                    break;
                                }
                            }
                        }
                    }
                }
            }, true);
        } catch (java.io.IOException ioex) {
            Exceptions.printStackTrace(ioex);
        }
    }
    return foundWebServiceAnnotation[0];
}
 
Example 8
Source File: PUCompletor.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private void doJavaCompletion(final FileObject fo, final JavaSource js, final List<JPACompletionItem> results,
        final String typedPrefix, final int substitutionOffset) throws IOException {
    js.runUserActionTask(new Task<CompilationController>() {

        @Override
        public void run(CompilationController cc) throws Exception {
            cc.toPhase(Phase.ELEMENTS_RESOLVED);
            Project project = FileOwnerQuery.getOwner(fo);
            EntityClassScopeProvider provider = (EntityClassScopeProvider) project.getLookup().lookup(EntityClassScopeProvider.class);
            EntityClassScope ecs = null;
            Entity[] entities = null;
            if (provider != null) {
                ecs = provider.findEntityClassScope(fo);
            }
            if (ecs != null) {
                entities = ecs.getEntityMappingsModel(false).runReadAction(new MetadataModelAction<EntityMappingsMetadata, Entity[]>() {

                    @Override
                    public Entity[] run(EntityMappingsMetadata metadata) throws Exception {
                        return metadata.getRoot().getEntity();
                    }
                });
            }
            // add classes 
            if(entities != null) {
                for (Entity entity : entities) {
                    if (typedPrefix.length() == 0 || entity.getClass2().toLowerCase().startsWith(typedPrefix.toLowerCase()) || entity.getName().toLowerCase().startsWith(typedPrefix.toLowerCase())) {
                        JPACompletionItem item = JPACompletionItem.createAttribValueItem(substitutionOffset, entity.getClass2());
                        results.add(item);
                    }
                }
            }
        }
    }, true);

    setAnchorOffset(substitutionOffset);
}
 
Example 9
Source File: AnnotationModelHelper.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Runs the given callable as a JavaSource user action task. Not private because
 * used in unit tests.
 *
 * @param notify whether to notify <code>JavaContextListener</code>s.
 */
<V> V runJavaSourceTask(final Callable<V> callable, final boolean notify) throws IOException {
    JavaSource existingJavaSource;
    synchronized (this) {
        existingJavaSource = javaSource;
    }
    JavaSource newJavaSource = existingJavaSource != null ? existingJavaSource : JavaSource.create(cpi);
    final List<V> result = new ArrayList<V>();
    try {
        newJavaSource.runUserActionTask(new CancellableTask<CompilationController>() {
            @Override
            public void run(CompilationController controller) throws Exception {
                result.add(runCallable(callable, controller, notify));
            }
            @Override
            public void cancel() {
                // we can't cancel
            }
        }, true);
    } catch (IOException e) {
        Throwable cause = e.getCause();
        if (cause instanceof MetadataModelException) {
            throw (MetadataModelException)cause;
        }
        throw e;
    }
    return result.get(0);
}
 
Example 10
Source File: TopClassFinder.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Finds main top classes, i.e. those whose name matches with the name
 * of the file they reside in.
 */
static List<ElementHandle<TypeElement>> findMainTopClasses(
                                                JavaSource javaSource)
                                                    throws IOException {
    TopClassFinderTask analyzer = new TopClassFinderTask(new MainClassOnly());
    javaSource.runUserActionTask(analyzer, true);
    return analyzer.topClassElems;
}
 
Example 11
Source File: WebBeansActionHelper.java    From netbeans with Apache License 2.0 5 votes vote down vote up
static boolean getClassAtDot(
        final JTextComponent component , final Object[] subject, 
        final PositionStrategy strategy )
{
    JavaSource javaSource = JavaSource.forDocument(component.getDocument());
    if ( javaSource == null ){
        Toolkit.getDefaultToolkit().beep();
        return false;
    }
    try {
        javaSource.runUserActionTask( new Task<CompilationController>(){
            @Override
            public void run(CompilationController controller) throws Exception {
                controller.toPhase( Phase.ELEMENTS_RESOLVED );
                int dot = strategy.getOffset(component);
                TreePath tp = controller.getTreeUtilities()
                    .pathFor(dot);
                Element element = controller.getTrees().getElement(tp );
                if ( element == null ){
                    StatusDisplayer.getDefault().setStatusText(
                            NbBundle.getMessage(
                                    WebBeansActionHelper.class, 
                            "LBL_ElementNotFound"));
                    return;
                }
                if ( element instanceof TypeElement ){
                    subject[0] = ElementHandle.create(element);
                    subject[1] = element.getSimpleName();
                    subject[2] = InspectActionId.CLASS_CONTEXT;
                }
            }
        }, true );
    }
    catch(IOException e ){
        Logger.getLogger( WebBeansActionHelper.class.getName()).
            log( Level.WARNING, e.getMessage(), e);
    }
                
    return subject[0]!=null;
}
 
Example 12
Source File: LocationOpener.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private int getMethodLine(final FileObject fo, final String methodName) {
    final int[] line = new int[1];
    JavaSource javaSource = JavaSource.forFileObject(fo);
    if (javaSource != null) {
        try {
            javaSource.runUserActionTask((CompilationController compilationController) -> {
                compilationController.toPhase(JavaSource.Phase.ELEMENTS_RESOLVED);
                Trees trees = compilationController.getTrees();
                CompilationUnitTree compilationUnitTree = compilationController.getCompilationUnit();
                List<? extends Tree> typeDecls = compilationUnitTree.getTypeDecls();
                for (Tree tree : typeDecls) {
                    Element element = trees.getElement(trees.getPath(compilationUnitTree, tree));
                    if (element != null && element.getKind() == ElementKind.CLASS && element.getSimpleName().contentEquals(fo.getName())) {
                        List<? extends ExecutableElement> methodElements = ElementFilter.methodsIn(element.getEnclosedElements());
                        for (Element child : methodElements) {
                            if (child.getSimpleName().contentEquals(methodName)) {
                                long pos = trees.getSourcePositions().getStartPosition(compilationUnitTree, trees.getTree(child));
                                line[0] = (int) compilationUnitTree.getLineMap().getLineNumber(pos);
                                break;
                            }
                        }
                    }
                }
            }, true);
            return line[0];
        } catch (IOException ioe) {
            //TODO: Do nothing?
        }
    }
    return 1;
}
 
Example 13
Source File: JPDAMethodChooserUtils.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private static void detectUnreachableOps(String url, final EditorContext.Operation[] operations,
                                         final int[] flags, final EditorContext.Operation currOp) {
    FileObject fileObj = null;
    try {
        fileObj = URLMapper.findFileObject(new URL(url));
    } catch (MalformedURLException e) {
    }
    if (fileObj == null) return;
    JavaSource js = JavaSource.forFileObject(fileObj);
    if (js == null) return;

    try {
        js.runUserActionTask(new CancellableTask<CompilationController>() {
            @Override
            public void cancel() {
            }
            @Override
            public void run(CompilationController ci) throws Exception {
                if (ci.toPhase(JavaSource.Phase.RESOLVED).compareTo(JavaSource.Phase.RESOLVED) < 0) {
                    Logger.getLogger(JPDAMethodChooserUtils.class.getName()).warning(
                            "Unable to resolve "+ci.getFileObject()+" to phase "+JavaSource.Phase.RESOLVED+", current phase = "+ci.getPhase()+
                            "\nDiagnostics = "+ci.getDiagnostics()+
                            "\nFree memory = "+Runtime.getRuntime().freeMemory());
                    return;
                }
                SourcePositions positions = ci.getTrees().getSourcePositions();
                CompilationUnitTree compUnit = ci.getCompilationUnit();
                TreeUtilities treeUtils = ci.getTreeUtilities();
                int pcOffset = currOp == null ? 0 : currOp.getMethodStartPosition().getOffset() + 1;
                for (int i = 0; i < operations.length; i++) {
                    int offset = operations[i].getMethodStartPosition().getOffset() + 1;
                    TreePath path = treeUtils.pathFor(offset);
                    while (path != null) {
                        Tree tree = path.getLeaf();
                        if (tree instanceof ConditionalExpressionTree) {
                            ConditionalExpressionTree ternaryOpTree = (ConditionalExpressionTree)tree;
                            //Tree condTree = ternaryOpTree.getCondition();
                            Tree trueTree = ternaryOpTree.getTrueExpression();
                            Tree falseTree = ternaryOpTree.getFalseExpression();
                            //long condStart = positions.getStartPosition(compUnit, condTree);
                            //long condEnd = positions.getEndPosition(compUnit, condTree);
                            long trueStart = positions.getStartPosition(compUnit, trueTree);
                            long trueEnd = positions.getEndPosition(compUnit, trueTree);
                            long falseStart = positions.getStartPosition(compUnit, falseTree);
                            long falseEnd = positions.getEndPosition(compUnit, falseTree);

                            if (trueStart <= offset && offset <= trueEnd) {
                                if (pcOffset < trueStart) {
                                    markSegment(i, false);
                                }
                            } else if (falseStart <= offset && offset <= falseEnd) {
                                if (pcOffset < trueStart) {
                                    markSegment(i, false);
                                } else if (trueStart <= pcOffset && pcOffset <= trueEnd) {
                                    markSegment(i, true);
                                }
                            }
                        } else if (tree.getKind() == Tree.Kind.CONDITIONAL_AND ||
                                tree.getKind() == Tree.Kind.CONDITIONAL_OR) {
                            BinaryTree binaryTree = (BinaryTree)tree;
                            Tree rightTree = binaryTree.getRightOperand();
                            long rightStart = positions.getStartPosition(compUnit, rightTree);
                            long rightEnd = positions.getEndPosition(compUnit, rightTree);

                            if (rightStart <= offset && offset <= rightEnd) {
                                if (pcOffset < rightStart) {
                                    markSegment(i, false);
                                }
                            }
                        }
                        path = path.getParentPath();
                    } // while
                } // for
            }

            public void markSegment(int index, boolean excludeSegment) {
                if (flags[index] == 2) return;
                flags[index] = excludeSegment ? 2 : 1;
            }

        }, true);
    } catch (IOException ioex) {
        Exceptions.printStackTrace(ioex);
    }
}
 
Example 14
Source File: GenerateJavadocAction.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private boolean prepareGenerating(final Document doc, final Descriptor desc) throws IOException {
    JavaSource js = JavaSource.forDocument(doc);
    if (js == null) {
        return false;
    }

    FileObject file = js.getFileObjects().iterator().next();
    SourceVersion sv = JavadocUtilities.resolveSourceVersion(file);
    final JavadocGenerator gen = new JavadocGenerator(sv);
    gen.updateSettings(file);
    
    js.runUserActionTask(new Task<CompilationController>() {

        public void run(CompilationController javac) throws Exception {
            javac.toPhase(JavaSource.Phase.ELEMENTS_RESOLVED);
            TokenHierarchy tokens = javac.getTokenHierarchy();
            TokenSequence ts = tokens.tokenSequence();
            ts.move(desc.caret.getOffset());
            if (!ts.moveNext() || ts.token().id() != JavaTokenId.JAVADOC_COMMENT) {
                return;
            }
            
            desc.caret = doc.createPosition(desc.caret.getOffset());
            final int jdBeginOffset = ts.offset();
            int offsetBehindJavadoc = ts.offset() + ts.token().length();
            
            while (ts.moveNext()) {
                TokenId tid = ts.token().id();
                if (tid != JavaTokenId.WHITESPACE && tid != JavaTokenId.LINE_COMMENT && tid != JavaTokenId.BLOCK_COMMENT) {
                    offsetBehindJavadoc = ts.offset();
                    // it is magic for TreeUtilities.pathFor
                    ++offsetBehindJavadoc;
                    break;
                }
            }
            
            TreePath tp = javac.getTreeUtilities().pathFor(offsetBehindJavadoc);
            Tree leaf = tp.getLeaf();
            Kind kind = leaf.getKind();
            SourcePositions positions = javac.getTrees().getSourcePositions();
            
            while (!TreeUtilities.CLASS_TREE_KINDS.contains(kind) && kind != Kind.METHOD && kind != Kind.VARIABLE && kind != Kind.COMPILATION_UNIT) {
                tp = tp.getParentPath();
                if (tp == null) {
                    leaf = null;
                    kind = null;
                    break;
                }
                leaf = tp.getLeaf();
                kind = leaf.getKind();
            }
            
            if (leaf == null || positions.getStartPosition(javac.getCompilationUnit(), leaf) < jdBeginOffset) {
                // not a class member javadoc -> ignore
                return;
            }
            
            if (kind != Kind.COMPILATION_UNIT && !JavadocUtilities.hasErrors(leaf) /*&& Access.PRIVATE.isAccessible(javac, tp, true)*/) {
                Element el = javac.getTrees().getElement(tp);
                if (el != null) {
                    String javadoc = gen.generateComment(el, javac);
                    if(javadoc == null) {
                        return;
                    }
                    desc.javadoc = javadoc;
                }
            }
        }
        
    }, true);
    
    return desc.javadoc != null;
}
 
Example 15
Source File: EqualsHashCodeGeneratorTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public void testEnabledFieldsWhenEqualsExists() throws Exception {
    FileObject java = FileUtil.createData(fo, "X.java");
    String what1 = "class X {" +
        "  private int x;" +
        "  private int y;" +
        "  public Object equals(Object snd) {" +
        "    if (snd instanceof X) {" +
        "       X x2 = (X)snd;";
    
    String what2 = 
        "       return this.x == x2.x;" +
        "    }" +
        "    return false;" +
        "  }" +
        "}";
    String what = what1 + what2;
    GeneratorUtilsTest.writeIntoFile(java, what);
    
    JavaSource js = JavaSource.forFileObject(java);
    assertNotNull("Created", js);
    
    class Task implements CancellableTask<CompilationController> {
        EqualsHashCodeGenerator generator;
        
        public void cancel() {
            throw new UnsupportedOperationException("Not supported yet.");
        }

        public void run(CompilationController cc) throws Exception {
            cc.toPhase(JavaSource.Phase.ELEMENTS_RESOLVED);
            Element el = cc.getElements().getTypeElement("X");
            generator = EqualsHashCodeGenerator.createEqualsHashCodeGenerator(null, cc, el);
        }
        
        
        public void post() throws Exception {
            assertNotNull("panel", generator);
            
            assertEquals("Two fields", 2, generator.description.getSubs().size());
            assertEquals("x field selected", true, generator.description.getSubs().get(0).isSelected());
            assertEquals("y field not selected", false, generator.description.getSubs().get(1).isSelected());
            assertEquals("generate hashCode", true, generator.generateHashCode);
            assertEquals("generate equals", false, generator.generateEquals);
        }
    }
    Task t = new Task();
    
    js.runUserActionTask(t, false);
    t.post();
}
 
Example 16
Source File: EjbRefactoringPlugin.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
public Problem checkParameters() {
    final Problem[] result = new Problem[1];
    final TreePathHandle tph = refactoring.getRefactoringSource().lookup(TreePathHandle.class);
    if (tph != null) {
        FileObject fo = tph.getFileObject();
        if (fo != null) {
            try {
                JavaSource js = JavaSource.forFileObject(fo);
                if (js != null) {
                    js.runUserActionTask(new CancellableTask<CompilationController>() {
                        @Override
                        public void run(CompilationController info) throws Exception {
                            info.toPhase(JavaSource.Phase.RESOLVED);
                            Element el = tph.resolveElement(info);
                            if (el == null) {
                                return;
                            }

                            if (el.getModifiers().contains(Modifier.PRIVATE)) {
                                result[0] = null;
                            } else {
                                String refactoringWarning = getRefactoringWarning();
                                if (refactoringWarning != null) {
                                    result[0] = new Problem(false, refactoringWarning);
                                }
                            }
                        }

                        @Override
                        public void cancel() {
                            throw new UnsupportedOperationException("Not supported yet."); // NOI18N
                        }
                    }, true);
                }
            } catch (IOException ex) {
                LOG.log(Level.INFO, null, ex);
            }
        }
    }
    return result[0];
}
 
Example 17
Source File: ELDeclarationFinder.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
public DeclarationLocation findDeclaration(final ParserResult info, int offset) {
    final Pair<Node, ELElement> nodeElem = ELHyperlinkProvider.resolveNodeAndElement(info.getSnapshot().getSource(), offset, new AtomicBoolean());
    if (nodeElem == null) {
        return DeclarationLocation.NONE;
    }
    final FileObject file = info.getSnapshot().getSource().getFileObject();
    final ClasspathInfo cp = ELTypeUtilities.getElimplExtendedCPI(file);
    final RefsHolder refs = new RefsHolder();
    final List<AlternativeLocation> alternatives = new ArrayList<>();
    try {
        JavaSource.create(cp).runUserActionTask(new Task<CompilationController>() {
            @Override
            public void run(CompilationController cc) throws Exception {
                cc.toPhase(JavaSource.Phase.RESOLVED);
                CompilationContext context = CompilationContext.create(file, cc);

                // resolve beans
                Element javaElement = ELTypeUtilities.resolveElement(context, nodeElem.second(), nodeElem.first());
                if (javaElement != null) {
                    refs.handle = ElementHandle.<Element>create(javaElement);
                    refs.fo = SourceUtils.getFile(refs.handle, cp);
                }

                // resolve resource bundles
                ResourceBundles resourceBundles = ResourceBundles.get(file);
                if (resourceBundles.canHaveBundles()) {
                    List<ResourceBundles.Location> bundleLocations = getBundleLocations(resourceBundles, nodeElem);
                    if (!bundleLocations.isEmpty()) {
                        refs.fo = bundleLocations.get(0).getFile();
                        refs.offset = bundleLocations.get(0).getOffset();
                        for (ResourceBundles.Location location : bundleLocations) {
                            alternatives.add(new ResourceBundleAlternative(location));
                        }
                    }
                }
            }
        }, true);
        if (refs.fo != null) {
            JavaSource javaSource = JavaSource.forFileObject(refs.fo);
            if (javaSource != null) {
                // java bean
                javaSource.runUserActionTask(new Task<CompilationController>() {
                    @Override
                    public void run(CompilationController controller) throws Exception {
                        controller.toPhase(JavaSource.Phase.ELEMENTS_RESOLVED);
                        Element element = refs.handle.resolve(controller);
                        Trees trees = controller.getTrees();
                        Tree tree = trees.getTree(element);
                        SourcePositions sourcePositions = trees.getSourcePositions();
                        refs.offset = (int) sourcePositions.getStartPosition(controller.getCompilationUnit(), tree);
                    }
                }, true);
            }
        }
    } catch (IOException ex) {
        Exceptions.printStackTrace(ex);
    }

    if (refs.fo != null && refs.offset != -1) {
        DeclarationLocation declarationLocation = new DeclarationLocation(refs.fo, refs.offset);
        for (AlternativeLocation alternativeLocation : alternatives) {
            declarationLocation.addAlternative(alternativeLocation);
        }
        return declarationLocation;
    }
    return DeclarationLocation.NONE;
}
 
Example 18
Source File: JaxWsNode.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private void resolveServiceInfo(final ServiceInfo serviceInfo, 
        final boolean inEjbProject) throws UnsupportedEncodingException 
{
    final String[] serviceName = new String[1];
    final String[] name = new String[1];
    final boolean[] isProvider = {false};
    serviceInfo.setEjb(inEjbProject);
    JavaSource javaSource = getImplBeanJavaSource();
    if (javaSource != null) {
        CancellableTask<CompilationController> task = new 
            CancellableTask<CompilationController>() 
            {

                @Override
                public void run(CompilationController controller) 
                    throws IOException 
                {
                    controller.toPhase(Phase.ELEMENTS_RESOLVED);
                    TypeElement typeElement = SourceUtils.
                        getPublicTopLevelElement(controller);
                    if ( typeElement == null ){
                        return;
                    }
                    boolean foundWsAnnotation = resolveServiceUrl(controller, 
                            typeElement,  serviceName, name);
                    if (!foundWsAnnotation) {
                        isProvider[0] = JaxWsUtils.hasAnnotation(typeElement, 
                                "javax.xml.ws.WebServiceProvider");     // NOI18N
                    }
                    if (!inEjbProject) {
                        serviceInfo.setEjb(isStatelessEjb(typeElement));
                    }
                }

            @Override
            public void cancel() {
            }
        };
        try {
            javaSource.runUserActionTask(task, true);
        } catch (IOException ex) {
            ErrorManager.getDefault().notify(ex);
        }
    }

    String qualifiedImplClassName = service.getImplementationClass();
    String implClassName = getNameFromPackageName(qualifiedImplClassName);
    if (serviceName[0] == null) {
        serviceName[0] = URLEncoder.encode(implClassName + "Service", "UTF-8");
    }
    serviceInfo.setServiceName(serviceName[0]);
    if (name[0] == null) {
        if (isProvider[0]) {
            //per JSR 109, use qualified impl class name for EJB
            name[0] = qualifiedImplClassName;
        } else {
            name[0] = implClassName;
        }
        name[0] = URLEncoder.encode(name[0], "UTF-8"); //NOI18N
    }
    serviceInfo.setPortName(name[0]);
}
 
Example 19
Source File: ToStringGeneratorTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public void testToStringWithPlusOperator() throws Exception {
    FileObject javaFile = FileUtil.createData(fo, "NewClass.java");
    String what1 = ""
            + "public class NewClass {\n"
            + "    private final String test1 = \"test\";\n"
            + "    private final String test2 = \"test\";\n"
            + "    private final String test3 = \"test\";\n";

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

    JavaSource javaSource = JavaSource.forFileObject(javaFile);
    assertNotNull("Created", javaSource);

    Document doc = getDocuemnt(javaFile);

    final JTextArea component = new JTextArea(doc);
    component.setCaretPosition(what1.length());

    class Task implements org.netbeans.api.java.source.Task<CompilationController> {

        private ToStringGenerator generator;

        @Override
        public void run(CompilationController controller) throws Exception {
            controller.toPhase(JavaSource.Phase.ELEMENTS_RESOLVED);
            Element typeElement = controller.getElements().getTypeElement("NewClass");
            generator = ToStringGenerator.createToStringGenerator(component, controller, typeElement, false);
        }

        public void post() throws Exception {
            assertNotNull("Created", generator);

            assertEquals("Three fields", 3, generator.getDescription().getSubs().size());
            assertEquals("test1 field selected", true, generator.getDescription().getSubs().get(0).isSelected());
            assertEquals("test2 field selected", true, generator.getDescription().getSubs().get(1).isSelected());
            assertEquals("test3 field selected", true, generator.getDescription().getSubs().get(2).isSelected());
            assertEquals("Don't use StringBuilder", false, generator.useStringBuilder());
        }
    }
    final Task task = new Task();

    javaSource.runUserActionTask(task, false);
    task.post();

    SwingUtilities.invokeAndWait(() -> task.generator.invoke());

    Document document = component.getDocument();
    String text = document.getText(0, document.getLength());
    String expected = ""
            + "public class NewClass {\n"
            + "    private final String test1 = \"test\";\n"
            + "    private final String test2 = \"test\";\n"
            + "    private final String test3 = \"test\";\n"
            + "\n"
            + "    @Override\n"
            + "    public String toString() {\n"
            + "        return \"NewClass{\" + \"test1=\" + test1 + \", test2=\" + test2 + \", test3=\" + test3 + '}';\n"
            + "    }\n"
            + "\n"
            + "}";
    assertEquals(expected, text);
}
 
Example 20
Source File: ToStringGeneratorTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public void testToStringExists() throws Exception {
    FileObject javaFile = FileUtil.createData(fo, "NewClass.java");
    String what1 = ""
            + "public class NewClass {\n"
            + "    private final String test1 = \"test\";\n"
            + "    private final String test2 = \"test\";\n"
            + "    private final String test3 = \"test\";\n";

    String what2 = ""
            + "\n"
            + "    @Override\n"
            + "    public String toString() {\n"
            + "        StringBuilder sb = new StringBuilder();\n"
            + "        sb.append(\"NewClass{\");\n"
            + "        sb.append(\"test1=\").append(test1);\n"
            + "        sb.append(\", \");\n"
            + "        sb.append(\"test2=\").append(test2);\n"
            + "        sb.append(\", \");\n"
            + "        sb.append(\"test3=\").append(test3);\n"
            + "        sb.append('}');\n"
            + "        return sb.toString();\n"
            + "    }\n"
            + "\n"
            + "}";
    String what = what1 + what2;
    GeneratorUtilsTest.writeIntoFile(javaFile, what);

    JavaSource javaSource = JavaSource.forFileObject(javaFile);
    assertNotNull("Created", javaSource);

    Document doc = getDocuemnt(javaFile);

    final JTextArea component = new JTextArea(doc);
    component.setCaretPosition(what1.length());

    class Task implements org.netbeans.api.java.source.Task<CompilationController> {

        private ToStringGenerator generator;

        @Override
        public void run(CompilationController controller) throws Exception {
            controller.toPhase(JavaSource.Phase.ELEMENTS_RESOLVED);
            Element typeElement = controller.getElements().getTypeElement("NewClass");
            generator = ToStringGenerator.createToStringGenerator(component, controller, typeElement, true);
        }

        public void post() throws Exception {
            assertNull("Not created", generator);
        }
    }
    final Task task = new Task();

    javaSource.runUserActionTask(task, false);
    task.post();
}