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

The following examples show how to use org.netbeans.api.java.source.JavaSource#runModificationTask() . 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: Utils.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public static boolean canExposeInRemote(FileObject ejbClassFO, final ElementHandle<ExecutableElement> methodHandle) throws IOException {
    JavaSource javaSource = JavaSource.forFileObject(ejbClassFO);
    final String[] ejbClassName = new String[1];
    final MethodModel[] methodModel = new MethodModel[1];
    javaSource.runModificationTask(new Task<WorkingCopy>() {
        public void run(WorkingCopy workingCopy) throws IOException {
            workingCopy.toPhase(JavaSource.Phase.ELEMENTS_RESOLVED);
            ExecutableElement executableElement = methodHandle.resolve(workingCopy);
            Set<Modifier> modifiers = executableElement.getModifiers();
            boolean signatureOk = modifiers.contains(Modifier.PUBLIC) && !modifiers.contains(Modifier.STATIC);
            if (signatureOk) {
                Element enclosingElement = executableElement.getEnclosingElement();
                ejbClassName[0] = ((TypeElement) enclosingElement).getQualifiedName().toString();
                methodModel[0] = MethodModelSupport.createMethodModel(workingCopy, executableElement);
            }
        }
    });
    if (methodModel[0] != null) {
        EjbMethodController ejbMethodController = EjbMethodController.createFromClass(ejbClassFO, ejbClassName[0]);
        return ejbMethodController != null && ejbMethodController.hasRemote() && !ejbMethodController.hasMethodInInterface(methodModel[0], ejbMethodController.getMethodTypeFromImpl(methodModel[0]), true);
    }
    return false;
}
 
Example 2
Source File: GenerationUtilsTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static ModificationResult runModificationTask(FileObject javaFile, final Task<WorkingCopy> taskToTest) throws Exception {
    JavaSource javaSource = JavaSource.forFileObject(javaFile);
    return javaSource.runModificationTask(new Task<WorkingCopy>() {
        public void run(WorkingCopy controller) throws Exception {
            controller.toPhase(Phase.RESOLVED);
            taskToTest.run(controller);
        }
    });
}
 
Example 3
Source File: GenericResourceGenerator.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private void addInputParamFields(JavaSource source) throws IOException {
    ModificationResult result = source.runModificationTask(new AbstractTask<WorkingCopy>() {
        @Override
        public void run(WorkingCopy copy) throws IOException {
            copy.toPhase(JavaSource.Phase.ELEMENTS_RESOLVED);
            List<ParameterInfo> params = bean.getInputParameters();
            
            JavaSourceHelper.addFields(copy, getParamNames(params),
                    getParamTypeNames(params), getParamValues(params));
        }
    });
    result.commit();
}
 
Example 4
Source File: CompilationUnitTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void test157760b() throws Exception {
    testFile = new File(getWorkDir(), "package-info.java");
    TestUtilities.copyStringToFile(testFile, "@AA\n@BB\n@CC\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\n@CC\n@DD\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);
}
 
Example 5
Source File: JavaUtil.java    From netbeans with Apache License 2.0 5 votes vote down vote up
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();
    }
}
 
Example 6
Source File: J2eeUtil.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 *  Return target and generated file objects
 */
public static void addServletMethod(final SaasBean bean,
        String groupName, final String methodName, final JavaSource source,
        final String[] parameters, final Object[] paramTypes,
        final String bodyText) throws IOException {

    if (JavaSourceHelper.isContainsMethod(source, methodName, parameters, paramTypes)) {
        return;
    }
    ModificationResult result = source.runModificationTask(new AbstractTask<WorkingCopy>() {

        public void run(WorkingCopy copy) throws IOException {
            copy.toPhase(JavaSource.Phase.RESOLVED);

            javax.lang.model.element.Modifier[] modifiers = JavaUtil.PROTECTED;

            String type = Constants.VOID;

            String comment = "\n";// NOI18N
            for (String param : parameters) {
                comment += "@param $PARAM$ resource URI parameter\n".replace("$PARAM$", param);// NOI18N
            }
            comment += "@return an instance of " + type;// NOI18N
            ClassTree initial = JavaSourceHelper.getTopLevelClassTree(copy);
            ClassTree tree = JavaSourceHelper.addMethod(copy, initial,
                    modifiers, null, null,
                    methodName, type, parameters, paramTypes,
                    null, null, new String[]{"javax.servlet.ServletException", "java.io.IOException"},
                    bodyText, comment);      //NOI18N
            copy.rewrite(initial, tree);
        }
    });
    result.commit();
}
 
Example 7
Source File: JaxWsUtils.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static void doModifySoap12Binding(final JavaSource javaSource, 
        final CancellableTask<WorkingCopy> modificationTask, 
        final FileObject implClass, boolean isIncomplete ) 
{
    try {
        ModificationResult result = javaSource.runModificationTask(modificationTask);
        if ( isIncomplete && 
                org.netbeans.api.java.source.SourceUtils.isScanInProgress())
        {
            final Runnable runnable = new Runnable(){
                /* (non-Javadoc)
                 * @see java.lang.Runnable#run()
                 */
                @Override
                public void run() {
                    modifySoap12Binding(javaSource, modificationTask, 
                                implClass, false);
                }
            };
            SwingUtilities.invokeLater( new Runnable(){
                @Override
                public void run() {
                    ScanDialog.runWhenScanFinished( runnable, NbBundle.getMessage(
                            JaxWsUtils.class, "LBL_ConfigureSoapBinding"));  // NOI18N
                }
            });
        }
        else { 
            result.commit();
            saveFile(implClass);
        }
    }
    catch (IOException ex) {
        Logger.getLogger( JaxWsUtils.class.getName()).log( 
                Level.WARNING, null , ex);
    }
}
 
Example 8
Source File: AddJavaFXPropertyCodeGenerator.java    From netbeans with Apache License 2.0 5 votes vote down vote up
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);
        }
    }
}
 
Example 9
Source File: ListenerGenerator.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void generate(JavaSource clazz) throws IOException {
        Task<WorkingCopy> task = new Task<WorkingCopy>() {
            public void run(WorkingCopy workingCopy) throws Exception {
                workingCopy.toPhase(Phase.RESOLVED);
                CompilationUnitTree cut = workingCopy.getCompilationUnit();

                gu = GenerationUtils.newInstance(workingCopy);
                for (Tree typeDecl : cut.getTypeDecls()) {
                    if (TreeUtilities.CLASS_TREE_KINDS.contains(typeDecl.getKind())) {
                        Element e = workingCopy.getTrees().getElement(new TreePath(new TreePath(workingCopy.getCompilationUnit()), typeDecl));
                        if (e != null && e.getKind().isClass()) {
                            TypeElement te = (TypeElement) e;
                            ClassTree ct = (ClassTree) typeDecl;
                            workingCopy.rewrite(ct, generateInterfaces(workingCopy, te, ct, gu));
                        }
                    }
                }
            }
        };
        ModificationResult result = clazz.runModificationTask(task);
        result.commit();

//        if (isContext) addContextListenerMethods();
//        if (isContextAttr) addContextAttrListenerMethods();
//        if (isSession) addSessionListenerMethods();
//        if (isSessionAttr) addSessionAttrListenerMethods();
//        if (isRequest) addRequestListenerMethods();
//        if (isRequestAttr) addRequestAttrListenerMethods();
    }
 
Example 10
Source File: ClientJavaSourceHelper.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private static void addJerseyClient (
        final JavaSource source,
        final String className,
        final String resourceUri,
        final RestServiceDescription restServiceDesc,
        final WadlSaasResource saasResource,
        final PathFormat pf,
        final Security security, final ClientGenerationStrategy strategy ) 
{
    try {
        final Task<WorkingCopy> task = new AbstractTask<WorkingCopy>() {

            @Override
            public void run(WorkingCopy copy) throws java.io.IOException {
                copy.toPhase(JavaSource.Phase.RESOLVED);

                ClassTree tree = JavaSourceHelper.getTopLevelClassTree(copy);
                ClassTree modifiedTree = null;
                if (className == null) {
                    modifiedTree = modifyJerseyClientClass(copy, tree, 
                            resourceUri, restServiceDesc, saasResource, pf, 
                            security, strategy );
                } else {
                    modifiedTree = addJerseyClientClass(copy, tree, 
                            className, resourceUri, restServiceDesc, 
                            saasResource, pf, security, strategy);
                }

                copy.rewrite(tree, modifiedTree);
            }
        };
        ModificationResult result = source.runModificationTask(task);

        if ( SourceUtils.isScanInProgress() ){
            source.runWhenScanFinished( new Task<CompilationController>(){
                @Override
                public void run(CompilationController controller) throws Exception {
                    source.runModificationTask(task).commit();
                }
            }, true);
        }
        else {
            result.commit();
        }
    } catch (java.io.IOException ex) {
        if (ex.getCause() instanceof GuardedException) {
            DialogDisplayer.getDefault().notify(
                    new NotifyDescriptor.Message(
                        NbBundle.getMessage(ClientJavaSourceHelper.class, 
                                "ERR_CannotApplyGuarded"),              // NOI18N
                        NotifyDescriptor.ERROR_MESSAGE));
            Logger.getLogger(ClientJavaSourceHelper.class.getName()).
                log(Level.FINE, null, ex);
        }
        else {
            Logger.getLogger(ClientJavaSourceHelper.class.getName()).
                log(Level.WARNING, null, ex);
        }
    }
}
 
Example 11
Source File: CompilationUnitTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public void test117607_2() throws Exception {
    testFile = new File(getWorkDir(), "Test.java");
    TestUtilities.copyStringToFile(testFile, 
        "package zoo;\n" +
        "\n" +
        "import java.io.File;\n" +
        "\n" +
        "public class A {\n" +
        "  public class Krtek {\n" +
        "    File m() {\n" +
        "      return null;\n" +
        "    }\n" +
        "  }\n" +
        "}\n"
    );
    
    FileObject emptyJava = FileUtil.createData(FileUtil.getConfigRoot(), "Templates/Classes/Empty.java");
    emptyJava.setAttribute("template", Boolean.TRUE);
    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" +
        "import java.io.File;\n" +
        "\n" +
        "public class Krtek {\n" +
        "\n" +
        "    File m() {\n" +
        "        return null;\n" +
        "    }\n" +
        "}\n";
    String golden2 = 
        "package zoo;\n" +
        "\n" +
        "import java.io.File;\n" +
        "\n" +
        "public class A {\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 cut = workingCopy.getCompilationUnit();
            if (cut.getTypeDecls().isEmpty()) return;
            ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
            clazz = (ClassTree) clazz.getMembers().get(1);
            CompilationUnitTree newTree = make.CompilationUnit(
                    sourceRoot,
                    "zoo/Krtek.java",
                    Collections.<ImportTree>emptyList(),
                    Collections.<Tree>emptyList()
            );
            newTree = make.addCompUnitTypeDecl(newTree, GeneratorUtilities.get(workingCopy).importFQNs(clazz));
            workingCopy.rewrite(null, newTree);
            workingCopy.rewrite(
                    cut.getTypeDecls().get(0), 
                    make.removeClassMember((ClassTree) cut.getTypeDecls().get(0), clazz)
            );
        }
    };
    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);
    res = TestUtilities.copyFileToString(testFile);
    //System.err.println(res);
    assertEquals(res, golden2);
}
 
Example 12
Source File: ToStringGenerator.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
public void invoke() {
    final int caretOffset = component.getCaretPosition();
    final ToStringPanel panel = new ToStringPanel(description, useStringBuilder, supportsStringBuilder);
    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(), panel.useStringBuilder());
                        copy.rewrite(cls, GeneratorUtils.insertClassMembers(copy, cls, Collections.singletonList(mth), caretOffset));
                    }
                }
            });
            GeneratorUtils.guardedCommit(component, mr);
        } catch (IOException ex) {
            Exceptions.printStackTrace(ex);
        }
    }
}
 
Example 13
Source File: CompilationUnitTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
/** 
 * With bugfix #239849, newly created compilation units should retain their initial template comment, UNLESS
 * the replacement tree comes with its own initial comment(s). This test ensures that a CU correctly replaces
 * the template initial comment. The {@link #testNewCompilationUnitFromTemplate} checks that the template
 * init comment is retained in case the new CU content does not specify any.
 */
public void testReplaceInitialComment() 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" +
        " * replaced\n" +
        " * content */\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()
            );
            GeneratorUtilities gu = GeneratorUtilities.get(workingCopy);

            Comment comment = Comment.create(Comment.Style.BLOCK, 0, 0, 0, "\nreplaced\ncontent\n");
            
            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)));
            make.addComment(newTree, comment, true);
            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(golden1, res);
}
 
Example 14
Source File: SelectMethodGeneratorTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public void testGenerateCmpCardinalityOne() throws IOException {
    TestModule testModule = createEjb21Module();

    // add create method into local and remote interfaces of CMP Entity EJB 
    FileObject beanClass = testModule.getSources()[0].getFileObject("cmplr/CmpLRBean.java");
    EjbJar ejbJar = DDProvider.getDefault().getDDRoot(testModule.getDeploymentDescriptor());
    SelectMethodGenerator generator = SelectMethodGenerator.create("cmplr.CmpLRBean", beanClass);
    final MethodModel methodModel = MethodModel.create(
            "ejbSelectTest",
            "int",
            "",
            Collections.singletonList(MethodModel.Variable.create("java.lang.String", "name")),
            Collections.<String>emptyList(),
            Collections.<Modifier>emptySet()
            );
    String ejbql = "SELECT COUNT(o) FROM CmpLR o";
    generator.generate(methodModel, true, true, true, ejbql);
    
    final boolean[] found = new boolean[] { false };
    JavaSource javaSource = JavaSource.forFileObject(beanClass);
    javaSource.runModificationTask(new Task<WorkingCopy>() {
        public void run(WorkingCopy workingCopy) throws IOException {
            workingCopy.toPhase(JavaSource.Phase.ELEMENTS_RESOLVED);
            TypeElement typeElement = workingCopy.getElements().getTypeElement("cmplr.CmpLRBean");
            for (ExecutableElement executableElement : ElementFilter.methodsIn(typeElement.getEnclosedElements())) {
                if (executableElement.getSimpleName().contentEquals("ejbSelectTest")) {
                    MethodTree methodTree = workingCopy.getTrees().getTree(executableElement);
                    assertNull(methodTree.getBody());
                    assertSame(TypeKind.INT, executableElement.getReturnType().getKind());
                    TypeElement finderException = workingCopy.getElements().getTypeElement("javax.ejb.FinderException");
                    assertTrue(executableElement.getThrownTypes().contains(finderException.asType()));
                    VariableElement parameter = executableElement.getParameters().get(0);
                    TypeElement stringTypeElement = workingCopy.getElements().getTypeElement(String.class.getName());
                    assertTrue(workingCopy.getTypes().isSameType(stringTypeElement.asType(), parameter.asType()));
                    found[0] = true;
                }
            }
        }
    });
    assertTrue(found[0]);
    
    // entry in deployment descriptor
    Entity entity = (Entity) ejbJar.getEnterpriseBeans().findBeanByName(EnterpriseBeans.ENTITY, Entity.EJB_CLASS, "cmplr.CmpLRBean");
    boolean queryFound = false;
    for (Query query : entity.getQuery()) {
        QueryMethod queryMethod = query.getQueryMethod();
        if ("ejbSelectTest".equals(queryMethod.getMethodName())) {
            assertEquals(ejbql, query.getEjbQl());
            queryFound = true;
        }
    }
    assertTrue(queryFound);
    
}
 
Example 15
Source File: CompilationUnitTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public void testNewCompilationUnitFromTemplate() throws Exception {
    testFile = new File(getWorkDir(), "Test.java");

    File fakeFile = new File(getWorkDir(), "Fake.java");
    FileObject fakeFO = FileUtil.createData(fakeFile);

    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);
    classJava.setAttribute("verbatim-create-from-template", Boolean.TRUE);
    Writer w = new OutputStreamWriter(classJava.getOutputStream(), "UTF-8");
    w.write("/*\n * License\n */\npackage zoo;\n\n/**\n * trida\n */\npublic class Template {\n}");
    w.close();

    FileObject packageJava = FileUtil.createData(FileUtil.getConfigRoot(), "Templates/Classes/package-info.java");
    packageJava.setAttribute("template", Boolean.TRUE);
    packageJava.setAttribute("verbatim-create-from-template", Boolean.TRUE);
    Writer w2 = new OutputStreamWriter(packageJava.getOutputStream(), "UTF-8");
    w2.write("/*\n * License\n */\npackage zoo;\n");
    w2.close();

    FileObject testSourceFO = FileUtil.createData(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);
    JavaSource javaSource = JavaSource.create(cpInfo, fakeFO);

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

        public void cancel() {
        }

        public void run(WorkingCopy workingCopy) throws Exception {
            workingCopy.toPhase(JavaSource.Phase.PARSED);
            TreeMaker make = workingCopy.getTreeMaker();
            String path = "zoo/Krtek.java";
            GeneratorUtilities genUtils = GeneratorUtilities.get(workingCopy);
            CompilationUnitTree newTree = genUtils.createFromTemplate(sourceRoot, path, ElementKind.CLASS);
            MethodTree nju = make.Method(
                    make.Modifiers(Collections.<Modifier>emptySet()),
                    "m",
                    make.PrimitiveType(TypeKind.VOID), // return type - void
                    Collections.<TypeParameterTree>emptyList(),
                    Collections.<VariableTree>emptyList(),
                    Collections.<ExpressionTree>emptyList(),
                    make.Block(Collections.<StatementTree>emptyList(), false),
                    null // default value - not applicable
            );
            ClassTree clazz = make.Class(
                    make.Modifiers(Collections.<Modifier>singleton(Modifier.PUBLIC)),
                    "Krtek",
                    Collections.<TypeParameterTree>emptyList(),
                    null,
                    Collections.<Tree>emptyList(),
                    Collections.singletonList(nju)
            );
            if(newTree.getTypeDecls().isEmpty()) {
                newTree = make.addCompUnitTypeDecl(newTree, clazz);
            } else {
                Tree templateClass = newTree.getTypeDecls().get(0);
                genUtils.copyComments(templateClass, clazz, true);
                genUtils.copyComments(templateClass, clazz, false);
                newTree = make.removeCompUnitTypeDecl(newTree, 0);
                newTree = make.insertCompUnitTypeDecl(newTree, 0, clazz);
            }
            workingCopy.rewrite(null, newTree);

            String packagePath = "zoo/package-info.java";
            CompilationUnitTree newPackageTree = genUtils.createFromTemplate(sourceRoot, packagePath, ElementKind.PACKAGE);
            workingCopy.rewrite(null, newPackageTree);
        }
    };
    ModificationResult result = javaSource.runModificationTask(task);
    result.commit();

    String goldenClass =
        "/*\n * License\n */\n" +
        "package zoo;\n" +
        "\n" +
        "/**\n * trida\n */\n" +
        "public class Krtek {\n" +
        "\n" +
        "    void m() {\n" +
        "    }\n" +
        "}";
    String res = TestUtilities.copyFileToString(new File(getDataDir().getAbsolutePath() + "/zoo/Krtek.java"));
    assertEquals(goldenClass, res);

    String goldenPackage =
        "/*\n * License\n */\n" +
        "package zoo;\n";
    res = TestUtilities.copyFileToString(new File(getDataDir().getAbsolutePath() + "/zoo/package-info.java"));
    assertEquals(goldenPackage, res);
}
 
Example 16
Source File: CompilationUnitTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public void testRemoveClassFromCompUnit() throws Exception {
    testFile = new File(getWorkDir(), "Test.java");
    TestUtilities.copyStringToFile(testFile, 
            "package zoo;\n"
            + "\n"
            + "public class A {\n"
            + "  /** Something about a */\n"
            + "  int a;\n"
            + "  public class Krtek {\n"
            + "    public void foo() {\n"
            + "      int c=a;\n"
            + "    }\n"
            + "  }\n"
            + "}\n"
            + "class B {\n"
            + "    int a = 42;\n"
            + "}\n");
    
    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" +
        "class B {\n" +
        "    int a = 42;\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.PARSED);
            TreeMaker make = workingCopy.getTreeMaker();
            CompilationUnitTree cut = workingCopy.getCompilationUnit();
            CompilationUnitTree ccut = GeneratorUtilities.get(workingCopy).importComments(cut, cut);
            ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
            CompilationUnitTree newTree = make.removeCompUnitTypeDecl(ccut, clazz);
            workingCopy.rewrite(cut, newTree);
        }
    };
    ModificationResult result = javaSource.runModificationTask(task);
    result.commit();
    String res = TestUtilities.copyFileToString(testFile);
    //System.err.println(res);
    assertEquals(golden1, res);
}
 
Example 17
Source File: TreeTaggingTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
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]));
    }
 
Example 18
Source File: TreeTaggingTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
/**
 * 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]));
}
 
Example 19
Source File: TreeTaggingTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
/**
 * Adds 'System.err.println(true);' statement to the method body,
 * tags the tree and checks the marks are valid
 */
public void testTaggingOfGeneratedMethodBody() 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);
            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(115, span[0]);

    assertEquals("System.err.println(true);", diff.getResultingSource(FileUtil.toFileObject(testFile)).substring(span[0], span[1]));
}
 
Example 20
Source File: ImplementOverrideMethodGenerator.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
public void invoke() {
    final int caretOffset = component.getCaretPosition();
    final List<ElementHandle<? extends Element>> methodList = displaySelectionDialog(description, isImplement);
    if (methodList != null) {
        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 = handle.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(ImplementOverrideMethodGenerator.class, "ERR_CannotFindOriginalClass"); //NOI18N
                            org.netbeans.editor.Utilities.setStatusBoldText(component, message);
                        } else {
                            ArrayList<ExecutableElement> methodElements = new ArrayList<>();
                            for (ElementHandle<? extends Element> elementHandle : methodList) {
                                ExecutableElement methodElement = (ExecutableElement)elementHandle.resolve(copy);
                                if (methodElement != null) {
                                    methodElements.add(methodElement);
                                }
                            }
                            if (!methodElements.isEmpty()) {
                                if (isImplement) {
                                    GeneratorUtils.generateAbstractMethodImplementations(copy, path, methodElements, caretOffset);
                                } else {
                                    GeneratorUtils.generateMethodOverrides(copy, path, methodElements, caretOffset);
                                }
                            }
                        }
                    }
                });
                GeneratorUtils.guardedCommit(component, mr);
                int span[] = mr.getSpan("methodBodyTag"); // NOI18N
                if(span != null) {
                    component.setSelectionStart(span[0]);
                    component.setSelectionEnd(span[1]);
                }
            } catch (IOException ex) {
                Exceptions.printStackTrace(ex);
            }
        }
    }
}