xapi.dev.template.TemplateToJava Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of xapi-gwt Show documentation
Show all versions of xapi-gwt Show documentation
This module exists solely to package all other gwt modules into a single
uber jar. This makes deploying to non-mavenized targets much easier.
Of course, you would be wise to inherit your dependencies individually;
the uber jar is intended for projects like collide,
which have complex configuration, and adding many jars would be a pain.
The newest version!
/*
* Copyright 2013, We The Internet Ltd.
*
* All rights reserved.
*
* Distributed under a modified BSD License as follow:
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* Redistribution in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution, unless otherwise
* agreed to in a written document signed by a director of We The Internet Ltd.
*
* Neither the name of We The Internet nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
package xapi.dev.template;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;
import xapi.collect.impl.SimpleFifo;
import xapi.dev.source.ImportSection;
import xapi.dev.source.SourceBuilder;
import xapi.log.api.LogLevel;
import xapi.log.api.LogService;
import xapi.log.impl.JreLog;
public class TemplateToJava {
private static final String templateSuffix = System.getProperty("template.suffix", ".x");
private static final Pattern lineMatcher = Pattern.compile("\\s*//.*//\\s*");
private static final Charset utf8 = Charset.forName("UTF-8");
public static void main(String[] templates) {
TemplateToJava generator = new TemplateToJava();
LogService logger = new JreLog();
TemplateGeneratorOptions options = new TemplateGeneratorOptions();
if (options.processArgs(templates)) {
logger.setLogLevel(options.getLogLevel());
for (String template : options.getTemplates()) {
generator.generate(logger, template, options);
}
} else {
throw new RuntimeException("Invalid arguments specified;" + " see console logs for help.");
}
}
private Class> generatorClass;
private final Map,Object> generators = new HashMap,Object>();
public void generate(LogService logger, String template, TemplateGeneratorOptions options) {
SourceBuilder> context = options.getContext(logger, template);
InputStream input = null;
try {
if (new File(template).exists()) {
input = new FileInputStream(template);
} else {
URL url = getClass().getClassLoader().getResource(template);
if (url == null) {
url = ClassLoader.getSystemResource(template);
if (url == null) {
logger.log(LogLevel.ERROR, "You requested code generation for template " + template +
", but the file could not be found.");
throw new CompilationFailed();
}
}
input = url.openStream();
}
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
String line;
while ((line = reader.readLine()) != null) {
if (lineMatcher.matcher(line).matches()) {
// we have a template command to parse!
applyTemplate(logger, reader, context, options, line.trim());
} else {
context.getBuffer().append(line).append('\n');
}
}
exportClass(logger, template, context, options);
} catch (Exception e) {
throw new CompilationFailed("Unable to generate java source file for template " + template, e);
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {}
}
}
}
private static final int BUF_SIZE = 16 * 1024;
private void exportClass(LogService logger, String filename, SourceBuilder> context,
TemplateGeneratorOptions opts) {
File outputFile = new File(opts.getOutputLocation());
// normalize filename
if (filename.endsWith(templateSuffix))
filename = filename.substring(0, filename.length() - templateSuffix.length());
if (!filename.endsWith(".java")) filename = filename + ".java";
// repackage if requested; useful for generating non-transient super-source
String packageName = context.getPackage();
if (packageName != null) {
filename = packageName.replace('.', File.separatorChar) + File.separator +
filename.substring(filename.lastIndexOf('/'));
}
// save the source to file
outputFile = new File(outputFile.getAbsoluteFile(), filename);
outputFile.getParentFile().mkdirs();
try {
logger.log(LogLevel.INFO, "Writing generated output to " + outputFile.getAbsolutePath());
InputStream in = new ByteArrayInputStream(context.toString().getBytes(utf8));
OutputStream out = new FileOutputStream(outputFile);
byte[] buf = new byte[BUF_SIZE];
try {
int i;
while ((i = in.read(buf)) != -1) {
out.write(buf, 0, i);
}
} finally {
in.close();
out.close();
}
} catch (IOException e) {
logger.doLog(LogLevel.ERROR, new SimpleFifo