Java 类com.sun.codemodel.JCodeModel 实例源码

项目:GitHub    文件:SelfRefIT.java   
@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"));

}
项目:GitHub    文件:TypeRuleTest.java   
@Test
public void applyGeneratesDate() {

    JPackage jpackage = new JCodeModel()._package(getClass().getPackage().getName());

    ObjectNode objectNode = new ObjectMapper().createObjectNode();
    objectNode.put("type", "string");

    TextNode formatNode = TextNode.valueOf("date-time");
    objectNode.set("format", formatNode);

    JType mockDateType = mock(JType.class);
    FormatRule mockFormatRule = mock(FormatRule.class);
    when(mockFormatRule.apply(eq("fooBar"), eq(formatNode), Mockito.isA(JType.class), isNull(Schema.class))).thenReturn(mockDateType);
    when(ruleFactory.getFormatRule()).thenReturn(mockFormatRule);

    JType result = rule.apply("fooBar", objectNode, jpackage, null);

    assertThat(result, equalTo(mockDateType));
}
项目:GitHub    文件:TypeRuleTest.java   
@Test
public void applyGeneratesArray() {

    JPackage jpackage = new JCodeModel()._package(getClass().getPackage().getName());

    ObjectNode objectNode = new ObjectMapper().createObjectNode();
    objectNode.put("type", "array");

    JClass mockArrayType = mock(JClass.class);
    ArrayRule mockArrayRule = mock(ArrayRule.class);
    when(mockArrayRule.apply("fooBar", objectNode, jpackage, null)).thenReturn(mockArrayType);
    when(ruleFactory.getArrayRule()).thenReturn(mockArrayRule);

    JType result = rule.apply("fooBar", objectNode, jpackage, null);

    assertThat(result, is((JType) mockArrayType));
}
项目:GitHub    文件:TypeRuleTest.java   
@Test
public void applyGeneratesCustomObject() {

    JPackage jpackage = new JCodeModel()._package(getClass().getPackage().getName());

    ObjectNode objectNode = new ObjectMapper().createObjectNode();
    objectNode.put("type", "object");

    JDefinedClass mockObjectType = mock(JDefinedClass.class);
    ObjectRule mockObjectRule = mock(ObjectRule.class);
    when(mockObjectRule.apply("fooBar", objectNode, jpackage, null)).thenReturn(mockObjectType);
    when(ruleFactory.getObjectRule()).thenReturn(mockObjectRule);

    JType result = rule.apply("fooBar", objectNode, jpackage, null);

    assertThat(result, is((JType) mockObjectType));
}
项目:GitHub    文件:ArrayRuleTest.java   
@Test
public void arrayWithUniqueItemsProducesSet() {
    JCodeModel codeModel = new JCodeModel();
    JPackage jpackage = codeModel._package(getClass().getPackage().getName());

    ObjectMapper mapper = new ObjectMapper();

    ObjectNode itemsNode = mapper.createObjectNode();
    itemsNode.put("type", "integer");

    ObjectNode propertyNode = mapper.createObjectNode();
    propertyNode.set("uniqueItems", BooleanNode.TRUE);
    propertyNode.set("items", itemsNode);

    JClass propertyType = rule.apply("fooBars", propertyNode, jpackage, mock(Schema.class));

    assertThat(propertyType, notNullValue());
    assertThat(propertyType.erasure(), is(codeModel.ref(Set.class)));
    assertThat(propertyType.getTypeParameters().get(0).fullName(), is(Integer.class.getName()));
}
项目:GitHub    文件:ArrayRuleTest.java   
@Test
public void arrayWithNonUniqueItemsProducesList() {
    JCodeModel codeModel = new JCodeModel();
    JPackage jpackage = codeModel._package(getClass().getPackage().getName());

    ObjectMapper mapper = new ObjectMapper();

    ObjectNode itemsNode = mapper.createObjectNode();
    itemsNode.put("type", "number");

    ObjectNode propertyNode = mapper.createObjectNode();
    propertyNode.set("uniqueItems", BooleanNode.FALSE);
    propertyNode.set("items", itemsNode);

    Schema schema = mock(Schema.class);
    when(schema.getId()).thenReturn(URI.create("http://example/nonUniqueArray"));
    when(config.isUseDoubleNumbers()).thenReturn(true);

    JClass propertyType = rule.apply("fooBars", propertyNode, jpackage, schema);

    assertThat(propertyType, notNullValue());
    assertThat(propertyType.erasure(), is(codeModel.ref(List.class)));
    assertThat(propertyType.getTypeParameters().get(0).fullName(), is(Double.class.getName()));
}
项目:GitHub    文件:ArrayRuleTest.java   
@Test
public void arrayOfPrimitivesProducesCollectionOfWrapperTypes() {
    JCodeModel codeModel = new JCodeModel();
    JPackage jpackage = codeModel._package(getClass().getPackage().getName());

    ObjectMapper mapper = new ObjectMapper();

    ObjectNode itemsNode = mapper.createObjectNode();
    itemsNode.put("type", "number");

    ObjectNode propertyNode = mapper.createObjectNode();
    propertyNode.set("uniqueItems", BooleanNode.FALSE);
    propertyNode.set("items", itemsNode);

    Schema schema = mock(Schema.class);
    when(schema.getId()).thenReturn(URI.create("http://example/nonUniqueArray"));
    when(config.isUsePrimitives()).thenReturn(true);
    when(config.isUseDoubleNumbers()).thenReturn(true);

    JClass propertyType = rule.apply("fooBars", propertyNode, jpackage, schema);

    assertThat(propertyType, notNullValue());
    assertThat(propertyType.erasure(), is(codeModel.ref(List.class)));
    assertThat(propertyType.getTypeParameters().get(0).fullName(), is(Double.class.getName()));
}
项目:GitHub    文件:ArrayRuleTest.java   
@Test
public void arrayDefaultsToNonUnique() {
    JCodeModel codeModel = new JCodeModel();
    JPackage jpackage = codeModel._package(getClass().getPackage().getName());

    ObjectMapper mapper = new ObjectMapper();

    ObjectNode itemsNode = mapper.createObjectNode();
    itemsNode.put("type", "boolean");

    ObjectNode propertyNode = mapper.createObjectNode();
    propertyNode.set("uniqueItems", BooleanNode.FALSE);
    propertyNode.set("items", itemsNode);

    Schema schema = mock(Schema.class);
    when(schema.getId()).thenReturn(URI.create("http://example/defaultArray"));

    JClass propertyType = rule.apply("fooBars", propertyNode, jpackage, schema);

    assertThat(propertyType.erasure(), is(codeModel.ref(List.class)));
}
项目:beanvalidation-benchmark    文件:MetaJavaBean.java   
/**
 * Creates a new MetaJavaBean with random fields.
 * 
 * @param fqn
 *            The fully qualified name of the bean's class.
 * @param numFields
 *            Number of simple type fields that will be added.
 */
public MetaJavaBean(JCodeModel cm, String fqn, int numFields) {

    super(cm, fqn, ClassType.CLASS);

    // Empty constructor
    getGeneratedClass().constructor(JMod.PUBLIC);

    // Init the simple fields
    this.fields = Maps.newHashMapWithExpectedSize(numFields);
    for (int i = 0; i < numFields; ++i) {
        String fieldName = "field" + Config.CFG.nextUniqueNum();
        JavaBeanBasicField field = new JavaBeanBasicField(this, fieldName);
        fields.put(fieldName, field);
    }

}
项目:QDrill    文件:ClassGenerator.java   
@SuppressWarnings("unchecked")
ClassGenerator(CodeGenerator<T> codeGenerator, MappingSet mappingSet, SignatureHolder signature, EvaluationVisitor eval, JDefinedClass clazz, JCodeModel model) throws JClassAlreadyExistsException {
  this.codeGenerator = codeGenerator;
  this.clazz = clazz;
  this.mappings = mappingSet;
  this.sig = signature;
  this.evaluationVisitor = eval;
  this.model = model;
  blocks = (LinkedList<JBlock>[]) new LinkedList[sig.size()];
  for (int i =0; i < sig.size(); i++) {
    blocks[i] = Lists.newLinkedList();
  }
  rotateBlock();

  for (SignatureHolder child : signature.getChildHolders()) {
    String innerClassName = child.getSignatureClass().getSimpleName();
    JDefinedClass innerClazz = clazz._class(Modifier.FINAL + Modifier.PRIVATE, innerClassName);
    innerClasses.put(innerClassName, new ClassGenerator<>(codeGenerator, mappingSet, child, eval, innerClazz, model));
  }
}
项目:QDrill    文件:CodeGenerator.java   
CodeGenerator(MappingSet mappingSet, TemplateClassDefinition<T> definition,
    FunctionImplementationRegistry funcRegistry) {
  Preconditions.checkNotNull(definition.getSignature(),
      "The signature for defintion %s was incorrectly initialized.", definition);
  this.definition = definition;
  this.className = definition.getExternalInterface().getSimpleName() + "Gen" + definition.getNextClassNumber();
  this.fqcn = PACKAGE_NAME + "." + className;
  try {
    this.model = new JCodeModel();
    JDefinedClass clazz = model._package(PACKAGE_NAME)._class(className);
    rootGenerator = new ClassGenerator<>(this, mappingSet, definition.getSignature(), new EvaluationVisitor(
        funcRegistry), clazz, model);
  } catch (JClassAlreadyExistsException e) {
    throw new IllegalStateException(e);
  }
}
项目:sc-generator    文件:JsonSchemaController.java   
@RequestMapping(value = "/generator/preview", method = RequestMethod.POST)
public String preview(@RequestParam(value = "schema") String schema,
                      @RequestParam(value = "targetpackage") String targetpackage,
                      @RequestParam(value = "sourcetype", required = false) final String sourcetype,
                      @RequestParam(value = "annotationstyle", required = false) final String annotationstyle,
                      @RequestParam(value = "usedoublenumbers", required = false) final boolean usedoublenumbers,
                      @RequestParam(value = "includeaccessors", required = false) final boolean includeaccessors,
                      @RequestParam(value = "includeadditionalproperties", required = false) final boolean includeadditionalproperties,
                      @RequestParam(value = "propertyworddelimiters", required = false) final String propertyworddelimiters,
                      @RequestParam(value = "classname") String classname) throws IOException {

    final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    JCodeModel codegenModel = getCodegenModel(schema, targetpackage, sourcetype, annotationstyle, usedoublenumbers, includeaccessors, includeadditionalproperties, propertyworddelimiters, classname);
    codegenModel.build(new CodeWriter() {
        @Override
        public OutputStream openBinary(JPackage pkg, String fileName) throws IOException {
            return byteArrayOutputStream;
        }

        @Override
        public void close() throws IOException {
            byteArrayOutputStream.close();
        }
    });
    return byteArrayOutputStream.toString("utf-8");
}
项目:dremio-oss    文件:CodeGenerator.java   
CodeGenerator(CodeCompiler compiler, MappingSet mappingSet, TemplateClassDefinition<T> definition) {
  Preconditions.checkNotNull(definition.getSignature(),
      "The signature for defintion %s was incorrectly initialized.", definition);
  this.definition = definition;
  this.compiler = compiler;
  this.className = definition.getExternalInterface().getSimpleName() + "Gen" + definition.getNextClassNumber();
  this.fqcn = PACKAGE_NAME + "." + className;
  try {
    this.model = new JCodeModel();
    JDefinedClass clazz = model._package(PACKAGE_NAME)._class(className);
    clazz = clazz._extends(model.directClass(definition.getTemplateClassName()));
    clazz.constructor(JMod.PUBLIC).body().invoke(SignatureHolder.INIT_METHOD);
    rootGenerator = new ClassGenerator<>(this, mappingSet, definition.getSignature(), new EvaluationVisitor(), clazz, model);
  } catch (JClassAlreadyExistsException e) {
    throw new IllegalStateException(e);
  }
}
项目:dremio-oss    文件:HiveFuncHolder.java   
private JInvocation getUDFInstance(JCodeModel m) {
  if (isGenericUDF) {
    return JExpr._new(m.directClass(genericUdfClazz.getCanonicalName()));
  } else {
    return JExpr._new(m.directClass(GenericUDFBridge.class.getCanonicalName()))
      .arg(JExpr.lit(udfName))
      .arg(JExpr.lit(false))
      .arg(JExpr.lit(udfClazz.getCanonicalName().toString()));
  }
}
项目:libraries    文件:SourceFactoryUtilities.java   
public static IProcedure<JVar, RuntimeException> createAddIfNullSetEmptyArrayAndReturnClosure(
    final JCodeModel codeModel,
    final JMethod method,
    final JExpression returnValue) {
  ensureThatArgument(method, notNull());
  return new IProcedure<JVar, RuntimeException>() {

    @Override
    public void execute(final JVar param) throws RuntimeException {
      ensureThatArgument(param, notNull());
      final ValueConverter valueConverter = new ValueConverter(codeModel);
      final JInvocation invocation = JExpr._new(param.type());
      method
          .body()
          ._if(param.eq(JExpr._null()))
          ._then()
          .block()
          .assign(JExpr.refthis(param.name()), valueConverter.convert(invocation))
          ._return(returnValue);
    }
  };
}
项目:jpa-unit    文件:GraphElementFactoryTest.java   
@BeforeClass
public static void generateTestModel() throws Exception {
    final JCodeModel jCodeModel = new JCodeModel();

    final JPackage jp = jCodeModel.rootPackage();
    final JDefinedClass jClass = jp._class(JMod.PUBLIC, "A");
    jClass.annotate(Entity.class);
    jClass.field(JMod.PRIVATE, Long.class, "id").annotate(Id.class);
    jClass.field(JMod.PRIVATE, String.class, "value");

    buildModel(testFolder.getRoot(), jCodeModel);

    compileModel(testFolder.getRoot());

    entityAClass = loadClass(testFolder.getRoot(), jClass.name());
}
项目:jpa-unit    文件:JpaUnitRuleTest.java   
@Test
public void testClassWithPersistenceContextWithKonfiguredUnitNameSpecified() throws Exception {
    // GIVEN
    final JCodeModel jCodeModel = new JCodeModel();
    final JPackage jp = jCodeModel.rootPackage();
    final JDefinedClass jClass = jp._class(JMod.PUBLIC, "ClassUnderTest");
    final JFieldVar ruleField = jClass.field(JMod.PUBLIC, JpaUnitRule.class, "rule");
    ruleField.annotate(Rule.class);
    final JInvocation instance = JExpr._new(jCodeModel.ref(JpaUnitRule.class)).arg(JExpr.direct("getClass()"));
    ruleField.init(instance);
    final JFieldVar emField = jClass.field(JMod.PRIVATE, EntityManager.class, "em");
    final JAnnotationUse jAnnotation = emField.annotate(PersistenceContext.class);
    jAnnotation.param("unitName", "test-unit-1");
    final JMethod jMethod = jClass.method(JMod.PUBLIC, jCodeModel.VOID, "testMethod");
    jMethod.annotate(Test.class);

    buildModel(testFolder.getRoot(), jCodeModel);
    compileModel(testFolder.getRoot());

    final Class<?> cut = loadClass(testFolder.getRoot(), jClass.name());
    final BlockJUnit4ClassRunner runner = new BlockJUnit4ClassRunner(cut);

    final RunListener listener = mock(RunListener.class);
    final RunNotifier notifier = new RunNotifier();
    notifier.addListener(listener);

    // WHEN
    runner.run(notifier);

    // THEN
    final ArgumentCaptor<Description> descriptionCaptor = ArgumentCaptor.forClass(Description.class);
    verify(listener).testStarted(descriptionCaptor.capture());
    assertThat(descriptionCaptor.getValue().getClassName(), equalTo("ClassUnderTest"));
    assertThat(descriptionCaptor.getValue().getMethodName(), equalTo("testMethod"));

    verify(listener).testFinished(descriptionCaptor.capture());
    assertThat(descriptionCaptor.getValue().getClassName(), equalTo("ClassUnderTest"));
    assertThat(descriptionCaptor.getValue().getMethodName(), equalTo("testMethod"));
}
项目:jpa-unit    文件:AnnotationInspectorTest.java   
@BeforeClass
public static void generateModel() throws Exception {
    final JCodeModel jCodeModel = new JCodeModel();
    final JPackage jp = jCodeModel.rootPackage();
    final JDefinedClass jClass = jp._class(JMod.PUBLIC, "ClassUnderTest");
    JAnnotationUse jAnnotationUse = jClass.annotate(InitialDataSets.class);
    jAnnotationUse.param("value", "Script.file");
    jClass.annotate(Cleanup.class);
    final JFieldVar jField = jClass.field(JMod.PRIVATE, String.class, "testField");
    jField.annotate(PersistenceContext.class);
    final JMethod jMethod = jClass.method(JMod.PUBLIC, jCodeModel.VOID, "testMethod");
    jAnnotationUse = jMethod.annotate(InitialDataSets.class);
    jAnnotationUse.param("value", "InitialDataSets.file");
    jAnnotationUse = jMethod.annotate(ApplyScriptsAfter.class);
    jAnnotationUse.param("value", "ApplyScriptsAfter.file");

    buildModel(testFolder.getRoot(), jCodeModel);

    compileModel(testFolder.getRoot());

    cut = loadClass(testFolder.getRoot(), jClass.name());
}
项目:drill    文件:CodeGenerator.java   
CodeGenerator(MappingSet mappingSet, TemplateClassDefinition<T> definition, OptionSet optionManager) {
  Preconditions.checkNotNull(definition.getSignature(),
      "The signature for defintion %s was incorrectly initialized.", definition);
  this.definition = definition;
  this.className = definition.getExternalInterface().getSimpleName() + "Gen" + definition.getNextClassNumber();
  this.fqcn = PACKAGE_NAME + "." + className;
  try {
    this.model = new JCodeModel();
    JDefinedClass clazz = model._package(PACKAGE_NAME)._class(className);
    rootGenerator = new ClassGenerator<>(this, mappingSet,
      definition.getSignature(), new EvaluationVisitor(),
      clazz, model, optionManager);
  } catch (JClassAlreadyExistsException e) {
    throw new IllegalStateException(e);
  }
}
项目:kb_sdk    文件:JsonSchemaToPojoCustomObjectRule.java   
private JClass loadParameterizedType(JsonNode node, JCodeModel codeModel) {
    String className = node.get("javaType").asText();                       
    JClass ret = codeModel.ref(className);
    if (node.has("javaTypeParams")) {
        List<JClass> paramTypes = new ArrayList<JClass>();
        JsonNode paramNode = node.get("javaTypeParams");
        if (paramNode.isArray()) {
            Iterator<JsonNode> it = paramNode.elements();
            while (it.hasNext())
                paramTypes.add(loadParameterizedType(it.next(), codeModel));
        } else {
            paramTypes.add(loadParameterizedType(paramNode, codeModel));
        }
        ret = ret.narrow(paramTypes);
    }
    return ret;
}
项目:alchemy-rest-client-generator    文件:ServiceStubGenerator.java   
/**
 * Convert a generic {@link Type} to {@link JType}.
 *
 * @param rawType
 *            the raw type
 * @param type
 *            the generic type
 * @param jCodeModel
 *            the code model
 *
 * @return converted {@link JType}.
 */
private JType typeToJType(final Class<?> rawType, final Type type, final JCodeModel jCodeModel) {
    final JType jType = jCodeModel._ref(rawType);
    if (jType instanceof JPrimitiveType) {
        return jType;
    }
    JClass result = (JClass) jType;
    if (type instanceof ParameterizedType) {
        for (final Type typeArgument : ((ParameterizedType) type).getActualTypeArguments()) {
            if (typeArgument instanceof WildcardType) {
                result = result.narrow(jCodeModel.wildcard());
            } else if (typeArgument instanceof Class) {
                result = result.narrow(jCodeModel._ref((Class<?>) typeArgument));
            }
        }
    }
    return result;
}
项目:springmvc-raml-plugin    文件:SpringMvcEndpointGeneratorMojo.java   
/**
 * @param codeModel   If not null this will operated assuming a unified code model for all output
 * @param controllers
 * @param rootDir
 */
private void generateCode(JCodeModel codeModel, Set<ApiResourceMetadata> controllers, File rootDir) {
    for (ApiResourceMetadata met : controllers) {
        this.getLog().debug("");
        this.getLog().debug("-----------------------------------------------------------");
        this.getLog().info("Generating Code for Resource: " + met.getName());
        this.getLog().debug("");

        if (codeModel == null) {
            Set<ApiBodyMetadata> dependencies = met.getDependencies();
            for (ApiBodyMetadata body : dependencies) {
                generateModelSources(codeModel, body, rootDir, generationConfig, useJackson1xCompatibility ? new Jackson1Annotator(generationConfig) : null);
            }
        }

        generateControllerSource(codeModel, met, rootDir);
    }
}
项目:springmvc-raml-plugin    文件:SpringMvcEndpointGeneratorMojo.java   
@SuppressWarnings("unchecked")
private Rule<JCodeModel, JDefinedClass, ApiResourceMetadata> loadRule() {
    Rule<JCodeModel, JDefinedClass, ApiResourceMetadata> ruleInstance = new Spring4ControllerStubRule();
    try {
        ruleInstance = (Rule<JCodeModel, JDefinedClass, ApiResourceMetadata>) getClassRealm().loadClass(rule).newInstance();
        this.getLog().debug(StringUtils.collectionToCommaDelimitedString(ruleConfiguration.keySet()));
        this.getLog().debug(StringUtils.collectionToCommaDelimitedString(ruleConfiguration.values()));

        if (ruleInstance instanceof ConfigurableRule<?, ?, ?> && !CollectionUtils.isEmpty(ruleConfiguration)) {
            this.getLog().debug("SETTING CONFIG");
            ((ConfigurableRule<?, ?, ?>) ruleInstance).applyConfiguration(ruleConfiguration);
        }
    } catch (Exception e) {
        getLog().error("Could not instantiate Rule " + this.rule + ". The default Rule will be used for code generation.", e);
    }
    return ruleInstance;
}
项目:springmvc-raml-plugin    文件:AnyTypeInterpreter.java   
@Override
public RamlInterpretationResult interpret(RamlRoot document, TypeDeclaration type, JCodeModel builderModel,
        PojoGenerationConfig config, boolean property) {

    AnyTypeDeclaration anyTypeDeclaration = (AnyTypeDeclaration) type;

    RamlInterpretationResult result = new RamlInterpretationResult(type.required());
    String objectName;
    if ("array".equalsIgnoreCase(anyTypeDeclaration.type())) {
        objectName = Object.class.getSimpleName();
    } else {
        objectName = Void.class.getSimpleName();
    }

    result.setResolvedClass(CodeModelHelper.findFirstClassBySimpleName(builderModel, objectName));
    return result;
}
项目:springmvc-raml-plugin    文件:SpringControllerInterfaceRule.java   
@Override
public final JDefinedClass apply(ApiResourceMetadata metadata, JCodeModel generatableType) {

    GenericJavaClassRule generator = new GenericJavaClassRule()
            .setPackageRule(new PackageRule())
            .setClassCommentRule(new ClassCommentRule())
            .addClassAnnotationRule(getControllerAnnotationRule())
            .addClassAnnotationRule(new SpringValidatedClassAnnotationRule())
            .addClassAnnotationRule(new SpringRequestMappingClassAnnotationRule())
            .setClassRule(new ControllerInterfaceDeclarationRule())
            .setMethodCommentRule(new MethodCommentRule())
            .addMethodAnnotationRule(isUseShortcutMethodMappings() ?
                    new SpringShortcutMappingMethodAnnotationRule() : new SpringRequestMappingMethodAnnotationRule())
            .addMethodAnnotationRule(getResponseBodyAnnotationRule())
            .setMethodSignatureRule(new ControllerMethodSignatureRule(
                    isCallableResponse() ? new SpringCallableResponseEntityRule() :
                                    isSimpleReturnTypes() ? new SpringObjectReturnTypeRule() :
                                    new SpringResponseEntityRule(),
                    new SpringMethodParamsRule(isAddParameterJavadoc(), isAllowArrayParameters()))
            );
    return generator.apply(metadata, generatableType);
}
项目:springmvc-raml-plugin    文件:SpringFeignClientInterfaceDecoratorRule.java   
@Override
public final JDefinedClass apply(ApiResourceMetadata metadata, JCodeModel generatableType) {

    GenericJavaClassRule generator = new GenericJavaClassRule()
            .setPackageRule(new PackageRule())
            .setClassCommentRule(new ClassCommentRule())
            .addClassAnnotationRule(new SpringFeignClientClassAnnotationRule())
            .setClassRule(new SpringFeignClientInterfaceDeclarationRule())
            .setMethodCommentRule(new MethodCommentRule())
            .addMethodAnnotationRule(new SpringRequestMappingMethodAnnotationRule())
            .setMethodSignatureRule(new ControllerMethodSignatureRule(
                    new SpringFeignClientResponseTypeRule(),
                    new SpringMethodParamsRule())
            );
    return generator.apply(metadata, generatableType);
}
项目:springmvc-raml-plugin    文件:SpringControllerStubRule.java   
@Override
public final JDefinedClass apply(ApiResourceMetadata metadata, JCodeModel generatableType) {

    GenericJavaClassRule generator = new GenericJavaClassRule()
            .setPackageRule(new PackageRule())
            .setClassCommentRule(new ClassCommentRule())
            .addClassAnnotationRule(getControllerAnnotationRule())
            .addClassAnnotationRule(new SpringRequestMappingClassAnnotationRule())
            .addClassAnnotationRule(new SpringValidatedClassAnnotationRule())
            .setClassRule(new ControllerClassDeclarationRule())
            .setMethodCommentRule(new MethodCommentRule())
            .addMethodAnnotationRule(new SpringRequestMappingMethodAnnotationRule())
            .addMethodAnnotationRule(getResponseBodyAnnotationRule())
            .setMethodSignatureRule(new ControllerMethodSignatureRule(
                    isCallableResponse() ? new SpringSimpleCallableResponseTypeRule() :  new SpringSimpleResponseTypeRule(),
                    new SpringMethodParamsRule(isAddParameterJavadoc(), isAllowArrayParameters())
            ))
            .setMethodBodyRule(new ImplementMeMethodBodyRule());

    return generator.apply(metadata, generatableType);
}
项目:springmvc-raml-plugin    文件:GenericJavaClassRule.java   
/**
 * @throws IllegalStateException if a packageRule or classRule is missing or if the ApiControllerMetadata
 *         requires a missing methodSignatureRule.
 */
@Override
public JDefinedClass apply(ApiResourceMetadata metadata, JCodeModel codeModel) {

    if(packageRule == null || classRule == null) {
        throw new IllegalStateException("A packageRule and classRule are mandatory.");
    }
    if(!metadata.getApiCalls().isEmpty() && methodSignatureRule == null) {
        throw new IllegalStateException("Since there are API Calls in the metadata at least a methodSignatureRule is mandatory");
    }

    JPackage jPackage = packageRule.apply(metadata, codeModel);
    JDefinedClass jClass = classRule.apply(metadata, jPackage);
    implementsExtendsRule.ifPresent(rule -> rule.apply(metadata, jClass));
    classCommentRule.ifPresent(rule-> rule.apply(metadata, jClass));
    classAnnotationRules.forEach(rule -> rule.apply(metadata, jClass));
    fieldDeclerationRules.forEach(rule -> rule.apply(metadata, jClass));
    metadata.getApiCalls().forEach( apiMappingMetadata -> {
        JMethod jMethod = methodSignatureRule.apply(apiMappingMetadata, jClass);
        methodCommentRule.ifPresent(rule-> rule.apply(apiMappingMetadata, jMethod));
        methodAnnotationRules.forEach(rule -> rule.apply(apiMappingMetadata, jMethod));
        methodBodyRule.ifPresent( rule -> rule.apply(apiMappingMetadata, CodeModelHelper.ext(jMethod, jClass.owner())));
    });
    return jClass;
}
项目:springmvc-raml-plugin    文件:SpringMvcResourceParserTest.java   
@Test
  public void test_seperateContentType__Success() throws Exception {
      RamlRoot published = RamlLoader.loadRamlFromFile("test-responsebody-multipletype.raml");
      RamlParser par = new RamlParser("com.gen.test", "/api", true, false);
      Set<ApiResourceMetadata> controllersMetadataSet = par.extractControllers(new JCodeModel(), published);

      assertEquals(1, controllersMetadataSet.size());
      assertEquals(2, controllersMetadataSet.iterator().next().getApiCalls().size());

      //lets check that names wont collide
      Iterator<ApiActionMetadata> apiCallIterator = controllersMetadataSet.iterator().next().getApiCalls().iterator();
assertTrue(apiCallIterator.next().getName().contains("As"));
assertTrue(apiCallIterator.next().getName().contains("As"));

      //lets check that it switches off correctly
      par = new RamlParser("com.gen.test", "/api", false, false);
      controllersMetadataSet = par.extractControllers(new JCodeModel(), published);
      assertEquals(1, controllersMetadataSet.size());
      assertEquals(1, controllersMetadataSet.iterator().next().getApiCalls().size());

      //lets check that names arent changed
      apiCallIterator = controllersMetadataSet.iterator().next().getApiCalls().iterator();
assertFalse(apiCallIterator.next().getName().contains("As"));


  }
项目:map-engine    文件:MapperEngineCodeGenerator.java   
private static void createRetrieveClass(Retrieve retrieve, String packageName, File destinationDir) throws JClassAlreadyExistsException, IOException {
    JCodeModel codeModel = new JCodeModel();

    JClass mapClass = codeModel.ref(String.format("%s.%sMap", packageName, retrieve.getId()));

    JDefinedClass retrieveClass = codeModel._class(String.format("%s.%sRetrieve", packageName, retrieve.getId()));
    retrieveClass.javadoc().append("Auto generated class. Do not modify!");
    retrieveClass._extends(codeModel.ref(AbstractRetrieve.class).narrow(mapClass));

    // Constructor
    JMethod constructor = retrieveClass.constructor(JMod.PUBLIC);
    constructor.param(String.class, "id");
    constructor.body().invoke("super").arg(JExpr.ref("id"));

    // Implemented method
    JMethod getMapMethod = retrieveClass.method(JMod.PUBLIC, mapClass, "getMap");
    getMapMethod.annotate(Override.class);
    getMapMethod.param(codeModel.ref(Map.class).narrow(String.class, Object.class), "data");
    getMapMethod.body()._return(JExpr._new(mapClass).arg(JExpr.ref("data")));

    codeModel.build(destinationDir);
}
项目:thrift-java-compiler    文件:JavaGeneratorUtil.java   
public static String getThriftType(JCodeModel cm, JType jType) {

    if (cm.BOOLEAN.equals(jType) || cm.ref(Boolean.class).equals(jType)) {
        return "org.apache.thrift.protocol.TType.BOOL";
    } else if (cm.BYTE.equals(jType) || cm.ref(Byte.class).equals(jType)) {
        return "org.apache.thrift.protocol.TType.BYTE";
    } else if (cm.CHAR.equals(jType) || cm.ref(Character.class).equals(jType)) {
        return "org.apache.thrift.protocol.TType.STRING";
    } else if (cm.DOUBLE.equals(jType) || cm.ref(Double.class).equals(jType)) {
        return "org.apache.thrift.protocol.TType.DOUBLE";
    } else if (cm.FLOAT.equals(jType) || cm.ref(Float.class).equals(jType)) {
        return "org.apache.thrift.protocol.TType.DOUBLE";
    } else if (cm.INT.equals(jType) || cm.ref(Integer.class).equals(jType)) {
        return "org.apache.thrift.protocol.TType.I32";
    } else if (cm.LONG.equals(jType) || cm.ref(Long.class).equals(jType)) {
        return "org.apache.thrift.protocol.TType.I64";
    } else if (cm.ref(String.class).equals(jType)) {
        return "org.apache.thrift.protocol.TType.STRING";
    } else if (cm.SHORT.equals(jType) || cm.ref(Short.class).equals(jType)) {
        return "org.apache.thrift.protocol.TType.I16";
    } else if (jType instanceof JDefinedClass && ClassType.ENUM.equals(((JDefinedClass) jType).getClassType())) {
        return "org.apache.thrift.protocol.TType.ENUM";
    } else {
        return "org.apache.thrift.protocol.TType.STRUCT";
    }
}
项目:thrift-java-compiler    文件:TypeToJavaConverter.java   
public TypeToJavaConverter(
        final TypeRegistry typeRegistry,
        final TypedefRegistry typedefRegistry,
        final JCodeModel codeModel,
        final String namespace,
        final String javaPackage)
{
    Preconditions.checkNotNull(typeRegistry);
    Preconditions.checkNotNull(typedefRegistry);
    Preconditions.checkNotNull(namespace);
    this.typeRegistry = typeRegistry;
    this.typedefRegistry = typedefRegistry;
    this.codeModel = codeModel;
    this.namespace = namespace;
    this.javaPackage = javaPackage;

    final ImmutableList.Builder<Converter> builder = ImmutableList.builder();
    builder.add(new VoidConverter());
    builder.add(new BaseConverter());
    builder.add(new IdentifierConverter());
    builder.add(new SetConverter());
    builder.add(new ListConverter());
    builder.add(new MapConverter());
    converters = builder.build();
}
项目:jaxb2-annotate-plugin    文件:AnnotatePlugin.java   
protected void annotateEnumOutline(final JCodeModel codeModel,
        final EnumOutline enumOutline,
        final CCustomizations customizations,
        final ErrorHandler errorHandler) {
    for (final CPluginCustomization customization : customizations) {
        final Element element = customization.element;
        final QName name = new QName(element.getNamespaceURI(),
                element.getLocalName());
        if (Constants.NAMESPACE_URI.equals(name.getNamespaceURI())) {
            customization.markAsAcknowledged();
            final AnnotationTarget annotationTarget = AnnotationTarget
                    .getAnnotationTarget(element, AnnotationTarget.ENUM);
            try {
                final JAnnotatable annotatable = annotationTarget
                        .getAnnotatable(enumOutline.parent(), enumOutline);
                annotate(codeModel, errorHandler, customization, element,
                        annotatable);
            } catch (IllegalArgumentException iaex) {
                logger.error("Error applying the annotation.", iaex);
            }
        }
    }
}
项目:jpmml-model    文件:InheritancePlugin.java   
static
private JClass parseType(Map<String, JClass> typeCache, JCodeModel codeModel, String name){
    JClass type = typeCache.get(name);

    if(type == null){

        try {
            type = (JClass)codeModel.parseType(name);
        } catch(ClassNotFoundException cnfe){
            throw new RuntimeException(cnfe);
        }

        typeCache.put(name, type);
    }

    return type;
}
项目:jaxb2-basics    文件:RunPluginsForMain.java   
@Test
    public void compilesSchema() throws Exception {

        new File("target/generated-sources/xjc").mkdirs();

        URL schema = getClass().getResource("/main.xsd");
        URL binding = getClass().getResource("/main.xjb");
        final String[] arguments = new String[] { "-xmlschema",
                schema.toExternalForm(), "-b", binding.toExternalForm(), "-d",
                "target/generated-sources/xjc", "-extension",
                "-XsimpleHashCode",
//              "-XsimpleEquals", "-XsimpleToString"
                };

        Options options = new Options();
        options.parseArguments(arguments);
        ConsoleErrorReporter receiver = new ConsoleErrorReporter();
        Model model = ModelLoader.load(options, new JCodeModel(), receiver);
        model.generateCode(options, receiver);
        com.sun.codemodel.CodeWriter cw = options.createCodeWriter();
        model.codeModel.build(cw);
    }
项目:jaxb2-basics    文件:RunSimplifyPlugin.java   
@Test
public void compilesSchema() throws Exception {

    new File("target/generated-sources/xjc").mkdirs();

    URL schema = getClass().getResource("/schema.xsd");
    URL binding = getClass().getResource("/binding.xjb");
    final String[] arguments = new String[] { "-xmlschema",
            schema.toExternalForm(), "-b", binding.toExternalForm(), "-d",
            "target/generated-sources/xjc", "-extension", "-Xsimplify", "-Xsimplify-usePluralForm=true"};

    Options options = new Options();
    options.parseArguments(arguments);
    ConsoleErrorReporter receiver = new ConsoleErrorReporter();
    Model model = ModelLoader.load(options, new JCodeModel(), receiver);
    model.generateCode(options, receiver);
    com.sun.codemodel.CodeWriter cw = options.createCodeWriter();
    model.codeModel.build(cw);
}
项目:jaxb2-basics    文件:ExecuteJAXB1058.java   
@Test
public void compilesContext_V_1_1_0() throws Exception {

    new File("target/generated-sources/xjc").mkdirs();

    final String[] arguments = new String[] { "-xmlschema",
            new File("src/main/resources/schema.xsd").toURI().toString(),
            "-d",
            "target/generated-sources/xjc", 
            "-XfixJAXB1058",
            "-extension", "-XtoString",
            "-Xequals", "-XhashCode", "-Xcopyable", "-Xmergeable"};

    Options options = new Options();
    options.parseArguments(arguments);
    ConsoleErrorReporter receiver = new ConsoleErrorReporter();
    Model model = ModelLoader.load(options, new JCodeModel(), receiver);
    model.generateCode(options, receiver);
    com.sun.codemodel.CodeWriter cw = options.createCodeWriter();
    model.codeModel.build(cw);
}
项目:silver    文件:SilverWorker.java   
@Inject
public SilverWorker(Provider<RoundEnvironment> roundEnvironmentProvider,
                    ASTElementFactory astElementFactory,
                    ASTClassFactory astClassFactory,
                    ASTFactory astFactory,
                    ClassGenerationUtil generationUtil,
                    UniqueVariableNamer namer,
                    JCodeModel codeModel,
                    Validator validator) {
    this.roundEnvironmentProvider = roundEnvironmentProvider;
    this.astElementFactory = astElementFactory;
    this.astClassFactory = astClassFactory;
    this.astFactory = astFactory;
    this.generationUtil = generationUtil;
    this.namer = namer;
    this.codeModel = codeModel;
    this.validator = validator;
}
项目:jaxb2-annotate-plugin    文件:AnnotatePlugin.java   
protected void annotateEnumConstantOutline(final JCodeModel codeModel,
        final Outline outline,
        final EnumConstantOutline enumConstantOutline,
        final CCustomizations customizations,
        final ErrorHandler errorHandler) {
    for (final CPluginCustomization customization : customizations) {
        final Element element = customization.element;
        final QName name = new QName(element.getNamespaceURI(),
                element.getLocalName());
        if (Constants.NAMESPACE_URI.equals(name.getNamespaceURI())) {
            customization.markAsAcknowledged();
            final AnnotationTarget annotationTarget = AnnotationTarget
                    .getAnnotationTarget(element,
                            AnnotationTarget.ENUM_CONSTANT);
            try {
                final JAnnotatable annotatable = annotationTarget
                        .getAnnotatable(outline, enumConstantOutline);
                annotate(codeModel, errorHandler, customization, element,
                        annotatable);
            } catch (IllegalArgumentException iaex) {
                logger.error("Error applying the annotation.", iaex);
            }

        }
    }
}
项目:jaxb2-basics    文件:JavaTypeParser.java   
private JType parseType(String type, JCodeModel codeModel) {
    final String text = "public class Ignored extends " + type + " {}";
    try {
        CompilationUnit compilationUnit = JavaParser.parse(
                new ByteArrayInputStream(text.getBytes("UTF-8")), "UTF-8");
        final List<TypeDeclaration> typeDeclarations = compilationUnit
                .getTypes();
        final TypeDeclaration typeDeclaration = typeDeclarations.get(0);
        final ClassOrInterfaceDeclaration classDeclaration = (ClassOrInterfaceDeclaration) typeDeclaration;
        final List<ClassOrInterfaceType> _extended = classDeclaration
                .getExtends();
        final ClassOrInterfaceType classOrInterfaceType = _extended.get(0);

        return classOrInterfaceType.accept(
                this.typeToJTypeConvertingVisitor, codeModel);
    } catch (ParseException pex) {
        throw new IllegalArgumentException(
                "Could not parse the type definition [" + type + "].", pex);
    } catch (UnsupportedEncodingException uex) {
        throw new UnsupportedOperationException(uex);
    }
}