Refine search
private void addEquals(JDefinedClass jclass, JsonNode node) { Map<String, JFieldVar> fields = removeFieldsExcludedFromEqualsAndHashCode(jclass.fields(), node); JMethod equals = jclass.method(JMod.PUBLIC, boolean.class, "equals"); JVar otherObject = equals.param(Object.class, "other"); JBlock body = equals.body(); JVar rhsVar = body.decl(jclass, "rhs").init(JExpr.cast(jclass, otherObject)); JExpression result = JExpr.lit(true); JClass doubleClass = jclass.owner().ref(Double.class); fieldEquals = doubleClass.staticInvoke("doubleToLongBits").arg(thisFieldRef).eq( doubleClass.staticInvoke("doubleToLongBits").arg(otherFieldRef)); } else if ("float".equals(fieldVar.type().name())) { JClass floatClass = jclass.owner().ref(Float.class); fieldEquals = floatClass.staticInvoke("floatToIntBits").arg(thisFieldRef).eq( floatClass.staticInvoke("floatToIntBits").arg(otherFieldRef)); fieldEquals = jclass.owner().ref(Arrays.class).staticInvoke("equals").arg(thisFieldRef).arg(otherFieldRef); } else { fieldEquals = thisFieldRef.eq(otherFieldRef).cor( body._return(result); equals.annotate(Override.class);
JCodeModel cm = new JCodeModel(); JDefinedClass dc = cm._class("foo.Bar"); JMethod m = dc.method(0, int.class, "foo"); m.body()._return(JExpr.lit(5)); File file = new File("./target/classes"); file.mkdirs(); cm.build(file);
public JType generate(JCodeModel codeModel, String className, String packageName, String json, URI schemaLocation) throws IOException { JPackage jpackage = codeModel._package(packageName); JsonNode schemaNode = objectMapper().readTree(json); return ruleFactory.getSchemaRule().apply(className, schemaNode, null, jpackage, new Schema(schemaLocation, schemaNode, null)); }
JVar oiArray = sub.decl( m._ref(ObjectInspector[].class), "argOIs", JExpr.newArray(m._ref(ObjectInspector.class), argTypes.length)); JClass oih = m.directClass(ObjectInspectorHelper.class.getCanonicalName()); JClass mt = m.directClass(TypeProtos.MinorType.class.getCanonicalName()); JClass mode = m.directClass(DataMode.class.getCanonicalName()); for(int i=0; i<argTypes.length; i++) { sub.assign( oiArray.component(JExpr.lit(i)), oih.staticInvoke("getDrillObjectInspector") .arg(mode.staticInvoke("valueOf").arg(JExpr.lit(argTypes[i].getMode().getNumber()))) .arg(mt.staticInvoke("valueOf").arg(JExpr.lit(argTypes[i].getMinorType().getNumber()))) .arg((((PrimitiveObjectInspector) returnOI).getPrimitiveCategory() == PrimitiveObjectInspector.PrimitiveCategory.STRING) ? JExpr.lit(true) : JExpr.lit(false))); sub.assign(workspaceJVars[2], JExpr.newArray(m._ref(DrillDeferredObject.class), argTypes.length)); sub.assign( workspaceJVars[2].component(JExpr.lit(i)), JExpr._new(m.directClass(DrillDeferredObject.class.getCanonicalName()))); sub.assign(workspaceJVars[3], JExpr.newArray(m._ref(DrillDeferredObject.class), argTypes.length)); JCatchBlock udfInitCatch = udfInitTry._catch(m.directClass(Exception.class.getCanonicalName())); JVar exVar = udfInitCatch.param("ex"); udfInitCatch.body() ._throw(JExpr._new(m.directClass(RuntimeException.class.getCanonicalName()))
private JDefinedClass createEnum(JsonNode node, String nodeName, JClassContainer container) throws ClassAlreadyExistsException { try { if (node.has("javaType")) { String fqn = node.get("javaType").asText(); if (isPrimitive(fqn, container.owner())) { throw new GenerationException("Primitive type '" + fqn + "' cannot be used as an enum."); } try { Class<?> existingClass = Thread.currentThread().getContextClassLoader().loadClass(fqn); throw new ClassAlreadyExistsException(container.owner().ref(existingClass)); } catch (ClassNotFoundException e) { return container.owner()._class(fqn, ClassType.ENUM); } } else { try { return container._class(JMod.PUBLIC, getEnumName(nodeName, node, container), ClassType.ENUM); } catch (JClassAlreadyExistsException e) { throw new GenerationException(e); } } } catch (JClassAlreadyExistsException e) { throw new ClassAlreadyExistsException(e.getExistingClass()); } }
JBlock body = toString.body(); JClass stringBuilderClass = jclass.owner().ref(StringBuilder.class); JVar sb = body.decl(stringBuilderClass, "sb", JExpr._new(stringBuilderClass)); body.add(sb .invoke("append").arg(jclass.dotclass().invoke("getName")) .invoke("append").arg(JExpr.lit('@')) .invoke("append").arg( jclass.owner().ref(Integer.class).staticInvoke("toHexString").arg( jclass.owner().ref(System.class).staticInvoke("identityHashCode").arg(JExpr._this()))) .invoke("append").arg(JExpr.lit('['))); if (!jclass._extends().fullName().equals(Object.class.getName())) { JVar baseLength = body.decl(jclass.owner().INT, "baseLength", sb.invoke("length")); JVar superString = body.decl(jclass.owner().ref(String.class), "superString", JExpr._super().invoke("toString")); JBlock superToStringBlock = body._if(superString.ne(JExpr._null()))._then(); JExpr.refthis(fieldVar.name()).eq(JExpr._null()), JExpr.lit("<null>"), jclass.owner().ref(Arrays.class).staticInvoke("toString") .arg(JExpr.refthis(fieldVar.name())) .invoke("replace").arg(JExpr.lit('[')).arg(JExpr.lit('{')) body._return(sb.invoke("toString")); toString.annotate(Override.class);
private void addHashCode(JDefinedClass jclass, JsonNode node) { Map<String, JFieldVar> fields = removeFieldsExcludedFromEqualsAndHashCode(jclass.fields(), node); JFieldRef fieldRef = JExpr.refthis(fieldVar.name()); fieldHash = fieldRef; } else if ("double".equals(fieldVar.type().name())) { JClass doubleClass = jclass.owner().ref(Double.class); JExpression longField = doubleClass.staticInvoke("doubleToLongBits").arg(fieldRef); fieldHash = JExpr.cast(jclass.owner().INT, longField.xor(longField.shrz(JExpr.lit(32)))); } else if ("float".equals(fieldVar.type().name())) { fieldHash = jclass.owner().ref(Float.class).staticInvoke("floatToIntBits").arg(fieldRef); } else { fieldHash = JExpr.cast(jclass.owner().INT, fieldRef); fieldHash = jclass.owner().ref(Arrays.class).staticInvoke("hashCode").arg(fieldRef); } else { fieldHash = JOp.cond(fieldRef.eq(JExpr._null()), JExpr.lit(0), fieldRef.invoke("hashCode")); body.assign(result, result.mul(JExpr.lit(31)).plus(fieldHash)); if (!jclass._extends().fullName().equals(Object.class.getName())) { body.assign(result, result.mul(JExpr.lit(31)).plus(JExpr._super().invoke("hashCode"))); body._return(result); hashCode.annotate(Override.class);
private JMethod addInternalGetMethodJava6(JDefinedClass jclass, JsonNode propertiesNode) { JMethod method = jclass.method(PROTECTED, jclass.owner()._ref(Object.class), DEFINED_GETTER_NAME); JVar nameParam = method.param(String.class, "name"); JVar notFoundParam = method.param(jclass.owner()._ref(Object.class), "notFoundValue"); JBlock body = method.body(); JConditional propertyConditional = null; JType propertyType = jclass.fields().get(fieldName).type(); JExpression condition = lit(propertyName).invoke("equals").arg(nameParam); if (propertyConditional == null) { propertyConditional = body._if(condition); } else { propertyConditional = propertyConditional._elseif(condition); JMethod propertyGetter = jclass.getMethod(getGetterName(propertyName, propertyType, node), new JType[] {}); propertyConditional._then()._return(invoke(propertyGetter)); JDefinedClass parentClass = (JDefinedClass) extendsType; JMethod parentMethod = parentClass.getMethod(DEFINED_GETTER_NAME, new JType[] { parentClass.owner()._ref(String.class), parentClass.owner()._ref(Object.class) }); lastBlock._return(_super().invoke(parentMethod).arg(nameParam).arg(notFoundParam)); } else { lastBlock._return(notFoundParam);
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; }
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(_enum, fromValue); }
public JCodeModel generate(JCodeModel jCodeModel, RefHelper ref) throws IOException { try { jClass = jCodeModel._class(appDetails.getViewPagerAdapterPackage()); jClass._extends(ref.fragmentPagerAdapter()); if (hasLocationsField) { locationsField = jClass.field(JMod.PRIVATE, ref.string().array(), "locations"); JBlock constructorBody = constructor.body(); constructorBody.directStatement("super(fm);"); constructorBody.assign(JExpr._this().ref("locations"), locationsField); if (hasLocationsField) { getCountMethodBody._return(locationsField.ref("length")); } else { JVar fragmentVar = getItemMethodBody.decl(ref.fragment(), "fragment", JExpr._new(ref.ref(sampleFragmentPackage))); JVar bundleVar = getItemMethodBody.decl(ref.bundle(), "bundle", JExpr._new(ref.bundle())); getItemMethodBody.invoke(fragmentVar, "setArguments").arg(bundleVar);
private JMethod addInternalGetMethodJava7(JDefinedClass jclass, JsonNode propertiesNode) { JMethod method = jclass.method(PROTECTED, jclass.owner()._ref(Object.class), DEFINED_GETTER_NAME); JVar nameParam = method.param(String.class, "name"); JVar notFoundParam = method.param(jclass.owner()._ref(Object.class), "notFoundValue"); JBlock body = method.body(); JSwitch propertySwitch = body._switch(nameParam); if (propertiesNode != null) { for (Iterator<Map.Entry<String, JsonNode>> properties = propertiesNode.fields(); properties.hasNext();) { Map.Entry<String, JsonNode> property = properties.next(); String propertyName = property.getKey(); JsonNode node = property.getValue(); String fieldName = ruleFactory.getNameHelper().getPropertyName(propertyName, node); JType propertyType = jclass.fields().get(fieldName).type(); addGetPropertyCase(jclass, propertySwitch, propertyName, propertyType, node); } } JClass extendsType = jclass._extends(); if (extendsType != null && extendsType instanceof JDefinedClass) { JDefinedClass parentClass = (JDefinedClass) extendsType; JMethod parentMethod = parentClass.getMethod(DEFINED_GETTER_NAME, new JType[] { parentClass.owner()._ref(String.class), parentClass.owner()._ref(Object.class) }); propertySwitch._default().body() ._return(_super().invoke(parentMethod).arg(nameParam).arg(notFoundParam)); } else { propertySwitch._default().body() ._return(notFoundParam); } return method; }
jClass = jCodeModel._class(appDetails.getSampleFragmentPackage()); jClass._extends(ref.ref(appDetails.getRoboSherlockFragmentPackage())); } else if (appDetails.isRoboguice()) { jClass._extends(ref.roboFragment()); } else { jClass._extends(ref.fragment()); if (appDetails.isAndroidAnnotations()) { jClass.annotate(ref.efragment()).param("value", ref.r().staticRef("layout").ref("fragment_sample")); JMethod onCreateViewMethod = jClass.method(JMod.NONE, jCodeModel.VOID, "afterViews"); onCreateViewMethod.annotate(ref.afterViews()); onCreateViewMethodBody = onCreateViewMethod.body(); JFieldRef field = ref.r().staticRef("id").ref("label_text"); injectViewAnnotation.param("value", field); onCreateViewMethodBody = onCreateViewMethod.body(); onCreateViewMethodBody._return(inflateView(inflaterParam, containerParam)); onViewCreatedMethodBody.invoke(JExpr._super(), "onViewCreated").arg(viewParam).arg(savedInstanceStateParam); JVar contentViewVar = onCreateViewMethodBody.decl(ref.view(), "contentView", inflateInvoke);
JBlock sub = new JBlock(true, true); 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()); JVar retVal = sub.decl(m._ref(Object.class), "ret"); 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));
static private void createCopyMethod(JDefinedClass clazz){ JCodeModel codeModel = clazz.owner(); JClass reportClazz = codeModel.ref("org.jpmml.evaluator.Report"); JMethod method = clazz.method(JMod.PUBLIC, clazz, "copy"); method.annotate(Override.class); JBlock body = method.body(); JVar reportVariable = body.decl(reportClazz, "report", JExpr.invoke("getReport")); body._return(JExpr._new(clazz).arg(JExpr._super().ref("value")).arg(reportVariable.invoke("copy")).arg(JExpr._null())); }
private JFieldVar addQuickLookupMap(JDefinedClass _enum, JType backingType) { JClass lookupType = _enum.owner().ref(Map.class).narrow(backingType.boxify(), _enum); JFieldVar lookupMap = _enum.field(JMod.PRIVATE | JMod.STATIC | JMod.FINAL, lookupType, "CONSTANTS"); JClass lookupImplType = _enum.owner().ref(HashMap.class).narrow(backingType.boxify(), _enum); lookupMap.init(JExpr._new(lookupImplType)); JForEach forEach = _enum.init().forEach(_enum, "c", JExpr.invoke("values")); JInvocation put = forEach.body().invoke(lookupMap, "put"); put.arg(forEach.var().ref("value")); put.arg(forEach.var()); return lookupMap; }
private void addEquals(JDefinedClass jclass) { JMethod equals = jclass.method(JMod.PUBLIC, boolean.class, "equals"); JVar otherObject = equals.param(Object.class, "other"); JBlock body = equals.body(); JInvocation reflectionEquals = jclass.owner().ref(EqualsBuilder.class).staticInvoke("reflectionEquals"); reflectionEquals.arg(JExpr._this()); reflectionEquals.arg(otherObject); body._return(reflectionEquals); equals.annotate(Override.class); }
private JMethod addGetter(JDefinedClass c, JFieldVar field, String jsonPropertyName, JsonNode node, boolean isRequired, boolean usesOptional) { JType type = getReturnType(c, field, isRequired, usesOptional); JMethod getter = c.method(JMod.PUBLIC, type, getGetterName(jsonPropertyName, field.type(), node)); JBlock body = getter.body(); if ((ruleFactory.getGenerationConfig().isUseOptionalForGetters() || usesOptional) && !isRequired && field.type().isReference()) { body._return(c.owner().ref("java.util.Optional").staticInvoke("ofNullable").arg(field)); } else { body._return(field); } return getter; }
JClass listGenericType = ((JClass) fieldType).getTypeParameters().get(0); JClass listImplClass = fieldType.owner().ref(ArrayList.class); listImplClass = listImplClass.narrow(listGenericType); JInvocation newListImpl = JExpr._new(listImplClass); JInvocation invokeAsList = fieldType.owner().ref(Arrays.class).staticInvoke("asList"); for (JsonNode defaultValue : node) { invokeAsList.arg(getDefaultValue(listGenericType, defaultValue)); newListImpl.arg(invokeAsList); } else if (!ruleFactory.getGenerationConfig().isInitializeCollections()) { return JExpr._null();
public JCodeModel generate(JCodeModel jCodeModel, RefHelper ref) throws IOException { logger = LoggerFactory.getLogger(getClass()); try { jClass = jCodeModel._class(appDetails.getApplicationPackage()); jClass._extends(ref.application()); jClass.annotate(ref.reportsCrashes()).param("formKey", "YOUR_FORM_KEY"); JMethod onCreateMethod = jClass.method(JMod.PUBLIC, jCodeModel.VOID, "onCreate"); onCreateMethod.annotate(ref.override()); JBlock onCreateMethodBody = onCreateMethod.body(); onCreateMethodBody.staticInvoke(ref.acra(), "init").arg(JExpr._this()); onCreateMethodBody.invoke(JExpr._super(), "onCreate"); } catch (JClassAlreadyExistsException e1) { logger.error("Classname already exists", e1); } return jCodeModel; }