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());
}
use of com.sun.codemodel.JCodeModel in project scout.rt by eclipse.
the class HandlerArtifactProcessor method createAndPersistHandlerDelegate.
/**
* Generates the entry point for a handler.
*/
public String createAndPersistHandlerDelegate(final JClass portTypeEntryPoint, final EntryPointDefinition entryPointDefinition, final HandlerDefinition handler, final int idx, final ProcessingEnvironment env) throws IOException, JClassAlreadyExistsException {
final JCodeModel model = new JCodeModel();
final String fullName = entryPointDefinition.getEntryPointQualifiedName() + "_" + handler.getHandlerSimpleName() + HANDLER_SUFFIX;
final JDefinedClass handlerDelegate = model._class(fullName);
// Add 'Generated' annotation
final JAnnotationUse generatedAnnotation = handlerDelegate.annotate(Generated.class);
generatedAnnotation.param("value", JaxWsAnnotationProcessor.class.getName());
generatedAnnotation.param("date", new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss:SSSZ").format(new Date()));
generatedAnnotation.param("comments", "Handler delegate for " + handler.getHandlerQualifiedName());
AptUtil.addJavaDoc(handlerDelegate, format("This class is auto-generated by APT triggered by Maven build and is based on the handler configuration declared in {@link %s}.", entryPointDefinition.getSimpleName()));
switch(handler.getHandlerType()) {
case SOAP:
handlerDelegate._extends(model.ref(SOAPHandlerDelegate.class));
break;
case LOGICAL:
handlerDelegate._extends(model.ref(HandlerDelegate.class).narrow(LogicalMessageContext.class));
handlerDelegate._implements(model.ref(LogicalHandler.class).narrow(LogicalMessageContext.class));
break;
default:
handlerDelegate._extends(model.ref(HandlerDelegate.class).narrow(MessageContext.class));
break;
}
// Add default constructor with super call to provide handler annotation.
final JClass entryPointDefinitionClass = model.ref(entryPointDefinition.getQualifiedName());
final JMethod defaultConstructor = handlerDelegate.constructor(JMod.PUBLIC);
defaultConstructor.body().invoke("super").arg(JExpr.dotclass(entryPointDefinitionClass).invoke("getAnnotation").arg(JExpr.dotclass(model.ref(WebServiceEntryPoint.class))).invoke("handlerChain").component(JExpr.lit(idx)));
AptUtil.buildAndPersist(model, env.getFiler());
return handlerDelegate.fullName();
}
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 drill by apache.
the class HiveFuncHolder method generateEval.
private HoldingContainer generateEval(ClassGenerator<?> g, HoldingContainer[] inputVariables, JVar[] workspaceJVars) {
HoldingContainer out = g.declare(returnType);
JCodeModel m = g.getModel();
JBlock sub = new JBlock(true, true);
// initialize DeferredObject's. For an optional type, assign the value holder only if it is not null
for (int i = 0; i < argTypes.length; i++) {
if (inputVariables[i].isOptional()) {
sub.assign(workspaceJVars[3].component(JExpr.lit(i)), workspaceJVars[2].component(JExpr.lit(i)));
JBlock conditionalBlock = new JBlock(false, false);
JConditional jc = conditionalBlock._if(inputVariables[i].getIsSet().ne(JExpr.lit(0)));
jc._then().assign(JExpr.ref(workspaceJVars[3].component(JExpr.lit(i)), "valueHolder"), inputVariables[i].getHolder());
jc._else().assign(JExpr.ref(workspaceJVars[3].component(JExpr.lit(i)), "valueHolder"), JExpr._null());
sub.add(conditionalBlock);
} else {
sub.assign(workspaceJVars[3].component(JExpr.lit(i)), workspaceJVars[2].component(JExpr.lit(i)));
sub.assign(JExpr.ref(workspaceJVars[3].component(JExpr.lit(i)), "valueHolder"), inputVariables[i].getHolder());
}
}
// declare generic object for storing return value from GenericUDF.evaluate
JVar retVal = sub.decl(m._ref(Object.class), "ret");
// create try..catch block to call the GenericUDF instance with given input
JTryBlock udfEvalTry = sub._try();
udfEvalTry.body().assign(retVal, workspaceJVars[1].invoke("evaluate").arg(workspaceJVars[3]));
JCatchBlock udfEvalCatch = udfEvalTry._catch(m.directClass(Exception.class.getCanonicalName()));
JVar exVar = udfEvalCatch.param("ex");
udfEvalCatch.body()._throw(JExpr._new(m.directClass(RuntimeException.class.getCanonicalName())).arg(JExpr.lit(String.format("GenericUDF.evaluate method failed"))).arg(exVar));
// get the ValueHolder from retVal and return ObjectInspector
sub.add(ObjectInspectorHelper.getDrillObject(m, returnOI, workspaceJVars[0], workspaceJVars[4], retVal));
sub.assign(out.getHolder(), workspaceJVars[4]);
// now add it to the doEval block in Generated class
JBlock setup = g.getBlock(ClassGenerator.BlockType.EVAL);
setup.directStatement(String.format("/** start %s for function %s **/ ", ClassGenerator.BlockType.EVAL.name(), genericUdfClazz.getName() + (!isGenericUDF ? "(" + udfName + ")" : "")));
setup.add(sub);
setup.directStatement(String.format("/** end %s for function %s **/ ", ClassGenerator.BlockType.EVAL.name(), genericUdfClazz.getName() + (!isGenericUDF ? "(" + udfName + ")" : "")));
return out;
}
Aggregations