コード例 #1
0
 @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"));
 }
コード例 #2
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);
    }
  }
コード例 #3
0
 @Override
 public JPackage apply(ApiResourceMetadata controllerMetadata, JCodeModel generatableType) {
   if (StringUtils.hasText(controllerMetadata.getBasePackage())) {
     return generatableType._package(controllerMetadata.getBasePackage());
   }
   return generatableType.rootPackage();
 }
コード例 #4
0
 @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);
 }
コード例 #5
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));
  }
コード例 #6
0
 @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());
 }
コード例 #7
0
 @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"));
 }
コード例 #8
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);
          }
        });
  }
コード例 #9
0
ファイル: WrapperGenerator.java プロジェクト: pihme/sandbox
  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);
  }
コード例 #10
0
  public XjcGuavaPluginTest() throws Exception {
    aPackage = aModel._package("test");
    aClass = aPackage._class("AClass");

    aSetter = aClass.method(JMod.PUBLIC, aModel.VOID, "setField");

    aField = aClass.field(JMod.PRIVATE, aModel.INT, "field");
    anotherField = aClass.field(JMod.PRIVATE, aModel.BOOLEAN, "anotherField");
    aStaticField = aClass.field(JMod.STATIC | JMod.PUBLIC, aModel.SHORT, "staticField");
    aGetter = aClass.method(JMod.PUBLIC, aModel.INT, "getField");
    aGetter.body()._return(aField);
    final JVar setterParam = aSetter.param(aModel.INT, "field");
    aSetter.body().assign(aField, setterParam);

    aSuperClass = aPackage._class("ASuperClass");
    aClass._extends(aSuperClass);
    aSuperClassField = aSuperClass.field(JMod.PRIVATE, aModel.DOUBLE, "superClassField");
  }
コード例 #11
0
  @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());
  }
コード例 #12
0
ファイル: HoldrGenerator.java プロジェクト: h87kg/holdr
  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);
    }
  }
コード例 #13
0
ファイル: Main.java プロジェクト: romuloquadros/LazyBoy
 public static void main(String[] args) {
   JCodeModel codeModel = new JCodeModel();
   codeModel._package("");
 }