Java Code Examples for com.sun.codemodel.JBlock
The following are top voted examples for showing how to use
com.sun.codemodel.JBlock. These examples are extracted from open source projects.
You can vote up the examples you like and your votes will be used in our system to generate
more good examples.
Example 1
Project: GitHub File: EnumRule.java View source code | 7 votes |
private void addFactoryMethod(JDefinedClass _enum, JType backingType) { JFieldVar quickLookupMap = addQuickLookupMap(_enum, backingType); JMethod fromValue = _enum.method(JMod.PUBLIC | JMod.STATIC, _enum, "fromValue"); JVar valueParam = fromValue.param(backingType, "value"); JBlock body = fromValue.body(); JVar constant = body.decl(_enum, "constant"); constant.init(quickLookupMap.invoke("get").arg(valueParam)); JConditional _if = body._if(constant.eq(JExpr._null())); JInvocation illegalArgumentException = JExpr._new(_enum.owner().ref(IllegalArgumentException.class)); JExpression expr = valueParam; // if string no need to add "" if(!isString(backingType)){ expr = expr.plus(JExpr.lit("")); } illegalArgumentException.arg(expr); _if._then()._throw(illegalArgumentException); _if._else()._return(constant); ruleFactory.getAnnotator().enumCreatorMethod(fromValue); }
Example 2
Project: GitHub File: DynamicPropertiesRule.java View source code | 6 votes |
private JMethod addPublicGetMethod(JDefinedClass jclass, JMethod internalGetMethod, JFieldRef notFoundValue) { JMethod method = jclass.method(PUBLIC, jclass.owner()._ref(Object.class), GETTER_NAME); JTypeVar returnType = method.generify("T"); method.type(returnType); Models.suppressWarnings(method, "unchecked"); JVar nameParam = method.param(String.class, "name"); JBlock body = method.body(); JVar valueVar = body.decl(jclass.owner()._ref(Object.class), "value", invoke(internalGetMethod).arg(nameParam).arg(notFoundValue)); JConditional found = method.body()._if(notFoundValue.ne(valueVar)); found._then()._return(cast(returnType, valueVar)); JBlock notFound = found._else(); JMethod getAdditionalProperties = jclass.getMethod("getAdditionalProperties", new JType[] {}); if (getAdditionalProperties != null) { notFound._return(cast(returnType, invoke(getAdditionalProperties).invoke("get").arg(nameParam))); } else { notFound._throw(illegalArgumentInvocation(jclass, nameParam)); } return method; }
Example 3
Project: GitHub File: DynamicPropertiesRule.java View source code | 6 votes |
private JMethod addPublicSetMethod(JDefinedClass jclass, JMethod internalSetMethod) { JMethod method = jclass.method(PUBLIC, jclass.owner().VOID, SETTER_NAME); JVar nameParam = method.param(String.class, "name"); JVar valueParam = method.param(Object.class, "value"); JBlock body = method.body(); JBlock notFound = body._if(JOp.not(invoke(internalSetMethod).arg(nameParam).arg(valueParam)))._then(); // if we have additional properties, then put value. JMethod getAdditionalProperties = jclass.getMethod("getAdditionalProperties", new JType[] {}); if (getAdditionalProperties != null) { JType additionalPropertiesType = ((JClass) (getAdditionalProperties.type())).getTypeParameters().get(1); notFound.add(invoke(getAdditionalProperties).invoke("put").arg(nameParam) .arg(cast(additionalPropertiesType, valueParam))); } // else throw exception. else { notFound._throw(illegalArgumentInvocation(jclass, nameParam)); } return method; }
Example 4
Project: GitHub File: DynamicPropertiesRule.java View source code | 6 votes |
private JMethod addPublicWithMethod(JDefinedClass jclass, JMethod internalSetMethod) { JMethod method = jclass.method(PUBLIC, jclass, BUILDER_NAME); JVar nameParam = method.param(String.class, "name"); JVar valueParam = method.param(Object.class, "value"); JBlock body = method.body(); JBlock notFound = body._if(JOp.not(invoke(internalSetMethod).arg(nameParam).arg(valueParam)))._then(); // if we have additional properties, then put value. JMethod getAdditionalProperties = jclass.getMethod("getAdditionalProperties", new JType[] {}); if (getAdditionalProperties != null) { JType additionalPropertiesType = ((JClass) (getAdditionalProperties.type())).getTypeParameters().get(1); notFound.add(invoke(getAdditionalProperties).invoke("put").arg(nameParam) .arg(cast(additionalPropertiesType, valueParam))); } // else throw exception. else { notFound._throw(illegalArgumentInvocation(jclass, nameParam)); } body._return(_this()); return method; }
Example 5
Project: GitHub File: ObjectRule.java View source code | 6 votes |
private void addToString(JDefinedClass jclass) { Map<String, JFieldVar> fields = jclass.fields(); JMethod toString = jclass.method(JMod.PUBLIC, String.class, "toString"); Set<String> excludes = new HashSet<String>(Arrays.asList(ruleFactory.getGenerationConfig().getToStringExcludes())); JBlock body = toString.body(); Class<?> toStringBuilder = ruleFactory.getGenerationConfig().isUseCommonsLang3() ? org.apache.commons.lang3.builder.ToStringBuilder.class : org.apache.commons.lang.builder.ToStringBuilder.class; JClass toStringBuilderClass = jclass.owner().ref(toStringBuilder); JInvocation toStringBuilderInvocation = JExpr._new(toStringBuilderClass).arg(JExpr._this()); if (!jclass._extends().fullName().equals(Object.class.getName())) { toStringBuilderInvocation = toStringBuilderInvocation.invoke("appendSuper").arg(JExpr._super().invoke("toString")); } for (JFieldVar fieldVar : fields.values()) { if (excludes.contains(fieldVar.name()) || (fieldVar.mods().getValue() & JMod.STATIC) == JMod.STATIC) { continue; } toStringBuilderInvocation = toStringBuilderInvocation.invoke("append").arg(fieldVar.name()).arg(fieldVar); } body._return(toStringBuilderInvocation.invoke("toString")); toString.annotate(Override.class); }
Example 6
Project: GitHub File: ObjectRule.java View source code | 6 votes |
private void addHashCode(JDefinedClass jclass, JsonNode node) { Map<String, JFieldVar> fields = removeFieldsExcludedFromEqualsAndHashCode(jclass.fields(), node); 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().fullName().equals(Object.class.getName())) { hashCodeBuilderInvocation = hashCodeBuilderInvocation.invoke("appendSuper").arg(JExpr._super().invoke("hashCode")); } for (JFieldVar fieldVar : fields.values()) { if ((fieldVar.mods().getValue() & JMod.STATIC) == JMod.STATIC) { continue; } hashCodeBuilderInvocation = hashCodeBuilderInvocation.invoke("append").arg(fieldVar); } body._return(hashCodeBuilderInvocation.invoke("toHashCode")); hashCode.annotate(Override.class); }
Example 7
Project: beanvalidation-benchmark File: Generator.java View source code | 6 votes |
/** * Recursive method that handles the creation of reference beans at * different depth levels. * * @param mjb * The target bean to create an instance of. * @param body * The current block of code. * @param level * The current depth level. * @return A generated variable referencing the created bean. */ private JVar generateBeanNonStaticInitCode(MetaJavaBean mjb, JBlock body, int level) { JVar beanDecl = body.decl(mjb.getGeneratedClass(), "lvl" + level + mjb.getName() + "_" + Config.CFG.nextUniqueNum()); body.assign(beanDecl, JExpr._new(mjb.getGeneratedClass())); for (AbstractMetaField amf : mjb.getFields()) { if (amf instanceof JavaBeanRefField) { JavaBeanRefField jbrf = (JavaBeanRefField) amf; // Should a nested bean be created? if (Config.CFG.shouldAddNestedBean(level)) { JVar nestedBeanDecl = generateBeanNonStaticInitCode(jbrf.getRefBean(), body, level + 1); jbrf.generateAssignCode(body, beanDecl, nestedBeanDecl); } } } return beanDecl; }
Example 8
Project: QDrill File: EvaluationVisitor.java View source code | 6 votes |
@Override public HoldingContainer visitDecimal9Constant(Decimal9Expression e, ClassGenerator<?> generator) throws RuntimeException { MajorType majorType = e.getMajorType(); JBlock setup = generator.getBlock(BlockType.SETUP); JType holderType = generator.getHolderType(majorType); JVar var = generator.declareClassField("dec9", holderType); JExpression valueLiteral = JExpr.lit(e.getIntFromDecimal()); JExpression scaleLiteral = JExpr.lit(e.getScale()); JExpression precisionLiteral = JExpr.lit(e.getPrecision()); setup.assign( var, generator.getModel().ref(ValueHolderHelper.class).staticInvoke("getDecimal9Holder").arg(valueLiteral) .arg(scaleLiteral).arg(precisionLiteral)); return new HoldingContainer(majorType, var, null, null); }
Example 9
Project: QDrill File: EvaluationVisitor.java View source code | 6 votes |
@Override public HoldingContainer visitDecimal18Constant(Decimal18Expression e, ClassGenerator<?> generator) throws RuntimeException { MajorType majorType = e.getMajorType(); JBlock setup = generator.getBlock(BlockType.SETUP); JType holderType = generator.getHolderType(majorType); JVar var = generator.declareClassField("dec18", holderType); JExpression valueLiteral = JExpr.lit(e.getLongFromDecimal()); JExpression scaleLiteral = JExpr.lit(e.getScale()); JExpression precisionLiteral = JExpr.lit(e.getPrecision()); setup.assign( var, generator.getModel().ref(ValueHolderHelper.class).staticInvoke("getDecimal18Holder").arg(valueLiteral) .arg(scaleLiteral).arg(precisionLiteral)); return new HoldingContainer(majorType, var, null, null); }
Example 10
Project: QDrill File: ClassGenerator.java View source code | 6 votes |
@SuppressWarnings("unchecked") ClassGenerator(CodeGenerator<T> codeGenerator, MappingSet mappingSet, SignatureHolder signature, EvaluationVisitor eval, JDefinedClass clazz, JCodeModel model) throws JClassAlreadyExistsException { this.codeGenerator = codeGenerator; this.clazz = clazz; this.mappings = mappingSet; this.sig = signature; this.evaluationVisitor = eval; this.model = model; blocks = (LinkedList<JBlock>[]) new LinkedList[sig.size()]; for (int i =0; i < sig.size(); i++) { blocks[i] = Lists.newLinkedList(); } rotateBlock(); for (SignatureHolder child : signature.getChildHolders()) { String innerClassName = child.getSignatureClass().getSimpleName(); JDefinedClass innerClazz = clazz._class(Modifier.FINAL + Modifier.PRIVATE, innerClassName); innerClasses.put(innerClassName, new ClassGenerator<>(codeGenerator, mappingSet, child, eval, innerClazz, model)); } }
Example 11
Project: QDrill File: DrillAggFuncHolder.java View source code | 6 votes |
@Override public HoldingContainer renderEnd(ClassGenerator<?> g, HoldingContainer[] inputVariables, JVar[] workspaceJVars) { HoldingContainer out = g.declare(returnValue.type, false); JBlock sub = new JBlock(); g.getEvalBlock().add(sub); JVar internalOutput = sub.decl(JMod.FINAL, g.getHolderType(returnValue.type), returnValue.name, JExpr._new(g.getHolderType(returnValue.type))); addProtectedBlock(g, sub, output, null, workspaceJVars, false); sub.assign(out.getHolder(), internalOutput); //hash aggregate uses workspace vectors. Initialization is done in "setup" and does not require "reset" block. if (!g.getMappingSet().isHashAggMapping()) { generateBody(g, BlockType.RESET, reset, null, workspaceJVars, false); } generateBody(g, BlockType.CLEANUP, cleanup, null, workspaceJVars, false); return out; }
Example 12
Project: dremio-oss File: EvaluationVisitor.java View source code | 6 votes |
@Override public HoldingContainer visitDecimalConstant(DecimalExpression e, ClassGenerator<?> generator) throws RuntimeException { CompleteType majorType= e.getCompleteType(); JBlock setup = generator.getBlock(BlockType.SETUP); JType holderType = majorType.getHolderType(generator.getModel()); JVar var = generator.declareClassField("dec", holderType); JExpression valueLiteral = JExpr.lit(e.getIntFromDecimal()); JExpression scaleLiteral = JExpr.lit(e.getScale()); JExpression precisionLiteral = JExpr.lit(e.getPrecision()); setup.assign( var, generator.getModel().ref(ValueHolderHelper.class).staticInvoke("getNullableDecimalHolder").arg(valueLiteral) .arg(scaleLiteral).arg(precisionLiteral)); return new HoldingContainer(majorType, var, var.ref("value"), var.ref("isSet")); }
Example 13
Project: dremio-oss File: ClassGenerator.java View source code | 6 votes |
public JVar declareVectorValueSetupAndMember(DirectExpression batchName, TypedFieldId fieldId) { final ValueVectorSetup setup = new ValueVectorSetup(batchName, fieldId); final Class<?> valueVectorClass = fieldId.getIntermediateClass(); final JClass vvClass = model.ref(valueVectorClass); final JClass retClass = fieldId.isHyperReader() ? vvClass.array() : vvClass; final JVar vv = declareClassField("vv", retClass); final JBlock b = getSetupBlock(); int[] fieldIndices = fieldId.getFieldIds(); JInvocation invoke = model.ref(VectorResolver.class).staticInvoke(fieldId.isHyperReader() ? "hyper" : "simple") .arg(batchName) .arg(vvClass.dotclass()); for(int i = 0; i < fieldIndices.length; i++){ invoke.arg(JExpr.lit(fieldIndices[i])); } // we have to cast here since Janino doesn't handle generic inference well. JExpression casted = JExpr.cast(retClass, invoke); b.assign(vv, casted); vvDeclaration.put(setup, vv); return vv; }
Example 14
Project: dremio-oss File: AggrFunctionHolder.java View source code | 6 votes |
@Override public HoldingContainer renderEnd(ClassGenerator<?> g, CompleteType resolvedOutput, HoldingContainer[] inputVariables, JVar[] workspaceJVars) { HoldingContainer out = g.declare(resolvedOutput, false); JBlock sub = new JBlock(); g.getEvalBlock().add(sub); JVar internalOutput = sub.decl(JMod.FINAL, resolvedOutput.getHolderType(g.getModel()), getReturnName(), JExpr._new(resolvedOutput.getHolderType(g.getModel()))); addProtectedBlock(g, sub, output(), null, workspaceJVars, false); sub.assign(out.getHolder(), internalOutput); //hash aggregate uses workspace vectors. Initialization is done in "setup" and does not require "reset" block. if (!g.getMappingSet().isHashAggMapping()) { generateBody(g, BlockType.RESET, reset(), null, workspaceJVars, false); } generateBody(g, BlockType.CLEANUP, cleanup(), null, workspaceJVars, false); return out; }
Example 15
Project: libraries File: EqualsFactory.java View source code | 6 votes |
public void createEquals(final JDefinedClass bean, final Iterable<JFieldVar> fields) { final JMethod method = bean.method(JMod.PUBLIC, this.codeModel.BOOLEAN, "equals"); method.annotate(java.lang.Override.class); final JVar object = method.param(_type(java.lang.Object.class.getName()), "object"); final JBlock block = method.body(); block._if(JExpr._this().eq(object))._then()._return(JExpr.TRUE); block._if(object._instanceof(bean).not())._then()._return(JExpr.FALSE); JExpression result = JExpr.TRUE; final JExpression other = block.decl(bean, "other", JExpr.cast(bean, object)); final JClass objectUtilities = _classByNames(net.anwiba.commons.lang.object.ObjectUtilities.class.getName()); for (final JFieldVar field : fields) { result = result.cand(objectUtilities.staticInvoke("equals").arg(JExpr.refthis(field.name())).arg(other.ref(field))); } block._return(result); }
Example 16
Project: aml File: GenericAcAdapterWriter.java View source code | 6 votes |
protected JBlock generateWriter(AcScheme scheme, JavaWriter writer) { JBlock bl=new JBlock(); for (AbstractType tp:scheme.getSchemes().keySet()){ String name = getName(tp, writer); String ge="value.get"+Character.toUpperCase(name.charAt(0))+name.substring(1)+"()"; JBlock th=bl._if(JExpr.direct(ge+"!=null"))._then(); th.add(new JStatement() { @Override public void state(JFormatter f) { f.p("gson.toJson("+ge+","+ge+".getClass(), out);"); f.nl(); } }); } return bl; }
Example 17
Project: aml File: JacksonSerializerWriter.java View source code | 6 votes |
protected JBlock generateWriter(AcScheme scheme, JavaWriter writer) { JBlock bl=new JBlock(); for (AbstractType tp:scheme.getSchemes().keySet()){ String name = getName(tp, writer); String ge="value.get"+Character.toUpperCase(name.charAt(0))+name.substring(1)+"()"; JBlock th=bl._if(JExpr.direct(ge+"!=null"))._then(); th.add(new JStatement() { @Override public void state(JFormatter f) { f.p("gen.writeObject("+ge+");"); f.nl(); } }); } return bl; }
Example 18
Project: drill File: EvaluationVisitor.java View source code | 6 votes |
@Override public HoldingContainer visitDecimal9Constant(Decimal9Expression e, ClassGenerator<?> generator) throws RuntimeException { MajorType majorType = e.getMajorType(); JBlock setup = generator.getBlock(BlockType.SETUP); JType holderType = generator.getHolderType(majorType); JVar var = generator.declareClassField("dec9", holderType); JExpression valueLiteral = JExpr.lit(e.getIntFromDecimal()); JExpression scaleLiteral = JExpr.lit(e.getScale()); JExpression precisionLiteral = JExpr.lit(e.getPrecision()); setup.assign( var, generator.getModel().ref(ValueHolderHelper.class).staticInvoke("getDecimal9Holder").arg(valueLiteral) .arg(scaleLiteral).arg(precisionLiteral)); return new HoldingContainer(majorType, var, null, null); }
Example 19
Project: drill File: EvaluationVisitor.java View source code | 6 votes |
@Override public HoldingContainer visitDecimal18Constant(Decimal18Expression e, ClassGenerator<?> generator) throws RuntimeException { MajorType majorType = e.getMajorType(); JBlock setup = generator.getBlock(BlockType.SETUP); JType holderType = generator.getHolderType(majorType); JVar var = generator.declareClassField("dec18", holderType); JExpression valueLiteral = JExpr.lit(e.getLongFromDecimal()); JExpression scaleLiteral = JExpr.lit(e.getScale()); JExpression precisionLiteral = JExpr.lit(e.getPrecision()); setup.assign( var, generator.getModel().ref(ValueHolderHelper.class).staticInvoke("getDecimal18Holder").arg(valueLiteral) .arg(scaleLiteral).arg(precisionLiteral)); return new HoldingContainer(majorType, var, null, null); }
Example 20
Project: drill File: ClassGenerator.java View source code | 6 votes |
/** * Create a new code block, closing the current block. * * @param mode the {@link BlkCreateMode block create mode} * for the new block. */ private void rotateBlock(BlkCreateMode mode) { boolean blockRotated = false; for (LinkedList<SizedJBlock> b : blocks) { if (mode == BlkCreateMode.TRUE || (mode == BlkCreateMode.TRUE_IF_BOUND && optionManager != null && b.getLast().getCount() > optionManager.getOption(ExecConstants.CODE_GEN_EXP_IN_METHOD_SIZE_VALIDATOR))) { b.add(new SizedJBlock(new JBlock(true, true))); blockRotated = true; } } if (blockRotated) { evaluationVisitor.previousExpressions.clear(); setupValidBlocks(); } }
Example 21
Project: drill File: ClassGenerator.java View source code | 6 votes |
/** * The code generator creates a method called __DRILL_INIT__ which takes the * place of the constructor when the code goes though the byte code merge. * For Plain-old Java, we call the method from a constructor created for * that purpose. (Generated code, fortunately, never includes a constructor, * so we can create one.) Since the init block throws an exception (which * should never occur), the generated constructor converts the checked * exception into an unchecked one so as to not require changes to the * various places that create instances of the generated classes. * * Example:<code><pre> * public StreamingAggregatorGen1() { * try { * __DRILL_INIT__(); * } catch (SchemaChangeException e) { * throw new UnsupportedOperationException(e); * } * }</pre></code> * * Note: in Java 8 we'd use the <tt>Parameter</tt> class defined in Java's * introspection package. But, Drill prefers Java 7 which only provides * parameter types. */ private void addCtor(Class<?>[] parameters) { JMethod ctor = clazz.constructor(JMod.PUBLIC); JBlock body = ctor.body(); // If there are parameters, need to pass them to the super class. if (parameters.length > 0) { JInvocation superCall = JExpr.invoke("super"); // This case only occurs for nested classes, and all nested classes // in Drill are inner classes. Don't pass along the (hidden) // this$0 field. for (int i = 1; i < parameters.length; i++) { Class<?> p = parameters[i]; superCall.arg(ctor.param(model._ref(p), "arg" + i)); } body.add(superCall); } JTryBlock tryBlock = body._try(); tryBlock.body().invoke(SignatureHolder.DRILL_INIT_METHOD); JCatchBlock catchBlock = tryBlock._catch(model.ref(SchemaChangeException.class)); catchBlock.body()._throw(JExpr._new(model.ref(UnsupportedOperationException.class)).arg(catchBlock.param("e"))); }
Example 22
Project: drill File: DrillAggFuncHolder.java View source code | 6 votes |
@Override public HoldingContainer renderEnd(ClassGenerator<?> classGenerator, HoldingContainer[] inputVariables, JVar[] workspaceJVars, FieldReference fieldReference) { HoldingContainer out = classGenerator.declare(getReturnType(), false); JBlock sub = new JBlock(); classGenerator.getEvalBlock().add(sub); JVar internalOutput = sub.decl(JMod.FINAL, classGenerator.getHolderType(getReturnType()), getReturnValue().getName(), JExpr._new(classGenerator.getHolderType(getReturnType()))); addProtectedBlock(classGenerator, sub, output(), null, workspaceJVars, false); sub.assign(out.getHolder(), internalOutput); //hash aggregate uses workspace vectors. Initialization is done in "setup" and does not require "reset" block. if (!classGenerator.getMappingSet().isHashAggMapping()) { generateBody(classGenerator, BlockType.RESET, reset(), null, workspaceJVars, false); } generateBody(classGenerator, BlockType.CLEANUP, cleanup(), null, workspaceJVars, false); return out; }
Example 23
Project: raml-module-builder File: ClientGenerator.java View source code | 6 votes |
private void addParameter(JBlock methodBody, JVar queryParams, String valueName, Boolean encode, Boolean simple, boolean isList) { JBlock b = methodBody; if (!simple) { JConditional _if = methodBody._if(JExpr.ref(valueName).ne(JExpr._null())); b = _if._then(); } b.invoke(queryParams, "append").arg(JExpr.lit(valueName + "=")); if (encode) { JExpression expr = jCodeModel.ref(java.net.URLEncoder.class).staticInvoke("encode").arg(JExpr.ref(valueName)).arg("UTF-8"); b.invoke(queryParams, "append").arg(expr); } else { if(isList){ b.directStatement("if("+valueName+".getClass().isArray())" +"{queryParams.append(String.join(\"&"+valueName+"=\"," +valueName+"));}"); } else{ b.invoke(queryParams, "append").arg(JExpr.ref(valueName)); } } b.invoke(queryParams, "append").arg(JExpr.lit("&")); }
Example 24
Project: android-modules File: InjectHandler.java View source code | 6 votes |
@Override public void process(Element element, EComponentHolder holder) throws Exception { // I just copied this block from BeanHandler, I'm not sure I understand it TypeMirror typeMirror = annotationHelper.extractAnnotationClassParameter(element); if (typeMirror == null) { typeMirror = element.asType(); typeMirror = holder.processingEnvironment().getTypeUtils().erasure(typeMirror); } JClass injectedClass = refClass(typeMirror.toString()); JFieldRef injectField = ref(element.getSimpleName().toString()); final JBlock initBody = holder.getInitBody(); initBody.assign(injectField, ModuleCodeGenerator.moduleGetInstanceOrAddDefaultIfNeeded(holder, annotationHelper, holder.getGeneratedClass(), holder.getInit(), injectedClass, "", typeHasAnnotation(typeMirror, EBean.class))); // field = Module.getInstance() }
Example 25
Project: springmvc-raml-plugin File: PojoBuilder.java View source code | 6 votes |
private void withEquals() { JMethod equals = this.pojo.method(JMod.PUBLIC, boolean.class, "equals"); JVar otherObject = equals.param(Object.class, "other"); Class<?> equalsBuilderClass = org.apache.commons.lang3.builder.EqualsBuilder.class; if (!config.isUseCommonsLang3()) { equalsBuilderClass = org.apache.commons.lang.builder.EqualsBuilder.class; } JBlock body = equals.body(); body._if(otherObject.eq(JExpr._null()))._then()._return(JExpr.FALSE); body._if(otherObject.eq(JExpr._this()))._then()._return(JExpr.TRUE); body._if(JExpr._this().invoke("getClass").ne(otherObject.invoke("getClass")))._then()._return(JExpr.FALSE); JVar otherObjectVar = body.decl(this.pojo, "otherObject").init(JExpr.cast(this.pojo, otherObject)); JClass equalsBuilderRef = this.pojo.owner().ref(equalsBuilderClass); JInvocation equalsBuilderInvocation = appendFieldsToEquals(getNonTransientAndNonStaticFields(), otherObjectVar, equalsBuilderRef); body._return(equalsBuilderInvocation.invoke("isEquals")); }
Example 26
Project: thrift-java-compiler File: StructCodeGeneratorHelper.java View source code | 6 votes |
private void createMethodFieldIsSet(JDefinedClass _class, Map<String, JType> fields) { JMethod method = _class.method(JMod.PUBLIC, codeModel.BOOLEAN, "isSet"); JClass refEnumFields = codeModel.ref(_class.fullName() + DOT_FIELD); JVar param = method.param(refEnumFields, "field"); method.body()._if(param.eq(JExpr._null()))._then()._throw(JExpr._new(codeModel.ref(IllegalStateException.class))); JSwitch _switch = method.body()._switch(param); for (Map.Entry<String, JType> entry : fields.entrySet()) { JBlock bodyCase = _switch._case(JExpr.ref(entry.getKey().toUpperCase())).body(); String capitalizeName = JavaGeneratorUtil.getCapitalizeString(entry.getKey()); bodyCase._return(JExpr.invoke("isSet" + capitalizeName)); } JInvocation _newException = JExpr._new(codeModel.ref(IllegalStateException.class)); method.body()._throw(_newException); }
Example 27
Project: thrift-java-compiler File: StructCodeGeneratorHelper.java View source code | 6 votes |
private void createMethodFieldSetFieldValue(JDefinedClass _class, Map<String, JType> fields) { JMethod method = _class.method(JMod.PUBLIC, Void.TYPE, "setFieldValue"); JClass refEnumFields = codeModel.ref(_class.fullName() + DOT_FIELD); JVar param = method.param(refEnumFields, "field"); JVar param2 = method.param(codeModel.ref(Object.class), "value"); JBlock body = method.body(); JSwitch _switch = body._switch(param); for (Map.Entry<String, JType> entry : fields.entrySet()) { JBlock bodyCase = _switch._case(JExpr.ref(entry.getKey().toUpperCase())).body(); JConditional _if = bodyCase._if(param2.eq(JExpr._null())); String capitalizeName = JavaGeneratorUtil.getCapitalizeString(entry.getKey()); _if._then().invoke("unset" + capitalizeName); _if._else().invoke("set" + capitalizeName).arg(JExpr.cast(getTypeGetMethodByName(_class, capitalizeName), param2)); bodyCase._break(); } // JInvocation _newException = JExpr._new(codeModel.ref(IllegalStateException.class)); // _switch._default().body()._throw(_newException); }
Example 28
Project: thrift-java-compiler File: StructCodeGeneratorHelper.java View source code | 6 votes |
private void createMethodFielGetFieldValue(JDefinedClass _class, Map<String, JType> fields) { JMethod method = _class.method(JMod.PUBLIC, codeModel.ref(Object.class), "getFieldValue"); JClass refEnumFields = codeModel.ref(_class.fullName() + DOT_FIELD); JVar param = method.param(refEnumFields, "field"); JBlock body = method.body(); JSwitch _switch = body._switch(param); for (Map.Entry<String, JType> entry : fields.entrySet()) { _switch._case(JExpr.ref(entry.getKey().toUpperCase())).body()._return(JExpr.invoke("get" + JavaGeneratorUtil.getCapitalizeString(entry.getKey()))); } JInvocation _newException = JExpr._new(codeModel.ref(IllegalStateException.class)); // _switch._default().body()._throw(_newException); body._throw(_newException); }
Example 29
Project: jsignalml File: JavaClassGen.java View source code | 6 votes |
public JMethod getFormatIDMethod(JDefinedClass klass) { final JMethod method = klass.method(JMod.PUBLIC, String_t, "getFormatID"); final JBlock body = method.body(); comment_stamp(body); final JVar value = body.decl(Type_t, "value", JExpr._this() .invoke(makeGetter("header")) .invoke(makeGetter("format_id")) .invoke("get")); final JVar cast = body.decl(TypeString_t, "cast", JExpr.cast(TypeString_t, value)); body._return(cast.invoke("getValue")); return method; }
Example 30
Project: jsignalml File: JavaClassGen.java View source code | 6 votes |
/** * Print a stack trace of generating method in generating code. * The stacktrace is snipped to include JavaClassGen methods * plus one before. */ private void comment_stamp(Object where) { if (!this._comments) return; final StackTraceElement[] trace = new Throwable().getStackTrace(); final String trigger = JavaClassGen.class.getName(); boolean flag = false; for(int i=trace.length-1; i>=1; i--) { flag |= trace[i-1].getClassName().startsWith(trigger); if (flag || i==1) // print at least one if (where instanceof JBlock) comment((JBlock)where, "%s", trace[i]); else if (where instanceof JDefinedClass) comment((JDefinedClass)where, "%s", trace[i]); else throw new RuntimeException(); } }
Example 31
Project: jsignalml File: JavaClassGen.java View source code | 6 votes |
/** * Print a stack trace of generating method in generating code. * The stacktrace is snipped to include JavaClassGen methods * plus one before. */ private void comment_stamp(Object where) { if (!this._comments) return; final StackTraceElement[] trace = new Throwable().getStackTrace(); final String trigger = JavaClassGen.class.getName(); boolean flag = false; for(int i=trace.length-1; i>=1; i--) { flag |= trace[i-1].getClassName().startsWith(trigger); if (flag || i==1) // print at least one if (where instanceof JBlock) comment((JBlock)where, "%s", trace[i]); else if (where instanceof JDefinedClass) comment((JDefinedClass)where, "%s", trace[i]); else throw new RuntimeException(); } }
Example 32
Project: jsignalml File: JavaClassGen.java View source code | 6 votes |
public JMethod headerFieldMethod(JDefinedClass klass, String method_name, String header_section, String field_name) { final JMethod method = klass.method(JMod.PUBLIC, String_t, method_name); final JBlock body = method.body(); comment_stamp(body); final JVar value = body.decl(Type_t, "value", JExpr._this() .invoke(makeGetter("header")) .invoke(makeGetter(header_section)) .ref(field_name).invoke("get")); // XXX: this implementation is horrible. There's no reason // not to export individual header fields. final JVar cast = body.decl(TypeString_t, "cast", JExpr.cast(TypeString_t, value)); body._return(cast.invoke("getValue")); return method; }
Example 33
Project: jaxb2-basics File: ToStringPlugin.java View source code | 6 votes |
protected JMethod generateObject$toString(final ClassOutline classOutline, final JDefinedClass theClass) { final JCodeModel codeModel = theClass.owner(); final JMethod object$toString = theClass.method(JMod.PUBLIC, codeModel.ref(String.class), "toString"); { final JBlock body = object$toString.body(); final JVar toStringStrategy = body.decl(JMod.FINAL, codeModel.ref(ToStringStrategy2.class), "strategy", createToStringStrategy(codeModel)); final JVar buffer = body.decl(JMod.FINAL, codeModel.ref(StringBuilder.class), "buffer", JExpr._new(codeModel.ref(StringBuilder.class))); body.invoke("append").arg(JExpr._null()).arg(buffer) .arg(toStringStrategy); body._return(buffer.invoke("toString")); } return object$toString; }
Example 34
Project: jaxb2-basics File: ToStringPlugin.java View source code | 6 votes |
protected JMethod generateToString$append(final ClassOutline classOutline, final JDefinedClass theClass) { final JCodeModel codeModel = theClass.owner(); final JMethod toString$append = theClass.method(JMod.PUBLIC, codeModel.ref(StringBuilder.class), "append"); { final JVar locator = toString$append.param(ObjectLocator.class, "locator"); final JVar buffer = toString$append.param(StringBuilder.class, "buffer"); final JVar toStringStrategy = toString$append.param( ToStringStrategy2.class, "strategy"); final JBlock body = toString$append.body(); body.invoke(toStringStrategy, "appendStart").arg(locator) .arg(JExpr._this()).arg(buffer); body.invoke("appendFields").arg(locator).arg(buffer) .arg(toStringStrategy); body.invoke(toStringStrategy, "appendEnd").arg(locator) .arg(JExpr._this()).arg(buffer); body._return(buffer); } return toString$append; }
Example 35
Project: jsignalml File: JavaClassGen.java View source code | 6 votes |
public JMethod loopClassConstructor(JDefinedClass klass, String id, Type type, JDefinedClass indexClass) { final JMethod cons = klass.constructor(JMod.NONE); final JVar index = cons.param(convertTypeToJClass(type), id); final JBlock body = cons.body(); comment_stamp(body); klass.field(JMod.FINAL, indexClass, "index"); // work around bug in jcodemodel on using index instead of this.index body.assign(JExpr.refthis("index"), JExpr._new(indexClass).arg(index)); body.add(JExpr.invoke("register").arg(id) .arg(JExpr.refthis("index"))); return cons; }
Example 36
Project: jsignalml File: JavaClassGen.java View source code | 6 votes |
JMethod _cacheMethod(JDefinedClass parent, JClass klass, String id, String methodname, JExpression init) { final JFieldVar stor = parent.field(JMod.NONE, klass, methodname, JExpr._null()); final JMethod getter = parent.method(JMod.PUBLIC, klass, methodname); comment_stamp(getter.body()); final JBlock then = getter.body()._if(stor.eq(JExpr._null()))._then(); then.assign(stor, init); if (id != null) then.add(JExpr.invoke("register").arg(id).arg(stor)); if (ChannelSet_t.isAssignableFrom(klass)) then.add(JExpr.invoke("registerChannelSet").arg(stor)); if (Channel_t.isAssignableFrom(klass)) then.add(JExpr.invoke("registerChannel").arg(stor)); getter.body()._return(stor); return getter; }
Example 37
Project: jaxb2-basics File: JAXBElementCodeGenerator.java View source code | 6 votes |
@Override public void generate(JBlock block, JType type, Collection<JType> possibleTypes, boolean isAlwaysSet, A arguments) { Validate.isInstanceOf(JClass.class, type); final JClass _class = (JClass) type; // Get the T from JAXBElement<T> final JClass valueType = getValueType(_class); // Gather possible values types final Set<JType> possibleValueTypes = getPossibleValueTypes(possibleTypes); onJAXBElement(block, valueType, possibleValueTypes, isAlwaysSet, arguments); }
Example 38
Project: jaxb2-basics File: JAXBElementCodeGenerator.java View source code | 6 votes |
private void append(JBlock block, String propertyName, String propertyMethod, JType propertyType, Collection<JType> possiblePropertyTypes, A arguments) { block = block.block(); final JType declarablePropertyType = getTypeFactory().create( propertyType).getDeclarableType(); // We assume that primitive properties are always set boolean isAlwaysSet = propertyType.isPrimitive(); getCodeGenerator().generate( block, propertyType, possiblePropertyTypes, isAlwaysSet, arguments.property(block, propertyName, propertyMethod, declarablePropertyType, declarablePropertyType, possiblePropertyTypes)); }
Example 39
Project: rice File: ImmutableJaxbGenerator.java View source code | 6 votes |
private void renderBuilderCreateContract(JDefinedClass builderClass, JClass literalBuilderClass, List<FieldModel> fields, Class<?> contractInterface) { JMethod createContractMethod = builderClass.method(JMod.PUBLIC | JMod.STATIC, literalBuilderClass, "create"); JVar contractParam = createContractMethod.param(contractInterface, "contract"); JBlock body = createContractMethod.body(); JConditional nullContractCheck = body._if(contractParam.eq(JExpr._null())); nullContractCheck._then().directStatement("throw new IllegalArgumentException(\"contract was null\");"); body.directStatement("// TODO if create() is modified to accept required parameters, this will need to be modified"); body.directStatement("Builder builder = create();"); for (FieldModel fieldModel : fields) { String fieldName = fieldModel.fieldName; body.directStatement("builder." + Util.generateSetter(fieldName, "contract." + Util.generateGetter(fieldName, isBoolean(fieldModel.fieldType))) + ";"); } body.directStatement("return builder;"); }
Example 40
Project: jaxb2-basics File: EqualsArguments.java View source code | 6 votes |
public EqualsArguments property(JBlock block, String propertyName, String propertyMethod, JType declarablePropertyType, JType propertyType, Collection<JType> possiblePropertyTypes) { final JVar leftPropertyValue = block.decl(JMod.FINAL, declarablePropertyType, leftValue().name() + propertyName, leftValue().invoke(propertyMethod)); final JVar rightPropertyValue = block.decl(JMod.FINAL, declarablePropertyType, rightValue().name() + propertyName, rightValue().invoke(propertyMethod)); // We assume that primitive properties are always set boolean isAlwaysSet = propertyType.isPrimitive(); final JExpression leftPropertyHasSetValue = isAlwaysSet ? JExpr.TRUE : leftPropertyValue.ne(JExpr._null()); final JExpression rightPropertyHasSetValue = isAlwaysSet ? JExpr.TRUE : rightPropertyValue.ne(JExpr._null()); return spawn(leftPropertyValue, leftPropertyHasSetValue, rightPropertyValue, rightPropertyHasSetValue); }