@Test
 public void testLoadedInterfaceNoMembers() throws Exception {
   String[] namesToLoad =
       new String[] {
         "InterfaceA.json", "AImpl.json",
       };
   List<ObjectSchema> schemaList = new ArrayList<ObjectSchema>();
   for (String name : namesToLoad) {
     String fileString =
         FileUtils.loadFileAsStringFromClasspath(
             PojoGeneratorDriverTest.class.getClassLoader(), name);
     ObjectSchema schema = new ObjectSchema(new JSONObjectAdapterImpl(fileString));
     schema.setId(schema.getName());
     schemaList.add(schema);
   }
   JCodeModel codeModel = new JCodeModel();
   driver.createAllClasses(codeModel, schemaList);
   // Get the class
   JPackage _package = codeModel._package("");
   JDefinedClass impl = null;
   try {
     impl = _package._class("AImpl");
   } catch (JClassAlreadyExistsException e) {
     impl = e.getExistingClass();
   }
   String classString = declareToString(impl);
   //		System.out.println(classString);
   Map<String, JFieldVar> fields = impl.fields();
   assertNotNull(fields);
   assertNotNull(fields.get("fromInterfaceA"));
   assertNotNull(fields.get("alsoFromInterfaceA"));
 }
Exemplo n.º 2
0
  /**
   * Creates the getter and setter methods on the supplied class for the supplied name.
   *
   * @param clazz to put getter and setter methods on
   * @param name of the property
   * @param syntaxType of the property
   * @param multivalue whether this property is a collection
   */
  protected void createMutators(
      final JDefinedClass clazz,
      final String name,
      final Class<?> syntaxType,
      final boolean multivalue) {
    final String upperName = name.substring(0, 1).toUpperCase() + name.substring(1, name.length());
    if (multivalue) {
      final JClass detailClass = codeModel.ref(syntaxType);
      final JClass collectionClass = codeModel.ref(Collection.class);
      final JClass genericClass = collectionClass.narrow(detailClass);
      final JFieldVar field = clazz.field(JMod.PRIVATE, genericClass, name);
      final JMethod getterMethod = clazz.method(JMod.PUBLIC, genericClass, "get" + upperName);
      getterMethod.body()._return(field);

      final JMethod setterMethod = clazz.method(JMod.PUBLIC, Void.TYPE, "set" + upperName);
      setterMethod.param(genericClass, "c");
      setterMethod.body().assign(JExpr._this().ref(name), JExpr.ref("c"));

    } else {
      final JFieldVar field = clazz.field(JMod.PRIVATE, syntaxType, name);
      final JMethod getterMethod = clazz.method(JMod.PUBLIC, syntaxType, "get" + upperName);
      getterMethod.body()._return(field);

      final JMethod setterMethod = clazz.method(JMod.PUBLIC, Void.TYPE, "set" + upperName);
      setterMethod.param(syntaxType, "s");
      setterMethod.body().assign(JExpr._this().ref(name), JExpr.ref("s"));
    }
  }
Exemplo n.º 3
0
  /**
   * Process the root WADL file and generate code.
   *
   * @param rootDesc the URI of the WADL file to process
   * @throws javax.xml.bind.JAXBException if the WADL file is invalid, a referenced WADL file is
   *     invalid, or if the code generator encounters a problem.
   * @throws java.io.IOException if the specified WADL file cannot be read.
   * @throws com.sun.codemodel.JClassAlreadyExistsException if, during code generation, the WADL
   *     processor attempts to create a duplicate class. This indicates a structural problem with
   *     the WADL file, e.g. duplicate peer resource entries.
   */
  public void process(URI rootDesc)
      throws JAXBException, IOException, JClassAlreadyExistsException {
    // read in root WADL file
    JAXBContext jbc =
        JAXBContext.newInstance("org.jvnet.ws.wadl", this.getClass().getClassLoader());
    u = jbc.createUnmarshaller();
    s2j = new SchemaCompilerImpl();
    errorListener = new SchemaCompilerErrorListener();
    if (!autoPackage) s2j.setDefaultPackageName(pkg);
    s2j.setErrorListener(errorListener);
    idMap = new HashMap<String, Object>();
    ifaceMap = new HashMap<String, ResourceTypeNode>();
    Application a = processDescription(rootDesc);
    ResourceNode r = buildAst(a, rootDesc);

    // generate code
    s2jModel = s2j.bind();
    if (s2jModel != null) {
      codeModel = s2jModel.generateCode(null, errorListener);
      Iterator<JPackage> packages = codeModel.packages();
      StringBuilder buf = new StringBuilder();
      while (packages.hasNext()) {
        JPackage genPkg = packages.next();
        if (!genPkg.isDefined("ObjectFactory")) continue;
        if (buf.length() > 0) buf.append(':');
        buf.append(genPkg.name());
      }
      generatedPackages = buf.toString();
      jPkg = codeModel._package(pkg);
      generateResourceTypeInterfaces();
      generateEndpointClass(r);
      codeModel.build(outputDir);
    }
  }
Exemplo n.º 4
0
  @Test
  public void nestedSelfRefsInStringContentWithoutParentFile()
      throws NoSuchMethodException, ClassNotFoundException, IOException {

    String schemaContents =
        IOUtils.toString(
            CodeGenerationHelper.class.getResource("/schema/ref/nestedSelfRefsReadAsString.json"));
    JCodeModel codeModel = new JCodeModel();
    new SchemaMapper().generate(codeModel, "NestedSelfRefsInString", "com.example", schemaContents);

    codeModel.build(schemaRule.getGenerateDir());

    ClassLoader classLoader = schemaRule.compile();

    Class<?> nestedSelfRefs = classLoader.loadClass("com.example.NestedSelfRefsInString");
    assertThat(
        nestedSelfRefs.getMethod("getThings").getReturnType().getSimpleName(), equalTo("List"));

    Class<?> listEntryType =
        (Class<?>)
            ((ParameterizedType) nestedSelfRefs.getMethod("getThings").getGenericReturnType())
                .getActualTypeArguments()[0];
    assertThat(listEntryType.getName(), equalTo("com.example.Thing"));

    Class<?> thingClass = classLoader.loadClass("com.example.Thing");
    assertThat(
        thingClass.getMethod("getNamespace").getReturnType().getSimpleName(), equalTo("String"));
    assertThat(thingClass.getMethod("getName").getReturnType().getSimpleName(), equalTo("String"));
    assertThat(
        thingClass.getMethod("getVersion").getReturnType().getSimpleName(), equalTo("String"));
  }
 @Override
 public JPackage apply(ApiResourceMetadata controllerMetadata, JCodeModel generatableType) {
   if (StringUtils.hasText(controllerMetadata.getBasePackage())) {
     return generatableType._package(controllerMetadata.getBasePackage());
   }
   return generatableType.rootPackage();
 }
  public static void createEventInterface(
      Option option, String packageName, String rootDirectoryPathName) {
    JCodeModel model = new JCodeModel();

    try {
      JDefinedClass jClass =
          model._class(
              packageName + "." + EventHelper.getEventNamePrefix(option) + EventHelper.EVENT_SUFFIX,
              ClassType.INTERFACE);
      // jClass._extends(NativeEvent.class);

      // TODO this logic should not be in an helper, pb it is duplicated
      // inside all helper, should have a common algo
      // write getter for Series / Point / Chart / Axis (context) inside
      // event
      if (option.getContext() != null)
        EventHelper.getType(option)
            .accept(new EventGetterWriterVisitor(option, jClass, model), OutputType.Interface);

      ClassRegistry.INSTANCE.put(option, OutputType.Interface, jClass);

    } catch (JClassAlreadyExistsException e) {
      throw new RuntimeException(e);
    }

    try {
      model.build(new File(rootDirectoryPathName));
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }
Exemplo n.º 7
0
  private static void generateEnum() throws JClassAlreadyExistsException, IOException {
    JCodeModel codeModel = new JCodeModel();
    JDefinedClass enumClass = codeModel._class("com.foo.Bar", ClassType.ENUM);
    // This code creates field within the enum class
    JFieldVar columnField = enumClass.field(JMod.PRIVATE | JMod.FINAL, String.class, "column");
    JFieldVar filterableField =
        enumClass.field(JMod.PRIVATE | JMod.FINAL, codeModel.BOOLEAN, "filterable");

    // Define the enum constructor
    JMethod enumConstructor = enumClass.constructor(JMod.PRIVATE);
    enumConstructor.param(String.class, "column");
    enumConstructor.param(codeModel.BOOLEAN, "filterable");
    enumConstructor.body().assign(JExpr._this().ref("column"), JExpr.ref("column"));
    enumConstructor.body().assign(JExpr._this().ref("filterable"), JExpr.ref("filterable"));

    JMethod getterColumnMethod = enumClass.method(JMod.PUBLIC, String.class, "getColumn");
    getterColumnMethod.body()._return(columnField);
    JMethod getterFilterMethod = enumClass.method(JMod.PUBLIC, codeModel.BOOLEAN, "isFilterable");
    getterFilterMethod.body()._return(filterableField);

    JEnumConstant enumConst = enumClass.enumConstant("FOO_BAR");
    enumConst.arg(JExpr.lit("fooBar"));
    enumConst.arg(JExpr.lit(true));
    codeModel.build(new File("src"));
    /*
     * //creating an enum class within our main class JDefinedClass enumClass =
     * codeModel._class(JMod.PUBLIC, "REPORT_COLUMNS"); //This code creates
     * field within the enum class JFieldVar columnField =
     * enumClass.field(JMod.PRIVATE|JMod.FINAL, String.class, "column");
     * JFieldVar filterableField = enumClass.field(JMod.PRIVATE|JMod.FINAL,
     * codeModel.BOOLEAN, "filterable");
     */
  }
 @Test(expected = IllegalArgumentException.class)
 public void testRecursivlyCreateAllTypesArrayNoType() throws ClassNotFoundException {
   schema.setType(TYPE.ARRAY);
   JCodeModel codeModel = new JCodeModel();
   JPackage _package = codeModel._package("org.sample");
   // should fail since the array type is not set
   JType type = driver.createOrGetType(codeModel, schema);
 }
 @Test
 public void testRecursivlyCreateAllTypesNumber() throws ClassNotFoundException {
   ObjectSchema schema = new ObjectSchema();
   schema.setType(TYPE.NUMBER);
   JCodeModel codeModel = new JCodeModel();
   schema.setId("org.sample.SampleClass");
   JPackage _package = codeModel._package("org.sample");
   JType type = driver.createOrGetType(codeModel, schema);
   assertNotNull(type);
   assertEquals(Double.class.getName(), type.fullName());
 }
Exemplo n.º 10
0
  @Test
  public void selfRefWithoutParentFile() throws IOException {
    JCodeModel codeModel = new JCodeModel();
    JsonNode schema =
        new ObjectMapper()
            .readTree(
                "{\"type\":\"object\", \"properties\":{\"a\":{\"$ref\":\"#/b\"}}, \"b\":\"string\"}");

    JPackage p = codeModel._package("com.example");
    new RuleFactory().getSchemaRule().apply("Example", schema, p, new Schema(null, schema));
  }
Exemplo n.º 11
0
 @Override
 public JExpression testExpr(JCodeModel codeModel, JVar sexpVariable, JvmMethod.Argument formal) {
   JExpression vectorTest = super.testExpr(codeModel, sexpVariable, formal);
   if (formal.isAnnotatedWith(CoerceLanguageToString.class)) {
     return vectorTest
         .cor(sexpVariable._instanceof(codeModel.ref(FunctionCall.class)))
         .cor(sexpVariable._instanceof(codeModel.ref(Symbol.class)));
   } else {
     return vectorTest;
   }
 }
 @Test
 public void testLoadedInterfaces() throws Exception {
   String[] namesToLoad =
       new String[] {
         "InterfaceA.json", "InterfaceB.json", "ABImpl.json",
       };
   List<ObjectSchema> schemaList = new ArrayList<ObjectSchema>();
   for (String name : namesToLoad) {
     String fileString =
         FileUtils.loadFileAsStringFromClasspath(
             PojoGeneratorDriverTest.class.getClassLoader(), name);
     ObjectSchema schema = new ObjectSchema(new JSONObjectAdapterImpl(fileString));
     //			schema.setName(name);
     schema.setId(schema.getName());
     schemaList.add(schema);
   }
   JCodeModel codeModel = new JCodeModel();
   driver.createAllClasses(codeModel, schemaList);
   // Get the class
   JPackage _package = codeModel._package("");
   JDefinedClass impl = null;
   try {
     impl = _package._class("ABImpl");
   } catch (JClassAlreadyExistsException e) {
     impl = e.getExistingClass();
   }
   String classString = declareToString(impl);
   //		System.out.println(classString);
   Iterator<JClass> it = impl._implements();
   assertNotNull(it);
   String intA = "InterfaceA";
   String intB = "InterfaceB";
   String jsonEntity = "JSONEntity";
   Map<String, JClass> map = new HashMap<String, JClass>();
   while (it.hasNext()) {
     JClass impClass = it.next();
     if (intA.equals(impClass.name())) {
       map.put(intA, impClass);
     } else if (intB.equals(impClass.name())) {
       map.put(intB, impClass);
     } else if (jsonEntity.equals(impClass.name())) {
       map.put(jsonEntity, impClass);
     }
   }
   assertEquals("Should have implemented two interfaces", 3, map.size());
   // Now get the fields from the object an confirm they are all there
   Map<String, JFieldVar> fields = impl.fields();
   assertNotNull(fields);
   assertEquals(6, fields.size());
   assertNotNull(fields.get("fromInterfaceA"));
   assertNotNull(fields.get("alsoFromInterfaceB"));
   assertNotNull(fields.get("fromMe"));
 }
Exemplo n.º 13
0
 public FeedQueryGenerator(JCodeModel model, JPackage pkg) {
   this.model = model;
   this.pkg = pkg;
   this.parent = model.directClass(BaseApiQuery.class.getCanonicalName());
   this.precs = model.directClass(Preconditions.class.getCanonicalName());
   this.immutableList = model.directClass(ImmutableList.class.getCanonicalName());
   this.immutableMap = model.directClass(ImmutableMap.class.getCanonicalName());
   this.immutableMapBldr =
       model
           .directClass(ImmutableMap.Builder.class.getCanonicalName())
           .narrow(String.class, Object.class);
 }
Exemplo n.º 14
0
 private void addResultTypeMethod(JCodeModel model, JDefinedClass cls, JClass transformedType) {
   JClass classCls = model.ref(Class.class);
   JMethod method =
       cls.method(JMod.PROTECTED | JMod.FINAL, classCls.narrow(transformedType), "resultsType");
   method.body()._return(JExpr.dotclass(transformedType));
   method.annotate(Override.class);
 }
  public void build() {
    declareMethod();

    ExceptionWrapper mainTryBlock = new ExceptionWrapper(codeModel, method.body(), context);
    for (Integer arity : primitive.getArity()) {
      JInvocation invocation = invoke("doApply").arg(context).arg(environment);

      for (int i = 0; i < arity; ++i) {
        invocation.arg(args.component(lit(i)));
      }
      mainTryBlock
          .body()
          ._if(JExpr.direct("args.length").eq(JExpr.lit(arity)))
          ._then()
          ._return(invocation);
    }

    mainTryBlock.catchEvalExceptions();
    mainTryBlock.catchRuntimeExceptions();
    mainTryBlock.catchExceptions();

    method
        .body()
        ._throw(
            JExpr._new(codeModel.ref(EvalException.class))
                .arg(lit(primitive.getName() + ": max arity is " + primitive.getMaxArity())));
  }
Exemplo n.º 16
0
 /**
  * Writes the generated classes to disk at the supplied path.
  *
  * @param path to write the classes to
  * @throws IOException if the write fails
  */
 public void write(final String path) throws IOException {
   final File f = new File(path);
   if (!f.exists()) {
     f.mkdirs();
   }
   codeModel.build(f);
 }
 @Test
 public void testGenerateEquals() throws ClassNotFoundException {
   plugin.generateEqualsMethod(aModel, aClass);
   final JMethod generatedMethod =
       aClass.getMethod("equals", new JType[] {aModel.parseType("java.lang.Object")});
   assertThat(generatedMethod, not(nullValue()));
   assertThat(generatedMethod.type().fullName(), equalTo("boolean"));
 }
Exemplo n.º 18
0
  private static void generate(Templates packetNodes)
      throws IOException, JClassAlreadyExistsException {
    JCodeModel codeModel = new JCodeModel();

    // outer nodes
    for (CommunicationDirection direction : packetNodes.getProtocol()) {
      // check if we process inbound or outbounf packets and the server type
      CommunicationDirectionTypes prot = direction.getType();

      // crappy enumeration types due to keeping backwards compatibility
      boolean fromClient =
          (prot == CommunicationDirectionTypes.CTOGS)
              || (prot == CommunicationDirectionTypes.CTO_GS)
              || (prot == CommunicationDirectionTypes.CTOLS)
              || (prot == CommunicationDirectionTypes.CTO_LS);

      String serverName =
          (prot == CommunicationDirectionTypes.LSTOC)
                  || (prot == CommunicationDirectionTypes.L_STO_C)
                  || (prot == CommunicationDirectionTypes.CTOLS)
                  || (prot == CommunicationDirectionTypes.CTO_LS)
              ? "loginserver"
              : "gameserver";

      // set the new packet's package
      JPackage directionPackage =
          codeModel._package(
              "gwlpr.protocol." + serverName + "." + (fromClient ? "inbound" : "outbound"));

      LOGGER.info("Processing packets of package: {}", directionPackage);

      for (PacketType packet : direction.getPacket()) {
        processPacket(packet, directionPackage, codeModel, fromClient);
      }
    }

    // finally take the output and generate the files
    codeModel.build(
        new File("output"),
        new PrintStream(new ByteArrayOutputStream()) {
          @Override
          public void print(String s) {
            LOGGER.debug("CodeModel: {}", s);
          }
        });
  }
Exemplo n.º 19
0
  public void execute(String schema, String tableName, String fullClassName) throws Exception {

    JCodeModel codeModel = new JCodeModel();

    // 生成するクラス定義
    JDefinedClass clazz = codeModel._class(fullClassName);

    this.addClassComment(clazz, this.getTableComment(tableName) + "のDTO");

    JMethod constructor = clazz.constructor(JMod.PUBLIC); // コンストラクタ
    this.addMethodDoc(constructor, "コンストラクタ");

    source(codeModel, clazz);

    // ソース生成
    codeModel.build(new File(Env.DIR_OUTPUT_SRC.value()));
  }
Exemplo n.º 20
0
  public static void main(String[] args) throws JClassAlreadyExistsException, IOException {
    JCodeModel codeModel = new JCodeModel();

    Class template = AbstractBaseWrapper.class;

    String packageName = template.getPackage().getName();

    String className = template.getSimpleName().replace("Abstract", "") + "Impl";
    JPackage generatedPackage = codeModel._package(packageName);

    JDefinedClass generatedClass = generatedPackage._class(JMod.FINAL, className); // Creates
    // a
    // new
    // class
    generatedClass._extends(template);

    for (Method method : template.getMethods()) {

      if (Modifier.isAbstract(method.getModifiers())) {
        System.out.println(
            "Found abstract method "
                + Modifier.toString(method.getModifiers())
                + " "
                + method.getName());

        JMethod generatedMethod =
            generatedClass.method(JMod.PUBLIC, method.getReturnType(), method.getName());

        for (Parameter parameter : method.getParameters()) {
          generatedMethod.param(parameter.getModifiers(), parameter.getType(), parameter.getName());
        }

        if (method.getReturnType().equals(Void.TYPE)) {
          generatedMethod.body().add(generateInvocation(method));
        } else {

          generatedMethod.body()._return(generateInvocation(method));
        }
      }
    }

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    codeModel.build(new SingleStreamCodeWriter(out));

    System.out.println(out);
  }
Exemplo n.º 21
0
 /**
  * Creates the equals method on the supplied class. Leverages {@link
  * org.ldaptive.LdapUtils#areEqual(Object, Object)}.
  *
  * @param clazz to put equals method on
  */
 private void createEquals(final JDefinedClass clazz) {
   final JClass ldapUtilsClass = codeModel.ref(org.ldaptive.LdapUtils.class);
   final JInvocation areEqual = ldapUtilsClass.staticInvoke("areEqual");
   final JMethod equals = clazz.method(JMod.PUBLIC, boolean.class, "equals");
   equals.annotate(java.lang.Override.class);
   areEqual.arg(JExpr._this());
   areEqual.arg(equals.param(Object.class, "o"));
   equals.body()._return(areEqual);
 }
Exemplo n.º 22
0
 private JClass mapType(Filter filter) throws JClassAlreadyExistsException {
   if (!(filter.getOption() == null || filter.getOption().isEmpty())) {
     return getParamTypeEnum(filter);
   }
   String type = filter.getType();
   Class<?> typeCls = typeMap.get(type);
   checkState(typeCls != null, "Unexpected type: %s", type);
   return model.ref(typeCls);
 }
Exemplo n.º 23
0
  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"));
  }
Exemplo n.º 24
0
  @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 JInvocation buildScopeKey(InjectionNode injectionNode) {
    InjectionSignature signature = injectionNode.getTypeSignature();

    JClass injectionNodeClassRef = generationUtil.ref(injectionNode.getASTType());

    return codeModel
        .ref(ScopeKey.class)
        .staticInvoke(ScopeKey.GET_METHOD)
        .arg(injectionNodeClassRef.dotclass())
        .arg(JExpr.lit(signature.buildScopeKeySignature()));
  }
Exemplo n.º 26
0
 private JClass getTransformedType(Feed feed) {
   Class<?> cls = null;
   String name = feed.getName();
   if (name.equals("Versions")) {
     cls = Version.class;
     return model.ref(cls);
   }
   if (name.equals("Groups")) {
     cls = GroupBody.class;
     return model.ref(cls);
   }
   cls = tryLoadClass(MODEL_PKG + name);
   if (cls == null) { // attempt in possible naive singular.
     cls = tryLoadClass(MODEL_PKG + name.substring(0, name.length() - 1));
   }
   if (cls == null) {
     cls = Object.class;
   }
   return model.ref(cls);
 }
Exemplo n.º 27
0
 /**
  * Creates the hashCode method on the supplied class. Leverages {@link
  * org.ldaptive.LdapUtils#computeHashCode(int, Object...)}.
  *
  * @param clazz to put hashCode method on
  */
 private void createHashCode(final JDefinedClass clazz) {
   final JClass ldapUtilsClass = codeModel.ref(org.ldaptive.LdapUtils.class);
   final JInvocation computeHashCode = ldapUtilsClass.staticInvoke("computeHashCode");
   final JMethod hashCode = clazz.method(JMod.PUBLIC, int.class, "hashCode");
   hashCode.annotate(java.lang.Override.class);
   // CheckStyle:MagicNumber OFF
   computeHashCode.arg(JExpr.lit(7919));
   // CheckStyle:MagicNumber ON
   for (Map.Entry<String, JFieldVar> entry : clazz.fields().entrySet()) {
     computeHashCode.arg(JExpr._this().ref(entry.getValue()));
   }
   hashCode.body()._return(computeHashCode);
 }
  @Test
  public void testCreateAllClassesEnum() throws Exception {
    String[] namesToLoad =
        new String[] {
          "PetEnum.json",
        };
    List<ObjectSchema> schemaList = new ArrayList<ObjectSchema>();
    for (String name : namesToLoad) {
      String fileString =
          FileUtils.loadFileAsStringFromClasspath(
              PojoGeneratorDriverTest.class.getClassLoader(), name);
      ObjectSchema schema = new ObjectSchema(new JSONObjectAdapterImpl(fileString));
      schema.setId(schema.getName());
      schemaList.add(schema);
    }
    JCodeModel codeModel = new JCodeModel();
    driver.createAllClasses(codeModel, schemaList);
    // Get the class
    JPackage _package = codeModel._package("");
    JDefinedClass impl = null;
    try {
      impl = _package._class("PetEnum");
    } catch (JClassAlreadyExistsException e) {
      impl = e.getExistingClass();
    }
    String classString = declareToString(impl);
    System.out.println(classString);

    Map<String, JFieldVar> fields = impl.fields();
    assertNotNull(fields);
    // Enums should have no fields
    assertEquals(1, fields.size());
    Collection<JMethod> methods = impl.methods();
    assertNotNull(methods);
    // enums should have no methods
    assertEquals(0, methods.size());
    // Enums should have no constructors
    assertFalse(impl.constructors().hasNext());
  }
  public static JDefinedClass createFunctionCallbackInterface(
      Option option, String packageName, String rootDirectoryPathName) {
    JCodeModel model = new JCodeModel();

    JDefinedClass jClass = null;

    try {
      String fqn = FunctionHelper.getFunctionCallbackFqn(option, packageName);

      JClass contextObject = FunctionHelper.getContextObject(option, OutputType.Interface);

      jClass = model._class(fqn, ClassType.INTERFACE);

      JMethod method = jClass.method(JMod.NONE, Object.class, EventHelper.ON_PREFIX + "Callback");

      if (contextObject != null)
        method.param(
            contextObject,
            option.getContext().substring(0, 1).toLowerCase() + option.getContext().substring(1));

      ClassRegistry.INSTANCE
          .getRegistry()
          .put(new ClassRegistry.RegistryKey(option, OutputType.Interface), jClass);

      logger.info("Function callback created;" + option.getTitle());

    } catch (JClassAlreadyExistsException e) {
      throw new RuntimeException(e);
    }

    try {
      model.build(new File(rootDirectoryPathName));
    } catch (IOException e) {
      throw new RuntimeException(e);
    }

    return jClass;
  }
Exemplo n.º 30
0
  public void generate(String layoutName, String superclass, Collection<Ref> refs, Writer writer)
      throws IOException {
    JCodeModel m = new JCodeModel();
    JPackage pkg = m._package(packageName + "." + HoldrCompiler.PACKAGE);

    try {
      Refs r = new Refs(m, packageName, layoutName, superclass);

      // public class MyLayoutViewModel {
      JDefinedClass clazz = pkg._class(PUBLIC, getClassName(layoutName))._extends(r.viewHolder);

      // public static final int LAYOUT = R.id.my_layout;
      JFieldVar layoutVar = clazz.field(PUBLIC | STATIC | FINAL, m.INT, "LAYOUT", r.layoutRef);

      Map<Ref, JFieldVar> fieldVarMap = genFields(r, clazz, refs);

      Map<Listener.Type, ListenerType> listenerTypeMap = createListenerTypeMap(r);

      // public interface Listener {
      JClass listenerInterface = genListenerInterface(r, clazz, refs, listenerTypeMap);
      // }
      JFieldVar holdrListener = null;
      if (listenerInterface != null) {
        // private Listener _holdrListener;
        holdrListener = clazz.field(PRIVATE, listenerInterface, "_holdrListener");
      }

      genConstructor(r, clazz, refs, fieldVarMap, holdrListener, listenerTypeMap);

      // public void setListener(Listener listener) {
      genSetListener(r, clazz, listenerInterface, holdrListener);

      m.build(new WriterCodeWriter(writer));
    } catch (JClassAlreadyExistsException e) {
      throw new IOException(e);
    }
  }