Java Code Examples for org.openide.filesystems.FileObject.setAttribute()

The following are Jave code examples for showing how to use setAttribute() of the org.openide.filesystems.FileObject class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: incubator-netbeans   File: IndentEngineIntTest.java   View Source Code Vote up 6 votes
public void testCreateFromTemplateUsingFreemarker() throws Exception {
    FileObject root = FileUtil.createMemoryFileSystem().getRoot();
    FileObject fo = FileUtil.createData(root, "simpleObject.txt");
    OutputStream os = fo.getOutputStream();
    String txt = "<html><h1>${title}</h1></html>";
    os.write(txt.getBytes());
    os.close();
    fo.setAttribute("javax.script.ScriptEngine", "freemarker");
    
    
    DataObject obj = DataObject.find(fo);
    
    DataFolder folder = DataFolder.findFolder(FileUtil.createFolder(root, "target"));
    
    Map<String,String> parameters = Collections.singletonMap("title", "Nazdar");
    DataObject n = obj.createFromTemplate(folder, "complex", parameters);
    
    assertEquals("Created in right place", folder, n.getFolder());
    assertEquals("Created with right name", "complex.txt", n.getName());
    
    String exp = ">lmth/<>1h/<radzaN>1h<>lmth<";
    assertEquals(exp, readFile(n.getPrimaryFile()));
    
}
 
Example 2
Project: incubator-netbeans   File: ScriptingCreateFromTemplateTest.java   View Source Code Vote up 6 votes
public void testCreateFromTemplateEncodingProperty() throws Exception {
    FileObject root = FileUtil.createMemoryFileSystem().getRoot();
    FileObject fo = FileUtil.createData(root, "simpleObject.txt");
    OutputStream os = fo.getOutputStream();
    os.write("${encoding}".getBytes());
    os.close();
    assertEquals("content/unknown", fo.getMIMEType());
    fo.setAttribute ("template", Boolean.TRUE);
    assertEquals("content/unknown", fo.getMIMEType());
    fo.setAttribute("javax.script.ScriptEngine", "freemarker");
    assertEquals("text/x-freemarker", fo.getMIMEType());
    
    DataObject obj = DataObject.find(fo);
    DataFolder folder = DataFolder.findFolder(FileUtil.createFolder(root, "target"));
    
    Map<String,String> parameters = Collections.emptyMap();
    DataObject inst = obj.createFromTemplate(folder, "complex", parameters);
    FileObject instFO = inst.getPrimaryFile();
    
    Charset targetEnc = FileEncodingQuery.getEncoding(instFO);
    assertNotNull("Template encoding is null", targetEnc);
    assertEquals("Encoding in template doesn't match", targetEnc.name(), instFO.asText());
}
 
Example 3
Project: incubator-netbeans   File: CompoundFolderChildrenTest.java   View Source Code Vote up 6 votes
public void testFilesHiddenByAttribute() throws Exception {
    String fileName1 = "file-on-layer-A.instance";
    String fileName2 = "file-on-layer-B.instance";
    TestUtilities.createFile(getWorkDir(), "Tmp/A/B/C/D/" + fileName1);
    TestUtilities.createFile(getWorkDir(), "Tmp/A/B/" + fileName2);
    TestUtilities.createFile(getWorkDir(), "Tmp/A/" + fileName2);

    // Check precondition
    FileObject f = FileUtil.getConfigFile("Tmp/A/B/" + fileName2);
    assertNotNull("The hidden file on the second layer does not exist", f);

    // Mark the file as hidden, which should hide both this file and
    // the same one on the third layer.
    f.setAttribute("hidden", Boolean.TRUE);
    
    f = FileUtil.getConfigFile("Tmp/A/" + fileName2);
    assertNotNull("The original file on the third layer that should be hidden does not exist", f);
    
    // Test compound children
    CompoundFolderChildren cfch = new CompoundFolderChildren(new String [] { "Tmp/A/B/C/D", "Tmp/A/B", "Tmp/A" }, false);
    List files = cfch.getChildren();
    
    assertEquals("Wrong number of files", 1, files.size());
    assertEquals("Wrong layerA file", fileName1, ((FileObject) files.get(0)).getNameExt());
}
 
Example 4
Project: incubator-netbeans   File: CreateFromTemplateTest.java   View Source Code Vote up 6 votes
public void testNoTemplateFlagUnset() throws Exception {
    String folderName = "/Templates/";
    FileObject data = org.openide.filesystems.FileUtil.createData (
        FileUtil.getConfigRoot(), 
        folderName + "/" + "X.prima"
    );
    data.setAttribute ("template", Boolean.TRUE);
    FileObject fo = data.getParent ();
    assertNotNull ("FileObject " + folderName + " found on DefaultFileSystem.", fo);
    DataFolder f = DataFolder.findFolder (fo);
    DataObject templ = DataObject.find(data);
    
    DataObject res = templ.createFromTemplate(f);
    
    assertFalse("Not marked as template", res.isTemplate());
    assertEquals(SimpleLoader.class, res.getLoader().getClass());
}
 
Example 5
Project: incubator-netbeans   File: TemplateUtilsTest.java   View Source Code Vote up 5 votes
/**
 * Forces plain default processing, although the template contains replaceable parts
 */
public void testCreateForcePlain() throws Exception {
    FileObject dataRoot = FileUtil.toFileObject(getDataDir());
    FileObject template = dataRoot.getFileObject("templates/SimpleReplacements.java");
    template.setAttribute("template", Boolean.TRUE);
    FileObject workRoot = FileUtil.toFileObject(getWorkDir());
    Map m = new HashMap();
    m.put("USER", "foobar");
    FileObject result = FileBuilder.createFromTemplate(template, workRoot, "NoReplacements", m, FileBuilder.Mode.COPY);
    FileObject pass = dataRoot.getFileObject("golden/ForceNoReplacements.java");
    assertFile(FileUtil.toFile(result), FileUtil.toFile(pass));
}
 
Example 6
Project: incubator-netbeans   File: RootNodeTest.java   View Source Code Vote up 5 votes
public void testGetActions() throws Exception {
    RootNode rn = RootNode.getInstance();
    FileObject fo = FileUtil.getConfigFile("Servers/Actions");
    assertNotNull("Folder for actions precreated", fo);
    FileObject x = fo.createData(MyAction.class.getName().replace('.', '-') + ".instance");
    x.setAttribute("position", 37);
    Action[] arr = rn.getActions(true);
    assertEquals("Two actions and one separator found: " + Arrays.asList(arr), 3, arr.length);
    assertEquals("Last one is separator", null, arr[2]);
    MyAction a = MyAction.get(MyAction.class);

    if (a != arr[0] && a != arr[1]) {
        fail("My action shall be present in the node context actions: " + arr[0] + " 2nd: " + arr[1]);
    }
}
 
Example 7
Project: incubator-netbeans   File: AutoupdateCatalogFactoryTest.java   View Source Code Vote up 5 votes
public void testCreateUpdateProviderWithOwnIcon() throws Exception {
    FileObject f = FileUtil.getConfigRoot().createData("whatever.instance");
    f.setAttribute("url", "file:/wherever.xml");
    f.setAttribute("displayName", "Whatever");
    f.setAttribute("category", "Jarda's Updates");
    f.setAttribute("iconBase", "org/netbeans/modules/autoupdate/services/resources/icon-standard.png");
    UpdateProvider up = AutoupdateCatalogFactory.createUpdateProvider(f);
    UpdateUnitProvider uup = Trampoline.API.createUpdateUnitProvider (new UpdateUnitProviderImpl (up));
    assertEquals("whatever", uup.getName());
    assertEquals("Whatever", uup.getDisplayName());
    assertEquals(new URL("file:/wherever.xml"), uup.getProviderURL());
    Image img = ImageUtilities.loadImage("org/netbeans/modules/autoupdate/services/resources/icon-standard.png");
    assertEquals("Icons are the same", img, uup.getSourceIcon());
}
 
Example 8
Project: incubator-netbeans   File: SCFTHandlerTest.java   View Source Code Vote up 5 votes
public void testBasePropertiesAlwaysPresent() throws Exception {
    FileObject root = FileUtil.createMemoryFileSystem().getRoot();
    FileObject fo = FileUtil.createData(root, "simpleObject.txt");
    OutputStream os = fo.getOutputStream();
    String txt = "print('<html><h1>'); print(name); print('</h1>');" +
        "print('<h2>'); print(date); print('</h2>');" +
        "print('<h3>'); print(time); print('</h3>');" +
        "print('<h4>'); print(user); print('</h4>');" +
        "print('<h4>'); print(dateTime.getTime()); print('</h4>');" +
        "print('</html>');";
    os.write(txt.getBytes());
    os.close();
    fo.setAttribute(ScriptingCreateFromTemplateHandler.SCRIPT_ENGINE_ATTR, "js");
    
    
    DataObject obj = DataObject.find(fo);
    
    DataFolder folder = DataFolder.findFolder(FileUtil.createFolder(root, "target"));
    
    Map<String,String> parameters = Collections.singletonMap("title", "Nazdar");
    DataObject n = obj.createFromTemplate(folder, "complex", parameters);
    
    assertEquals("Created in right place", folder, n.getFolder());
    assertEquals("Created with right name", "complex.txt", n.getName());
    
    String res = readFile(n.getPrimaryFile());
    
    if (res.indexOf("date") >= 0) fail(res);
    if (res.indexOf("time") >= 0) fail(res);
    if (res.indexOf("user") >= 0) fail(res);
    if (res.indexOf("name") >= 0) fail(res);
    if (res.indexOf("dateTime") >= 0) fail(res);
}
 
Example 9
Project: incubator-netbeans   File: DefaultSettingsContext.java   View Source Code Vote up 5 votes
public void rebind(Name name, Object obj) throws NamingException {
    String attrName = getRelativeName(name);
    FileObject fo = dobj.getPrimaryFile();
    
    try {
        fo.setAttribute(attrName, obj);
    } catch (IOException ex) {
        NamingException ne = new NamingException(name + " = " + obj); // NOI18N
        ne.setRootCause(ex);
    }
}
 
Example 10
Project: incubator-netbeans   File: MockWizardProvider.java   View Source Code Vote up 5 votes
public static void registerWizardProvider(String instanceName, ServerWizardProvider provider) throws IOException {
    if (provider == null) {
        return;
    }

    Lookup.getDefault().lookup(ModuleInfo.class);

    FileObject servers = FileUtil.getConfigFile(ServerRegistry.SERVERS_PATH);
    FileObject testProvider = FileUtil.createData(servers, instanceName);

    testProvider.setAttribute("instanceOf", ServerWizardProvider.class.getName()); // NOI18N
    testProvider.setAttribute("instanceCreate", provider); // NOI18N
}
 
Example 11
Project: incubator-netbeans   File: PickNameAction.java   View Source Code Vote up 5 votes
protected @Override void performAction(Node[] activatedNodes) {
    NotifyDescriptor.InputLine d = new NotifyDescriptor.InputLine(
            NbBundle.getMessage(PickNameAction.class, "PickNameAction_dialog_label"),
            NbBundle.getMessage(PickNameAction.class, "PickNameAction_dialog_title"));
    if (DialogDisplayer.getDefault().notify(d) != NotifyDescriptor.OK_OPTION) {
        return;
    }
    String name = d.getInputText();
    FileObject f = findFile(activatedNodes);
    if (f == null) {
        return;
    }
    NbModuleProvider p = findProject(f);
    if (p == null) {
        return;
    }
    String bundlePath = findBundlePath(p);
    if (bundlePath == null) {
        return;
    }
    try {
        FileObject properties = p.getSourceDirectory().getFileObject(bundlePath);
        EditableProperties ep = Util.loadProperties(properties);
        final String key = LayerUtil.generateBundleKeyForFile(f.getPath());
        ep.setProperty(key, name);
        Util.storeProperties(properties, ep);
        f.setAttribute("displayName", "bundlevalue:"
                + bundlePath.substring(0, bundlePath.length() - ".properties".length())   // NOI18N
                .replace('/', '.')  // NOI18N
                + "#" + key); // NOI18N
    } catch (IOException e) {
        Util.err.notify(ErrorManager.INFORMATIONAL, e);
    }
}
 
Example 12
Project: incubator-netbeans   File: MenuBarTest.java   View Source Code Vote up 5 votes
private void generateTenActions() throws IOException {
    FileObject fo = df.getPrimaryFile().createFolder("1Menu");
    for (int i = 0; i < 10; i++) {
        FileObject item = fo.createData("item-" + i + ".instance");
        item.setAttribute("instanceCreate", new JMenuItem("" + i));
    }
}
 
Example 13
Project: incubator-netbeans   File: LayoutIterator.java   View Source Code Vote up 5 votes
public void run(FileSystem layer) throws IOException {
    FileObject folder = layer.getRoot().getFileObject("Actions/Window");// NOI18N
    if (folder == null) {
        folder = FileUtil.createFolder(layer.getRoot(), "Actions/Window"); // NOI18N
    }
    String instance = packageName.replace('.','-') + "-" + name; // NOI18N
    FileObject file = folder.createData(instance, "instance"); // NOI18N
    folder = layer.getRoot().getFileObject("Menu/Window");// NOI18N
    if (folder == null) {
        folder = FileUtil.createFolder(layer.getRoot(), "Menu/Window"); // NOI18N
    }
    file = folder.createData(name, "shadow"); // NOI18N
    file.setAttribute("originalFile", "Actions/Window/" + instance + ".instance"); // NOI18N
}
 
Example 14
Project: incubator-netbeans   File: ExLocalFileSystemTest.java   View Source Code Vote up 5 votes
private void doTest(boolean delete) throws Exception {
    clearWorkDir();
    
    File nf = new File(getWorkDir(), "ud");
    File var = new File(nf, "var");
    System.setProperty("netbeans.user", nf.getPath());
    
    FileSystem fs = FileUtil.createMemoryFileSystem();
    FileObject data = FileUtil.createData(fs.getRoot(), "My/Fld/data.txt");
    data.setAttribute("hello", "world");
    
    File root = new File(getWorkDir(), "fs");
    root.mkdirs();
    ExLocalFileSystem fs2 = ExLocalFileSystem.getInstance(root);
    
    MultiFileSystem mfs = new MultiFileSystem(new FileSystem[] { fs2, fs });
    
    FileObject ndata = mfs.findResource(data.getPath());
    assertNotNull("data found", ndata);
    assertEquals("They have the right attribute", "world", ndata.getAttribute("hello"));
 
    ndata.setAttribute("hello", "kuk");
    assertEquals("New attribute value is there", "kuk", ndata.getAttribute("hello"));

    ndata.setAttribute("hello", "buk");
    assertEquals("Newer attribute value is there", "buk", ndata.getAttribute("hello"));
    
    if (delete && var.exists() && !var.delete()) {
        for (File file : var.listFiles()) {
            file.delete();
        }
        assertTrue("Can delete " + var, var.delete());
    }

    ndata.setAttribute("hello", "muk");
    assertEquals("Newest attribute value is there", "muk", ndata.getAttribute("hello"));
}
 
Example 15
Project: incubator-netbeans   File: DefaultSettingsContext.java   View Source Code Vote up 5 votes
public void bind(Name name, Object obj) throws NamingException {
    String attrName = getRelativeName(name);
    FileObject fo = dobj.getPrimaryFile();
    Object attrVal = fo.getAttribute(attrName);
    if (attrVal != null) {
        throw new NameAlreadyBoundException(attrName + " = " + attrVal); // NOI18N
    }
    
    try {
        fo.setAttribute(attrName, obj);
    } catch (IOException ex) {
        NamingException ne = new NamingException(attrName + " = " + obj); // NOI18N
        ne.setRootCause(ex);
    }
}
 
Example 16
Project: incubator-netbeans   File: DynamicSFSFallbackTest.java   View Source Code Vote up 4 votes
public void testDynamicSystemsCanAlsoBeBehindLayers() throws Exception {
    FileObject global = FileUtil.getConfigFile("Toolbars/Standard.xml");
    assertNotNull("File Object installed: " + global, global);
    if (global.asText().indexOf("<Toolbar name=") == -1) {
        fail("Expecting toolbar definition: " + global.asText());
    }

    final LocalFileSystem lfs1 = new LocalFileSystem();
    File dir1 = new File(getWorkDir(), "dir1");
    dir1.mkdirs();
    lfs1.setRootDirectory(dir1);
    lfs1.getRoot().setAttribute("fallback", Boolean.TRUE);
    assertEquals("Position attribute is there", Boolean.TRUE, lfs1.getRoot().getAttribute("fallback"));
    fs1 = lfs1;
    fs2 = FileUtil.createMemoryFileSystem();

    FileObject fo1 = FileUtil.createData(fs1.getRoot(), global.getPath());
    fo1.setAttribute("one", 1);
    write(fo1, "fileone");

    FileObject fo11 = FileUtil.createData(fs1.getRoot(), "test-fs-is-there.txt");
    write(fo11, "hereIam");

    MainLookup.register(fs1, this);
    MainLookup.register(fs2, this);

    Iterator<? extends FileSystem> it = Lookup.getDefault().lookupAll(FileSystem.class).iterator();
    assertTrue("At least One", it.hasNext());
    assertEquals("first is fs1", fs1, it.next());
    assertTrue("At least two ", it.hasNext());
    assertEquals("first is fs2", fs2, it.next());

    if (global.asText().indexOf("<Toolbar name=") == -1) {
        fail("Still Expecting toolbar definition: " + global.asText());
    }
    assertTrue("Still valid", global.isValid());

    FileObject fo = FileUtil.getConfigFile("test-fs-is-there.txt");
    assertNotNull("File found: " + Arrays.toString(FileUtil.getConfigRoot().getChildren()), fo);
    assertEquals("Text is correct", "hereIam", fo.asText());
}
 
Example 17
Project: incubator-netbeans   File: CompilationUnitTest.java   View Source Code Vote up 4 votes
public void test196276() throws Exception {
    testFile = new File(getWorkDir(), "Test.java");
    TestUtilities.copyStringToFile(testFile,
        "package zoo;\n" +
        "\n" +
        "public class A {\n" +
        "}\n"
    );

    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);
    Writer w = new OutputStreamWriter(classJava.getOutputStream(), "UTF-8");
    w.write("package zoo;\npublic class Template {\n    public Template() {}\n}");
    w.close();
    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" +
        "\n" + //XXX
        "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()
            );
            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)));
            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(res, golden1);
}
 
Example 18
Project: incubator-netbeans   File: CompilationUnitTest.java   View Source Code Vote up 4 votes
public void testNewCompilationUnitInDefaultPackage() 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 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);

    String golden =
        "\n" +
        "public class Krtek {\n" +
        "\n" +
        "    void m() {\n" +
        "    }\n" +
        "}\n";
    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 newTree = make.CompilationUnit(
                    sourceRoot,
                    "Krtek.java",
                    Collections.<ImportTree>emptyList(),
                    Collections.<Tree>emptyList()
            );
            ClassTree clazz = make.Class(
                    make.Modifiers(Collections.<Modifier>singleton(Modifier.PUBLIC)),
                    "Krtek",
                    Collections.<TypeParameterTree>emptyList(),
                    null,
                    Collections.<Tree>emptyList(),
                    Collections.<Tree>emptyList()
            );
            newTree = make.addCompUnitTypeDecl(newTree, clazz);
            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
            );
            workingCopy.rewrite(null, newTree);
            workingCopy.rewrite(clazz, make.addClassMember(clazz, nju));
        }
    };
    ModificationResult result = javaSource.runModificationTask(task);
    result.commit();
    String res = TestUtilities.copyFileToString(new File(getDataDir().getAbsolutePath() + "/Krtek.java"));
    System.err.println(res);
    assertEquals(res, golden);
}
 
Example 19
Project: incubator-netbeans   File: CompilationUnitTest.java   View Source Code Vote up 4 votes
public void testNewCompilationUnit() 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 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);
    
    String golden = 
        "package zoo;\n" +
        "\n" +
        "public class Krtek {\n" +
        "\n" +
        "    void m() {\n" +
        "    }\n" +
        "}\n";
    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 newTree = make.CompilationUnit(
                    sourceRoot,
                    "zoo/Krtek.java",
                    Collections.<ImportTree>emptyList(),
                    Collections.<Tree>emptyList()
            );
            ClassTree clazz = make.Class(
                    make.Modifiers(Collections.<Modifier>singleton(Modifier.PUBLIC)),
                    "Krtek",
                    Collections.<TypeParameterTree>emptyList(),
                    null,
                    Collections.<Tree>emptyList(),
                    Collections.<Tree>emptyList()
            );
            newTree = make.addCompUnitTypeDecl(newTree, clazz);
            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
            );
            workingCopy.rewrite(null, newTree);
            workingCopy.rewrite(clazz, make.addClassMember(clazz, nju));
        }
    };
    ModificationResult result = javaSource.runModificationTask(task);
    result.commit();
    String res = TestUtilities.copyFileToString(new File(getDataDir().getAbsolutePath() + "/zoo/Krtek.java"));
    System.err.println(res);
    assertEquals(res, golden);
}
 
Example 20
Project: incubator-netbeans   File: CompilationUnitTest.java   View Source Code Vote up 4 votes
public void doTest197097() throws Exception {
    testFile = new File(getWorkDir(), "Test.java");
    TestUtilities.copyStringToFile(testFile,
        "package zoo;\n" +
        "\n" +
        "public class A {\n" +
        "    public class I extends java.util.ArrayList {\n" +
        "        public I(java.util.Collection c) {\n" +
        "            super(c);\n" +
        "        }\n" +
        "    }\n" +
        "}\n"
    );

    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);
    Writer w = new OutputStreamWriter(classJava.getOutputStream(), "UTF-8");
    w.write("package zoo;\npublic class Template {\n  \n}");
    w.close();
    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" +
        "\n" + //XXX
        "public class I extends java.util.ArrayList {\n\n" +
        "    public I(java.util.Collection c) {\n" +
        "        super(c);\n" +
        "    }\n" +
        "  \n" +//XXX
        "}\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();
            Tree classDecl = ((ClassTree) workingCopy.getCompilationUnit().getTypeDecls().get(0)).getMembers().get(1);
            CompilationUnitTree newTree = make.CompilationUnit(
                    sourceRoot,
                    "zoo/I.java",
                    Collections.<ImportTree>emptyList(),
                    Collections.<Tree>singletonList(classDecl)
            );
            workingCopy.rewrite(null, newTree);
            MethodTree constructor = (MethodTree) ((ClassTree) classDecl).getMembers().get(0);
            workingCopy.rewrite(constructor, make.setLabel(constructor, "I"));
        }
    };
    ModificationResult result = javaSource.runModificationTask(task);
    result.commit();
    String res = TestUtilities.copyFileToString(new File(getDataDir().getAbsolutePath() + "/zoo/I.java"));
    System.err.println(res);
    assertEquals(res, golden1);
}