This Bugzilla instance is a read-only archive of historic NetBeans bug reports. To report a bug in NetBeans please follow the project's instructions for reporting issues.

View | Details | Raw Unified | Return to bug 209798
Collapse All | Expand All

(-)a/java.source/apichanges.xml (+14 lines)
Lines 108-113 Link Here
108
    <!-- ACTUAL CHANGES BEGIN HERE: -->
108
    <!-- ACTUAL CHANGES BEGIN HERE: -->
109
109
110
    <changes>
110
    <changes>
111
        <change id="GeneratorUtilities-createFromTemplate">
112
             <api name="general"/>
113
             <summary>Added <code>GeneratorUtilities.createFromTemplate</code>.</summary>
114
             <version major="0" minor="100"/>
115
             <date day="27" month="3" year="2012"/>
116
             <author login="ralphbenjamin"/>
117
             <compatibility addition="yes" binary="compatible" semantic="compatible" source="compatible" deletion="no" deprecation="no" modification="no"/>
118
             <description>
119
                 Added the method <code>createFromTemplate</code> to class <code>GeneratorUtilities</code>,
120
                 which will create a new CompilationUnitTree from a template.
121
             </description>
122
             <class package="org.netbeans.api.java.source" name="GeneratorUtilities"/>
123
             <issue number="209798"/>
124
        </change>
111
        <change id="GeneratorUtilities-appendToAnnotationValue">
125
        <change id="GeneratorUtilities-appendToAnnotationValue">
112
             <api name="general"/>
126
             <api name="general"/>
113
             <summary>Added <code>GeneratorUtilities.appendToAnnotationValue</code>.</summary>
127
             <summary>Added <code>GeneratorUtilities.appendToAnnotationValue</code>.</summary>
(-)a/java.source/src/org/netbeans/api/java/source/AssignComments.java (-1 / +1 lines)
Lines 106-112 Link Here
106
            boolean oldMapComments = mapComments;
106
            boolean oldMapComments = mapComments;
107
            try {
107
            try {
108
                mapComments |= tree == commentMapTarget;
108
                mapComments |= tree == commentMapTarget;
109
                if ((commentMapTarget != null) && info.getTreeUtilities().isSynthetic(new TreePath(new TreePath(info.getCompilationUnit()), tree)))
109
                if ((commentMapTarget != null) && info.getTreeUtilities().isSynthetic(new TreePath(new TreePath(unit), tree)))
110
                    return null;
110
                    return null;
111
                if (commentMapTarget != null) {
111
                if (commentMapTarget != null) {
112
                    mapComments2(tree, true);
112
                    mapComments2(tree, true);
(-)a/java.source/src/org/netbeans/api/java/source/GeneratorUtilities.java (+31 lines)
Lines 84-89 Link Here
84
import com.sun.tools.javac.tree.JCTree.JCCompilationUnit;
84
import com.sun.tools.javac.tree.JCTree.JCCompilationUnit;
85
85
86
import java.io.IOException;
86
import java.io.IOException;
87
import java.net.URI;
87
import java.util.ArrayList;
88
import java.util.ArrayList;
88
import java.util.Arrays;
89
import java.util.Arrays;
89
import java.util.Collections;
90
import java.util.Collections;
Lines 120-125 Link Here
120
import javax.lang.model.util.Elements;
121
import javax.lang.model.util.Elements;
121
import javax.swing.text.Document;
122
import javax.swing.text.Document;
122
import javax.swing.text.JTextComponent;
123
import javax.swing.text.JTextComponent;
124
import javax.tools.JavaFileObject;
123
125
124
import org.netbeans.api.editor.EditorRegistry;
126
import org.netbeans.api.editor.EditorRegistry;
125
import org.netbeans.api.java.lexer.JavaTokenId;
127
import org.netbeans.api.java.lexer.JavaTokenId;
Lines 127-136 Link Here
127
import org.netbeans.editor.GuardedDocument;
129
import org.netbeans.editor.GuardedDocument;
128
import org.netbeans.modules.java.source.builder.CommentHandlerService;
130
import org.netbeans.modules.java.source.builder.CommentHandlerService;
129
import org.netbeans.modules.java.source.builder.CommentSetImpl;
131
import org.netbeans.modules.java.source.builder.CommentSetImpl;
132
import org.netbeans.modules.java.source.parsing.FileObjects;
130
import org.netbeans.modules.java.source.parsing.SourceFileObject;
133
import org.netbeans.modules.java.source.parsing.SourceFileObject;
131
import org.netbeans.modules.java.source.query.CommentSet.RelativePosition;
134
import org.netbeans.modules.java.source.query.CommentSet.RelativePosition;
132
import org.netbeans.modules.java.source.save.DiffContext;
135
import org.netbeans.modules.java.source.save.DiffContext;
133
import org.openide.cookies.EditorCookie;
136
import org.openide.cookies.EditorCookie;
137
import org.openide.filesystems.FileObject;
138
import org.openide.filesystems.FileUtil;
134
import org.openide.loaders.DataObject;
139
import org.openide.loaders.DataObject;
135
import org.openide.util.Exceptions;
140
import org.openide.util.Exceptions;
136
141
Lines 159-164 Link Here
159
    }
164
    }
160
165
161
    /**
166
    /**
167
     * Create a new CompilationUnitTree from a template.
168
     *
169
     * @param sourceRoot a source root under which the new file is created
170
     * @param path a relative path to file separated by '/'
171
     * @param kind the kind of Element to use for the template, can be null or
172
     * CLASS, INTERFACE, ANNOTATION_TYPE, ENUM, PACKAGE
173
     * @return new CompilationUnitTree created from a template
174
     * @throws IOException when an exception occurs while creating the template
175
     * @since 0.100
176
     */
177
    public CompilationUnitTree createFromTemplate(FileObject sourceRoot, String path, ElementKind kind) throws IOException {
178
        String[] nameComponent = FileObjects.getFolderAndBaseName(path, '/');
179
        JavaFileObject sourceFile = FileObjects.templateFileObject(sourceRoot, nameComponent[0], nameComponent[1]);
180
        FileObject template = FileUtil.getConfigFile(copy.template(kind));
181
        FileObject targetFile = copy.doCreateFromTemplate(template, sourceFile);
182
        CompilationUnitTree templateCUT = copy.impl.getJavacTask().parse(FileObjects.nbFileObject(targetFile, targetFile.getParent())).iterator().next();
183
        CompilationUnitTree importComments = GeneratorUtilities.get(copy).importComments(templateCUT, templateCUT);
184
        CompilationUnitTree result = copy.getTreeMaker().CompilationUnit(importComments.getPackageAnnotations(),
185
                sourceRoot,
186
                path,
187
                importComments.getImports(),
188
                importComments.getTypeDecls());
189
        return result;
190
    }
191
192
    /**
162
     * Inserts a member to a class. Using the rules specified in the {@link CodeStyle}
193
     * Inserts a member to a class. Using the rules specified in the {@link CodeStyle}
163
     * it finds the proper place for the member and calls {@link TreeMaker.insertClassMember}
194
     * it finds the proper place for the member and calls {@link TreeMaker.insertClassMember}
164
     *
195
     *
(-)a/java.source/src/org/netbeans/api/java/source/WorkingCopy.java (-12 / +43 lines)
Lines 61-66 Link Here
61
import java.io.IOException;
61
import java.io.IOException;
62
import java.io.StringWriter;
62
import java.io.StringWriter;
63
import java.lang.ref.Reference;
63
import java.lang.ref.Reference;
64
import java.net.URI;
64
import java.util.ArrayList;
65
import java.util.ArrayList;
65
import java.util.Collections;
66
import java.util.Collections;
66
import java.util.HashMap;
67
import java.util.HashMap;
Lines 74-79 Link Here
74
import java.util.logging.Level;
75
import java.util.logging.Level;
75
import java.util.logging.Logger;
76
import java.util.logging.Logger;
76
import javax.lang.model.element.Element;
77
import javax.lang.model.element.Element;
78
import javax.lang.model.element.ElementKind;
77
import javax.swing.text.BadLocationException;
79
import javax.swing.text.BadLocationException;
78
import javax.tools.JavaFileObject;
80
import javax.tools.JavaFileObject;
79
81
Lines 550-557 Link Here
550
            try {
552
            try {
551
                FileObject targetFile = doCreateFromTemplate(t);
553
                FileObject targetFile = doCreateFromTemplate(t);
552
                CompilationUnitTree templateCUT = impl.getJavacTask().parse(FileObjects.nbFileObject(targetFile, targetFile.getParent())).iterator().next();
554
                CompilationUnitTree templateCUT = impl.getJavacTask().parse(FileObjects.nbFileObject(targetFile, targetFile.getParent())).iterator().next();
555
                CompilationUnitTree importComments = GeneratorUtilities.get(this).importComments(templateCUT, templateCUT);
553
556
554
                changes.put(templateCUT, t);
557
                changes.put(importComments, t);
555
558
556
                StringWriter target = new StringWriter();
559
                StringWriter target = new StringWriter();
557
560
Lines 568-593 Link Here
568
        return result;
571
        return result;
569
    }
572
    }
570
573
571
    private static String template(CompilationUnitTree cut) {
574
    String template(ElementKind kind) {
572
        if ("package-info.java".equals(cut.getSourceFile().getName())) return "Templates/Classes/package-info.java";
575
        if(kind == null) {
573
        if (cut.getTypeDecls().isEmpty()) return "Templates/Classes/Empty.java";
576
            return "Templates/Classes/Empty.java"; // NOI18N
574
577
        }
575
        switch (cut.getTypeDecls().get(0).getKind()) {
578
        switch (kind) {
576
            case CLASS: return "Templates/Classes/Class.java"; // NOI18N
579
            case CLASS: return "Templates/Classes/Class.java"; // NOI18N
577
            case INTERFACE: return "Templates/Classes/Interface.java"; // NOI18N
580
            case INTERFACE: return "Templates/Classes/Interface.java"; // NOI18N
578
            case ANNOTATION_TYPE: return "Templates/Classes/AnnotationType.java"; // NOI18N
581
            case ANNOTATION_TYPE: return "Templates/Classes/AnnotationType.java"; // NOI18N
579
            case ENUM: return "Templates/Classes/Enum.java"; // NOI18N
582
            case ENUM: return "Templates/Classes/Enum.java"; // NOI18N
583
            case PACKAGE: return "Templates/Classes/package-info.java"; // NOI18N
580
            default:
584
            default:
581
                Logger.getLogger(WorkingCopy.class.getName()).log(Level.SEVERE, "Cannot resolve template for {0}", cut.getTypeDecls().get(0).getKind());
585
                Logger.getLogger(WorkingCopy.class.getName()).log(Level.SEVERE, "Cannot resolve template for {0}", kind);
582
                return "Templates/Classes/Empty.java";
586
                return "Templates/Classes/Empty.java"; // NOI18N
583
        }
587
        }
584
    }
588
    }
585
589
586
    private static FileObject doCreateFromTemplate(CompilationUnitTree t) throws IOException {
590
    FileObject doCreateFromTemplate(CompilationUnitTree cut) throws IOException {
591
        ElementKind kind;
592
        if ("package-info.java".equals(cut.getSourceFile().getName())) {
593
            kind = ElementKind.PACKAGE;
594
        } else if (cut.getTypeDecls().isEmpty()) {
595
            kind = null;
596
        } else {
597
            switch (cut.getTypeDecls().get(0).getKind()) {
598
                case CLASS:
599
                    kind = ElementKind.CLASS;
600
                    break;
601
                case INTERFACE:
602
                    kind = ElementKind.INTERFACE;
603
                    break;
604
                case ANNOTATION_TYPE:
605
                    kind = ElementKind.ANNOTATION_TYPE;
606
                    break;
607
                case ENUM:
608
                    kind = ElementKind.ENUM;
609
                    break;
610
                default:
611
                    Logger.getLogger(WorkingCopy.class.getName()).log(Level.SEVERE, "Cannot resolve template for {0}", cut.getTypeDecls().get(0).getKind());
612
                    kind = null;
613
            }
614
        }
615
        FileObject template = FileUtil.getConfigFile(template(kind));
616
        return doCreateFromTemplate(template, cut.getSourceFile());
617
    }
618
619
    FileObject doCreateFromTemplate(FileObject template, JavaFileObject sourceFile) throws IOException {
587
        FileObject scratchFolder = FileUtil.createMemoryFileSystem().getRoot();
620
        FileObject scratchFolder = FileUtil.createMemoryFileSystem().getRoot();
588
621
589
        FileObject template = FileUtil.getConfigFile(template(t));
590
591
        if (template == null) {
622
        if (template == null) {
592
            return scratchFolder.createData("out", "java");
623
            return scratchFolder.createData("out", "java");
593
        }
624
        }
Lines 598-604 Link Here
598
            return scratchFolder.createData("out", "java");
629
            return scratchFolder.createData("out", "java");
599
        }
630
        }
600
631
601
        File pack = new File(t.getSourceFile().toUri()).getParentFile();
632
        File pack = new File(sourceFile.toUri()).getParentFile();
602
633
603
        while (FileUtil.toFileObject(pack) == null) {
634
        while (FileUtil.toFileObject(pack) == null) {
604
            pack = pack.getParentFile();
635
            pack = pack.getParentFile();
(-)a/java.source/test/unit/src/org/netbeans/api/java/source/gen/CompilationUnitTest.java (+85 lines)
Lines 39-44 Link Here
39
import java.util.Collections;
39
import java.util.Collections;
40
import java.util.EnumSet;
40
import java.util.EnumSet;
41
import java.util.Map;
41
import java.util.Map;
42
import javax.lang.model.element.ElementKind;
42
import javax.lang.model.element.Modifier;
43
import javax.lang.model.element.Modifier;
43
import javax.lang.model.element.TypeElement;
44
import javax.lang.model.element.TypeElement;
44
import javax.lang.model.type.TypeKind;
45
import javax.lang.model.type.TypeKind;
Lines 90-95 Link Here
90
        if (templates != null) templates.delete();
91
        if (templates != null) templates.delete();
91
    }
92
    }
92
93
94
    public void testNewCompilationUnitFromTemplate() throws Exception {
95
        testFile = new File(getWorkDir(), "Test.java");
96
97
        File fakeFile = new File(getWorkDir(), "Fake.java");
98
        FileObject fakeFO = FileUtil.createData(fakeFile);
99
100
        FileObject emptyJava = FileUtil.createData(FileUtil.getConfigRoot(), "Templates/Classes/Empty.java");
101
        emptyJava.setAttribute("template", Boolean.TRUE);
102
103
        FileObject classJava = FileUtil.createData(FileUtil.getConfigRoot(), "Templates/Classes/Class.java");
104
        classJava.setAttribute("template", Boolean.TRUE);
105
        Writer w = new OutputStreamWriter(classJava.getOutputStream(), "UTF-8");
106
        w.write("package zoo;\n"
107
                + "/**\n * trida\n */\n"
108
                + "public class Template {\n"
109
                + "}");
110
        w.close();
111
112
        FileObject testSourceFO = FileUtil.createData(testFile); assertNotNull(testSourceFO);
113
        ClassPath sourcePath = ClassPath.getClassPath(testSourceFO, ClassPath.SOURCE); assertNotNull(sourcePath);
114
        FileObject[] roots = sourcePath.getRoots(); assertEquals(1, roots.length);
115
        final FileObject sourceRoot = roots[0]; assertNotNull(sourceRoot);
116
        ClassPath compilePath = ClassPath.getClassPath(testSourceFO, ClassPath.COMPILE); assertNotNull(compilePath);
117
        ClassPath bootPath = ClassPath.getClassPath(testSourceFO, ClassPath.BOOT); assertNotNull(bootPath);
118
        ClasspathInfo cpInfo = ClasspathInfo.create(bootPath, compilePath, sourcePath);
119
        JavaSource javaSource = JavaSource.create(cpInfo, fakeFO);
120
121
        Task<WorkingCopy> task = new Task<WorkingCopy>() {
122
123
            public void cancel() {
124
            }
125
126
            public void run(WorkingCopy workingCopy) throws Exception {
127
                workingCopy.toPhase(JavaSource.Phase.PARSED);
128
                TreeMaker make = workingCopy.getTreeMaker();
129
                String path = "zoo/Krtek.java";
130
                GeneratorUtilities genUtils = GeneratorUtilities.get(workingCopy);
131
                CompilationUnitTree newTree = genUtils.createFromTemplate(sourceRoot, path, ElementKind.CLASS);
132
                MethodTree nju = make.Method(
133
                        make.Modifiers(Collections.<Modifier>emptySet()),
134
                        "m",
135
                        make.PrimitiveType(TypeKind.VOID), // return type - void
136
                        Collections.<TypeParameterTree>emptyList(),
137
                        Collections.<VariableTree>emptyList(),
138
                        Collections.<ExpressionTree>emptyList(),
139
                        make.Block(Collections.<StatementTree>emptyList(), false),
140
                        null // default value - not applicable
141
                );
142
                ClassTree clazz = make.Class(
143
                        make.Modifiers(Collections.<Modifier>singleton(Modifier.PUBLIC)),
144
                        "Krtek",
145
                        Collections.<TypeParameterTree>emptyList(),
146
                        null,
147
                        Collections.<Tree>emptyList(),
148
                        Collections.singletonList(nju)
149
                );
150
                workingCopy.rewrite(null, newTree);
151
                if(newTree.getTypeDecls().isEmpty()) {
152
                    make.addCompUnitTypeDecl(newTree, clazz);
153
                } else {
154
                    Tree templateClass = newTree.getTypeDecls().get(0);
155
                    genUtils.copyComments(templateClass, clazz, true);
156
                    genUtils.copyComments(templateClass, clazz, false);
157
                    workingCopy.rewrite(templateClass, clazz);
158
                }
159
            }
160
        };
161
        ModificationResult result = javaSource.runModificationTask(task);
162
        result.commit();
163
164
        String golden =
165
            "package zoo;\n" +
166
            "\n" +
167
            "\n" + // XXX:
168
            "/**\n * trida\n */\n" +
169
            "public class Krtek {\n" +
170
            "\n" +
171
            "    void m() {\n" +
172
            "    }\n" +
173
            "}\n";
174
        String res = TestUtilities.copyFileToString(new File(getDataDir().getAbsolutePath() + "/zoo/Krtek.java"));
175
        assertEquals(golden, res);
176
    }
177
93
    public void testNewCompilationUnit() throws Exception {
178
    public void testNewCompilationUnit() throws Exception {
94
        testFile = new File(getWorkDir(), "Test.java");
179
        testFile = new File(getWorkDir(), "Test.java");
95
180

Return to bug 209798