private void addEnumConstants(JsonNode node, JDefinedClass _enum, JsonNode customNames, JType type) { Collection<String> existingConstantNames = new ArrayList<String>(); for (int i = 0; i < node.size(); i++) { JsonNode value = node.path(i); if (!value.isNull()) { String constantName = getConstantName(value.asText(), customNames.path(i).asText()); constantName = makeUnique(constantName, existingConstantNames); existingConstantNames.add(constantName); JEnumConstant constant = _enum.enumConstant(constantName); constant.arg(DefaultRule.getDefaultValue(type, value)); ruleFactory.getAnnotator().enumConstant(constant, value.asText()); } } }
@SuppressWarnings("unchecked") @Test public void shouldFindEnumValues() throws IllegalAccessException { klass = modelPackage._getClass("Colour"); assertThat(klass.getClassType()).isEqualTo(ClassType.ENUM); Map<String,JEnumConstant> enums = (Map<String, JEnumConstant>) FieldUtils.readField(klass, "enumConstantsByName", true); assertThat(enums.keySet()).contains("LIGHT_BLUE", "RED"); JEnumConstant lightBlue = enums.get("LIGHT_BLUE"); assertThat(lightBlue.javadoc().get(0)).isEqualTo("Colour of the sky"); List<JExpression> args = (List<JExpression>) FieldUtils.readField(lightBlue, "args", true); assertThat(args).hasSize(1); assertThat(args.get(0)).isInstanceOf(JStringLiteral.class); String literal = (String) FieldUtils.readField(args.get(0), "str", true); assertThat(literal).isEqualTo("lightBlue"); }
@Override public void caseAEnumConstant(AEnumConstant node) { // TypeModifierAdapter modap = new TypeModifierAdapter(); // for (PModifier m : node.getModifier()) { // m.apply(modap); // } // int mods = modap.getMods(); if (!node.getModifier().isEmpty()) { Logger.error(context.getFile(), node.getIdentifier(), "CodeModel does not support modifiers for enum constants, yet..."); } JEnumConstant ec = clazz.enumConstant(node.getIdentifier().getText()); EnumArgumentable ea = new EnumArgumentable(ec); for (PArgument arg : node.getArgument()) { ArgumentAdapter aa = new ArgumentAdapter(ea, context); arg.apply(aa); } if (node.getClassBody() != null) { Logger.error(context.getFile(), node.getIdentifier(), "CodeModel does not support class bodies for enum constants, yet..."); } }
private JEnumConstant defineAction(Action a){ String name = this.getActionEnumName(a); JEnumConstant actionConst = actionsEnum.enumConstant(name); if(definedActions.contains(a)){ return actionConst; } JBlock body = advanceActionSwitch._case(JExpr.ref(name)).body(); switch(a.id()){ case ACCEPT: body._return(f.getStatusEnum().staticRef("COMPLETE")); break; case GOTO: this.defineShiftGotoAction(a, body); break; case REDUCE: this.defineReduceAction(a, body); break; case SHIFT: this.defineShiftGotoAction(a, body); break; default: throw new Error(); } definedActions.add(a); return actionConst; }
private JDefinedClass buildEnumClass(String enumName, List<String> values) throws JClassAlreadyExistsException { if (pkg.isDefined(enumName)) { return pkg._getClass(enumName); } JDefinedClass valueEnum = pkg._enum(enumName); JFieldVar valField = valueEnum.field(JMod.PRIVATE | JMod.FINAL, String.class, "value"); JMethod ctor = valueEnum.constructor(JMod.PRIVATE); JVar param = ctor.param(String.class, "val"); ctor.body().assign(valField, param); JMethod toString = valueEnum.method(JMod.PUBLIC, String.class, "toString"); toString.annotate(Override.class); toString.body()._return(valField); for (String value : values) { JEnumConstant sortCnst = valueEnum.enumConstant(value.toUpperCase().replace(' ', '_')); sortCnst.arg(JExpr.lit(value)); } return valueEnum; }
private void generateEnumConstant(JDefinedClass klass, EnumValue enumValue) { JEnumConstant constant = klass.enumConstant(Names.buildConstantName(enumValue.getName())) .arg(JExpr.lit(enumValue.getName())); if (context.getConfig().isJacksonPropertyName()) { constant.annotate(JsonProperty.class).param(VALUE, enumValue.getName()); } if (enumValue.getDescription() != null) { constant.javadoc().add(enumValue.getDescription()); } }
@SuppressWarnings("unchecked") @Test public void shouldFindEnumValues() throws IllegalAccessException { klass = modelPackage._getClass("Colour"); assertThat(klass.getClassType()).isEqualTo(ClassType.ENUM); Map<String,JEnumConstant> enums = (Map<String, JEnumConstant>) FieldUtils.readField(klass, "enumConstantsByName", true); assertThat(enums.keySet()).containsExactly("LIGHT_BLUE", "RED", "YELLOW", "GREEN"); }
@SuppressWarnings("unused") private void parseEnumMember(Element root, ParsingContext context) { JDefinedClass enumClass = (JDefinedClass) context.getCmNode(); JEnumConstant enumConstant = enumClass.enumConstant( NameUtils.camelToUpper(enumClass.name()) + '_' + root.getAttributeValue("name").toUpperCase() ); long value = Long.parseLong(root.getAttributeValue("value")); enumConstant.arg(JExpr.lit(value)); System.out.println("--> " + enumConstant.getName() + " (" + value + ")"); }
public <T> EnumBuilder withEnum(T name, Class<T> type) { pojoCreationCheck(); String cleaned = NamingHelper.cleanNameForJavaEnum(name.toString()); if (!doesEnumContainField(type, cleaned)) { withValueField(type); ENUM_CACHE.put(cleaned, true); logger.debug("Adding field: " + name + " to " + this.pojo.name()); if (StringUtils.hasText(cleaned)) { JEnumConstant enumConstant = this.pojo.enumConstant(cleaned); if (type.equals(Integer.class)) { enumConstant.arg(JExpr.lit((Integer)name)); } else if (type.equals(Boolean.class)) { enumConstant.arg(JExpr.lit((Boolean)name)); } else if (type.equals(Double.class)) { enumConstant.arg(JExpr.lit((Double)name)); } else if (type.equals(Float.class)) { enumConstant.arg(JExpr.lit((Float)name)); } else if (type.equals(Long.class)) { enumConstant.arg(JExpr.lit((Long)name)); } else { enumConstant.arg(JExpr.lit(name.toString())); enumConstant.annotate(JsonProperty.class).param("value", name.toString()); } } } return this; }
public CMEnumConstantOutline(MEnumOutline enumOutline, MEnumConstantInfo<NType, NClass> target, JEnumConstant code) { Validate.notNull(enumOutline); Validate.notNull(target); Validate.notNull(code); this.enumOutline = enumOutline; this.target = target; this.code = code; }
private JDefinedClass generateEnum(EnumDataSchema schema) throws JClassAlreadyExistsException { JDefinedClass enumClass = getPackage(schema.getNamespace())._class(JMod.PUBLIC, escapeReserved(schema.getName()), ClassType.ENUM); enumClass.javadoc().append(schema.getDoc()); setDeprecatedAnnotationAndJavadoc(schema, enumClass); registerGeneratedClass(schema, enumClass); generateSchemaField(enumClass, schema); for (String value: schema.getSymbols()) { if (isReserved(value)) { throw new IllegalArgumentException("Enum contains Java reserved symbol: " + value + " schema: " + schema); } JEnumConstant enumConstant = enumClass.enumConstant(value); String enumConstantDoc = schema.getSymbolDocs().get(value); if (enumConstantDoc != null) { enumConstant.javadoc().append(enumConstantDoc); } setDeprecatedAnnotationAndJavadoc(schema, value, enumConstant); } enumClass.enumConstant(DataTemplateUtil.UNKNOWN_ENUM); return enumClass; }
private void setDeprecatedAnnotationAndJavadoc(EnumDataSchema enumSchema, String symbol, JEnumConstant constant) { Object deprecatedSymbolsProp = enumSchema.getProperties().get(DEPRECATED_SYMBOLS_KEY); if (deprecatedSymbolsProp instanceof DataMap) { DataMap deprecatedSymbols = (DataMap)deprecatedSymbolsProp; Object deprecatedProp = deprecatedSymbols.get(symbol); setDeprecatedAnnotationAndJavadoc(deprecatedProp, constant, constant); } }
private JMethod createStateActionMethod(State s){ JMethod method = clazz.method(JMod.PRIVATE, actionsEnum, "getState"+stateIndex.get(s)+"Action"); JVar lookahead = method.param(f.getNodeInterface().narrow(nodes.getVisitorInterface()), "lookahead"); JSwitch sw = method.body()._switch(symbolGen.castTo(JExpr.invoke(lookahead, "symbol"))); List<JExpression> expected = new ArrayList<JExpression>(); //add a case statement for each valid lookahead symbol for(String symbol : nodes.getAllSymbols()){ Action a = table.getAction(s, symbol); if(a != null){ JEnumConstant actionConst = this.defineAction(a); sw._case(symbolGen.getRef(symbol)).body()._return(actionConst); expected.add(symbolGen.getSymbolObj(symbol)); } } //the default case should return error action sw._default().body()._return(actionsEnum.enumConstant("ERROR")); JArray array = JExpr.newArray(f.getSymbolInterface()); for(JExpression exp : expected){ array.add(exp); } expectedStateSwitch._case(JExpr.lit(stateIndex.get(s))) .body()._return(array); return method; }
public JExpression getSymbolObj(String symbol){ JEnumConstant obj = enums.get(symbol); if(obj == null){ obj = clazz.enumConstant(symbol.toUpperCase()); String pseudo = g.getPseudonym(symbol); if(pseudo != null){ obj.arg(JExpr.lit(pseudo)); } enums.put(symbol, obj); } return obj; }
private JClass getParamTypeEnum(Filter filter) throws JClassAlreadyExistsException { String enumName = camel(filter.getName(), true) + "Option"; if (pkg.isDefined(enumName)) { return pkg._getClass(enumName); } List<Option> options = filter.getOption(); if (options.size() == 1) {/*turn into '*Only' method?*/} if (options.size() == 2) { if (ImmutableSet.of("true","false").equals( ImmutableSet.of(options.get(0).getValue().toLowerCase(), options.get(1).getValue().toLowerCase() ) )) { return model.ref(Boolean.class); } } JDefinedClass valueEnum = pkg._enum(enumName); JFieldVar valField = valueEnum.field(JMod.PRIVATE|JMod.FINAL, String.class, "value"); JMethod ctor = valueEnum.constructor(JMod.PRIVATE); JVar param = ctor.param(String.class, "val"); ctor.body().assign(valField, param); JMethod toString = valueEnum.method(JMod.PUBLIC, String.class, "toString"); toString.annotate(Override.class); toString.body()._return(valField); for (Option option : options) { String optionName = option.getValue().toUpperCase().replace(' ', '_'); JEnumConstant optionCst = valueEnum.enumConstant(optionName); optionCst.arg(JExpr.lit(option.getValue())); } return valueEnum; }
private void addEnumConstants(JsonNode node, JDefinedClass _enum) { for (Iterator<JsonNode> values = node.elements(); values.hasNext();) { JsonNode value = values.next(); if (!value.isNull()) { JEnumConstant constant = _enum.enumConstant(getConstantName(value.asText())); constant.arg(JExpr.lit(value.asText())); } } }
@Override public void enumConstant(JEnumConstant constant, String value) { constant.annotate(Json.class).param("name", value); }
@Override public void enumConstant(JEnumConstant constant, String value) { constant.annotate(SerializedName.class).param("value", value); }
@Override public void enumConstant(JEnumConstant constant, String value) { for (Annotator annotator : annotators) { annotator.enumConstant(constant, value); } }
@Override public void enumConstant(JEnumConstant constant, String value) { }
@Override public void enumConstant(JEnumConstant constant, String value) { constant.annotate(Deprecated.class); }
EnumArgumentable(JEnumConstant ec) { this.ec = ec; }
public JEnumConstant getCode() { return code; }
/** * Generates an enum for a given field * * @param f * @param name * of enum in UpperCamelCase * @return * @throws JClassAlreadyExistsException */ public JDefinedClass generateEnum(ApplicationField f, String name) throws JClassAlreadyExistsException { JDefinedClass result = jp != null ? jp._enum(name) : jc._package("")._enum(name); result._implements(PodioCategory.class); // fields: JFieldVar podioId = result.field(JMod.PRIVATE, jc.INT, "podioId"); JFieldVar value = result.field(JMod.PRIVATE, jc.ref(String.class), "value"); // constructor: JMethod constructor = result.constructor(JMod.PRIVATE); JVar constructorPodioIdParam = constructor.param(jc.INT, "podioId"); JVar constructorToStringParam = constructor.param(jc.ref(String.class), "value"); constructor.body().assign(JExpr._this().ref(podioId), constructorPodioIdParam); constructor.body().assign(JExpr._this().ref(value), constructorToStringParam); // toString: result.method(JMod.PUBLIC, String.class, "toString").body()._return(value); // getId: result.method(JMod.PUBLIC, jc.INT, "getPodioId").body()._return(podioId); // static byId: JMethod byId = result.method(JMod.PUBLIC | JMod.STATIC, result, "byId"); byId.javadoc().addReturn().add("{@code null}, if no element with given {@code id} exists."); JVar byIdParam = byId.param(jc.INT, "podioId"); JForEach forEach = byId.body().forEach(result, "e", result.staticInvoke("values")); forEach.body()._if(byIdParam.eq(forEach.var().invoke("getPodioId")))._then()._return(forEach.var()); byId.body()._return(JExpr._null()); // literals: result.enumConstant("NONE").arg(JExpr.lit(0)).arg(JExpr.lit("--")); for (CategoryOption option : f.getConfiguration().getSettings().getOptions()) { String constantName = JavaNames.createValidJavaTypeName(option.getText(), name); String finalConstantName = CaseFormat.UPPER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, constantName); JEnumConstant constant = result.enumConstant(finalConstantName); constant.arg(JExpr.lit(option.getId())).arg(JExpr.lit(option.getText())); if (option.getStatus().equals(CategoryOptionStatus.DELETED)) { constant.annotate(Deprecated.class); } } return result; }
/** * Add the necessary annotations to an enum constant. For instance, to force * the the given value to be used when serializing. */ void enumConstant(JEnumConstant constant, String value);
public JEnumConstant getCode();