@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")); }
/** * Creates a new Java class that will be generated. * * @param nodeName the node name which may be used to dictate the new class name * @param node the node representing the schema that caused the need for a new class. This node * may include a 'javaType' property which if present will override the fully qualified name * of the newly generated class. * @param _package the package which may contain a new class after this method call * @return a reference to a newly created class * @throws ClassAlreadyExistsException if the given arguments cause an attempt to create a class * that already exists, either on the classpath or in the current map of classes to be * generated. */ private JDefinedClass createClass(String nodeName, JsonNode node, JPackage _package) throws ClassAlreadyExistsException { JDefinedClass newType; try { boolean usePolymorphicDeserialization = usesPolymorphicDeserialization(node); if (node.has("javaType")) { String fqn = substringBefore(node.get("javaType").asText(), "<"); if (isPrimitive(fqn, _package.owner())) { throw new ClassAlreadyExistsException(primitiveType(fqn, _package.owner())); } int index = fqn.lastIndexOf(".") + 1; if (index >= 0 && index < fqn.length()) { fqn = fqn.substring(0, index) + ruleFactory.getGenerationConfig().getClassNamePrefix() + fqn.substring(index) + ruleFactory.getGenerationConfig().getClassNameSuffix(); } try { _package.owner().ref(Thread.currentThread().getContextClassLoader().loadClass(fqn)); JClass existingClass = TypeUtil.resolveType( _package, fqn + (node.get("javaType").asText().contains("<") ? "<" + substringAfter(node.get("javaType").asText(), "<") : "")); throw new ClassAlreadyExistsException(existingClass); } catch (ClassNotFoundException e) { if (usePolymorphicDeserialization) { newType = _package.owner()._class(JMod.PUBLIC, fqn, ClassType.CLASS); } else { newType = _package.owner()._class(fqn); } } } else { if (usePolymorphicDeserialization) { newType = _package._class(JMod.PUBLIC, getClassName(nodeName, _package), ClassType.CLASS); } else { newType = _package._class(getClassName(nodeName, _package)); } } } catch (JClassAlreadyExistsException e) { throw new ClassAlreadyExistsException(e.getExistingClass()); } ruleFactory.getAnnotator().propertyInclusion(newType, node); return newType; }
@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")); }
@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()); }
@Override public void execute() throws MojoExecutionException, MojoFailureException { File outputDir = getOutputDirectory(); if (!outputDir.exists() && outputDir.mkdirs()) { outputDir = getOutputDirectory(); } SoapStepsGenerator stepsGenerator = new SoapStepsGenerator(); Log log = getLog(); String soapStepsPackage = getSoapStepsPackage() == null ? "" : getSoapStepsPackage() + "."; try { for (String soapServicePack : getSoapServicePackages()) { stepsGenerator.generateFor( soapServicePack, getClassLoader(), outputDir, log, soapStepsPackage); } } catch (ClassNotFoundException e) { log.error(e.getMessage(), e); } catch (JClassAlreadyExistsException e) { log.error(e.getMessage(), e); } catch (IOException e) { log.error(e.getMessage(), e); } getProject().addTestCompileSourceRoot(outputDir.getAbsolutePath()); }
/** @param args */ public static void main(String[] args) { // Freemarker configuration object Configuration cfg = new Configuration(); try { Document doc = Jsoup.parse(new File("./src/identification.html"), "UTF-8"); // Load template from source folder Template template = cfg.getTemplate("src/com/convert/template/jsp/struts2.ftl"); // Build the data-model Map<String, Object> data = new HashMap<String, Object>(); final String pageName = "identification"; data.put("pageName", pageName); // get select tags Elements selectTags = doc.getElementsByTag("select"); for (Element selectTag : selectTags) { JCodeModel codeModel = new JCodeModel(); String enumName = StringUtils.capitalize(selectTag.attr("id") + "Type"); // String enumName=selectTag.attr("id")+"Type"; System.out.println(enumName); JDefinedClass enumClass = codeModel._class("com.foo." + enumName, ClassType.ENUM); JFieldVar field1 = enumClass.field(JMod.PRIVATE | JMod.FINAL, String.class, "column"); JMethod enumConstructor = enumClass.constructor(JMod.PRIVATE); enumConstructor.param(String.class, "column"); enumConstructor.body().assign(JExpr._this().ref("column"), JExpr.ref("column")); Elements options = selectTag.select("option"); for (Element element : options) { String text = element.text(); if (!text.contains("GenerateSelectHtml")) { JEnumConstant enumConst = enumClass.enumConstant(text.toUpperCase()); enumConst.arg(JExpr.lit(text)); } } String mehtodName = "get" + enumName; JMethod jmCreate = enumClass.method( JMod.PUBLIC | JMod.STATIC, java.util.ArrayList.class, "create" + mehtodName); JBlock jBlock = jmCreate.body(); jBlock.directStatement( "List<String> list = new ArrayList<String>();" + " for (SalutationsType value : SalutationsType.values()) {" + "list.add(value.getSalutation());" + "} " + "return list"); codeModel.build(new File("src")); } // generateEnum(); Elements links = doc.getElementsByTag("script"); data.put("javascripts", links); Elements styles = doc.getElementsByTag("link"); data.put("styles", styles); // links.remove(); Elements labels = doc.select("label"); Properties prop = new Properties(); OutputStream output = null; output = new FileOutputStream("config.properties"); Template templateLabels = cfg.getTemplate("src/com/convert/template/label/struts2.ftl"); for (Element label : labels) { if (label.hasText()) { String labelName = label.attr("for"); String pageNameText = pageName + ".label." + labelName; prop.setProperty(pageNameText, label.text()); data.put("labelName", label.text()); StringWriter writer = new StringWriter(); // Writer out = new OutputStreamWriter(System.out); templateLabels.process(data, writer); // out.flush(); label.html(writer.getBuffer().toString()); } } // save properties to project root folder prop.store(output, null); doc.select("script, style, meta, link, comment, CDATA, #comment").remove(); // removeComments(doc); // doc.body().html().replaceAll("<body>", "").replaceAll("</body>", // ""); data.put("body", doc.body().html().replaceAll("<body>", "").replaceAll("</body>", "")); /* * for (Element link : links) { System.out.println(link); } */ // Console output /* * Writer out = new OutputStreamWriter(System.out); template.process(data, * out); out.flush(); */ // File output Writer file = new FileWriter(new File("FTL_helloworld.jsp")); template.process(data, file); file.flush(); file.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (TemplateException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JClassAlreadyExistsException e) { // TODO Auto-generated catch block e.printStackTrace(); } }