Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: f35d9c56bcb080fd511a2ec29d592bb1c19cc664 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
/*******************************************************************************
 * Copyright (c) 2015 QNX Software Systems and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *******************************************************************************/
package org.eclipse.cdt.internal.qt.core;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.charset.StandardCharsets;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.FileLocator;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Status;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

public class QtTemplateGenerator {

	private final Configuration config;

	public QtTemplateGenerator() throws CoreException {
		config = new Configuration(Configuration.VERSION_2_3_22);
		URL templateDirURL = FileLocator.find(Activator.getDefault().getBundle(), new Path("/templates"), null); //$NON-NLS-1$
		try {
			config.setDirectoryForTemplateLoading(new File(FileLocator.toFileURL(templateDirURL).toURI()));
		} catch (IOException | URISyntaxException e) {
			throw new CoreException(new Status(IStatus.ERROR, Activator.ID, "Template configuration", e));
		}
	}

	public void generateFile(final Object model, String templateFile, final IFile outputFile, IProgressMonitor monitor)
			throws CoreException {
		try {
			final Template template = config.getTemplate(templateFile);
			try (StringWriter writer = new StringWriter()) {
				template.process(model, writer);
				try (ByteArrayInputStream in = new ByteArrayInputStream(
						writer.getBuffer().toString().getBytes(StandardCharsets.UTF_8))) {
					if (outputFile.exists()) {
						outputFile.setContents(in, true, true, monitor);
					} else {
						outputFile.create(in, true, monitor);
					}
				}
			}
		} catch (IOException | TemplateException e) {
			throw new CoreException(new Status(IStatus.ERROR, Activator.ID, "Processing template " + templateFile, e));
		}
	}

}

Back to the top