Re: Use file templates inside a project template

Iñigo Huguet <[email protected]> Wed, 5 Jul 2017 14:29:56 +0200
Newsgroups gmane.comp.java.netbeans.modules.openide.devel
Message-ID <[email protected]>
I found what I was doing wrong.


WHAT I DID WRONG:

First I registered the template file like this:

@TemplateRegistration(folder = "Others", content = 
"templateFiles/main.c", scriptEngine = "freemarker")

However, I didn't know which was the path to that file in the Netbeans 
filesystem, so I tried to register it in layer.xml

     <folder name="MyModuleOwnFolder">
         <folder name="templates">
             <file name="main.c" url="templateFiles/main.c" />
         </folder>
     </folder>

However, what I did with this was registering it twice: one via 
@TemplateRegistration and another via layer.xml, both in different 
locations of the Netbeans filesystem.


THE GOOD WAY:

Register the template file via @TemplateRegistration:

@TemplateRegistration(folder = "Others", content = 
"templateFiles/main.c", scriptEngine = "freemarker")

The templates registered with @TemplateRegistration are registered 
inside "Template" folder of the Netbeans filesystem (I think this is not 
documented at all, at least I didn't find it in any place).

The full path to get the template file in the Netbeans filesystem is 
"Template/Others/main.c" ("Others" is the folder registered in 
@TemplateRegistration, and "main.c" is the file name).

FileObject templ = FileUtil.getSystemConfigFile("Templates/Others/main.c");
attrs = new HashMap<>();
attrs.put("user", "My Name");  // replace "${user}" by "My Name" in the 
template
FileBuilder.createFromTemplate(templ, dir, "main", attrs, 
FileBuilder.Mode.FORMAT);


OTHER VALID WAY:

Instead of using @TemplateRegistration, it can be registered in 
layer.xml instead. However, I think the first one is the recommended 
way, and not this one.

<filesystem>
     <folder name="MyModuleOwnFolder">
         <folder name="templates">
             <file name="main.c" url="templateFiles/main.c">
                 <attr name="javax.script.ScriptEngine" 
stringvalue="freemarker"/>
             </file>
         </folder>
     </folder>
</filesystem>

The path in the filesystem is "MyModuleOwnFolder/templates/main.c"


NOTE: in all previous examples, the template file is stored in disk 
inside the java package, in the subfolder templateFiles


Geertjan, thanks for your help.


El 05/07/17 a las 13:06, geertjan wielenga escribió:
>
>
> Sounds like your TemplateRegistration was wrong, somehow. Those 
> annotations end up in the generated-layer.xml file.
>
> Gj
>
>
> On 5-7-2017 13:04, Iñigo Huguet wrote:
>>
>> OK, thanks!
>>
>> I will wait for you to take a look, and I will try to find it by 
>> myself, as well.
>>
>>
>> El 05/07/17 a las 12:38, geertjan wielenga escribió:
>>>
>>>
>>> OK, so now that it works, it's not a high priority for me, right 
>>> now. Will take a look at some point.
>>>
>>> Gj
>>>
>>>
>>> On 5-7-2017 11:43, Iñigo Huguet wrote:
>>>>
>>>> I had registered it in the TemplateRegistration annotation, but not 
>>>> in the layer.xml file.
>>>>
>>>> I just added '<attr name="javax.script.ScriptEngine" 
>>>> stringvalue="freemarker"/>' in the layer.xml file and now it's working.
>>>>
>>>> I can continue now. However, I would like to understand why it 
>>>> wasn't working, what I was doing wrong? What are the 
>>>> TemplateRegistration annotations for?
>>>>
>>>> Note: look to the explanation in my first message, not the github 
>>>> code, which is not complete
>>>>
>>>> Thanks
>>>>
>>>>
>>>> El 05/07/17 a las 11:13, geertjan wielenga escribió:
>>>>>
>>>>>
>>>>> Do you have your file template registered as FreeMarker"
>>>>>
>>>>>                         <attr name="javax.script.ScriptEngine" 
>>>>> stringvalue="freemarker"/>
>>>>>
>>>>> See:
>>>>>
>>>>> https://blogs.oracle.com/geertjan/registering-freemarker-templates-in-netbeans-ide-71
>>>>>
>>>>> Thanks,
>>>>>
>>>>> Gj
>>>>>
>>>>> On 5-7-2017 10:56, geertjan wielenga wrote:
>>>>>>
>>>>>> Maybe take a look at this:
>>>>>>
>>>>>> https://blogs.oracle.com/geertjan/extension-to-extended-java-project-part-2
>>>>>>
>>>>>> Gj
>>>>>>
>>>>>>
>>>>>> On 5-7-2017 10:33, Iñigo Huguet wrote:
>>>>>>>
>>>>>>> Hi.
>>>>>>>
>>>>>>> I just created a new module project following this tutorial: 
>>>>>>> https://platform.netbeans.org/tutorials/nbm-projectsamples.html
>>>>>>>
>>>>>>> I uploaded it to github, here: 
>>>>>>> https://github.com/naggety/Netbeans-MyCustomProjType
>>>>>>>
>>>>>>> This is just a custom template C/C++ project. Inside the zip 
>>>>>>> file of the project template, there is a 'main.c' file that I 
>>>>>>> need to be processed by freemarker when the new project is 
>>>>>>> created (this way, the text '${user}' in the file will be 
>>>>>>> replaced with the user name). I tried to achieve this in the way 
>>>>>>> I described in my first message, but it didn't work.
>>>>>>>
>>>>>>> As I said, there is a tutorial about file templates, but not for 
>>>>>>> file templates inside project templates nor for processing file 
>>>>>>> templates programmatically.
>>>>>>>
>>>>>>> In addition, but less important for the moment, when I install 
>>>>>>> the module from tools->plugins it says that the installation was 
>>>>>>> unsuccessful. However, if I restart the IDE, the module is 
>>>>>>> installed and working.
>>>>>>>
>>>>>>>
>>>>>>> El 04/07/17 a las 11:29, geertjan wielenga escribió:
>>>>>>>>
>>>>>>>> Best is to create a small application on GitHub containing a 
>>>>>>>> simple scenario and then to say what kind of help you'd need in 
>>>>>>>> the context of that scenario.
>>>>>>>>
>>>>>>>> Gj
>>>>>>>>
>>>>>>>>
>>>>>>>> On 4-7-2017 8:55, Iñigo Huguet wrote:
>>>>>>>>> There isn't a way to get a file, process it with freemarker 
>>>>>>>>> and save it in another location?
>>>>>>>>>
>>>>>>>>>
>>>>>>>>> El 28/06/17 a las 10:31, Iñigo Huguet escribió:
>>>>>>>>>> Hi!
>>>>>>>>>>
>>>>>>>>>> I wan't to create a project template with some files that are 
>>>>>>>>>> also template files. This template files contains some 
>>>>>>>>>> variables like ${user} which must be replaced with the "user" 
>>>>>>>>>> variable value.
>>>>>>>>>>
>>>>>>>>>> I have followed this tutorial to create the project template: 
>>>>>>>>>> https://platform.netbeans.org/tutorials/nbm-projectsamples.html
>>>>>>>>>>
>>>>>>>>>> However, I don't know how to get the template files to be 
>>>>>>>>>> processed with freemarker template engine, despite being 
>>>>>>>>>> trying for 3 days. I haven't found any information about how 
>>>>>>>>>> to do what I want (only info about project templates and file 
>>>>>>>>>> templates, but no one of both together).
>>>>>>>>>>
>>>>>>>>>> This is what I have tried:
>>>>>>>>>>
>>>>>>>>>> First, I modified the 'instantiate' method of the wizard 
>>>>>>>>>> iterator to process the template files:
>>>>>>>>>> [code]
>>>>>>>>>>     public Set/*<FileObject>*/ instantiate(/*ProgressHandle 
>>>>>>>>>> handle*/) throws IOException {
>>>>>>>>>>         Set<FileObject> resultSet = new 
>>>>>>>>>> LinkedHashSet<FileObject>();
>>>>>>>>>>         File dirF = FileUtil.normalizeFile((File) 
>>>>>>>>>> wiz.getProperty("projdir"));
>>>>>>>>>>         dirF.mkdirs();
>>>>>>>>>>
>>>>>>>>>>         FileObject template = Templates.getTemplate(wiz);
>>>>>>>>>>         FileObject dir = FileUtil.toFileObject(dirF);
>>>>>>>>>>         unZipFile(template.getInputStream(), dir);
>>>>>>>>>>
>>>>>>>>>>         ///// ADDED CODE
>>>>>>>>>>         FileObject templ = 
>>>>>>>>>> FileUtil.getSystemConfigFile("ADDITIONALSAMPLE_INIGO/templates/main.c"); 
>>>>>>>>>>
>>>>>>>>>>         Map<String, String> attrs = new HashMap<>();
>>>>>>>>>>         attrs.put("javax.script.ScriptEngine", "freemarker");
>>>>>>>>>>         attrs.put("user", "myName");
>>>>>>>>>>         FileBuilder.createFromTemplate(templ, dir, "main", 
>>>>>>>>>> attrs, FileBuilder.Mode.FORMAT);
>>>>>>>>>>         ///// END OF ADDED CODE
>>>>>>>>>>
>>>>>>>>>>
>>>>>>>>>>         // Always open top dir as a project:
>>>>>>>>>>         resultSet.add(dir);
>>>>>>>>>>         // Look for nested projects to open as well:
>>>>>>>>>>         Enumeration<? extends FileObject> e = 
>>>>>>>>>> dir.getFolders(true);
>>>>>>>>>>         while (e.hasMoreElements()) {
>>>>>>>>>>             FileObject subfolder = e.nextElement();
>>>>>>>>>>             if 
>>>>>>>>>> (ProjectManager.getDefault().isProject(subfolder)) {
>>>>>>>>>>                 resultSet.add(subfolder);
>>>>>>>>>>             }
>>>>>>>>>>         }
>>>>>>>>>>
>>>>>>>>>>         File parent = dirF.getParentFile();
>>>>>>>>>>         if (parent != null && parent.exists()) {
>>>>>>>>>> ProjectChooser.setProjectsFolder(parent);
>>>>>>>>>>         }
>>>>>>>>>>
>>>>>>>>>>         return resultSet;
>>>>>>>>>>     }
>>>>>>>>>> [/code]
>>>>>>>>>>
>>>>>>>>>>
>>>>>>>>>> I modified the templateregistration annotation of the top of 
>>>>>>>>>> the same file and let it like this:
>>>>>>>>>> [code]
>>>>>>>>>> @TemplateRegistrations(value = {
>>>>>>>>>>     @TemplateRegistration(folder = "Project/My custom 
>>>>>>>>>> project", displayName = "#customproj_displayName", 
>>>>>>>>>> description = "customproj.html", iconBase = 
>>>>>>>>>> "org/myplugins/additionalsample/MyCustomProject.png", content 
>>>>>>>>>> = "MyCustomProject.zip", scriptEngine = "freemarker"),
>>>>>>>>>>     @TemplateRegistration(folder = "Others", content = 
>>>>>>>>>> "templates/main.c", scriptEngine = "freemarker")
>>>>>>>>>> })
>>>>>>>>>> [/code]
>>>>>>>>>>
>>>>>>>>>>
>>>>>>>>>> And finally I created this layer.xml file:
>>>>>>>>>> [code]
>>>>>>>>>> <?xml version="1.0" encoding="UTF-8"?>
>>>>>>>>>> <!DOCTYPE filesystem PUBLIC "-//NetBeans//DTD Filesystem 
>>>>>>>>>> 1.2//EN" "http://www.netbeans.org/dtds/filesystem-1_2.dtd">
>>>>>>>>>> <filesystem>
>>>>>>>>>>     <folder name="ADDITIONALSAMPLE_INIGO">
>>>>>>>>>>         <folder name="templates">
>>>>>>>>>>             <file name="main.c" url="templates/main.c" />
>>>>>>>>>>         </folder>
>>>>>>>>>>     </folder>
>>>>>>>>>> </filesystem>
>>>>>>>>>> [/code]
>>>>>>>>>>
>>>>>>>>>> However, main.c file is copied as is, the text '${user}' in 
>>>>>>>>>> the file is copied literally, not processed by freemarker.
>>>>>>>>>>
>>>>>>>>>> And also, the project is created in disk but it's not added 
>>>>>>>>>> to the open projects.
>>>>>>>>>>
>>>>>>>>>> Hope anyone can help me.
>>>>>>>>>>
>>>>>>>>>> Thanks!
>>>>>>>>>>
>>>>>>>>>>
>>>>>>>>>
>>>>>>>>
>>>>>>>>
>>>>>>>
>>>>>>> -- 
>>>>>>> Pagina nueva 1
>>>>>>>
>>>>>>> ------------------------------------------------------------------------
>>>>>>> Fanamoel S.A. 	
>>>>>>>
>>>>>>> *P. I.  La Fuente, Nº 6*
>>>>>>>
>>>>>>> *31250 – Oteiza (Navarra)*
>>>>>>>
>>>>>>> *Tfno: +34 948 546 718*
>>>>>>>
>>>>>>> *Fax: +34 948 546 735*
>>>>>>>
>>>>>>> *Iñigo Huguet Embún *
>>>>>>>
>>>>>>> *D**epartamento Técnico*
>>>>>>>
>>>>>>> La información incluida en el presente correo electrónico y 
>>>>>>> cualquier archivo adjunto al mismo están dirigidos 
>>>>>>> exclusivamente a su destinatario. Pueden contener información 
>>>>>>> confidencial o privilegiada. Si recibe esta comunicación sin ser 
>>>>>>> el destinatario le informamos de que está prohibida cualquier 
>>>>>>> utilización de la misma y le rogamos que nos lo notifique 
>>>>>>> inmediatamente y la devuelva a su origen, asegurándose de que el 
>>>>>>> mensaje original, cualquier copia relacionada con el mismo y sus 
>>>>>>> archivos adjuntos sean eliminados de su sistema.
>>>>>>>
>>>>>>>
>>>>>>> Asimismo, le informamos de que trataremos de forma confidencial 
>>>>>>> su dirección de correo electrónico, así como el resto de los 
>>>>>>> datos de carácter personal que nos facilite, y serán incluidos 
>>>>>>> en un fichero del que FANAMOEL S.A., es titular y responsable. 
>>>>>>> La finalidad del tratamiento será informarle y ofrecerle 
>>>>>>> nuestros servicios. Vd. podrá ejercitar los derechos de acceso, 
>>>>>>> rectificación, cancelación y oposición enviando un e-mail a la 
>>>>>>> dirección arriba indicada.
>>>>>>>
>>>>>>
>>>>>
>>>>
>>>> -- 
>>>> Pagina nueva 1
>>>>
>>>> ------------------------------------------------------------------------
>>>> Fanamoel S.A. 	
>>>>
>>>> *P. I.  La Fuente, Nº 6*
>>>>
>>>> *31250 – Oteiza (Navarra)*
>>>>
>>>> *Tfno: +34 948 546 718*
>>>>
>>>> *Fax: +34 948 546 735*
>>>>
>>>> *Iñigo Huguet Embún *
>>>>
>>>> *D**epartamento Técnico*
>>>>
>>>> La información incluida en el presente correo electrónico y 
>>>> cualquier archivo adjunto al mismo están dirigidos exclusivamente a 
>>>> su destinatario. Pueden contener información confidencial o 
>>>> privilegiada. Si recibe esta comunicación sin ser el destinatario 
>>>> le informamos de que está prohibida cualquier utilización de la 
>>>> misma y le rogamos que nos lo notifique inmediatamente y la 
>>>> devuelva a su origen, asegurándose de que el mensaje original, 
>>>> cualquier copia relacionada con el mismo y sus archivos adjuntos 
>>>> sean eliminados de su sistema.
>>>>
>>>>
>>>> Asimismo, le informamos de que trataremos de forma confidencial su 
>>>> dirección de correo electrónico, así como el resto de los datos de 
>>>> carácter personal que nos facilite, y serán incluidos en un fichero 
>>>> del que FANAMOEL S.A., es titular y responsable. La finalidad del 
>>>> tratamiento será informarle y ofrecerle nuestros servicios. Vd. 
>>>> podrá ejercitar los derechos de acceso, rectificación, cancelación 
>>>> y oposición enviando un e-mail a la dirección arriba indicada.
>>>>
>>>
>>
>> -- 
>> Pagina nueva 1
>>
>> ------------------------------------------------------------------------
>> Fanamoel S.A. 	
>>
>> *P. I.  La Fuente, Nº 6*
>>
>> *31250 – Oteiza (Navarra)*
>>
>> *Tfno: +34 948 546 718*
>>
>> *Fax: +34 948 546 735*
>>
>> *Iñigo Huguet Embún *
>>
>> *D**epartamento Técnico*
>>
>> La información incluida en el presente correo electrónico y cualquier 
>> archivo adjunto al mismo están dirigidos exclusivamente a su 
>> destinatario. Pueden contener información confidencial o 
>> privilegiada. Si recibe esta comunicación sin ser el destinatario le 
>> informamos de que está prohibida cualquier utilización de la misma y 
>> le rogamos que nos lo notifique inmediatamente y la devuelva a su 
>> origen, asegurándose de que el mensaje original, cualquier copia 
>> relacionada con el mismo y sus archivos adjuntos sean eliminados de 
>> su sistema.
>>
>>
>> Asimismo, le informamos de que trataremos de forma confidencial su 
>> dirección de correo electrónico, así como el resto de los datos de 
>> carácter personal que nos facilite, y serán incluidos en un fichero 
>> del que FANAMOEL S.A., es titular y responsable. La finalidad del 
>> tratamiento será informarle y ofrecerle nuestros servicios. Vd. podrá 
>> ejercitar los derechos de acceso, rectificación, cancelación y 
>> oposición enviando un e-mail a la dirección arriba indicada.
>>
>

-- 
Pagina nueva 1

------------------------------------------------------------------------
Fanamoel S.A. 	

*P. I.  La Fuente, Nº 6*

*31250 – Oteiza (Navarra)*

*Tfno: +34 948 546 718*

*Fax: +34 948 546 735*

*Iñigo Huguet Embún *

*D**epartamento Técnico*

La información incluida en el presente correo electrónico y cualquier 
archivo adjunto al mismo están dirigidos exclusivamente a su 
destinatario. Pueden contener información confidencial o privilegiada. 
Si recibe esta comunicación sin ser el destinatario le informamos de que 
está prohibida cualquier utilización de la misma y le rogamos que nos lo 
notifique inmediatamente y la devuelva a su origen, asegurándose de que 
el mensaje original, cualquier copia relacionada con el mismo y sus 
archivos adjuntos sean eliminados de su sistema.


Asimismo, le informamos de que trataremos de forma confidencial su 
dirección de correo electrónico, así como el resto de los datos de 
carácter personal que nos facilite, y serán incluidos en un fichero del 
que FANAMOEL S.A., es titular y responsable. La finalidad del 
tratamiento será informarle y ofrecerle nuestros servicios. Vd. podrá 
ejercitar los derechos de acceso, rectificación, cancelación y oposición 
enviando un e-mail a la dirección arriba indicada.