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

The following examples show how to use org.netbeans.api.java.source.JavaSource#forFileObject() . 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: MarkOccurrencesTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private JavaSource openFile(String name) throws DataObjectNotFoundException, IOException, InterruptedException, InvocationTargetException {
    String dataDir = getDataDir().getAbsoluteFile().getPath();
    File sample = new File(dataDir+"/projects/java_editor_test/src/markOccurrences",name);
    assertTrue("file "+sample.getAbsolutePath()+" does not exist",sample.exists());
    
    fileObject = FileUtil.toFileObject(sample);
    dataObject = DataObject.find(fileObject);
    JavaSource js = JavaSource.forFileObject(fileObject);                
    final EditorCookie ec = dataObject.getCookie(EditorCookie.class);
    ec.openDocument();
    ec.open();
            
    SwingUtilities.invokeAndWait(new Runnable() {
        public void run() {
            JEditorPane[] panes = ec.getOpenedPanes();
            editorPane = panes[0];
            
        }
    });
    return js;
    
}
 
Example 2
Source File: SpringRefactorings.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public static List<String> getTopLevelClassNames(FileObject fo) throws IOException {
    JavaSource javaSource = JavaSource.forFileObject(fo);
    if (javaSource == null) {
        return Collections.emptyList();
    }
    final List<String> result = new ArrayList<String>(1);
    javaSource.runUserActionTask(new Task<CompilationController>() {
        public void run(CompilationController cc) throws IOException {
            cc.toPhase(Phase.ELEMENTS_RESOLVED);
            for (TypeElement typeElement : cc.getTopLevelElements()) {
                result.add(ElementUtilities.getBinaryName(typeElement));
            }
        }
    }, true);
    return result;
}
 
Example 3
Source File: JaxWsCodeGenerator.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static void getInitValue(final String type, FileObject targetFile, final ResultHolder<String> result) {
    if (targetFile == null) {
        return;
    }
    JavaSource targetSource = JavaSource.forFileObject(targetFile);

    if (targetSource == null) {
        result.setResult("null;"); //NOI18N
        return;
    }
    
    CancellableTask<CompilationController> task = new CancellableTask<CompilationController>() {

        public void run(CompilationController controller) throws IOException {
            controller.toPhase(Phase.ELEMENTS_RESOLVED);
            if (!isEnum(controller, type)) {
                if (hasNoArgConstructor(controller, type)) {
                    result.setResult("new " + type + "();");//NOI18N
                }
            }
        }

        public void cancel() {
        }
    };
    try {
        targetSource.runUserActionTask(task, true);
    } catch (IOException e) {
        ErrorManager.getDefault().notify(e);
    }
}
 
Example 4
Source File: ModifiersTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Original:
 * 
 * public Test() {
 * }
 * 
 * Result:
 * 
 * Test() {
 * }
 */
public void testMethodMods4() throws Exception {
    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 Test() {\n" +
            "    }\n" +
            "}\n"
            );
    String golden =
            "package hierbas.del.litoral;\n\n" +
            "import java.io.*;\n\n" +
            "public class Test {\n" +
            "    Test() {\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(0);
            ModifiersTree mods = method.getModifiers();
            workingCopy.rewrite(mods, make.Modifiers(Collections.<Modifier>emptySet()));
        }
        
    };
    testSource.runModificationTask(task).commit();
    String res = TestUtilities.copyFileToString(testFile);
    //System.err.println(res);
    assertEquals(golden, res);
}
 
Example 5
Source File: FeatureAddingTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testAddFieldToEmpty() throws Exception {
    testFile = new File(getWorkDir(), "Test.java");
    TestUtilities.copyStringToFile(testFile, 
        "package hierbas.del.litoral;\n" +
        "\n" +
        "import java.io.File;\n" +
        "\n" +
        "public class Test {\n" +
        "}\n"
        );
    String golden =
        "package hierbas.del.litoral;\n" +
        "\n" +
        "import java.io.File;\n" +
        "\n" +
        "public class Test {\n" +
        "\n" +
        "    String s;\n" +
        "}\n";

    JavaSource src = JavaSource.forFileObject(FileUtil.toFileObject(testFile));
    Task<WorkingCopy> task = new Task<WorkingCopy>() {
        
        public void run(WorkingCopy workingCopy) throws IOException {
            workingCopy.toPhase(Phase.RESOLVED);
            BlockTree block = (BlockTree) workingCopy.getTreeUtilities().parseStatement("{ String s; }", null);
            TreeMaker make = workingCopy.getTreeMaker();
            CompilationUnitTree cut = workingCopy.getCompilationUnit();
            ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
            VariableTree member = (VariableTree) block.getStatements().get(0);
            ClassTree copy = make.insertClassMember(clazz, 0, member);
            workingCopy.rewrite(clazz, copy);
        }
        
    };
    src.runModificationTask(task).commit();
    String res = TestUtilities.copyFileToString(testFile);
    //System.err.println(res);
    assertEquals(golden, res);
}
 
Example 6
Source File: JavaSourceHelper.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static JavaSource createJavaSource(String template, FileObject targetFolder, String packageName, String className) {
    try {
        FileObject fobj = targetFolder.getFileObject(className, Constants.JAVA_EXT);
        if (fobj == null) {
            fobj = createDataObjectFromTemplate(template, targetFolder, packageName, className).getPrimaryFile();
        }
        return JavaSource.forFileObject(fobj);
    } catch (IOException ex) {
        ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, ex);
    }

    return null;
}
 
Example 7
Source File: RemoveFinalModifier.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public ChangeInfo implement(){
    CancellableTask<WorkingCopy> task = new CancellableTask<WorkingCopy>(){
        public void cancel() {}
        
        public void run(WorkingCopy workingCopy) throws Exception {
            workingCopy.toPhase(JavaSource.Phase.RESOLVED);
            TypeElement clazz = classHandle.resolve(workingCopy);
            
            if (clazz != null){    
                ClassTree clazzTree = workingCopy.getTrees().getTree(clazz);
                TreeMaker make = workingCopy.getTreeMaker();
                
                Set<Modifier> flags = new HashSet<Modifier>(clazzTree.getModifiers().getFlags());
                flags.remove(Modifier.FINAL);
                ModifiersTree newModifiers = make.Modifiers(flags, clazzTree.getModifiers().getAnnotations());
                workingCopy.rewrite(clazzTree.getModifiers(), newModifiers);
            }
        }
    };
    
    JavaSource javaSource = JavaSource.forFileObject(fileObject);
    
    try{
        javaSource.runModificationTask(task).commit();
    } catch (IOException e){
        JPAProblemFinder.LOG.log(Level.SEVERE, e.getMessage(), e);
    }
    return null;
}
 
Example 8
Source File: SourceUtilsTest.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 9
Source File: ModifiersTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Original:
 * 
 * public static void method() {
 * }
 * 
 * Result:
 * 
 * static void method() {
 * }
 */
public void testMethodMods5() throws Exception {
    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 static void method() {\n" +
            "    }\n" +
            "}\n"
            );
    String golden =
            "package hierbas.del.litoral;\n\n" +
            "import java.io.*;\n\n" +
            "public class Test {\n" +
            "    static void method() {\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);
            ModifiersTree mods = method.getModifiers();
            workingCopy.rewrite(mods, make.Modifiers(Collections.<Modifier>singleton(Modifier.STATIC)));
        }
        
    };
    testSource.runModificationTask(task).commit();
    String res = TestUtilities.copyFileToString(testFile);
    //System.err.println(res);
    assertEquals(golden, res);
}
 
Example 10
Source File: EJBActionGroup.java    From netbeans with Apache License 2.0 5 votes vote down vote up
protected boolean enable(final org.openide.nodes.Node[] activatedNodes) {
    if (activatedNodes.length != 1) {
        return false;
    }
    final FileObject fileObject = activatedNodes[0].getLookup().lookup(FileObject.class);
    if (fileObject == null) {
        return false;
    }
    JavaSource javaSource = JavaSource.forFileObject(fileObject);
    if (javaSource == null) {
        return false;
    }
    // The following code atomically checks that the scan is not running and posts a JavaSource task 
    // which is expected to run synchronously. If the task does not run synchronously,
    // then we cancel it and return false from this method.
    final AtomicBoolean enabled = new AtomicBoolean(false);
    try {
        Future<Void> future = javaSource.runWhenScanFinished(new Task<CompilationController>() {
            public void run(CompilationController controller) throws Exception {
                String className = null;
                ElementHandle<TypeElement> elementHandle = _RetoucheUtil.getJavaClassFromNode(activatedNodes[0]);
                if (elementHandle != null) {
                    className = elementHandle.getQualifiedName();
                }
                EjbMethodController ejbMethodController = null;
                if (className != null) {
                     ejbMethodController = EjbMethodController.createFromClass(fileObject, className);
                }
                enabled.set(ejbMethodController != null);
            }
        }, true);
        // Cancel the task if it has not run yet (it will run asynchronously at a later point in time
        // which is too late for us -- we need the result now). If it has already run, the cancel() call is a no-op.
        future.cancel(true);
    } catch (IOException e) {
        Exceptions.printStackTrace(e);
    }
    return enabled.get();
}
 
Example 11
Source File: JaxWsNode.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private JavaSource getImplBeanJavaSource() {
    FileObject implBean = getImplBean();
    if (implBean != null) {
        return JavaSource.forFileObject(implBean);
    }
    return null;
}
 
Example 12
Source File: JaxWsCodeGenerator.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@org.netbeans.api.annotations.common.SuppressWarnings("NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE")
private static void insertJavaMethod( final Document document,
        final int pos, WsdlOperation operation, String wsdlUrl,
        PolicyManager manager, final String serviceJavaName,
        String serviceFieldName, String portJavaName,
        String portGetterMethod, String operationJavaName,
        String returnTypeName, String responseType,
        String argumentInitializationPart, String argumentDeclarationPart,
        String[] paramNames, String[] paramTypes, String[] exceptionTypes )
{
    // including code to java class
    final FileObject targetFo = NbEditorUtilities.getFileObject(document);

    JavaSource targetSource = JavaSource.forFileObject(targetFo);
    String respType = responseType;
    final String[] argumentInitPart = {argumentInitializationPart};
    final String[] argumentDeclPart = {argumentDeclarationPart};
    final String[] serviceFName = {serviceFieldName};

    try {
        CompilerTask task = getCompilerTask(serviceJavaName, serviceFName,
                argumentDeclPart, paramNames, argumentInitPart, manager);
        targetSource.runUserActionTask(task, true);
        
        if (WsdlOperation.TYPE_NORMAL == operation.getOperationType()) {
            String body = task.getMethodBody(portJavaName, 
                    portGetterMethod, returnTypeName, operationJavaName);
            // generate static method when @WebServiceRef injection is missing, or for J2ee Client application
            boolean isStatic = !task.isWsRefInjection() || 
                (Car.getCar(targetFo) != null);
            
            String webServiceRefWarning = task.isWsRefInjection() ? 
                    NbBundle.getMessage(JaxWsCodeGenerator.class, "WRN_WebServiceRef") : ""; //NOI18N
            JaxWsClientMethodGenerator clientMethodGenerator =
                new JaxWsClientMethodGenerator (
                        isStatic,
                        operationJavaName,
                        returnTypeName,
                        paramTypes,
                        paramNames,
                        exceptionTypes,
                        "{ "+webServiceRefWarning+body+"}"); //NOI18N

            targetSource.runModificationTask(clientMethodGenerator).commit();
        } else {
            // create & format inserted text
            final String invocationBody = task.getJavaInvocationBody(
                    operation,
                    portJavaName,
                    portGetterMethod,
                    returnTypeName,
                    operationJavaName,
                    respType);

            final Indent indent = Indent.get(document);
            indent.lock();
            try {
                ((BaseDocument)document).runAtomic(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            System.out.println("............. 11111111111 ............. ");
                            document.insertString(pos, invocationBody, null);
                            indent.reindent(pos, pos+invocationBody.length());
                        } catch (BadLocationException ex) {
                            Exceptions.printStackTrace(ex);
                        }
                    }
                }); 
            } finally {
                indent.unlock();
            }
        }

        // modify Class f.e. @insert WebServiceRef injection
        InsertTask modificationTask = getClassModificationTask(serviceJavaName, 
                serviceFName, wsdlUrl, manager , task.containsWsRefInjection());
        targetSource.runModificationTask(modificationTask).commit();
    } catch (IOException ioe) {
        ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, ioe);
    }
}
 
Example 13
Source File: ModifiersTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
/**
 * Original:
 * 
 * @Anotace()
 * public Test() {
 * }
 * 
 * Result:
 * 
 * @Annotaition()
 * protected Test() {
 * }
 */
public void testAnnRename() throws Exception {
    testFile = new File(getWorkDir(), "Test.java");
    TestUtilities.copyStringToFile(testFile,
            "package hierbas.del.litoral;\n" +
            "\n" +
            "import java.io.*;\n" +
            "\n" +
            "@Annotace()\n" +
            "public class Test {\n" +
            "    public Test() {\n" +
            "    }\n" +
            "}\n"
            );
    String golden =
            "package hierbas.del.litoral;\n" +
            "\n" +
            "import java.io.*;\n" +
            "\n" +
            "@Annotation()\n" +
            "public class Test {\n" +
            "    public Test() {\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);
            ModifiersTree mods = clazz.getModifiers();
            AnnotationTree ann = mods.getAnnotations().get(0);
            IdentifierTree ident = (IdentifierTree) ann.getAnnotationType();
            workingCopy.rewrite(ident, make.Identifier("Annotation"));
        }
        
    };
    testSource.runModificationTask(task).commit();
    String res = TestUtilities.copyFileToString(testFile);
    //System.err.println(res);
    assertEquals(golden, res);
}
 
Example 14
Source File: Hinter.java    From netbeans with Apache License 2.0 4 votes vote down vote up
/**
 * Tries to find the Java declaration of an instance attribute, and if successful, runs a task to modify it.
 * @param instanceAttribute the result of {@link FileObject#getAttribute} on a {@code literal:*} key (or {@link #instanceAttribute})
 * @param task a task to run (may modify Java sources and layer objects; all will be saved for you)
 * @throws IOException in case of problem (will instead show a message and return early if the type could not be found)
 */
@Messages({
    "# {0} - layer attribute", "Hinter.missing_instance_class=Could not find Java source corresponding to {0}.",
    "Hinter.do_not_edit_layer=Do not edit layer.xml until the hint has had a chance to run."
})
public void findAndModifyDeclaration(@NullAllowed final Object instanceAttribute, final ModifyDeclarationTask task) throws IOException {
    FileObject java = findDeclaringSource(instanceAttribute);
    if (java == null) {
        DialogDisplayer.getDefault().notify(new Message(Hinter_missing_instance_class(instanceAttribute), NotifyDescriptor.WARNING_MESSAGE));
        return;
    }
    JavaSource js = JavaSource.forFileObject(java);
    if (js == null) {
        throw new IOException("No source info for " + java);
    }
    js.runModificationTask(new Task<WorkingCopy>() {
        public @Override void run(WorkingCopy wc) throws Exception {
            wc.toPhase(JavaSource.Phase.RESOLVED);
            if (DataObject.find(layer.getLayerFile()).isModified()) { // #207077
                DialogDisplayer.getDefault().notify(new Message(Hinter_do_not_edit_layer(), NotifyDescriptor.WARNING_MESSAGE));
                return;
            }
            Element decl = findDeclaration(wc, instanceAttribute);
            if (decl == null) {
                DialogDisplayer.getDefault().notify(new Message(Hinter_missing_instance_class(instanceAttribute), NotifyDescriptor.WARNING_MESSAGE));
                return;
            }
            ModifiersTree mods;
            if (decl.getKind() == ElementKind.CLASS) {
                mods = wc.getTrees().getTree((TypeElement) decl).getModifiers();
            } else {
                mods = wc.getTrees().getTree((ExecutableElement) decl).getModifiers();
            }
            task.run(wc, decl, mods);
            saveLayer();
        }
    }).commit();
    SaveCookie sc = DataObject.find(java).getLookup().lookup(SaveCookie.class);
    if (sc != null) {
        sc.save();
    }
}
 
Example 15
Source File: JaxWsClassesCookieImpl.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@org.netbeans.api.annotations.common.SuppressWarnings("NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE")
@Override
public void addOperation(final MethodTree method) {
    JavaSource targetSource = JavaSource.forFileObject(implClassFO);
    CancellableTask<WorkingCopy> modificationTask = 
        new CancellableTask<WorkingCopy>() 
        {
        @Override
        public void run(WorkingCopy workingCopy) throws IOException {
            workingCopy.toPhase(Phase.RESOLVED);            
            TreeMaker make = workingCopy.getTreeMaker();
            ClassTree javaClass = SourceUtils.
                getPublicTopLevelTree(workingCopy);
            if (javaClass!=null) {
                GenerationUtils genUtils = GenerationUtils.newInstance(
                            workingCopy);
                
                AnnotationTree webMethodAnnotation = make.Annotation(
                    make.QualIdent("javax.jws.WebMethod"),      //NOI18N
                    Collections.<ExpressionTree>emptyList()
                );
                // add @WebMethod annotation
                ModifiersTree modifiersTree = make.addModifiersAnnotation(
                        method.getModifiers(), webMethodAnnotation);
                
                // add @Oneway annotation
                if (Kind.PRIMITIVE_TYPE == method.getReturnType().getKind()) {
                    PrimitiveTypeTree primitiveType = 
                        (PrimitiveTypeTree)method.getReturnType();
                    if (TypeKind.VOID == primitiveType.getPrimitiveTypeKind()) {
                        AnnotationTree oneWayAnnotation = make.Annotation(
                            make.QualIdent("javax.jws.Oneway"),         // NOI18N
                            Collections.<ExpressionTree>emptyList()
                        );
                        modifiersTree = make.addModifiersAnnotation(
                                modifiersTree, oneWayAnnotation);
                    }
                }
                
                // add @WebParam annotations 
                List<? extends VariableTree> parameters = method.getParameters();
                List<VariableTree> newParameters = new ArrayList<VariableTree>();
                for (VariableTree param:parameters) {
                    AnnotationTree paramAnnotation = make.Annotation(
                        make.QualIdent("javax.jws.WebParam"),           //NOI18N
                        Collections.<ExpressionTree>singletonList(
                            make.Assignment(make.Identifier("name"),    //NOI18N
                                    make.Literal(param.getName().toString()))) 
                    );
                    newParameters.add(genUtils.addAnnotation(param, paramAnnotation));
                }
                // create new (annotated) method
                MethodTree  annotatedMethod = make.Method(
                            modifiersTree,
                            method.getName(),
                            method.getReturnType(),
                            method.getTypeParameters(),
                            newParameters,
                            method.getThrows(),
                            method.getBody(),
                            (ExpressionTree)method.getDefaultValue());
                Comment comment = Comment.create(NbBundle.getMessage(
                        JaxWsClassesCookieImpl.class, "TXT_WSOperation"));      //NOI18N                 
                make.addComment(annotatedMethod, comment, true);
                
                ClassTree modifiedClass = make.addClassMember(javaClass,
                        annotatedMethod);
                workingCopy.rewrite(javaClass, modifiedClass);
            }
        }
        @Override
        public void cancel() {
            
        }
    };
    try {
        targetSource.runModificationTask(modificationTask).commit();
    } catch (IOException ex) {
        ErrorManager.getDefault().notify(ex);
    }
}
 
Example 16
Source File: BodyStatementTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
/**
 * #99445: Not well formatted statements when adding statement to body.
 */
public void test99445() throws Exception {
    testFile = new File(getWorkDir(), "Test.java");
    TestUtilities.copyStringToFile(testFile, 
        "package personal;\n" +
        "\n" +
        "public class Test {\n" +
        "    public Object method(Class o) {\n" +
        "        method(new Test());\n" +
        "    }\n" +
        "}\n");
     String golden = 
        "package personal;\n" +
        "\n" +
        "public class Test {\n" +
        "    public Object method(Class o) {\n" +
        "        method(new Test());\n" +
        "        System.out.println(\"Test\");\n" +
        "    }\n" +
        "}\n";
    JavaSource testSource = JavaSource.forFileObject(FileUtil.toFileObject(testFile));
    Task<WorkingCopy> task = new Task<WorkingCopy>() {

        public void run(WorkingCopy workingCopy) throws IOException {
            workingCopy.toPhase(Phase.RESOLVED);
            TreeMaker make = workingCopy.getTreeMaker();
            ClassTree clazz = (ClassTree)workingCopy.getCompilationUnit().getTypeDecls().get(0);
            MethodTree method = (MethodTree)clazz.getMembers().get(1);
            BlockTree block = method.getBody();
            ExpressionStatementTree est = make.ExpressionStatement(
                make.MethodInvocation(
                    Collections.<ExpressionTree>emptyList(),
                    make.MemberSelect(
                        make.MemberSelect(
                            make.Identifier("System"),
                            "out"
                        ),
                        "println"
                    ),
                    Collections.<ExpressionTree>singletonList(
                        make.Literal("Test")
                    )
                )
            );
            workingCopy.rewrite(block, make.addBlockStatement(block, est));
        }
        
    };
    testSource.runModificationTask(task).commit();
    String res = TestUtilities.copyFileToString(testFile);
    //System.err.println(res);
    assertEquals(golden, res);
}
 
Example 17
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 annonymous class
 */
public void testTaggingOfGeneratedMethodBodyInAnnonymousClass() throws Exception {

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

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

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

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

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

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

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

    assertEquals("System.err.println(true);", diff.getResultingSource(FileUtil.toFileObject(testFile)).substring(span[0], span[1]));
}
 
Example 18
Source File: MethodGenerator.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@org.netbeans.api.annotations.common.SuppressWarnings("NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE")
public void generateMethod(final String operationName) throws IOException {
    
    // Use Progress API to display generator messages.
    //ProgressHandle handle = ProgressHandleFactory.createHandle(NbBundle.getMessage(MethodGenerator.class, "TXT_AddingMethod")); //NOI18N
    //handle.start(100);
    
    JavaSource targetSource = JavaSource.forFileObject(implClassFo);
    CancellableTask<WorkingCopy> task = new CancellableTask<WorkingCopy>() {
        @Override
        public void run(WorkingCopy workingCopy) throws java.io.IOException {
            workingCopy.toPhase(Phase.RESOLVED);
            ClassTree javaClass = SourceUtils.getPublicTopLevelTree(workingCopy);
            if (javaClass!=null) {
          
                // get proper wsdlOperation;
                WsdlOperation wsdlOperation = getWsdlOperation(operationName);
                
                if (wsdlOperation != null) {
                    TreeMaker make = workingCopy.getTreeMaker();

                    // return type
                    String returnType = wsdlOperation.getReturnTypeName();

                    // create parameters
                    List<WsdlParameter> parameters = wsdlOperation.getParameters();
                    List<VariableTree> params = new ArrayList<VariableTree>();
                    for (WsdlParameter parameter:parameters) {
                        // create parameter:
                        params.add(make.Variable(
                                make.Modifiers(
                                Collections.<Modifier>emptySet(),
                                Collections.<AnnotationTree>emptyList()
                                ),
                                parameter.getName(), // name
                                make.Identifier(parameter.getTypeName()), // parameter type
                                null // initializer - does not make sense in parameters.
                                ));
                    }

                    // create exceptions
                    Iterator<String> exceptions = wsdlOperation.getExceptions();
                    List<ExpressionTree> exc = new ArrayList<ExpressionTree>();
                    while (exceptions.hasNext()) {
                        String exception = exceptions.next();
                        exc.add(make.Identifier(exception));
                    }

                    // create method
                    ModifiersTree methodModifiers = make.Modifiers(
                            Collections.<Modifier>singleton(Modifier.PUBLIC),
                            Collections.<AnnotationTree>emptyList()
                            );
                    MethodTree method = make.Method(
                            methodModifiers, // public
                            wsdlOperation.getJavaName(), // operation name
                            make.Identifier(returnType), // return type
                            Collections.<TypeParameterTree>emptyList(), // type parameters - none
                            params,
                            exc, // throws
                            "{ //TODO implement this method\nthrow new UnsupportedOperationException(\"Not implemented yet.\") }", // body text
                            null // default value - not applicable here, used by annotations
                            );

                    ClassTree modifiedClass =  make.addClassMember(javaClass, method);

                    workingCopy.rewrite(javaClass, modifiedClass);
                } else {
                    Logger.getLogger(MethodGenerator.class.getName()).log(Level.INFO, 
                            "Failed to bind WSDL operation to java method: "+operationName); //NOI18N             
                }
            }
        }
        
        public void cancel() {
        }
    };
    targetSource.runModificationTask(task).commit();
    DataObject dobj = DataObject.find(implClassFo);
    if (dobj!=null) {
        SaveCookie cookie = dobj.getCookie(SaveCookie.class);
        if (cookie!=null) cookie.save();
    }
}
 
Example 19
Source File: TryTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public void testWrapTryInTry() throws Exception {
    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" +
        "        try {\n" +
        "            File f = new File(\"auto\");\n" +
        "            FileInputStream fis = new FileInputStream(f);\n" +
        "        } catch (FileNotFoundException ex) {\n" +
        "        } finally {\n" +
        "        }\n" +
        "    }\n" +
        "}\n"
        );
    String golden =
        "package hierbas.del.litoral;\n" +
        "\n" +
        "import java.io.*;\n" +
        "\n" +
        "public class Test {\n" +
        "    public void taragui() {\n" +
        "        try {\n" +
        "            try {\n" +
        "                File f = new File(\"auto\");\n" +
        "                FileInputStream fis = new FileInputStream(f);\n" +
        "            } catch (FileNotFoundException ex) {\n" +
        "            } finally {\n" +
        "            }\n" +
        "        } finally {\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();

            ClassTree clazz = (ClassTree) workingCopy.getCompilationUnit().getTypeDecls().get(0);
            MethodTree method = (MethodTree) clazz.getMembers().get(1);
            TryTree tt = (TryTree) method.getBody().getStatements().get(0);
            workingCopy.rewrite(tt, make.Try(make.Block(Collections.singletonList(tt), false), Collections.<CatchTree>emptyList(), make.Block(Collections.<StatementTree>emptyList(), false)));
        }

    };
    testSource.runModificationTask(task).commit();
    String res = TestUtilities.copyFileToString(testFile);
    //System.err.println(res);
    assertEquals(golden, res);
}
 
Example 20
Source File: ToStringGeneratorTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public void testToStringCanNotUseStringBuilder() throws Exception {
    sourceLevel = "1.4";
    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, true);
        }

        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", true, 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"
            + "    public String toString() {\n"
            + "        return \"NewClass{\" + \"test1=\" + test1 + \", test2=\" + test2 + \", test3=\" + test3 + '}';\n"
            + "    }\n"
            + "\n"
            + "}";
    assertEquals(expected, text);
}