Java Code Examples for com.sun.codemodel.JCodeModel#build()

The following examples show how to use com.sun.codemodel.JCodeModel#build() . 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: SpringMvcEndpointGeneratorMojo.java    From springmvc-raml-plugin with Apache License 2.0 5 votes vote down vote up
private void buildCodeModelToDisk(JCodeModel codeModel, String name, File dir) {
	try {
		codeModel.build(dir);
	} catch (IOException e) {
		e.printStackTrace();
		this.getLog().error("Could not build code model for " + name, e);
	}
}
 
Example 3
Source File: SchemaHelperTest.java    From springmvc-raml-plugin with Apache License 2.0 5 votes vote down vote up
protected String serializeModel(JCodeModel jCodeModel) {
	ByteArrayOutputStream bos = new ByteArrayOutputStream();
	try {
		jCodeModel.build(new SingleStreamCodeWriter(bos));
	} catch (IOException e) {
		assertThat(e.getMessage(), is(nullValue()));
	}
	return bos.toString();
}
 
Example 4
Source File: AbstractRuleTestBase.java    From springmvc-raml-plugin with Apache License 2.0 5 votes vote down vote up
protected String serializeModel(JCodeModel jCodeModel) {
	ByteArrayOutputStream bos = new ByteArrayOutputStream();
	try {
		jCodeModel.build(new SingleStreamCodeWriter(bos));
	} catch (IOException e) {
		assertThat(e.getMessage(), is(nullValue()));
	}
	return bos.toString();
}
 
Example 5
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 6
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 7
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 8
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 9
Source File: GenerateWithJaxbApi.java    From java-9-wtf with Apache License 2.0 4 votes vote down vote up
private void writeCode(Outline outline) throws IOException {
	Model model = outline.getModel();
	JCodeModel codeModel = model.codeModel;
	codeModel.build(model.options.createCodeWriter());
}
 
Example 10
Source File: TestCodeUtils.java    From jpa-unit with Apache License 2.0 4 votes vote down vote up
public static void buildModel(final File destinationFolder, final JCodeModel jCodeModel) throws IOException {
    jCodeModel.build(destinationFolder, new PrintStream(new ByteArrayOutputStream()));
}
 
Example 11
Source File: TestCodeUtils.java    From jpa-unit with Apache License 2.0 4 votes vote down vote up
public static void buildModel(final File destinationFolder, final JCodeModel jCodeModel) throws IOException {
    jCodeModel.build(destinationFolder, new PrintStream(new ByteArrayOutputStream()));
}
 
Example 12
Source File: TestCodeUtils.java    From jpa-unit with Apache License 2.0 4 votes vote down vote up
public static void buildModel(final File destinationFolder, final JCodeModel jCodeModel) throws IOException {
    jCodeModel.build(destinationFolder, new PrintStream(new ByteArrayOutputStream()));
}
 
Example 13
Source File: OpenApi2JaxRs.java    From apicurio-studio with Apache License 2.0 4 votes vote down vote up
/**
 * Generates a Java Bean class for the given bean info.  The bean info should
 * have a name, package, and JSON Schema.  This information will be used to 
 * generate a POJO.
 * @param bean
 * @param info 
 * @param codeWriter
 * @throws IOException
 */
private void generateJavaBean(CodegenJavaBean bean, CodegenInfo info, IndexedCodeWriter codeWriter) throws IOException {
    JCodeModel codeModel = new JCodeModel();
    GenerationConfig config = new DefaultGenerationConfig() {
        @Override
        public boolean isUsePrimitives() {
            return false;
        }
        @Override
        public boolean isIncludeHashcodeAndEquals() {
            return false;
        }
        @Override
        public boolean isIncludeAdditionalProperties() {
            return false;
        }
        @Override
        public boolean isIncludeToString() {
            return false;
        }
    };

    SchemaMapper schemaMapper = new SchemaMapper(
            new JaxRsRuleFactory(config, new Jackson2Annotator(config), new SchemaStore() {
                @Override
                public Schema create(Schema parent, String path, String refFragmentPathDelimiters) {
                    String beanClassname = schemaRefToFQCN(path);
                    for (CodegenJavaBean cgBean : info.getBeans()) {
                        String cgBeanFQCN = cgBean.getPackage() + "." + StringUtils.capitalize(cgBean.getName());
                        if (beanClassname.equals(cgBeanFQCN)) {
                            Schema schema = new Schema(classnameToUri(beanClassname), cgBean.get$schema(), null);
                            JType jclass = codeModel._getClass(beanClassname);
                            if (jclass == null) {
                                jclass = codeModel.directClass(beanClassname);
                            }
                            schema.setJavaType(jclass);
                            return schema;
                        }
                    }
                    System.out.println("!!!!! :: " + beanClassname);
                    // TODO if we get here, we probably want to return an empty schema
                    return super.create(parent, path, refFragmentPathDelimiters);
                }
            }),
            new SchemaGenerator());
    String source = mapper.writeValueAsString(bean.get$schema());
    schemaMapper.generate(codeModel, bean.getName(), bean.getPackage(), source);
    codeModel.build(codeWriter);
}
 
Example 14
Source File: PojoGenerator.java    From Poseidon with Apache License 2.0 4 votes vote down vote up
public void generate(String pojoJson, JCodeModel jCodeModel, String destinationFolder, String className, String packageName) throws IOException {
    mapper.generate(jCodeModel, className, packageName, pojoJson);
    jCodeModel.build(new File(destinationFolder), (PrintStream) null);
}
 
Example 15
Source File: JAXBDataBinding.java    From cxf with Apache License 2.0 4 votes vote down vote up
public void generate(ToolContext c) throws ToolException {
    if (!initialized) {
        initialize(c);
    }
    if (rawJaxbModelGenCode == null) {
        return;
    }
    if (c.getErrorListener().getErrorCount() > 0) {
        return;
    }


    try {
        String dir = (String)context.get(ToolConstants.CFG_OUTPUTDIR);

        TypesCodeWriter fileCodeWriter = new TypesCodeWriter(new File(dir),
                                                             context.getExcludePkgList(),
                                                             (String)context.get(ToolConstants.CFG_ENCODING),
                                                             context.get(OutputStreamCreator.class));

        S2JJAXBModel schem2JavaJaxbModel = rawJaxbModelGenCode;

        ClassCollector classCollector = context.get(ClassCollector.class);
        for (JClass cls : schem2JavaJaxbModel.getAllObjectFactories()) {
            classCollector.getTypesPackages().add(cls._package().name());
        }

        JCodeModel jcodeModel = schem2JavaJaxbModel.generateCode(null, null);

        if (!isSuppressCodeGen()) {
            jcodeModel.build(fileCodeWriter);
        }

        context.put(JCodeModel.class, jcodeModel);

        for (String str : fileCodeWriter.getExcludeFileList()) {
            context.getExcludeFileList().add(str);
        }

        return;
    } catch (IOException e) {
        Message msg = new Message("FAIL_TO_GENERATE_TYPES", LOG);
        throw new ToolException(msg, e);
    }
}