Java Code Examples for org.netbeans.api.templates.FileBuilder

The following examples show how to use org.netbeans.api.templates.FileBuilder. These examples are extracted from open source projects. 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 Project: netbeans   Source File: SnippetClassGenerator.java    License: Apache License 2.0 6 votes vote down vote up
@NbBundle.Messages({
    "EXC_UnexpectedTemplateContents=Unexpected plain class template contents",
    "EXC_ShellTemplateMissing=Unexpected plain class template contents"
})
private FileObject createJavaFile() throws IOException {
    FileObject template = FileUtil.getConfigFile("Templates/Classes/ShellClass.java"); // NOI18N
    if (template == null) {
        throw new IOException(Bundle.EXC_ShellTemplateMissing());
    }
    FileBuilder builder = new FileBuilder(template, targetFolder);
    builder.name(className);
    builder.param("executables", executableContent.toString());
    builder.param("declaratives", declarativeConent.toString());
    
    Collection<FileObject> l = builder.build();
    if (l.size() != 1) {
        throw new IOException(Bundle.EXC_UnexpectedTemplateContents());
    }
    return l.iterator().next();
}
 
Example 2
@Override
public Map<String, ?> attributesFor(CreateDescriptor desc) {
    FileObject origFile = (FileObject) desc.getTarget().getAttribute(FileObjectFromTemplateCreator.ATTR_ORIG_FILE);
    if (origFile == null) return null;

    Map<String, Object> all = new HashMap<>();

    FileBuilder bld = new FileBuilder(desc.getTemplate(), origFile);
    CreateDescriptor childDesc = bld.withParameters(desc.getParameters()).createDescriptor(false);
    for (CreateFromTemplateAttributes provider : Lookup.getDefault().lookupAll(CreateFromTemplateAttributes.class)) {
        Map<String, ? extends Object> map = provider.attributesFor(childDesc);
        if (map != null) {
            for (Map.Entry<String, ? extends Object> e : map.entrySet()) {
                all.put(e.getKey(), e.getValue());
            }
        }
    }

    return all;
}
 
Example 3
Source Project: netbeans   Source File: FileEntry.java    License: Apache License 2.0 6 votes vote down vote up
@Override
@SuppressWarnings("AssignmentToMethodParameter")
public FileObject createFromTemplate (FileObject f, String name) throws IOException {
    String ext = getFile ().getExt ();
    if (name == null) {
        name = FileUtil.findFreeFileName(
                   f,
                   getFile ().getName (), ext
               );
    }
    java.text.Format frm = createFormat (f, name, ext);
    List<FileObject> fos = new FileBuilder(getFile(), f).name(name).
            withParameters(DataObject.CreateAction.getCallParameters(name)).
            useFormat(frm).build();
    FileObject fo = fos.get(0);
    // unmark template state
    DataObject.setTemplate (fo, false);

    return fo;
}
 
Example 4
Source Project: netbeans   Source File: TemplateUtilsTest.java    License: Apache License 2.0 6 votes vote down vote up
public void testOverridenParameters() throws Exception {
    MockLookup.setLookup(
            Lookups.metaInfServices(getClass().getClassLoader()),
            Lookups.fixed(new DefaultValueAttribute()));
    clearWorkDir();
    FileObject dataRoot = FileUtil.toFileObject(getDataDir());
    FileObject template = dataRoot.getFileObject("templates/GeneratedMethodBody.java");
    template.setAttribute("template", Boolean.TRUE);
    template.setAttribute(ScriptingCreateFromTemplateHandler.SCRIPT_ENGINE_ATTR, "freemarker");
    FileObject workRoot = FileUtil.toFileObject(getWorkDir());
    Map m = new HashMap();
    m.put("default_return_value", "24");
    FileObject result = FileBuilder.createFromTemplate(template, workRoot, "GeneratedMethodBody", m, FileBuilder.Mode.FORMAT);
    FileObject pass = dataRoot.getFileObject("golden/GeneratedMethodBody2.java");
    assertFile(FileUtil.toFile(result), FileUtil.toFile(pass));
}
 
Example 5
private void createNbActions(String bootVersion, String pkg, String mvnName, FileObject dir) throws IOException {
    // build main class string
    StringBuilder mainClass = new StringBuilder(pkg);
    mainClass.append('.')
            .append(Character.toUpperCase(mvnName.charAt(0)))
            .append(mvnName.substring(1))
            .append("Application");
    // retrieve default options from prefs
    final Preferences prefs = NbPreferences.forModule(PrefConstants.class);
    final boolean bForceColor = prefs.getBoolean(PREF_FORCE_COLOR_OUTPUT, true);
    final boolean bManualRestart = prefs.getBoolean(PREF_MANUAL_RESTART, false);
    final String strVmOpts = Utils.vmOptsFromPrefs();
    // create nbactions.xml from template
    FileObject foTmpl = Templates.getTemplate(wiz);
    new FileBuilder(foTmpl, dir)
            .name("nbactions")
            .param("mainClass", mainClass.toString())
            .param("forceColor", bForceColor)
            .param("manualRestart", bManualRestart)
            .param("isBoot2", bootVersion.startsWith("2"))
            .param("vmOpts", strVmOpts)
            .build();
}
 
Example 6
Source Project: nb-springboot   Source File: BasicProjectWizardIterator.java    License: Apache License 2.0 6 votes vote down vote up
private void createNbActions(FileObject dir) throws IOException {
    // retrieve default options from prefs
    final Preferences prefs = NbPreferences.forModule(PrefConstants.class);
    final boolean bForceColor = prefs.getBoolean(PREF_FORCE_COLOR_OUTPUT, true);
    final boolean bManualRestart = prefs.getBoolean(PREF_MANUAL_RESTART, false);
    final String strVmOpts = Utils.vmOptsFromPrefs();
    // compute name of devtools restart trigger file
    String triggerFileEnv = BOOTVERSION.startsWith("2") ? SpringBootService.ENV_RESTART_20 : SpringBootService.ENV_RESTART_15;
    // create nbactions.xml from template
    FileObject foTmpl = Templates.getTemplate(wiz);
    new FileBuilder(foTmpl, dir)
            .name("nbactions")
            .param("forceColor", bForceColor)
            .param("manualRestart", bManualRestart)
            .param("restartTriggerFileEnv", triggerFileEnv)
            .param("vmOpts", strVmOpts)
            .build();
}
 
Example 7
Source Project: nb-springboot   Source File: InjectSpringBootGenerator.java    License: Apache License 2.0 6 votes vote down vote up
private void createNbActions(FileObject dir) throws IOException {
    if (dir == null) {
        return;
    }
    // retrieve default options from prefs
    final Preferences prefs = NbPreferences.forModule(PrefConstants.class);
    final boolean bForceColor = prefs.getBoolean(PrefConstants.PREF_FORCE_COLOR_OUTPUT, true);
    final boolean bManualRestart = prefs.getBoolean(PrefConstants.PREF_MANUAL_RESTART, false);
    final String strVmOpts = Utils.vmOptsFromPrefs();
    // use template file from Initializr Spring Boot wizard
    FileObject foTmpl = FileUtil.getConfigFile("/Templates/Project/Maven2/initializr-nbactions.xml");
    FileBuilder fb = new FileBuilder(foTmpl, dir)
            .name("nbactions")
            .param("forceColor", bForceColor)
            .param("manualRestart", bManualRestart)
            .param("isBoot2", BasicProjectWizardIterator.BOOTVERSION.startsWith("2"))
            .param("vmOpts", strVmOpts);
    fb.build();
}
 
Example 8
Source Project: netbeans   Source File: ArchetypeTemplateHandlerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testOrderOfMerging1() throws Exception {
    CreateDescriptor desc = new FileBuilder(root.createData("template.txt"), root.createFolder("targetFolder")).
        param("wizard", Collections.singletonMap("key1", "value1")).
        createDescriptor(true);
    Properties archetypeFile = new Properties();

    ArchetypeTemplateHandler.mergeProperties(desc, archetypeFile);

    assertEquals("value1", archetypeFile.get("key1"));
}
 
Example 9
Source Project: netbeans   Source File: ArchetypeTemplateHandlerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testOrderOfMerging2() throws Exception {
    CreateDescriptor desc = new FileBuilder(root.createData("template.txt"), root.createFolder("targetFolder")).
        param("key1", "value1").
        createDescriptor(true);
    Properties archetypeFile = new Properties();

    ArchetypeTemplateHandler.mergeProperties(desc, archetypeFile);

    assertEquals("value1", archetypeFile.get("key1"));
}
 
Example 10
Source Project: netbeans   Source File: ArchetypeTemplateHandlerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testOrderOfMerging3() throws Exception {
    CreateDescriptor desc = new FileBuilder(root.createData("template.txt"), root.createFolder("targetFolder")).
        param("key2", "value2").
        param("wizard", Collections.singletonMap("key3", "value3")).
        createDescriptor(true);
    Properties archetypeFile = new Properties();
    archetypeFile.put("key1", "value1");

    ArchetypeTemplateHandler.mergeProperties(desc, archetypeFile);

    assertEquals("value1", archetypeFile.get("key1"));
    assertEquals("value2", archetypeFile.get("key2"));
    assertEquals("value3", archetypeFile.get("key3"));
}
 
Example 11
Source Project: netbeans   Source File: ArchetypeTemplateHandlerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testOrderOfMergingDescriptorTakePrecedence() throws Exception {
    CreateDescriptor desc = new FileBuilder(root.createData("template.txt"), root.createFolder("targetFolder")).
        param("key1", "value1").
        createDescriptor(true);
    Properties archetypeFile = new Properties();
    archetypeFile.put("key1", "value2");

    ArchetypeTemplateHandler.mergeProperties(desc, archetypeFile);

    assertEquals("value1", archetypeFile.get("key1"));
}
 
Example 12
Source Project: netbeans   Source File: ArchetypeTemplateHandlerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testOrderOfMergingWizardTakePrecedence() throws Exception {
    CreateDescriptor desc = new FileBuilder(root.createData("template.txt"), root.createFolder("targetFolder")).
        param("key1", "value1").
        param("wizard", Collections.singletonMap("key1", "value2")).
        createDescriptor(true);
    Properties archetypeFile = new Properties();
    archetypeFile.put("key1", "value3");

    ArchetypeTemplateHandler.mergeProperties(desc, archetypeFile);

    assertEquals("value2", archetypeFile.get("key1"));
}
 
Example 13
Source Project: netbeans   Source File: FileEntry.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public FileObject createFromTemplate (FileObject f, String name) throws IOException {
    FileObject fo = FileBuilder.createFromTemplate(getFile(), f, name, 
            DataObject.CreateAction.getCallParameters(name), 
            FileBuilder.Mode.COPY);
    // unmark template state
    DataObject.setTemplate (fo, false);

    return fo;
}
 
Example 14
/**
 * Checks that the attribute providers execute in the correct order and see other provider's data.
 * Legacy providers should execute first. New providers should execute after that. Each new-style
 * provider should see all attributes defined by previous providers (legacy or new).
 * 
 * @throws Exception 
 */
public void testProjectAttributeProviders() throws Exception {
    Project prj = ProjectManager.getDefault().findProject(projdir);
    FileObject folder = projdir.getFileObject("nbproject");
    FileObject template = FileUtil.toFileObject(getDataDir()).getFileObject("file.txt");
    Map<String, Object> init = new HashMap();
    init.put("mama", "se raduje");
    FileObject result = FileBuilder.createFromTemplate(template, folder, "honza", init, FileBuilder.Mode.FORMAT);
    
    assertEquals(
            "Jedna, 2, Honza jde. Nese 2 pytle s brouky. Mama se raduje, ze bude pect vdolky.\n",
            result.asText());
}
 
Example 15
Source Project: netbeans   Source File: TemplateUtilsTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Checks creation of templates without any special processing.
 * @throws Exception 
 */
public void testCreatePlain() throws Exception {
    FileObject dataRoot = FileUtil.toFileObject(getDataDir());
    FileObject template = dataRoot.getFileObject("templates/ClassWithoutReplacements.java");
    template.setAttribute("template", Boolean.TRUE);
    FileObject workRoot = FileUtil.toFileObject(getWorkDir());
    FileObject result = FileBuilder.createFromTemplate(template, workRoot, "NoReplacements", null, FileBuilder.Mode.FORMAT);
    FileObject pass = dataRoot.getFileObject("golden/ClassWithoutReplacements.java");
    assertFile(FileUtil.toFile(result), FileUtil.toFile(pass));
}
 
Example 16
Source Project: netbeans   Source File: TemplateUtilsTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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 17
Source Project: netbeans   Source File: TemplateUtilsTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Uses a simple format, this is the mode applied by former implementation in MultiDataObject
 */
public void testCreateReplaceSimple() throws Exception {
    clearWorkDir();
    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, "SimpleReplacements", m, FileBuilder.Mode.FORMAT);
    FileObject pass = dataRoot.getFileObject("golden/SimpleReplacements.java");
    assertFile(FileUtil.toFile(result), FileUtil.toFile(pass));
}
 
Example 18
Source Project: netbeans   Source File: TemplateUtilsTest.java    License: Apache License 2.0 5 votes vote down vote up
public void testScriptingTemplate() throws Exception {
    clearWorkDir();
    FileObject dataRoot = FileUtil.toFileObject(getDataDir());
    FileObject template = dataRoot.getFileObject("templates/GeneratedMethodBody.java");
    template.setAttribute("template", Boolean.TRUE);
    template.setAttribute(ScriptingCreateFromTemplateHandler.SCRIPT_ENGINE_ATTR, "freemarker");
    FileObject workRoot = FileUtil.toFileObject(getWorkDir());
    Map m = new HashMap();
    m.put("default_return_value", "42");
    FileObject result = FileBuilder.createFromTemplate(template, workRoot, "GeneratedMethodBody", m, FileBuilder.Mode.FORMAT);
    FileObject pass = dataRoot.getFileObject("golden/GeneratedMethodBody.java");
    assertFile(FileUtil.toFile(result), FileUtil.toFile(pass));
}
 
Example 19
Source Project: netbeans   Source File: TemplateUtilsTest.java    License: Apache License 2.0 5 votes vote down vote up
public void testAddTemplateParameters() throws Exception {
    MockLookup.setLookup(
            Lookups.metaInfServices(getClass().getClassLoader()),
            Lookups.fixed(new DefaultValueAttribute()));
    clearWorkDir();
    FileObject dataRoot = FileUtil.toFileObject(getDataDir());
    FileObject template = dataRoot.getFileObject("templates/GeneratedMethodBody.java");
    template.setAttribute("template", Boolean.TRUE);
    template.setAttribute(ScriptingCreateFromTemplateHandler.SCRIPT_ENGINE_ATTR, "freemarker");
    FileObject workRoot = FileUtil.toFileObject(getWorkDir());
    FileObject result = FileBuilder.createFromTemplate(template, workRoot, "GeneratedMethodBody", null, FileBuilder.Mode.FORMAT);
    FileObject pass = dataRoot.getFileObject("golden/GeneratedMethodBody.java");
    assertFile(FileUtil.toFile(result), FileUtil.toFile(pass));
}
 
Example 20
Source Project: netbeans   Source File: MultiDataObject.java    License: Apache License 2.0 4 votes vote down vote up
protected DataObject handleCreateFromTemplate (
    DataFolder df, String name
) throws IOException {
    if (name == null) {
        name = FileUtil.findFreeFileName(
                   df.getPrimaryFile (), getPrimaryFile ().getName (), getPrimaryFile ().getExt ()
               );
    }

    FileObject pf = null;
    Map<String, Object> params = CreateAction.getCallParameters(name);
    // #248975: backwards-compatible hack: initializes Lookup caches, so Lookup finds registrations against
    // the old deprecated service when trying to locate new CFTH instances. This allows to freely order
    // old and new handlers
    Lookup.getDefault().lookupAll(CreateFromTemplateHandler.class);
    pf = FileBuilder.createFromTemplate(getPrimaryFile(), df.getPrimaryFile(), name, params, FileBuilder.Mode.FAIL);
    if (pf == null) {
        // do the regular creation
        pf = getPrimaryEntry().createFromTemplate (df.getPrimaryFile (), name);
    }
    
    
    Iterator<Entry> it = secondaryEntries().iterator();
    NEXT_ENTRY: while (it.hasNext ()) {
        Entry entry = it.next();
        FileObject current = entry.getFile();
        FileObject fo = FileBuilder.createFromTemplate(current, df.getPrimaryFile(), name, params, FileBuilder.Mode.FAIL);
        if (fo == null) {
            entry.createFromTemplate (df.getPrimaryFile (), name);
        }
    }
    
    try {
        // #61600: not very object oriented, but covered by DefaultVersusXMLDataObjectTest
        if (getMultiFileLoader() == DataLoaderPool.getDefaultFileLoader()) {
            return DataObject.find(pf);
        }
        
        return createMultiObject (pf);
    } catch (DataObjectExistsException ex) {
        return ex.getDataObject ();
    }
}