private void genListeners( Refs r, Map<Ref, JFieldVar> fieldVarMap, JFieldVar holdrListener, Collection<Ref> refs, JBlock body, Map<Listener.Type, ListenerType> listenerTypeMap) { if (holdrListener == null) return; for (Ref ref : refs) { if (ref instanceof View) { JFieldVar fieldVar = fieldVarMap.get(ref); View view = (View) ref; if (view.isNullable) { body = body._if(fieldVar.ne(_null()))._then(); } for (Listener listener : view.listeners) { ListenerType listenerType = listenerTypeMap.get(listener.type); JDefinedClass listenerClass = r.m.anonymousClass(listenerType.classType); JMethod method = listenerClass.method(PUBLIC, listenerType.methodReturn, listenerType.methodName); List<JVar> params = new ArrayList<JVar>(); for (Pair<JType, String> arg : listenerType.methodParams) { JVar param = method.param(arg.first, arg.second); params.add(arg.second.equals("view") ? fieldVar : param); } method.annotate(r.overrideAnnotation); JBlock innerBody = method.body(); JBlock innerIf = innerBody._if(holdrListener.ne(_null()))._then(); JInvocation invokeHoldrListener; if (listenerType.defaultReturn == null) { invokeHoldrListener = innerIf.invoke(holdrListener, listener.name); } else { invokeHoldrListener = holdrListener.invoke(listener.name); innerIf._return(invokeHoldrListener); innerBody._return(listenerType.defaultReturn); } for (JVar param : params) { invokeHoldrListener.arg(param); } body.invoke(fieldVar, listenerType.setter).arg(_new(listenerClass)); } } } }
private void addHashCode(JDefinedClass jclass) { Map<String, JFieldVar> fields = jclass.fields(); if (fields.isEmpty()) { return; } JMethod hashCode = jclass.method(JMod.PUBLIC, int.class, "hashCode"); Class<?> hashCodeBuilder = ruleFactory.getGenerationConfig().isUseCommonsLang3() ? org.apache.commons.lang3.builder.HashCodeBuilder.class : org.apache.commons.lang.builder.HashCodeBuilder.class; JBlock body = hashCode.body(); JClass hashCodeBuilderClass = jclass.owner().ref(hashCodeBuilder); JInvocation hashCodeBuilderInvocation = JExpr._new(hashCodeBuilderClass); if (!jclass._extends().name().equals("Object")) { hashCodeBuilderInvocation = hashCodeBuilderInvocation.invoke("appendSuper").arg(JExpr._super().invoke("hashCode")); } for (JFieldVar fieldVar : fields.values()) { hashCodeBuilderInvocation = hashCodeBuilderInvocation.invoke("append").arg(fieldVar); } body._return(hashCodeBuilderInvocation.invoke("toHashCode")); hashCode.annotate(Override.class); }
private void addActionToIntentBuilder( EIntentServiceHolder holder, ExecutableElement executableElement, String methodName, JFieldVar actionKeyField) { JMethod method = holder.getIntentBuilderClass().method(PUBLIC, holder.getIntentBuilderClass(), methodName); JBlock body = method.body(); // setAction body.invoke("action").arg(actionKeyField); // For each method params, we get put value into extras List<? extends VariableElement> methodParameters = executableElement.getParameters(); if (methodParameters.size() > 0) { // Extras params for (VariableElement param : methodParameters) { String paramName = param.getSimpleName().toString(); JClass parameterClass = codeModelHelper.typeMirrorToJClass(param.asType(), holder); JFieldVar paramVar = getStaticExtraField(holder, paramName); JVar methodParam = method.param(parameterClass, paramName); JMethod putExtraMethod = holder.getIntentBuilder().getPutExtraMethod(param.asType(), paramName, paramVar); body.invoke(putExtraMethod).arg(methodParam); } } body._return(JExpr._this()); }
@Override public void generate(JDefinedClass cls, GenerationContext context) { if (classSpec.getFields().isEmpty()) { return; // No equals needed. } // Import the objects class, for hash coding. JClass objects = context.getTypeManager().getClassDirect("java.util.Objects"); // Create the equals method. JMethod hashMethod = cls.method(JMod.PUBLIC, int.class, "hashCode"); hashMethod.annotate(Override.class); JBlock body = hashMethod.body(); // Check if the object is null. JVar hash = body.decl(JType.parse(context.getCodeModel(), "int"), "hash", JExpr.lit(3)); // Do check for each field. for (DataFieldSpecification fieldSpec : classSpec.getFields()) { List<String> parts = NameFormat.namesToList(fieldSpec.getFieldName()); String camelCaseFieldName = NameFormat.camelCase(parts, false); // Get the field value. JExpression thisField = JExpr.refthis(camelCaseFieldName); // Accumulate the hash code. JExpression fieldHashCode = objects.staticInvoke("hashCode").arg(thisField); body.assign(hash, JExpr.lit(79).mul(hash).plus(fieldHashCode)); } // Return the processed hash value. body._return(hash); }
private void getter(JDefinedClass clazz, JFieldVar field, String fieldName, String remarks) { // getter JMethod getter = clazz.method(JMod.PUBLIC, field.type(), "get" + fieldName); /* Addign java doc for method */ JDocComment jDoc = addMethodDoc(getter, remarks + "取得"); JCommentPart rtn = jDoc.addReturn(); rtn.add(remarks); JBlock block = getter.body(); block._return(field); }
private void addActionInOnHandleIntent( EIntentServiceHolder holder, ExecutableElement executableElement, String methodName, JFieldVar actionKeyField) { // If action match, call the method JInvocation actionCondition = actionKeyField.invoke("equals").arg(holder.getOnHandleIntentIntentAction()); JBlock callActionBlock = holder.getOnHandleIntentBody()._if(actionCondition)._then(); JInvocation callActionInvocation = JExpr._super().invoke(methodName); // For each method params, we get back value from extras and put it // in super calls List<? extends VariableElement> methodParameters = executableElement.getParameters(); if (methodParameters.size() > 0) { // Extras JVar extras = callActionBlock.decl(classes().BUNDLE, "extras"); extras.init(holder.getOnHandleIntentIntent().invoke("getExtras")); JBlock extrasNotNullBlock = callActionBlock._if(extras.ne(_null()))._then(); // Extras params for (VariableElement param : methodParameters) { String paramName = param.getSimpleName().toString(); String extraParamName = paramName + "Extra"; JFieldVar paramVar = getStaticExtraField(holder, paramName); JClass extraParamClass = codeModelHelper.typeMirrorToJClass(param.asType(), holder); BundleHelper bundleHelper = new BundleHelper(annotationHelper, param); JExpression getExtraExpression = JExpr.invoke(extras, bundleHelper.getMethodNameToRestore()).arg(paramVar); if (bundleHelper.restoreCallNeedCastStatement()) { getExtraExpression = JExpr.cast(extraParamClass, getExtraExpression); if (bundleHelper.restoreCallNeedsSuppressWarning()) { JMethod onHandleIntentMethod = holder.getOnHandleIntentMethod(); if (onHandleIntentMethod.annotations().size() == 0) { onHandleIntentMethod.annotate(SuppressWarnings.class).param("value", "unchecked"); } } } JVar extraField = extrasNotNullBlock.decl(extraParamClass, extraParamName, getExtraExpression); callActionInvocation.arg(extraField); } extrasNotNullBlock.add(callActionInvocation); } else { callActionBlock.add(callActionInvocation); } callActionBlock._return(); }
private JMethod addIterableWither( Filter filter, JDefinedClass bldrCls, JVar paramBuilder, JFieldVar field, JClass paramType) throws JClassAlreadyExistsException { JMethod method = createWitherMethod(filter, bldrCls); if (filter.getTitle() != null) { method.javadoc().add(String.format("<p>%s</p>", filter.getTitle())); } JVar param = addParam(filter, method, iterable(paramType)); JBlock mthdBody = method.body(); mthdBody.add( paramBuilder.invoke("put").arg(field).arg(immutableList.staticInvoke("copyOf").arg(param))); mthdBody._return(JExpr._this()); return method; }
public void run(Set<ClassOutline> sorted, JDefinedClass transformer) { for (ClassOutline classOutline : sorted) { // skip over abstract classes if (!classOutline.target.isAbstract()) { // add the accept method to the bean JDefinedClass beanImpl = classOutline.implClass; JMethod acceptMethod = beanImpl.method(JMod.PUBLIC, Object.class, "accept"); JTypeVar genericType = acceptMethod.generify("T"); acceptMethod.type(genericType); JVar vizParam = acceptMethod.param(transformer.narrow(genericType), "aTransformer"); JBlock block = acceptMethod.body(); block._return(vizParam.invoke("transform").arg(JExpr._this())); } } }
/** * Add the pre-check to see if we are already in the UI thread. * * @param delegatingMethod * @param holder * @throws JClassAlreadyExistsException */ private void addUIThreadCheck( JMethod delegatingMethod, JBlock previousBody, EComponentHolder holder) throws JClassAlreadyExistsException { // Get the Thread and Looper class. JClass tClass = holder.classes().THREAD; JClass lClass = holder.classes().LOOPER; // invoke the methods. JExpression lhs = tClass.staticInvoke(METHOD_CUR_THREAD); JExpression rhs = lClass.staticInvoke(METHOD_MAIN_LOOPER).invoke(METHOD_GET_THREAD); // create the conditional and the block. JConditional con = delegatingMethod.body()._if(JOp.eq(lhs, rhs)); JBlock thenBlock = con._then().add(previousBody); thenBlock._return(); }
private void addToString(JDefinedClass jclass) { JMethod toString = jclass.method(JMod.PUBLIC, String.class, "toString"); Class<?> toStringBuilder = ruleFactory.getGenerationConfig().isUseCommonsLang3() ? org.apache.commons.lang3.builder.ToStringBuilder.class : org.apache.commons.lang.builder.ToStringBuilder.class; JBlock body = toString.body(); JInvocation reflectionToString = jclass.owner().ref(toStringBuilder).staticInvoke("reflectionToString"); reflectionToString.arg(JExpr._this()); body._return(reflectionToString); toString.annotate(Override.class); }
private JDefinedClass addBuilderCls(Feed feed, JDefinedClass cls) throws JClassAlreadyExistsException, ClassNotFoundException { JDefinedClass bldrCls = cls._class(JMod.PUBLIC | JMod.STATIC | JMod.FINAL, "Builder"); JVar paramBuilder = bldrCls .field(JMod.PRIVATE | JMod.FINAL, immutableMapBldr, "params") .init(immutableMap.staticInvoke("builder")); for (Filter filter : feed.getFilters().getFilter()) { if (!Boolean.TRUE.equals(filter.isDeprecated())) { addWithersFor(filter, bldrCls, paramBuilder); } } if (feed.getMixins() != null && feed.getMixins().getMixin() != null) { JDefinedClass mixinEnum = getMixinEnum(feed); for (Mixin mixin : feed.getMixins().getMixin()) { String mixinName = mixin.getName().toUpperCase().replace(' ', '_'); JEnumConstant mixinCnst = mixinEnum.enumConstant(mixinName); mixinCnst.arg(JExpr.lit(mixin.getName().replace(' ', '+'))); } JFieldVar field = cls.field(privateStaticFinal, String.class, "MIXIN"); field.init(JExpr.lit("mixin")); JMethod iterWither = bldrCls.method(JMod.PUBLIC, bldrCls, "withMixins"); JVar param = iterWither.param(iterable(mixinEnum), "mixins"); JBlock mthdBody = iterWither.body(); mthdBody.add( paramBuilder .invoke("put") .arg(field) .arg(immutableList.staticInvoke("copyOf").arg(param))); mthdBody._return(JExpr._this()); JMethod varArgWither = bldrCls.method(JMod.PUBLIC, bldrCls, "withMixins"); param = varArgWither.varParam(mixinEnum, "mixins"); varArgWither .body() ._return(JExpr.invoke(iterWither).arg(immutableList.staticInvoke("copyOf").arg(param))); } JMethod bldMthd = bldrCls.method(JMod.PUBLIC, cls, "build"); bldMthd.body()._return(JExpr._new(cls).arg(paramBuilder.invoke("build"))); // TODO: add sorts return bldrCls; }
private void addEquals(JDefinedClass jclass) { Map<String, JFieldVar> fields = jclass.fields(); if (fields.isEmpty()) { return; } JMethod equals = jclass.method(JMod.PUBLIC, boolean.class, "equals"); JVar otherObject = equals.param(Object.class, "other"); Class<?> equalsBuilder = ruleFactory.getGenerationConfig().isUseCommonsLang3() ? org.apache.commons.lang3.builder.EqualsBuilder.class : org.apache.commons.lang.builder.EqualsBuilder.class; JBlock body = equals.body(); body._if(otherObject.eq(JExpr._this()))._then()._return(JExpr.TRUE); body._if(otherObject._instanceof(jclass).eq(JExpr.FALSE))._then()._return(JExpr.FALSE); JVar rhsVar = body.decl(jclass, "rhs").init(JExpr.cast(jclass, otherObject)); JClass equalsBuilderClass = jclass.owner().ref(equalsBuilder); JInvocation equalsBuilderInvocation = JExpr._new(equalsBuilderClass); if (!jclass._extends().name().equals("Object")) { equalsBuilderInvocation = equalsBuilderInvocation .invoke("appendSuper") .arg(JExpr._super().invoke("equals").arg(otherObject)); } for (JFieldVar fieldVar : fields.values()) { equalsBuilderInvocation = equalsBuilderInvocation.invoke("append").arg(fieldVar).arg(rhsVar.ref(fieldVar.name())); } JInvocation reflectionEquals = jclass.owner().ref(equalsBuilder).staticInvoke("reflectionEquals"); reflectionEquals.arg(JExpr._this()); reflectionEquals.arg(otherObject); body._return(equalsBuilderInvocation.invoke("isEquals")); equals.annotate(Override.class); }
private void addWither( Filter filter, JDefinedClass bldrCls, JVar paramBuilder, JFieldVar field, JClass paramType) throws JClassAlreadyExistsException { JMethod method = createWitherMethod(filter, bldrCls); if (filter.getTitle() != null) { method.javadoc().add(String.format("<p>%s</p>", filter.getTitle())); } JVar param = addParam(filter, method, paramType); JBlock mthdBody = method.body(); boolean needsNullCheck = true; if (filter.getMinValue() != null) { mthdBody.add(precs.staticInvoke("checkNotNull").arg(param)); needsNullCheck = false; int min = filter.getMinValue().intValue(); mthdBody.add( precs .staticInvoke("checkArgument") .arg(JExpr.lit(min).lte(param)) .arg(JExpr.lit(param.name() + ": %s < " + min)) .arg(param)); } if (filter.getMaxValue() != null) { if (needsNullCheck) { mthdBody.add(precs.staticInvoke("checkNotNull").arg(param)); needsNullCheck = false; } int max = filter.getMaxValue().intValue(); mthdBody.add( precs .staticInvoke("checkArgument") .arg(JExpr.lit(max).gte(param)) .arg(JExpr.lit(param.name() + ": %s > " + max)) .arg(param)); } JInvocation putIntoMap = paramBuilder.invoke("put").arg(field); if (needsNullCheck) { putIntoMap.arg(precs.staticInvoke("checkNotNull").arg(param)); } else { putIntoMap.arg(param); } mthdBody.add(putIntoMap); mthdBody._return(JExpr._this()); }
private static void processToString(JDefinedClass packetClass, JCodeModel codeModel) { JClass string = codeModel.ref(String.class); JClass stringBuilder = codeModel.ref(StringBuilder.class); JClass arrays = codeModel.ref(Arrays.class); JMethod toStringMeth = packetClass.method(JMod.PUBLIC, String.class, "toString"); toStringMeth.annotate(Override.class); JBlock body = toStringMeth.body(); JVar stringBuilderVar = body.decl(stringBuilder, "sb"); stringBuilderVar = stringBuilderVar.init(JExpr._new(stringBuilder).arg(packetClass.name() + "[")); JInvocation appendChain = null; for (JFieldVar fieldVar : packetClass.fields().values()) { if (appendChain != null) { // a comma is needed appendChain = appendChain.invoke("append").arg("," + fieldVar.name() + "="); } else { appendChain = stringBuilderVar.invoke("append").arg(fieldVar.name() + "="); } // now add the field to the toString output JExpression expression = fieldVar.type().isArray() ? arrays.staticInvoke("toString").arg(JExpr._this().ref(fieldVar.name())) : fieldVar.type().isReference() ? JExpr._this().ref(fieldVar.name()).invoke("toString") : JExpr._this().ref(fieldVar.name()); appendChain = appendChain.invoke("append").arg(expression); } if (appendChain != null) { appendChain = appendChain.invoke("append").arg("]"); } else { appendChain = stringBuilderVar.invoke("append").arg("]"); } body.add(appendChain); body._return(stringBuilderVar.invoke("toString")); }
@Override public void generate(ASTType descriptor) { if (descriptor.isConcreteClass()) { throw new TransfuseAnalysisException("Unable to build injector from concrete class"); } try { JDefinedClass implClass = codeModel._class(JMod.PUBLIC, descriptor.getName() + IMPL_EXT, ClassType.CLASS); JClass interfaceClass = codeModel.ref(descriptor.getName()); implClass._implements(interfaceClass); for (ASTMethod interfaceMethod : descriptor.getMethods()) { MirroredMethodGenerator mirroredMethodGenerator = componentBuilderFactory.buildMirroredMethodGenerator(interfaceMethod, false); MethodDescriptor methodDescriptor = mirroredMethodGenerator.buildMethod(implClass); JBlock block = methodDescriptor.getMethod().body(); AnalysisContext context = analysisContextFactory.buildAnalysisContext(injectionNodeBuilderRepository); InjectionNodeFactory injectionNodeFactory = componentBuilderFactory.buildInjectionNodeFactory( interfaceMethod.getReturnType(), context); // Injections InjectionNode returnType = injectionNodeFactory.buildInjectionNode(methodDescriptor); Map<InjectionNode, TypedExpression> expressionMap = injectionFragmentGenerator.buildFragment(block, implClass, returnType); block._return(expressionMap.get(returnType).getExpression()); } injectorRepositoryGenerator.generateInjectorRepository(interfaceClass, implClass); } catch (JClassAlreadyExistsException e) { throw new TransfuseAnalysisException( "Class already exists for generated type " + descriptor.getName(), e); } catch (ClassNotFoundException e) { throw new TransfuseAnalysisException("Target class not found", e); } }
private void buildMethodInterceptor( JDefinedClass definedClass, ConstructorInjectionPoint proxyConstructorInjectionPoint, JMethod constructor, JBlock constructorBody, Map<ASTMethod, Map<InjectionNode, JFieldVar>> interceptorFields, Map.Entry<ASTMethod, Set<InjectionNode>> methodInterceptorEntry) throws ClassNotFoundException { ASTMethod method = methodInterceptorEntry.getKey(); if (method.getAccessModifier().equals(ASTAccessModifier.PRIVATE)) { throw new TransfuseAnalysisException("Unable to provide AOP on private methods"); } if (!interceptorFields.containsKey(methodInterceptorEntry.getKey())) { interceptorFields.put( methodInterceptorEntry.getKey(), new HashMap<InjectionNode, JFieldVar>()); } Map<InjectionNode, JFieldVar> injectionNodeInstanceNameMap = interceptorFields.get(methodInterceptorEntry.getKey()); // setup interceptor fields for (InjectionNode interceptorInjectionNode : methodInterceptorEntry.getValue()) { String interceptorInstanceName = namer.generateName(interceptorInjectionNode); JFieldVar interceptorField = definedClass.field( JMod.PRIVATE, codeModel.ref(interceptorInjectionNode.getClassName()), interceptorInstanceName); injectionNodeInstanceNameMap.put(interceptorInjectionNode, interceptorField); JVar interceptorParam = constructor.param( codeModel.ref(interceptorInjectionNode.getClassName()), namer.generateName(interceptorInjectionNode)); constructorBody.assign(interceptorField, interceptorParam); proxyConstructorInjectionPoint.addInjectionNode(interceptorInjectionNode); } JType returnType = codeModel.parseType(method.getReturnType().getName()); JMethod methodDeclaration = definedClass.method( method.getAccessModifier().getCodeModelJMod(), returnType, method.getName()); JBlock body = methodDeclaration.body(); // define method parameter Map<ASTParameter, JVar> parameterMap = new HashMap<ASTParameter, JVar>(); for (ASTParameter parameter : method.getParameters()) { parameterMap.put( parameter, methodDeclaration.param( JMod.FINAL, codeModel.ref(parameter.getASTType().getName()), namer.generateName(parameter.getASTType()))); } // aop interceptor Map<InjectionNode, JFieldVar> interceptorNameMap = interceptorFields.get(methodInterceptorEntry.getKey()); JArray paramArray = JExpr.newArray(codeModel.ref(Object.class)); for (ASTParameter astParameter : method.getParameters()) { paramArray.add(parameterMap.get(astParameter)); } JInvocation interceptorInvocation = buildInterceptorChain( definedClass, method, parameterMap, methodInterceptorEntry.getValue(), interceptorNameMap) .invoke("invoke"); interceptorInvocation.arg(paramArray); if (method.getReturnType().equals(ASTVoidType.VOID)) { body.add(interceptorInvocation); } else { body._return(JExpr.cast(returnType.boxify(), interceptorInvocation)); } }
private void createResponseBuilderInResourceMethodReturnType( final JDefinedClass responseClass, final int statusCode, final Response response, final MimeType responseMimeType) throws Exception { final String responseBuilderMethodName = Names.buildResponseMethodName(statusCode, responseMimeType); final JMethod responseBuilderMethod = responseClass.method(PUBLIC + STATIC, responseClass, responseBuilderMethodName); final JDocComment javadoc = responseBuilderMethod.javadoc(); if (isNotBlank(response.getDescription())) { javadoc.add(response.getDescription()); } if ((responseMimeType != null) && (isNotBlank(responseMimeType.getExample()))) { javadoc.add(EXAMPLE_PREFIX + responseMimeType.getExample()); } JInvocation builderArgument = types .getGeneratorClass(javax.ws.rs.core.Response.class) .staticInvoke("status") .arg(JExpr.lit(statusCode)); if (responseMimeType != null) { builderArgument = builderArgument .invoke("header") .arg(HttpHeaders.CONTENT_TYPE) .arg(responseMimeType.getType()); } final StringBuilder freeFormHeadersDescription = new StringBuilder(); for (final Entry<String, Header> namedHeaderParameter : response.getHeaders().entrySet()) { final String headerName = namedHeaderParameter.getKey(); final Header header = namedHeaderParameter.getValue(); if (headerName.contains(RESPONSE_HEADER_WILDCARD_SYMBOL)) { appendParameterJavadocDescription(header, freeFormHeadersDescription); continue; } final String argumentName = Names.buildVariableName(headerName); builderArgument = builderArgument.invoke("header").arg(headerName).arg(JExpr.ref(argumentName)); addParameterJavaDoc(header, argumentName, javadoc); responseBuilderMethod.param(types.buildParameterType(header, argumentName), argumentName); } final JBlock responseBuilderMethodBody = responseBuilderMethod.body(); final JVar builderVariable = responseBuilderMethodBody.decl( types.getGeneratorType(ResponseBuilder.class), "responseBuilder", builderArgument); if (freeFormHeadersDescription.length() > 0) { // generate a Map<String, List<Object>> argument for {?} headers final JClass listOfObjectsClass = types.getGeneratorClass(List.class).narrow(Object.class); final JClass headersArgument = types .getGeneratorClass(Map.class) .narrow(types.getGeneratorClass(String.class), listOfObjectsClass); builderArgument = responseBuilderMethodBody .invoke("headers") .arg(JExpr.ref(MULTIPLE_RESPONSE_HEADERS_ARGUMENT_NAME)) .arg(builderVariable); final JVar param = responseBuilderMethod.param(headersArgument, MULTIPLE_RESPONSE_HEADERS_ARGUMENT_NAME); javadoc.addParam(param).add(freeFormHeadersDescription.toString()); } if (responseMimeType != null) { responseBuilderMethodBody .invoke(builderVariable, "entity") .arg(JExpr.ref(GENERIC_PAYLOAD_ARGUMENT_NAME)); responseBuilderMethod.param( types.getResponseEntityClass(responseMimeType), GENERIC_PAYLOAD_ARGUMENT_NAME); javadoc .addParam(GENERIC_PAYLOAD_ARGUMENT_NAME) .add(defaultString(responseMimeType.getExample())); } responseBuilderMethodBody._return( JExpr._new(responseClass).arg(builderVariable.invoke("build"))); }