Search in sources :

Example 1 with Resource

use of org.bndtools.templating.Resource in project bndtools by bndtools.

the class NewBndProjectWizard method generateProjectContent.

@Override
protected void generateProjectContent(IProject project, IProgressMonitor monitor, Map<String, String> params) throws IOException {
    Map<String, List<Object>> templateParams = new HashMap<>();
    for (Entry<String, String> param : params.entrySet()) {
        templateParams.put(param.getKey(), Collections.<Object>singletonList(param.getValue()));
    }
    Template template = templatePage.getTemplate();
    try {
        ResourceMap outputs;
        if (template != null) {
            outputs = template.generateOutputs(templateParams);
        } else {
            // empty
            outputs = new ResourceMap();
        }
        SubMonitor progress = SubMonitor.convert(monitor, outputs.size() * 3);
        for (Entry<String, Resource> outputEntry : outputs.entries()) {
            String path = outputEntry.getKey();
            Resource resource = outputEntry.getValue();
            // Strip leading slashes from path
            while (path.startsWith("/")) path = path.substring(1);
            switch(resource.getType()) {
                case Folder:
                    if (!path.isEmpty()) {
                        IFolder folder = project.getFolder(path);
                        FileUtils.mkdirs(folder, progress.newChild(1, SubMonitor.SUPPRESS_ALL_LABELS));
                    }
                    break;
                case File:
                    IFile file = project.getFile(path);
                    FileUtils.mkdirs(file.getParent(), progress.newChild(1, SubMonitor.SUPPRESS_ALL_LABELS));
                    try (InputStream in = resource.getContent()) {
                        if (file.exists())
                            file.setContents(in, 0, progress.newChild(1, SubMonitor.SUPPRESS_NONE));
                        else
                            file.create(in, 0, progress.newChild(1, SubMonitor.SUPPRESS_NONE));
                        file.setCharset(resource.getTextEncoding(), progress.newChild(1));
                    }
                    break;
                default:
                    throw new IllegalArgumentException("Unknown resource type " + resource.getType());
            }
        }
    } catch (Exception e) {
        String message = MessageFormat.format("Error generating project contents from template \"{0}\": {1}", template != null ? template.getName() : "<null>", e.getMessage());
        throw new IOException(message);
    }
}
Also used : IFile(org.eclipse.core.resources.IFile) HashMap(java.util.HashMap) InputStream(java.io.InputStream) SubMonitor(org.eclipse.core.runtime.SubMonitor) StringResource(org.bndtools.templating.StringResource) Resource(org.bndtools.templating.Resource) IOException(java.io.IOException) IOException(java.io.IOException) BuiltInTemplate(org.bndtools.core.ui.wizards.shared.BuiltInTemplate) Template(org.bndtools.templating.Template) ResourceMap(org.bndtools.templating.ResourceMap) List(java.util.List) IFolder(org.eclipse.core.resources.IFolder)

Example 2 with Resource

use of org.bndtools.templating.Resource in project bndtools by bndtools.

the class BndRunFileWizard method getTemplateContents.

private InputStream getTemplateContents(String fileName) throws Exception {
    // Load properties
    Map<String, List<Object>> params = new HashMap<>();
    params.put(PROP_FILE_NAME, Collections.<Object>singletonList(fileName));
    params.put(PROP_FILE_BASE_NAME, Collections.<Object>singletonList(baseName(fileName)));
    IPath containerPath = mainPage.getContainerFullPath();
    if (containerPath != null) {
        IResource container = ResourcesPlugin.getWorkspace().getRoot().findMember(containerPath);
        if (container != null) {
            String projectName = container.getProject().getName();
            params.put(PROP_PROJECT_NAME, Collections.<Object>singletonList(projectName));
        }
    }
    Map<String, String> editedParams = paramsPage.getValues();
    for (Entry<String, String> editedParam : editedParams.entrySet()) {
        params.put(editedParam.getKey(), Collections.<Object>singletonList(editedParam.getValue()));
    }
    // Run the template processor
    Template template = templatePage.getTemplate();
    ResourceMap outputs;
    outputs = template.generateOutputs(params);
    Resource output = outputs.get(fileName);
    if (output == null) {
        throw new IllegalArgumentException(String.format("Template error: file '%s' not found in outputs. Available names: %s", fileName, outputs.getPaths()));
    }
    // Pull the generated content
    return output.getContent();
}
Also used : ResourceMap(org.bndtools.templating.ResourceMap) IPath(org.eclipse.core.runtime.IPath) HashMap(java.util.HashMap) StringResource(org.bndtools.templating.StringResource) Resource(org.bndtools.templating.Resource) IResource(org.eclipse.core.resources.IResource) List(java.util.List) IResource(org.eclipse.core.resources.IResource) BuiltInTemplate(org.bndtools.core.ui.wizards.shared.BuiltInTemplate) Template(org.bndtools.templating.Template)

Example 3 with Resource

use of org.bndtools.templating.Resource in project bndtools by bndtools.

the class WorkspacePreviewPage method createControl.

@Override
public void createControl(Composite parent) {
    setTitle("Preview Changes");
    //$NON-NLS-1$
    setImageDescriptor(Plugin.imageDescriptorFromPlugin("icons/bndtools-wizban.png"));
    imgAdded = AbstractUIPlugin.imageDescriptorFromPlugin(Plugin.PLUGIN_ID, "icons/incoming.gif").createImage(parent.getDisplay());
    imgOverwrite = AbstractUIPlugin.imageDescriptorFromPlugin(Plugin.PLUGIN_ID, "icons/conflict.gif").createImage(parent.getDisplay());
    imgError = AbstractUIPlugin.imageDescriptorFromPlugin(Plugin.PLUGIN_ID, "icons/error_obj.gif").createImage(parent.getDisplay());
    int columns = 4;
    Composite composite = new Composite(parent, SWT.NONE);
    GridLayout layout = new GridLayout(columns, false);
    composite.setLayout(layout);
    setControl(composite);
    Label lblTitle = new Label(composite, SWT.NONE);
    lblTitle.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false, columns, 1));
    // Table
    tblOutputs = new Table(composite, SWT.BORDER | SWT.CHECK);
    tblOutputs.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, columns, 1));
    vwrOutputs = new CheckboxTableViewer(tblOutputs);
    vwrOutputs.setContentProvider(ArrayContentProvider.getInstance());
    vwrOutputs.setLabelProvider(new StyledCellLabelProvider() {

        @Override
        public void update(ViewerCell cell) {
            StyledString label;
            Image icon;
            String path = (String) cell.getElement();
            String error = resourceErrors.get(path);
            if (error != null) {
                label = new StyledString(path, ItalicStyler.INSTANCE_ERROR);
                icon = imgError;
            } else {
                label = new StyledString(path);
                icon = existingFiles.contains(path) ? imgOverwrite : imgAdded;
            }
            cell.setText(path);
            cell.setStyleRanges(label.getStyleRanges());
            cell.setImage(icon);
        }
    });
    vwrOutputs.setSorter(new ViewerSorter(Collator.getInstance()));
    // Details display
    final Label lblDetails = new Label(composite, SWT.NONE);
    lblDetails.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false, columns, 1));
    lblDetails.setText(MSG_NOTHING_SELECTED);
    // Button Panel
    Label spacer1 = new Label(composite, SWT.NONE);
    spacer1.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
    Button btnSelectNonConflict = new Button(composite, SWT.PUSH);
    btnSelectNonConflict.setText("Select Non-Conflicting");
    btnSelectNonConflict.addSelectionListener(new SelectionAdapter() {

        @Override
        public void widgetSelected(SelectionEvent e) {
            modifyLock.modifyOperation(new Runnable() {

                @Override
                public void run() {
                    checkedPaths.clear();
                    for (Entry<String, Resource> entry : templateOutputs.entries()) {
                        String path = entry.getKey();
                        if (!existingFiles.contains(path))
                            checkedPaths.add(path);
                    }
                    vwrOutputs.setCheckedElements(checkedPaths.toArray());
                }
            });
        }
    });
    Button btnSelectAll = new Button(composite, SWT.PUSH);
    btnSelectAll.setText("Select All");
    btnSelectAll.addSelectionListener(new SelectionAdapter() {

        @Override
        public void widgetSelected(SelectionEvent e) {
            vwrOutputs.setAllChecked(true);
        }
    });
    Button btnSelectNone = new Button(composite, SWT.PUSH);
    btnSelectNone.setText("Select None");
    btnSelectNone.addSelectionListener(new SelectionAdapter() {

        @Override
        public void widgetSelected(SelectionEvent e) {
            vwrOutputs.setAllChecked(false);
        }
    });
    // Listeners
    vwrOutputs.addSelectionChangedListener(new ISelectionChangedListener() {

        @Override
        public void selectionChanged(SelectionChangedEvent event) {
            IStructuredSelection sel = (IStructuredSelection) vwrOutputs.getSelection();
            if (sel.isEmpty()) {
                lblDetails.setText(MSG_NOTHING_SELECTED);
            } else {
                String path = (String) sel.getFirstElement();
                String resourceError = resourceErrors.get(path);
                if (resourceError != null) {
                    lblDetails.setText(resourceError);
                } else if (existingFiles.contains(path)) {
                    lblDetails.setText("This file already exists and will be overwritten");
                } else {
                    lblDetails.setText("This file will be created");
                }
            }
        }
    });
    vwrOutputs.addCheckStateListener(new ICheckStateListener() {

        @Override
        public void checkStateChanged(final CheckStateChangedEvent event) {
            modifyLock.ifNotModifying(new Runnable() {

                @Override
                public void run() {
                    final String updatedPath = (String) event.getElement();
                    if (event.getChecked()) {
                        checkedPaths.add(updatedPath);
                        // Check any directories that are parents of this path
                        modifyLock.modifyOperation(new Runnable() {

                            @Override
                            public void run() {
                                for (Entry<String, Resource> entry : templateOutputs.entries()) {
                                    String path = entry.getKey();
                                    if (path.endsWith("/") && updatedPath.startsWith(path)) {
                                        checkedPaths.add(path);
                                        vwrOutputs.setChecked(path, true);
                                    }
                                }
                            }
                        });
                    } else {
                        checkedPaths.remove(updatedPath);
                        // Uncheck any paths that are descendants of this path
                        if (updatedPath.endsWith("/")) {
                            modifyLock.modifyOperation(new Runnable() {

                                @Override
                                public void run() {
                                    for (Entry<String, Resource> entry : templateOutputs.entries()) {
                                        String path = entry.getKey();
                                        if (path.startsWith(updatedPath)) {
                                            checkedPaths.remove(path);
                                            vwrOutputs.setChecked(path, false);
                                        }
                                    }
                                }
                            });
                        }
                    }
                }
            });
        }
    });
}
Also used : CheckboxTableViewer(org.eclipse.jface.viewers.CheckboxTableViewer) ICheckStateListener(org.eclipse.jface.viewers.ICheckStateListener) Label(org.eclipse.swt.widgets.Label) ViewerSorter(org.eclipse.jface.viewers.ViewerSorter) SelectionChangedEvent(org.eclipse.jface.viewers.SelectionChangedEvent) StyledString(org.eclipse.jface.viewers.StyledString) IStructuredSelection(org.eclipse.jface.viewers.IStructuredSelection) Image(org.eclipse.swt.graphics.Image) GridLayout(org.eclipse.swt.layout.GridLayout) Entry(java.util.Map.Entry) Button(org.eclipse.swt.widgets.Button) SelectionEvent(org.eclipse.swt.events.SelectionEvent) StyledCellLabelProvider(org.eclipse.jface.viewers.StyledCellLabelProvider) Table(org.eclipse.swt.widgets.Table) Composite(org.eclipse.swt.widgets.Composite) SelectionAdapter(org.eclipse.swt.events.SelectionAdapter) ISelectionChangedListener(org.eclipse.jface.viewers.ISelectionChangedListener) Resource(org.bndtools.templating.Resource) StyledString(org.eclipse.jface.viewers.StyledString) ViewerCell(org.eclipse.jface.viewers.ViewerCell) GridData(org.eclipse.swt.layout.GridData) CheckStateChangedEvent(org.eclipse.jface.viewers.CheckStateChangedEvent)

Example 4 with Resource

use of org.bndtools.templating.Resource in project bndtools by bndtools.

the class WorkspaceSetupWizard method performFinish.

@Override
public boolean performFinish() {
    final IWorkspace workspace = ResourcesPlugin.getWorkspace();
    final File targetDir = previewPage.getTargetDir();
    final Set<String> checkedPaths = previewPage.getCheckedPaths();
    final boolean cleanBuild = setupPage.isCleanBuild();
    try {
        // Expand the template
        ResourceMap outputs = previewPage.getTemplateOutputs();
        final Set<File> topLevelFolders = new HashSet<>();
        for (Entry<String, Resource> entry : outputs.entries()) {
            String path = entry.getKey();
            if (checkedPaths.contains(path)) {
                Resource resource = entry.getValue();
                // Create the folder or file resource
                File file = new File(targetDir, path);
                switch(resource.getType()) {
                    case Folder:
                        Files.createDirectories(file.toPath());
                        break;
                    case File:
                        File parentDir = file.getParentFile();
                        Files.createDirectories(parentDir.toPath());
                        try (InputStream in = resource.getContent()) {
                            IO.copy(in, file);
                        }
                        break;
                    default:
                        throw new IllegalArgumentException("Unknown resource type " + resource.getType());
                }
                // Remember the top-level folders we create, for importing below
                if (file.getParentFile().equals(targetDir))
                    topLevelFolders.add(file);
            }
        }
        // Import anything that looks like an Eclipse project & do a full rebuild
        final IWorkspaceRunnable importProjectsRunnable = new IWorkspaceRunnable() {

            @Override
            public void run(IProgressMonitor monitor) throws CoreException {
                File[] children = targetDir.listFiles();
                if (children != null) {
                    int work = children.length;
                    if (cleanBuild)
                        work += 2;
                    SubMonitor progress = SubMonitor.convert(monitor, work);
                    for (File folder : children) {
                        if (folder.isDirectory() && topLevelFolders.contains(folder)) {
                            String projectName = folder.getName();
                            File projectFile = new File(folder, IProjectDescription.DESCRIPTION_FILE_NAME);
                            if (projectFile.exists()) {
                                IProject project = workspace.getRoot().getProject(projectName);
                                if (!project.exists()) {
                                    // No existing project in the workspace, so import the generated project.
                                    SubMonitor subProgress = progress.newChild(1);
                                    project.create(subProgress.newChild(1));
                                    project.open(subProgress.newChild(1));
                                    // Now make sure it is associated with the right location
                                    IProjectDescription description = project.getDescription();
                                    IPath path = Path.fromOSString(projectFile.getParentFile().getAbsolutePath());
                                    description.setLocation(path);
                                    project.move(description, IResource.REPLACE, progress);
                                } else {
                                    // If a project with the same name exists, does it live in the same location? If not, we can't import the generated project.
                                    File existingLocation = project.getLocation().toFile();
                                    if (!existingLocation.equals(folder)) {
                                        String message = String.format("Cannot import generated project from %s. A project named %s already exists in the workspace and is mapped to location %s", folder.getAbsolutePath(), projectName, existingLocation);
                                        throw new CoreException(new Status(IStatus.ERROR, Plugin.PLUGIN_ID, 0, message, null));
                                    }
                                    SubMonitor subProgress = progress.newChild(1);
                                    // Open it if closed
                                    project.open(subProgress.newChild(1));
                                    // Refresh, as the template may have generated new content
                                    project.refreshLocal(IResource.DEPTH_INFINITE, subProgress.newChild(1));
                                }
                            }
                        }
                    }
                    if (cleanBuild)
                        workspace.build(IncrementalProjectBuilder.CLEAN_BUILD, progress.newChild(2));
                }
            }
        };
        getContainer().run(true, true, new IRunnableWithProgress() {

            @Override
            public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
                try {
                    workspace.run(importProjectsRunnable, monitor);
                } catch (CoreException e) {
                    throw new InvocationTargetException(e);
                }
                new WorkspaceJob("Load Repositories") {

                    @Override
                    public IStatus runInWorkspace(IProgressMonitor monitor) throws CoreException {
                        try {
                            Central.refreshPlugins();
                        } catch (Exception e) {
                        // There may be no workspace yet
                        }
                        return Status.OK_STATUS;
                    }
                }.schedule();
            }
        });
        // Prompt to switch to the bndtools perspective
        IWorkbenchWindow window = workbench.getActiveWorkbenchWindow();
        IPerspectiveDescriptor currentPerspective = window.getActivePage().getPerspective();
        if (!"bndtools.perspective".equals(currentPerspective.getId())) {
            if (MessageDialog.openQuestion(getShell(), "Bndtools Perspective", "Switch to the Bndtools perspective?")) {
                workbench.showPerspective("bndtools.perspective", window);
            }
        }
        return true;
    } catch (InvocationTargetException e) {
        ErrorDialog.openError(getShell(), "Error", null, new Status(IStatus.ERROR, Plugin.PLUGIN_ID, 0, "Error generating template output", e.getTargetException()));
        return false;
    } catch (Exception e) {
        ErrorDialog.openError(getShell(), "Error", null, new Status(IStatus.ERROR, Plugin.PLUGIN_ID, 0, "Error generating template output", e));
        return false;
    }
}
Also used : IRunnableWithProgress(org.eclipse.jface.operation.IRunnableWithProgress) HashSet(java.util.HashSet) IStatus(org.eclipse.core.runtime.IStatus) Status(org.eclipse.core.runtime.Status) IWorkspaceRunnable(org.eclipse.core.resources.IWorkspaceRunnable) IWorkbenchWindow(org.eclipse.ui.IWorkbenchWindow) IPath(org.eclipse.core.runtime.IPath) InputStream(java.io.InputStream) Resource(org.bndtools.templating.Resource) IResource(org.eclipse.core.resources.IResource) SubMonitor(org.eclipse.core.runtime.SubMonitor) WorkspaceJob(org.eclipse.core.resources.WorkspaceJob) IProject(org.eclipse.core.resources.IProject) InvocationTargetException(java.lang.reflect.InvocationTargetException) CoreException(org.eclipse.core.runtime.CoreException) InvocationTargetException(java.lang.reflect.InvocationTargetException) ResourceMap(org.bndtools.templating.ResourceMap) IProgressMonitor(org.eclipse.core.runtime.IProgressMonitor) CoreException(org.eclipse.core.runtime.CoreException) IWorkspace(org.eclipse.core.resources.IWorkspace) IProjectDescription(org.eclipse.core.resources.IProjectDescription) IPerspectiveDescriptor(org.eclipse.ui.IPerspectiveDescriptor) File(java.io.File)

Example 5 with Resource

use of org.bndtools.templating.Resource in project bndtools by bndtools.

the class ReposTemplateLoaderTest method testReferTemplateDefinitions.

public void testReferTemplateDefinitions() throws Exception {
    List<Template> templates = loader.findTemplates("test3", new ProgressMonitorReporter(new NullProgressMonitor(), "")).getValue();
    assertEquals(1, templates.size());
    Template template = templates.get(0);
    Map<String, List<Object>> parameters = new HashMap<>();
    parameters.put("name", Collections.<Object>singletonList("Homer Simpson"));
    ResourceMap outputs = template.generateOutputs(parameters);
    assertEquals(1, outputs.size());
    Iterator<Entry<String, Resource>> iter = outputs.entries().iterator();
    Entry<String, Resource> entry;
    entry = iter.next();
    assertEquals("example.html", entry.getKey());
    assertEquals("My name is <i>Homer Simpson</i>!", IO.collect(entry.getValue().getContent()));
}
Also used : NullProgressMonitor(org.eclipse.core.runtime.NullProgressMonitor) ProgressMonitorReporter(org.bndtools.utils.progress.ProgressMonitorReporter) HashMap(java.util.HashMap) Resource(org.bndtools.templating.Resource) Template(org.bndtools.templating.Template) ResourceMap(org.bndtools.templating.ResourceMap) Entry(java.util.Map.Entry) List(java.util.List)

Aggregations

Resource (org.bndtools.templating.Resource)17 ResourceMap (org.bndtools.templating.ResourceMap)10 StringResource (org.bndtools.templating.StringResource)10 HashMap (java.util.HashMap)8 StringReader (java.io.StringReader)7 Properties (java.util.Properties)7 List (java.util.List)6 Template (org.bndtools.templating.Template)6 InputStreamReader (java.io.InputStreamReader)5 Entry (java.util.Map.Entry)5 ProgressMonitorReporter (org.bndtools.utils.progress.ProgressMonitorReporter)4 NullProgressMonitor (org.eclipse.core.runtime.NullProgressMonitor)4 Reader (java.io.Reader)3 StringWriter (java.io.StringWriter)3 DigestInputStream (java.security.DigestInputStream)3 DefaultMustacheFactory (com.github.mustachejava.DefaultMustacheFactory)2 File (java.io.File)2 InputStream (java.io.InputStream)2 Enumeration (java.util.Enumeration)2 BuiltInTemplate (org.bndtools.core.ui.wizards.shared.BuiltInTemplate)2