Search code examples
javanetbeanscodenameonenetbeans-platformnetbeans-plugins

NetBeans createFromTemplate Passes Wrong Value To ${name}


I'm using code such as this in our NetBeans plugin:

DataObject result = dTemplate.createFromTemplate(df, name, args);

Which generates the file correctly. However if there is a file with the given name the template occupies a new file name (as reflected in the result object) but the ${name} value still refers to the old name. E.g. if name = Hi and Hi.java already exists then Hi_1.java will be created but ${name} will still be Hi.

Also I'm a bit baffled regarding the source of the .java extension. My original code had this:

DataObject result = dTemplate.createFromTemplate(df, name + ".java", args);

But it turns out the .java is unnecessary, and I'm not sure where I specify that this is indeed what I want?


Solution

  • I'm not sure if this is the "right way" but this is what I have so far that seems to work:

    private String getProperName(DataFolder f, String name, int suffix) {
        String actualName = name;
        if(suffix > 0) {
            actualName = actualName + "_" + suffix;
        }
        for(DataObject chld : f.getChildren()) {
            if(chld.getName().equals(actualName)) {
                suffix++;
                return getProperName(f, name, suffix);
            }
        }
        return actualName;
    }
    

    Then in the code:

    String actualName = getProperName(df, name, 0);        
    DataObject result = dTemplate.createFromTemplate(df, actualName, args);
    

    That way the renaming never happens and I sort of avoid the problem.