use of com.sun.codemodel.JCodeModel in project raml-for-jax-rs by mulesoft-labs.
the class JAXBHelper method generateClassesFromXmlSchemas.
private static List<JDefinedClass> generateClassesFromXmlSchemas(String pack, JCodeModel codeModel, File schemaFile) throws GenerationException {
try {
ArrayList<JDefinedClass> classList = new ArrayList<JDefinedClass>();
ArrayList<String> argList = new ArrayList<>();
argList.add("-mark-generated");
argList.add("-p");
argList.add(pack);
argList.add(schemaFile.getAbsolutePath());
String[] args = argList.toArray(new String[argList.size()]);
final Options opt = new Options();
opt.setSchemaLanguage(Language.XMLSCHEMA);
opt.parseArguments(args);
ErrorReceiver receiver = new ErrorReceiverFilter() {
@Override
public void info(SAXParseException exception) {
if (opt.verbose)
super.info(exception);
}
@Override
public void warning(SAXParseException exception) {
if (!opt.quiet)
super.warning(exception);
}
};
Model model = ModelLoader.load(opt, codeModel, receiver);
Outline outline = model.generateCode(opt, receiver);
for (ClassOutline co : outline.getClasses()) {
JDefinedClass cl = co.implClass;
if (cl.outer() == null) {
classList.add(cl);
}
}
return classList;
} catch (Exception e) {
throw new GenerationException(e);
}
}
use of com.sun.codemodel.JCodeModel in project raml-for-jax-rs by mulesoft-labs.
the class SchemaTypeFactory method createXmlType.
public static TypeGenerator createXmlType(CurrentBuild currentBuild, GType type) {
File schemaFile = null;
try {
schemaFile = JAXBHelper.saveSchema(type.schema(), currentBuild.getSchemaRepository());
final JCodeModel codeModel = new JCodeModel();
Map<String, JClass> generated = JAXBHelper.generateClassesFromXmlSchemas(currentBuild.getModelPackage(), schemaFile, codeModel);
XmlSchemaTypeGenerator gen = new XmlSchemaTypeGenerator(type, codeModel, currentBuild.getModelPackage(), generated.values().iterator().next());
type.setJavaType(gen.getGeneratedJavaType());
currentBuild.newGenerator(type.name(), gen);
return gen;
} catch (Exception e) {
throw new GenerationException(e);
}
}
use of com.sun.codemodel.JCodeModel in project raml-for-jax-rs by mulesoft-labs.
the class JsonSchemaTypeGenerator method output.
@Override
public void output(CodeContainer<JCodeModel> container, BuildPhase buildPhase) throws IOException {
GenerationConfig config = build.getJsonMapperConfig();
final SchemaMapper mapper = new SchemaMapper(new RuleFactory(config, new Jackson2Annotator(), new SchemaStore()), new SchemaGenerator());
final JCodeModel codeModel = new JCodeModel();
File schemaFile = File.createTempFile("schema", "json", build.getSchemaRepository());
Files.write(schema, schemaFile, Charset.defaultCharset());
try {
mapper.generate(codeModel, name.simpleName(), pack, schemaFile.toURL());
} catch (IOException e) {
throw new GenerationException(e);
}
container.into(codeModel);
}
use of com.sun.codemodel.JCodeModel in project rest.li by linkedin.
the class RestRequestBuilderGenerator method run.
/**
* @param generateLowercasePath true, files are generated with a lower case path; false, files are generated as spec specifies.
*/
public static GeneratorResult run(String resolverPath, String defaultPackage, String rootPath, final boolean generateImported, final boolean generateDataTemplates, RestliVersion version, RestliVersion deprecatedByVersion, String targetDirectoryPath, String[] sources, boolean generateLowercasePath) throws IOException {
final RestSpecParser parser = new RestSpecParser();
final JavaRequestBuilderGenerator generator = new JavaRequestBuilderGenerator(resolverPath, defaultPackage, generateDataTemplates, version, deprecatedByVersion, rootPath);
final ClassLoader classLoader = JavaCodeUtil.classLoaderFromResolverPath(resolverPath);
final RestSpecParser.ParseResult parseResult = parser.parseSources(sources);
final StringBuilder message = new StringBuilder();
for (CodeUtil.Pair<ResourceSchema, File> pair : parseResult.getSchemaAndFiles()) {
ResourceSchema resourceSchema = pair.first;
// Skip unstructured data resources for client generation
if (resourceSchema == null || ResourceEntityType.UNSTRUCTURED_DATA == resourceSchema.getEntityType()) {
continue;
}
try {
final JDefinedClass clazz = generator.generate(resourceSchema, pair.second, rootPath);
} catch (Exception e) {
_log.error("Failed to generate request builders for schema: " + resourceSchema.getName(), e);
message.append(e.getMessage()).append("\n");
}
}
if (message.length() > 0) {
throw new IOException(message.toString());
}
final DataTemplatePersistentClassChecker dataTemplateChecker = new DataTemplatePersistentClassChecker(generateImported, generator.getSpecGenerator(), generator.getJavaDataTemplateGenerator(), Collections.<File>emptySet());
final JavaCodeUtil.PersistentClassChecker checker = new JavaCodeUtil.PersistentClassChecker() {
@Override
public boolean isPersistent(JDefinedClass clazz) {
if (generateDataTemplates || generator.isGeneratedArrayClass(clazz)) {
try {
Class.forName(clazz.fullName(), false, classLoader);
} catch (ClassNotFoundException e) {
return true;
}
}
return dataTemplateChecker.isPersistent(clazz);
}
};
final JCodeModel requestBuilderCodeModel = generator.getCodeModel();
final JCodeModel dataTemplateCodeModel = generator.getJavaDataTemplateGenerator().getCodeModel();
final File targetDirectory = new File(targetDirectoryPath);
final List<File> targetFiles = JavaCodeUtil.targetFiles(targetDirectory, requestBuilderCodeModel, classLoader, checker, generateLowercasePath);
targetFiles.addAll(JavaCodeUtil.targetFiles(targetDirectory, dataTemplateCodeModel, classLoader, checker, generateLowercasePath));
final List<File> modifiedFiles;
if (FileUtil.upToDate(parseResult.getSourceFiles(), targetFiles)) {
modifiedFiles = Collections.emptyList();
_log.info("Target files are up-to-date: " + targetFiles);
} else {
modifiedFiles = targetFiles;
_log.info("Generating " + targetFiles.size() + " files");
_log.debug("Files: " + targetFiles);
requestBuilderCodeModel.build(new CaseSensitiveFileCodeWriter(targetDirectory, true, generateLowercasePath));
dataTemplateCodeModel.build(new CaseSensitiveFileCodeWriter(targetDirectory, true, generateLowercasePath));
}
return new DefaultGeneratorResult(parseResult.getSourceFiles(), targetFiles, modifiedFiles);
}
use of com.sun.codemodel.JCodeModel in project scout.rt by eclipse.
the class JaxWsAnnotationProcessor method generateEntryPoint.
/**
* Generates the entry point and associated artifacts for the given definition.
*/
protected void generateEntryPoint(final EntryPointDefinition entryPointDefinition, final RoundEnvironment roundEnv) throws JClassAlreadyExistsException, ClassNotFoundException, IOException {
final JCodeModel model = new JCodeModel();
// Create EntryPoint class.
final TypeElement _endpointInterface = entryPointDefinition.getEndpointInterface();
final JClass endpointInterface = model.ref(_endpointInterface.getQualifiedName().toString());
final JDefinedClass entryPoint = model._class(entryPointDefinition.getEntryPointQualifiedName())._implements(endpointInterface);
// Add annotations to the EntryPoint.
addAnnotations(model, entryPoint, entryPointDefinition, roundEnv);
// Create handler chain.
final HandlerChain _handlerChainAnnotation = _endpointInterface.getAnnotation(HandlerChain.class);
if (_handlerChainAnnotation != null) {
m_logger.info("Handler file not generated because provided as binding file [file={}, entryPoint={}, endpointInterface={}]", _handlerChainAnnotation.file(), entryPointDefinition.getEntryPointQualifiedName(), entryPointDefinition.getEndpointInterfaceQualifiedName());
} else if (!entryPointDefinition.getHandlerChain().isEmpty() || entryPointDefinition.isAuthenticationEnabled()) {
entryPoint.annotate(HandlerChain.class).param("file", new HandlerArtifactProcessor().generateHandlerArtifacts(entryPoint, entryPointDefinition, processingEnv, m_logger));
}
// Add JavaDoc to the EntryPoint.
AptUtil.addJavaDoc(entryPoint, createJavaDocForEntryPoint(entryPointDefinition));
// Inject WebServiceContext
final JFieldVar webServiceContext = entryPoint.field(JMod.PROTECTED, WebServiceContext.class, WEBSERVICE_CONTEXT_FIELD_NAME);
webServiceContext.annotate(Resource.class);
// Overwrite all methods declared on the PortType interface.
for (final Element _element : _endpointInterface.getEnclosedElements()) {
if (!(ElementKind.METHOD.equals(_element.getKind()))) {
continue;
}
final ExecutableElement _method = (ExecutableElement) _element;
final String methodName = _method.getSimpleName().toString();
final JType returnType = JTypeParser.parseType(model, _method.getReturnType());
// Create the method.
final JMethod method = entryPoint.method(JMod.PUBLIC, returnType, methodName);
method.annotate(Override.class);
// Add the method parameters.
for (final VariableElement _param : _method.getParameters()) {
method.param(JMod.FINAL, JTypeParser.parseType(model, _param.asType()), _param.getSimpleName().toString());
}
// Add exception throw clauses.
final List<JClass> throwTypes = new ArrayList<>();
for (final TypeMirror _throwType : _method.getThrownTypes()) {
final JClass throwType = model.ref(_throwType.toString());
throwTypes.add(throwType);
method._throws(throwType);
}
// Create the method implementation.
addEntryPointMethodImplementation(model, webServiceContext, method, throwTypes, TypeKind.VOID.equals(_method.getReturnType().getKind()), _endpointInterface.getQualifiedName().toString());
}
// Create the method to handle undeclared errors.
addHandleUndeclaredFaultMethod(model, entryPoint);
// Create the method to lookup the RunContext.
addLookupRunContextMethod(model, entryPoint, webServiceContext);
// Build and persist this compilation unit.
AptUtil.buildAndPersist(model, processingEnv.getFiler());
m_logger.info("Entry point successfully generated. [entryPoint={}, endpointInterface={}, entryPointDefinition={}]", entryPoint.fullName(), endpointInterface.fullName(), entryPointDefinition.getQualifiedName());
}
Aggregations