com.sun.codemodel.CodeWriter Java Examples

The following examples show how to use com.sun.codemodel.CodeWriter. 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 File: JsonSchemaController.java    From sc-generator with Apache License 2.0 6 votes vote down vote up
@RequestMapping(value = "/generator/preview", method = RequestMethod.POST)
public String preview(@RequestParam(value = "schema") String schema,
                      @RequestParam(value = "targetpackage") String targetpackage,
                      @RequestParam(value = "sourcetype", required = false) final String sourcetype,
                      @RequestParam(value = "annotationstyle", required = false) final String annotationstyle,
                      @RequestParam(value = "usedoublenumbers", required = false) final boolean usedoublenumbers,
                      @RequestParam(value = "includeaccessors", required = false) final boolean includeaccessors,
                      @RequestParam(value = "includeadditionalproperties", required = false) final boolean includeadditionalproperties,
                      @RequestParam(value = "propertyworddelimiters", required = false) final String propertyworddelimiters,
                      @RequestParam(value = "classname") String classname) throws IOException {

    final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    JCodeModel codegenModel = getCodegenModel(schema, targetpackage, sourcetype, annotationstyle, usedoublenumbers, includeaccessors, includeadditionalproperties, propertyworddelimiters, classname);
    codegenModel.build(new CodeWriter() {
        @Override
        public OutputStream openBinary(JPackage pkg, String fileName) throws IOException {
            return byteArrayOutputStream;
        }

        @Override
        public void close() throws IOException {
            byteArrayOutputStream.close();
        }
    });
    return byteArrayOutputStream.toString("utf-8");
}
 
Example #2
Source File: JAXBDataBinding.java    From cxf with Apache License 2.0 6 votes vote down vote up
private void checkEncoding(ToolContext c) {
    String encoding = (String)c.get(ToolConstants.CFG_ENCODING);
    if (encoding != null) {
        try {
            CodeWriter.class.getDeclaredField("encoding");
        } catch (Throwable t) {
            c.remove(ToolConstants.CFG_ENCODING);
            String fenc = System.getProperty("file.encoding");
            if (!encoding.equals(fenc)) {
                LOG.log(Level.WARNING, "JAXB_NO_ENCODING_SUPPORT",
                        new String[] {Driver.getBuildID(), fenc});
            }
        }
    }

}
 
Example #3
Source File: DynamicCompiler.java    From hyperjaxb3 with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public void execute() throws IOException, BadCommandLineException {

		final Options options = createOptions();
		final JCodeModel codeModel = createCodeModel();
		final CodeWriter codeWriter = createCodeWriter();
		final ErrorReceiver errorReceiver = createErrorReceiver();
		execute(options, codeModel, codeWriter, errorReceiver);

	}
 
Example #4
Source File: XJC21Mojo.java    From maven-jaxb2-plugin with BSD 2-Clause "Simplified" License 5 votes vote down vote up
protected void writeCode(Outline outline) throws MojoExecutionException {

		if (getWriteCode()) {
			final Model model = outline.getModel();
			final JCodeModel codeModel = model.codeModel;
			final File targetDirectory = model.options.targetDir;
			if (getVerbose()) {
				getLog().info(
						MessageFormat.format("Writing output to [{0}].",
								targetDirectory.getAbsolutePath()));
			}
			try {
				if (getCleanPackageDirectories()) {
					if (getVerbose()) {
						getLog().info("Cleaning package directories.");
					}
					cleanPackageDirectories(targetDirectory, codeModel);
				}
				final CodeWriter codeWriter = new LoggingCodeWriter(
						model.options.createCodeWriter(), getLog(),
						getVerbose());
				codeModel.build(codeWriter);
			} catch (IOException e) {
				throw new MojoExecutionException("Unable to write files: "
						+ e.getMessage(), e);
			}
		} else {
			getLog().info(
					"The [writeCode] setting is set to false, the code will not be written.");
		}
	}
 
Example #5
Source File: XJC23Mojo.java    From maven-jaxb2-plugin with BSD 2-Clause "Simplified" License 5 votes vote down vote up
protected void writeCode(Outline outline) throws MojoExecutionException {

		if (getWriteCode()) {
			final Model model = outline.getModel();
			final JCodeModel codeModel = model.codeModel;
			final File targetDirectory = model.options.targetDir;
			if (getVerbose()) {
				getLog().info(
						MessageFormat.format("Writing output to [{0}].",
								targetDirectory.getAbsolutePath()));
			}
			try {
				if (getCleanPackageDirectories()) {
					if (getVerbose()) {
						getLog().info("Cleaning package directories.");
					}
					cleanPackageDirectories(targetDirectory, codeModel);
				}
				final CodeWriter codeWriter = new LoggingCodeWriter(
						model.options.createCodeWriter(), getLog(),
						getVerbose());
				codeModel.build(codeWriter);
			} catch (IOException e) {
				throw new MojoExecutionException("Unable to write files: "
						+ e.getMessage(), e);
			}
		} else {
			getLog().info(
					"The [writeCode] setting is set to false, the code will not be written.");
		}
	}
 
Example #6
Source File: XJC22Mojo.java    From maven-jaxb2-plugin with BSD 2-Clause "Simplified" License 5 votes vote down vote up
protected void writeCode(Outline outline) throws MojoExecutionException {

		if (getWriteCode()) {
			final Model model = outline.getModel();
			final JCodeModel codeModel = model.codeModel;
			final File targetDirectory = model.options.targetDir;
			if (getVerbose()) {
				getLog().info(
						MessageFormat.format("Writing output to [{0}].",
								targetDirectory.getAbsolutePath()));
			}
			try {
				if (getCleanPackageDirectories()) {
					if (getVerbose()) {
						getLog().info("Cleaning package directories.");
					}
					cleanPackageDirectories(targetDirectory, codeModel);
				}
				final CodeWriter codeWriter = new LoggingCodeWriter(
						model.options.createCodeWriter(), getLog(),
						getVerbose());
				codeModel.build(codeWriter);
			} catch (IOException e) {
				throw new MojoExecutionException("Unable to write files: "
						+ e.getMessage(), e);
			}
		} else {
			getLog().info(
					"The [writeCode] setting is set to false, the code will not be written.");
		}
	}
 
Example #7
Source File: XJC20Mojo.java    From maven-jaxb2-plugin with BSD 2-Clause "Simplified" License 5 votes vote down vote up
protected void writeCode(Outline outline) throws MojoExecutionException {

		if (getWriteCode()) {
			final Model model = outline.getModel();
			final JCodeModel codeModel = model.codeModel;
			final File targetDirectory = model.options.targetDir;
			if (getVerbose()) {
				getLog().info(
						MessageFormat.format("Writing output to [{0}].",
								targetDirectory.getAbsolutePath()));
			}
			try {
				if (getCleanPackageDirectories()) {
					if (getVerbose()) {
						getLog().info("Cleaning package directories.");
					}
					cleanPackageDirectories(targetDirectory, codeModel);
				}
				final CodeWriter codeWriter = new LoggingCodeWriter(
						model.options.createCodeWriter(), getLog(),
						getVerbose());
				codeModel.build(codeWriter);
			} catch (IOException e) {
				throw new MojoExecutionException("Unable to write files: "
						+ e.getMessage(), e);
			}
		} else {
			getLog().info(
					"The [writeCode] setting is set to false, the code will not be written.");
		}
	}
 
Example #8
Source File: TypesCodeWriter.java    From cxf with Apache License 2.0 5 votes vote down vote up
private void setEncoding(String s) {
    if (s != null) {
        try {
            //requires XJC 2.2.5 or newer
            Field f = CodeWriter.class.getDeclaredField("encoding");
            ReflectionUtil.setAccessible(f).set(this, s);
        } catch (Throwable t) {
            //ignore - should be caught in JAXBDataBinding.checkEncoding already
        }
    }
}
 
Example #9
Source File: DynamicCompiler.java    From hyperjaxb3 with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public CodeWriter createCodeWriter() throws IOException {
	return new FileCodeWriter(targetDirectory, false);
}
 
Example #10
Source File: DynamicCompiler.java    From hyperjaxb3 with BSD 2-Clause "Simplified" License 4 votes vote down vote up
protected void execute(final Options options, final JCodeModel codeModel,
		final CodeWriter codeWriter, final ErrorReceiver errorReceiver)
		throws IOException {
	logger.debug("Loading the model.");
	final Model model = ModelLoader.load(options, codeModel, errorReceiver);
	logger.debug("Generating the code.");
	final Outline outline = model.generateCode(options, errorReceiver);
	logger.debug("Writing the code.");
	model.codeModel.build(codeWriter);
	this.outline = outline;
	final StringBuffer contextPathStringBuffer = new StringBuffer();
	String delimiter = "";
	for (final PackageOutline packageOutline : this.outline
			.getAllPackageContexts()) {
		contextPathStringBuffer.append(delimiter);
		contextPathStringBuffer.append(packageOutline._package().name());
		delimiter = ":";
	}
	this.contextPath = contextPathStringBuffer.toString();
	logger.debug("Compiling the code.");
	final JavaCompiler systemJavaCompiler = ToolProvider
			.getSystemJavaCompiler();
	final DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
	final StandardJavaFileManager standardFileManager = systemJavaCompiler
			.getStandardFileManager(diagnostics, null, null);

	final Collection<File> javaFiles = FileUtils.listFiles(targetDirectory,
			FileFilterUtils.suffixFileFilter(".java"),
			TrueFileFilter.INSTANCE);

	final Iterable<? extends JavaFileObject> fileObjects = standardFileManager
			.getJavaFileObjectsFromFiles(javaFiles);

	ClassLoader contextClassLoader = Thread.currentThread()
			.getContextClassLoader();

	final List<String> compilerOptions = new LinkedList<String>();

	if (contextClassLoader instanceof URLClassLoader) {
		final URLClassLoader urlClassLoader = (URLClassLoader) contextClassLoader;
		final URL[] urls = urlClassLoader.getURLs();
		if (urls.length > 0) {
			compilerOptions.add("-classpath");

			final StringBuffer classpathStringBuffer = new StringBuffer();
			String separator = "";
			for (final URL url : urls) {
				logger.debug("URL:" + url);
				classpathStringBuffer.append(separator);
				try {
					classpathStringBuffer.
					// append("\"").
							append(new File(url.toURI()).getAbsolutePath())
					// .append("\"")
					;
					separator = SystemUtils.PATH_SEPARATOR;
				} catch (URISyntaxException ignored) {
				}
			}
			compilerOptions.add(classpathStringBuffer.toString());
		}
	}
	compilerOptions.add("-verbose");
	compilerOptions.add("-d");
	compilerOptions.add(targetDirectory.getAbsolutePath());

	logger.debug("Compiler options:"
			+ StringUtils.join(compilerOptions.iterator(), " "));
	// // conte
	//
	// final String[] compilerOptions = new String[] { "-d",
	// targetDirectory.getAbsolutePath(), "-verbose" };

	systemJavaCompiler.getTask(null, standardFileManager, null,
			compilerOptions, null, fileObjects).call();
	standardFileManager.close();
}
 
Example #11
Source File: LoggingCodeWriter.java    From maven-jaxb2-plugin with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public LoggingCodeWriter(CodeWriter output, Log log, boolean verbose) {
	super(output);
	this.log = log;
	this.verbose = verbose;
}
 
Example #12
Source File: LoggingCodeWriter.java    From maven-jaxb2-plugin with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public LoggingCodeWriter(CodeWriter output, Log log, boolean verbose) {
	super(output);
	this.log = log;
	this.verbose = verbose;
}
 
Example #13
Source File: LoggingCodeWriter.java    From maven-jaxb2-plugin with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public LoggingCodeWriter(CodeWriter output, Log log, boolean verbose) {
	super(output);
	this.log = log;
	this.verbose = verbose;
}
 
Example #14
Source File: LoggingCodeWriter.java    From maven-jaxb2-plugin with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public LoggingCodeWriter(CodeWriter output, Log log, boolean verbose) {
	super(output);
	this.log = log;
	this.verbose = verbose;
}
 
Example #15
Source File: Translator.java    From groovy-cps with Apache License 2.0 4 votes vote down vote up
/**
 * Generate transalted result into source files.
 */
public void generateTo(CodeWriter cw) throws IOException {
    codeModel.build(cw);
}
 
Example #16
Source File: PrologCodeWriter.java    From aem-component-generator with Apache License 2.0 2 votes vote down vote up
/**
 * @param core
 *      This CodeWriter will be used to actually create a storage for files.
 *      PrologCodeWriter simply decorates this underlying CodeWriter by
 *      adding prolog comments.
 * @param prolog
 *      Strings that will be added as comments
 *      and will be inserted at the beginning of each line to make it
 *      a valid Java comment.
 */
public PrologCodeWriter(CodeWriter core, String prolog ) {
    super(core);
    this.prolog = prolog;
}