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

项目:GitHub    文件:DefaultRule.java   
/**
 * Creates a default value for a set property by:
 * <ol>
 * <li>Creating a new {@link LinkedHashSet} with the correct generic type
 * <li>Using {@link Arrays#asList(Object...)} to initialize the set with the
 * correct default values
 * </ol>
 *
 * @param fieldType
 *            the java type that applies for this field ({@link Set} with
 *            some generic type argument)
 * @param node
 *            the node containing default values for this set
 * @return an expression that creates a default value that can be assigned
 *         to this field
 */
private JExpression getDefaultSet(JType fieldType, JsonNode node) {

    JClass setGenericType = ((JClass) fieldType).getTypeParameters().get(0);

    JClass setImplClass = fieldType.owner().ref(LinkedHashSet.class);
    setImplClass = setImplClass.narrow(setGenericType);

    JInvocation newSetImpl = JExpr._new(setImplClass);

    if (node instanceof ArrayNode && node.size() > 0) {
        JInvocation invokeAsList = fieldType.owner().ref(Arrays.class).staticInvoke("asList");
        for (JsonNode defaultValue : node) {
            invokeAsList.arg(getDefaultValue(setGenericType, defaultValue));
        }
        newSetImpl.arg(invokeAsList);
    } else if (!ruleFactory.getGenerationConfig().isInitializeCollections()) {
        return JExpr._null();
    }

    return newSetImpl;

}
项目:GitHub    文件:DynamicPropertiesRule.java   
private JMethod addPublicSetMethod(JDefinedClass jclass, JMethod internalSetMethod) {
    JMethod method = jclass.method(PUBLIC, jclass.owner().VOID, SETTER_NAME);
    JVar nameParam = method.param(String.class, "name");
    JVar valueParam = method.param(Object.class, "value");
    JBlock body = method.body();
    JBlock notFound = body._if(JOp.not(invoke(internalSetMethod).arg(nameParam).arg(valueParam)))._then();

    // if we have additional properties, then put value.
    JMethod getAdditionalProperties = jclass.getMethod("getAdditionalProperties", new JType[] {});
    if (getAdditionalProperties != null) {
        JType additionalPropertiesType = ((JClass) (getAdditionalProperties.type())).getTypeParameters().get(1);
        notFound.add(invoke(getAdditionalProperties).invoke("put").arg(nameParam)
                .arg(cast(additionalPropertiesType, valueParam)));
    }
    // else throw exception.
    else {
        notFound._throw(illegalArgumentInvocation(jclass, nameParam));
    }

    return method;
}
项目:GitHub    文件:DynamicPropertiesRule.java   
private JMethod addPublicWithMethod(JDefinedClass jclass, JMethod internalSetMethod) {
    JMethod method = jclass.method(PUBLIC, jclass, BUILDER_NAME);
    JVar nameParam = method.param(String.class, "name");
    JVar valueParam = method.param(Object.class, "value");
    JBlock body = method.body();
    JBlock notFound = body._if(JOp.not(invoke(internalSetMethod).arg(nameParam).arg(valueParam)))._then();

    // if we have additional properties, then put value.
    JMethod getAdditionalProperties = jclass.getMethod("getAdditionalProperties", new JType[] {});
    if (getAdditionalProperties != null) {
        JType additionalPropertiesType = ((JClass) (getAdditionalProperties.type())).getTypeParameters().get(1);
        notFound.add(invoke(getAdditionalProperties).invoke("put").arg(nameParam)
                .arg(cast(additionalPropertiesType, valueParam)));
    }
    // else throw exception.
    else {
        notFound._throw(illegalArgumentInvocation(jclass, nameParam));
    }
    body._return(_this());

    return method;
}
项目:GitHub    文件:DefaultRule.java   
/**
 * Creates a default value for a list property by:
 * <ol>
 * <li>Creating a new {@link ArrayList} with the correct generic type
 * <li>Using {@link Arrays#asList(Object...)} to initialize the list with
 * the correct default values
 * </ol>
 *
 * @param fieldType
 *            the java type that applies for this field ({@link List} with
 *            some generic type argument)
 * @param node
 *            the node containing default values for this list
 * @return an expression that creates a default value that can be assigned
 *         to this field
 */
private JExpression getDefaultList(JType fieldType, JsonNode node) {

    JClass listGenericType = ((JClass) fieldType).getTypeParameters().get(0);

    JClass listImplClass = fieldType.owner().ref(ArrayList.class);
    listImplClass = listImplClass.narrow(listGenericType);

    JInvocation newListImpl = JExpr._new(listImplClass);

    if (node instanceof ArrayNode && node.size() > 0) {
        JInvocation invokeAsList = fieldType.owner().ref(Arrays.class).staticInvoke("asList");
        for (JsonNode defaultValue : node) {
            invokeAsList.arg(getDefaultValue(listGenericType, defaultValue));
        }
        newListImpl.arg(invokeAsList);
    } else if (!ruleFactory.getGenerationConfig().isInitializeCollections()) {
        return JExpr._null();
    }

    return newListImpl;

}
项目:GitHub    文件:ObjectRule.java   
private void addToString(JDefinedClass jclass) {
    Map<String, JFieldVar> fields = jclass.fields();
    JMethod toString = jclass.method(JMod.PUBLIC, String.class, "toString");
    Set<String> excludes = new HashSet<String>(Arrays.asList(ruleFactory.getGenerationConfig().getToStringExcludes()));

    JBlock body = toString.body();
    Class<?> toStringBuilder = ruleFactory.getGenerationConfig().isUseCommonsLang3() ? org.apache.commons.lang3.builder.ToStringBuilder.class : org.apache.commons.lang.builder.ToStringBuilder.class;
    JClass toStringBuilderClass = jclass.owner().ref(toStringBuilder);
    JInvocation toStringBuilderInvocation = JExpr._new(toStringBuilderClass).arg(JExpr._this());

    if (!jclass._extends().fullName().equals(Object.class.getName())) {
        toStringBuilderInvocation = toStringBuilderInvocation.invoke("appendSuper").arg(JExpr._super().invoke("toString"));
    }

    for (JFieldVar fieldVar : fields.values()) {
        if (excludes.contains(fieldVar.name()) || (fieldVar.mods().getValue() & JMod.STATIC) == JMod.STATIC) {
            continue;
        }
        toStringBuilderInvocation = toStringBuilderInvocation.invoke("append").arg(fieldVar.name()).arg(fieldVar);
    }

    body._return(toStringBuilderInvocation.invoke("toString"));

    toString.annotate(Override.class);
}
项目:GitHub    文件:ObjectRule.java   
private void addHashCode(JDefinedClass jclass, JsonNode node) {
    Map<String, JFieldVar> fields = removeFieldsExcludedFromEqualsAndHashCode(jclass.fields(), node);

    JMethod hashCode = jclass.method(JMod.PUBLIC, int.class, "hashCode");

    Class<?> hashCodeBuilder = ruleFactory.getGenerationConfig().isUseCommonsLang3() ? org.apache.commons.lang3.builder.HashCodeBuilder.class : org.apache.commons.lang.builder.HashCodeBuilder.class;

    JBlock body = hashCode.body();
    JClass hashCodeBuilderClass = jclass.owner().ref(hashCodeBuilder);
    JInvocation hashCodeBuilderInvocation = JExpr._new(hashCodeBuilderClass);

    if (!jclass._extends().fullName().equals(Object.class.getName())) {
        hashCodeBuilderInvocation = hashCodeBuilderInvocation.invoke("appendSuper").arg(JExpr._super().invoke("hashCode"));
    }

    for (JFieldVar fieldVar : fields.values()) {
        if ((fieldVar.mods().getValue() & JMod.STATIC) == JMod.STATIC) {
            continue;
        }
        hashCodeBuilderInvocation = hashCodeBuilderInvocation.invoke("append").arg(fieldVar);
    }

    body._return(hashCodeBuilderInvocation.invoke("toHashCode"));

    hashCode.annotate(Override.class);
}
项目:GitHub    文件:SerializableHelper.java   
@Override
public int compare(JClass object1, JClass object2) {
    if (object1 == null && object2 == null) {
        return 0;
    }
    if (object1 == null) {
        return 1;
    }
    if (object2 == null) {
        return -1;
    }
    final String name1 = object1.fullName();
    final String name2 = object2.fullName();
    if (name1 == null && name2 == null) {
        return 0;
    }
    if (name1 == null) {
        return 1;
    }
    if (name2 == null) {
        return -1;
    }
    return name1.compareTo(name2);
}
项目: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    文件: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    文件:Jsr303Annotator.java   
private JDefinedClass buildTemplateConstraint(String name) {
    try {
        JDefinedClass tplConstraint = codeModel._class(Config.CFG.getBasePackageName() + ".annot."+name, ClassType.ANNOTATION_TYPE_DECL);
        tplConstraint.annotate(Documented.class);
        tplConstraint.annotate(Retention.class).param("value", RetentionPolicy.RUNTIME);
        tplConstraint.annotate(Target.class).paramArray("value").param(ElementType.TYPE).param(ElementType.ANNOTATION_TYPE).param(ElementType.FIELD).param(ElementType.METHOD);

        // Using direct as I don't know how to build default { } with code model
        tplConstraint.direct("\n" + "    Class<?>[] groups() default {};\n" + "    String message() default \"Invalid value\";\n" + "    Class<? extends Payload>[] payload() default {};\n");

        // Hack to force the import of javax.validation.Payload
        tplConstraint.javadoc().addThrows((JClass) codeModel._ref(Payload.class)).add("Force import");

        return tplConstraint;
    } catch (JClassAlreadyExistsException e) {
        throw new RuntimeException("Tried to create an already existing class: " + name, e);
    }
}
项目:dremio-oss    文件:ClassGenerator.java   
public JVar declareVectorValueSetupAndMember(DirectExpression batchName, TypedFieldId fieldId) {
  final ValueVectorSetup setup = new ValueVectorSetup(batchName, fieldId);

  final Class<?> valueVectorClass = fieldId.getIntermediateClass();
  final JClass vvClass = model.ref(valueVectorClass);
  final JClass retClass = fieldId.isHyperReader() ? vvClass.array() : vvClass;

  final JVar vv = declareClassField("vv", retClass);
  final JBlock b = getSetupBlock();
  int[] fieldIndices = fieldId.getFieldIds();
  JInvocation invoke = model.ref(VectorResolver.class).staticInvoke(fieldId.isHyperReader() ? "hyper" : "simple")
      .arg(batchName)
      .arg(vvClass.dotclass());

  for(int i = 0; i < fieldIndices.length; i++){
    invoke.arg(JExpr.lit(fieldIndices[i]));
  }

  // we have to cast here since Janino doesn't handle generic inference well.
  JExpression casted = JExpr.cast(retClass, invoke);
  b.assign(vv, casted);
  vvDeclaration.put(setup, vv);

  return vv;
}
项目:libraries    文件:AbstractSourceFactory.java   
protected JType _type(final String type, final String... generics) {
  ensureThatArgument(type, notNull());
  if (generics.length == 0) {
    try {
      return this.codeModel.parseType(type);
    } catch (final ClassNotFoundException exception) {
      return this.codeModel.ref(type);
    }
  }
  final JClass[] classes = ArrayUtilities.convert(new IConverter<String, JClass, RuntimeException>() {

    @SuppressWarnings("synthetic-access")
    @Override
    public JClass convert(final String input) throws RuntimeException {
      return AbstractSourceFactory.this.codeModel.ref(input);
    }
  }, generics, JClass.class);
  return this.codeModel.ref(type).narrow(classes);
}
项目:libraries    文件:CreatorFactory.java   
public JMethod createCreateBeanMethod(final JDefinedClass bean) {

    final JMethod method = bean.method(JMod.PRIVATE | JMod.STATIC, bean, "_createBean");
    final JVar param = method.param(
        _classByNames(java.lang.Class.class.getName(), MessageFormat.format("? extends {0}", bean.name())),
        "clazz");
    final JClass invokerClass = _classByNames(
        "net.anwiba.commons.reflection.ReflectionConstructorInvoker",
        bean.name());
    final JTryBlock _try = method.body()._try();
    final JVar invoker = _try.body().decl(invokerClass, "invoker", JExpr._new(invokerClass).arg(param)); //$NON-NLS-1$
    _try.body()._return(invoker.invoke("invoke"));
    final JCatchBlock _catch = _try._catch(_classByNames(java.lang.reflect.InvocationTargetException.class.getName()));
    final JVar exception = _catch.param("exception"); //$NON-NLS-1$
    _catch.body()._throw(JExpr._new(_classByNames(java.lang.RuntimeException.class.getName())).arg(exception));
    return method;
  }
项目:libraries    文件:EqualsFactory.java   
public void createEquals(final JDefinedClass bean, final Iterable<JFieldVar> fields) {
  final JMethod method = bean.method(JMod.PUBLIC, this.codeModel.BOOLEAN, "equals");
  method.annotate(java.lang.Override.class);
  final JVar object = method.param(_type(java.lang.Object.class.getName()), "object");
  final JBlock block = method.body();
  block._if(JExpr._this().eq(object))._then()._return(JExpr.TRUE);
  block._if(object._instanceof(bean).not())._then()._return(JExpr.FALSE);
  JExpression result = JExpr.TRUE;
  final JExpression other = block.decl(bean, "other", JExpr.cast(bean, object));
  final JClass objectUtilities = _classByNames(net.anwiba.commons.lang.object.ObjectUtilities.class.getName());
  for (final JFieldVar field : fields) {
    result =
        result.cand(objectUtilities.staticInvoke("equals").arg(JExpr.refthis(field.name())).arg(other.ref(field)));
  }
  block._return(result);
}
项目:aml    文件:Types.java   
/**
 * <p>buildParameterType.</p>
 *
 * @param parameter a {@link org.aml.typesystem.ramlreader.NamedParam} object.
 * @param name a {@link java.lang.String} object.
 * @return a {@link com.sun.codemodel.JType} object.
 * @throws java.lang.Exception if any.
 */
public JType buildParameterType(final INamedParam parameter, final String name) throws Exception
{
    if ((parameter.getEnumeration() != null) && (!parameter.getEnumeration().isEmpty())&&Names.isValidEnumValues(parameter.getEnumeration()))
    {
        return context.createResourceEnum(context.getCurrentResourceInterface(), capitalize(name),
            parameter.getEnumeration());
    }

    final JType codegenType = context.getGeneratorType(getJavaType(parameter));

    if (parameter.isRepeat())
    {
        return ((JClass) context.getGeneratorType(List.class)).narrow(codegenType);
    }
    else
    {
        return codegenType;
    }
}
项目:aml    文件:Types.java   
/**
 * <p>getRequestEntityClass.</p>
 *
 * @param mimeType a {@link org.aml.apimodel.MimeType} object.
 * @return a {@link com.sun.codemodel.JType} object.
 * @throws java.io.IOException if any.
 */
public JType getRequestEntityClass(final MimeType mimeType) throws IOException
{
    if (startsWith(mimeType.getType(), "text/"))
    {
        return getGeneratorType(String.class);
    }
    if (MediaType.APPLICATION_OCTET_STREAM.equals(mimeType.getType()))
    {
                    return getGeneratorType(InputStream.class);
    }
    else {
    final JClass schemaClass = getSchemaClass(mimeType);

    if (schemaClass != null)
    {
        return schemaClass;
    }
    }

        // fallback to a generic reader
       return getGeneratorType(Reader.class);

}
项目:aml    文件:Types.java   
/**
 * <p>getResponseEntityClass.</p>
 *
 * @param mimeType a {@link org.aml.apimodel.MimeType} object.
 * @return a {@link com.sun.codemodel.JType} object.
 * @throws java.io.IOException if any.
 */
public JType getResponseEntityClass(final MimeType mimeType) throws IOException
{
    final JClass schemaClass = getSchemaClass(mimeType);

    if (schemaClass != null)
    {
        return schemaClass;
    }
    else if (startsWith(mimeType.getType(), "text/"))
    {
        return getGeneratorType(String.class);
    }
    else
    {
        // fallback to a streaming output
        return getGeneratorType(StreamingOutput.class);
    }
}
项目:aml    文件:Context.java   
/**
 * <p>createResourceEnum.</p>
 *
 * @param resourceInterface a {@link com.sun.codemodel.JDefinedClass} object.
 * @param name a {@link java.lang.String} object.
 * @param values a {@link java.util.List} object.
 * @return a {@link com.sun.codemodel.JDefinedClass} object.
 * @throws java.lang.Exception if any.
 */
public JDefinedClass createResourceEnum(final JDefinedClass resourceInterface,
                                        final String name,
                                        final List<String> values) throws Exception
{
    JClass[] listClasses = resourceInterface.listClasses();
    for (JClass c:listClasses){
        if (c.name().equals(name)){
            return (JDefinedClass) c;
        }
    }
    final JDefinedClass _enum = resourceInterface._enum(name);

    for (final String value : values)
    {
        _enum.enumConstant(value);
    }

    return _enum;
}
项目:aml    文件:ImplementationGenerator.java   
protected void addCode(JMethod method, AbstractType tp, String kind, Action action) {
    ArrayList<Link> arrayList = links.get(tp);
    if (arrayList == null) {
        arrayList = new ArrayList<>();
        links.put(tp, arrayList);
    }
    String role = kind;
    if (kind.equals("get")) {
        role = "self";
    }
    arrayList.add(new Link(role, action.resource().getUri(), action.method()));

    JType type = context.getType(tp);
    if (type == null) {
        return;
    }
    JInvocation iv = JExpr.invoke(JExpr.ref("manager"), kind).arg(JExpr.dotclass((JClass) type))
            .arg(JExpr.ref(method.name() + "_meta"));

    method.body().decl((JClass) type, "result", iv);
    method.params().forEach(x -> iv.arg(x));
}
项目:aml    文件:Generator.java   
protected JClass createResourceMethodReturnType(final String methodName,
                                                     final Action action,
                                                     final JDefinedClass resourceInterface)
    throws Exception
{
    final JDefinedClass responseClass = resourceInterface._class(capitalize(methodName) + "Response")
        ._extends(context.getResponseWrapperType());

    final JMethod responseClassConstructor = responseClass.constructor(JMod.PRIVATE);
    responseClassConstructor.param(javax.ws.rs.core.Response.class, "delegate");
    responseClassConstructor.body().invoke("super").arg(JExpr.ref("delegate"));

    for (final Response statusCodeAndResponse : action.responses())
    {
        createResponseBuilderInResourceMethodReturnType(action, responseClass, statusCodeAndResponse);
    }

    return responseClass;
}
项目:aml    文件:AbstractGenerator.java   
/**
 * <p>addFormParameters.</p>
 *
 * @param bodyMimeType a {@link org.aml.apimodel.MimeType} object.
 * @param method a {@link com.sun.codemodel.JMethod} object.
 * @param javadoc a {@link com.sun.codemodel.JDocComment} object.
 * @throws java.lang.Exception if any.
 */
protected void addFormParameters(final MimeType bodyMimeType,
        final JMethod method, final JDocComment javadoc) throws Exception {
    if (hasAMultiTypeFormParameter(bodyMimeType)) {
        // use a "catch all" MultivaluedMap<String, String> parameter
        final JClass type = types.getGeneratorClass(MultivaluedMap.class)
                .narrow(String.class, String.class);

        addCatchAllFormParametersArgument(bodyMimeType, method, javadoc,
                type);
    } else {
        for (final INamedParam namedFormParameters : bodyMimeType.getFormParameters()) {
            addParameter(namedFormParameters.getKey(), namedFormParameters, FormParam.class, method, javadoc);
        }
    }
}
项目:aml    文件:Types.java   
/**
 * <p>buildParameterType.</p>
 *
 * @param parameter a {@link org.aml.typesystem.ramlreader.NamedParam} object.
 * @param name a {@link java.lang.String} object.
 * @return a {@link com.sun.codemodel.JType} object.
 * @throws java.lang.Exception if any.
 */
public JType buildParameterType(final INamedParam parameter, final String name) throws Exception
{
    if ((parameter.getEnumeration() != null) && (!parameter.getEnumeration().isEmpty())&&Names.isValidEnumValues(parameter.getEnumeration()))
    {
        return context.createResourceEnum(context.getCurrentResourceInterface(), capitalize(name),
            parameter.getEnumeration());
    }

    final JType codegenType = context.getGeneratorType(getJavaType(parameter));

    if (parameter.isRepeat())
    {
        return ((JClass) context.getGeneratorType(List.class)).narrow(codegenType);
    }
    else
    {
        return codegenType;
    }
}
项目:aml    文件:Types.java   
/**
 * <p>getRequestEntityClass.</p>
 *
 * @param mimeType a {@link org.aml.apimodel.MimeType} object.
 * @return a {@link com.sun.codemodel.JType} object.
 * @throws java.io.IOException if any.
 */
public JType getRequestEntityClass(final MimeType mimeType) throws IOException
{
    if (startsWith(mimeType.getType(), "text/"))
    {
        return getGeneratorType(String.class);
    }
    if (MediaType.APPLICATION_OCTET_STREAM.equals(mimeType.getType()))
    {
                    return getGeneratorType(InputStream.class);
    }
    else {
    final JClass schemaClass = getSchemaClass(mimeType);

    if (schemaClass != null)
    {
        return schemaClass;
    }
    }

        // fallback to a generic reader
       return getGeneratorType(Reader.class);

}
项目:aml    文件:Types.java   
/**
 * <p>getResponseEntityClass.</p>
 *
 * @param mimeType a {@link org.aml.apimodel.MimeType} object.
 * @return a {@link com.sun.codemodel.JType} object.
 * @throws java.io.IOException if any.
 */
public JType getResponseEntityClass(final MimeType mimeType) throws IOException
{
    final JClass schemaClass = getSchemaClass(mimeType);

    if (schemaClass != null)
    {
        return schemaClass;
    }
    else if (startsWith(mimeType.getType(), "text/"))
    {
        return getGeneratorType(String.class);
    }
    else
    {
        // fallback to a streaming output
        return getGeneratorType(StreamingOutput.class);
    }
}
项目:aml    文件:Context.java   
/**
 * <p>createResourceEnum.</p>
 *
 * @param resourceInterface a {@link com.sun.codemodel.JDefinedClass} object.
 * @param name a {@link java.lang.String} object.
 * @param values a {@link java.util.List} object.
 * @return a {@link com.sun.codemodel.JDefinedClass} object.
 * @throws java.lang.Exception if any.
 */
public JDefinedClass createResourceEnum(final JDefinedClass resourceInterface,
                                        final String name,
                                        final List<String> values) throws Exception
{
    JClass[] listClasses = resourceInterface.listClasses();
    for (JClass c:listClasses){
        if (c.name().equals(name)){
            return (JDefinedClass) c;
        }
    }
    final JDefinedClass _enum = resourceInterface._enum(name);

    for (final String value : values)
    {
        _enum.enumConstant(value);
    }

    return _enum;
}
项目:aml    文件:AbstractGenerator.java   
/**
 * <p>addFormParameters.</p>
 *
 * @param bodyMimeType a {@link org.aml.apimodel.MimeType} object.
 * @param method a {@link com.sun.codemodel.JMethod} object.
 * @param javadoc a {@link com.sun.codemodel.JDocComment} object.
 * @throws java.lang.Exception if any.
 */
protected void addFormParameters(final MimeType bodyMimeType,
        final JMethod method, final JDocComment javadoc) throws Exception {
    if (hasAMultiTypeFormParameter(bodyMimeType)) {
        // use a "catch all" MultivaluedMap<String, String> parameter
        final JClass type = types.getGeneratorClass(MultivaluedMap.class)
                .narrow(String.class, String.class);

        addCatchAllFormParametersArgument(bodyMimeType, method, javadoc,
                type);
    } else {
        for (final INamedParam namedFormParameters : bodyMimeType.getFormParameters()) {
            addParameter(namedFormParameters.getKey(), namedFormParameters, FormParam.class, method, javadoc);
        }
    }
}
项目:aml    文件:InterfaceGenerator.java   
@Override
public JType define(AbstractType t) {
    JDefinedClass defineClass = writer.defineClass(t, ClassType.INTERFACE);
    for (AbstractType st:t.superTypes()){
        AbstractType superType = st;
        JType type = writer.getType(superType);
        defineClass._extends((JClass) type);
    }
    t.toPropertiesView().properties().forEach(p -> {
        String name = writer.propNameGenerator.name(p);
        JType propType = writer.getType(p.range(), false, false, p);
        //defineClass.field(JMod.PRIVATE, propType, name);
        defineClass.method(JMod.PUBLIC, propType,
                "get" + Character.toUpperCase(name.charAt(0)) + name.substring(1));

        defineClass.method(JMod.PUBLIC, writer.getModel()._ref(void.class),
                (p.range().isBoolean() ? "is" : "set") + Character.toUpperCase(name.charAt(0)) + name.substring(1));

    });
    writer.annotate(defineClass, t);
    return defineClass;
}
项目:jaxb2-namespace-prefix    文件:NamespacePrefixPlugin.java   
@SuppressWarnings("unchecked")
private static JAnnotationUse getOrAddXmlSchemaAnnotation(JPackage p, JClass xmlSchemaClass) {

    JAnnotationUse xmlAnn = null;

    final List<JAnnotationUse> annotations = getAnnotations(p);
    if (annotations != null) {
        for (JAnnotationUse annotation : annotations) {
            final JClass clazz = getAnnotationJClass(annotation);
            if (clazz == xmlSchemaClass) {
                xmlAnn = annotation;
                break;
            }
        }
    }

    if (xmlAnn == null) {
        // XmlSchema annotation not found, let's add one
        xmlAnn = p.annotate(xmlSchemaClass);
    }

    return xmlAnn;
}
项目:org.ops4j.ramler    文件:PojoGeneratingApiVisitor.java   
/**
 * @param klass
 * @param property
 */
private void generateAdditionalPropertiesFieldAndAccessors(JDefinedClass klass,
    TypeDeclaration property) {
    String fieldName = Names.buildVariableName(property);
    JClass mapType = codeModel.ref(Map.class).narrow(String.class, Object.class);
    JFieldVar field = klass.field(JMod.PRIVATE, mapType, fieldName);
    annotateFieldWithPropertyName(field, property);

    JMethod getter = klass.method(JMod.PUBLIC, mapType, getGetterName(fieldName));
    getter.body()._return(field);

    if (property.description() != null) {
        getter.javadoc().add(property.description().value());
    }
    generateSetter(klass, mapType, fieldName);
}
项目:org.ops4j.ramler    文件:PojoGeneratingApiVisitor.java   
private void generateListFieldAndAccessors(JDefinedClass klass, ArrayTypeDeclaration property) {
    String fieldName = Names.buildVariableName(property);
    String itemTypeName = context.getApiModel().getItemType(property);
    JType elementType = findTypeVar(klass, property).orElse(context.getJavaType(itemTypeName));
    JClass listType = codeModel.ref(List.class).narrow(elementType);
    JFieldVar field = klass.field(JMod.PRIVATE, listType, fieldName);
    annotateFieldWithPropertyName(field, property);

    JMethod getter = klass.method(JMod.PUBLIC, listType, getGetterName(fieldName));
    getter.body()._return(field);

    if (property.description() != null) {
        getter.javadoc().add(property.description().value());
    }
    generateSetter(klass, listType, fieldName);
}
项目:org.ops4j.ramler    文件:PojoGeneratingApiVisitor.java   
private void generateObjectFieldAndAccessors(JDefinedClass klass, TypeDeclaration property) {
    String fieldName = Names.buildVariableName(property);

    JType jtype = findTypeVar(klass, property).orElse(context.getJavaType(property));
    List<String> args = Annotations.getStringAnnotations(property, TYPE_ARGS);
    if (!args.isEmpty()) {
        JClass jclass = (JClass) jtype;
        for (String arg : args) {
            JType typeArg = findTypeParam(klass, arg).get();
            jclass = jclass.narrow(typeArg);
        }
        jtype = jclass;
    }
    JFieldVar field = klass.field(JMod.PRIVATE, jtype, fieldName);
    annotateFieldWithPropertyName(field, property);

    generateGetter(property, klass, field, this::getGetterName);
    generateSetter(klass, jtype, fieldName);
}
项目:flowable-engine    文件:CxfWSDLImporter.java   
protected static void _importFields(final JDefinedClass theClass, final AtomicInteger index, final SimpleStructureDefinition structure) {

        final JClass parentClass = theClass._extends();
        if (parentClass instanceof JDefinedClass) {
            _importFields((JDefinedClass) parentClass, index, structure);
        }
        for (Entry<String, JFieldVar> entry : theClass.fields().entrySet()) {
            Class<?> fieldClass = ReflectUtil.loadClass(entry.getValue().type().boxify().erasure().fullName());

            String fieldName = entry.getKey();
            if (fieldName.startsWith("_")) {
                if (!JJavaName.isJavaIdentifier(fieldName.substring(1))) {
                    fieldName = fieldName.substring(1); // it was prefixed with '_' so we should use the original name.
                }
            }

            structure.setFieldName(index.getAndIncrement(), fieldName, fieldClass);
        }
    }
项目: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    文件:StructCodeGeneratorHelper.java   
private void createMethodFieldSetFieldValue(JDefinedClass _class, Map<String, JType> fields) {
        JMethod method = _class.method(JMod.PUBLIC, Void.TYPE, "setFieldValue");
        JClass refEnumFields = codeModel.ref(_class.fullName() + DOT_FIELD);
        JVar param = method.param(refEnumFields, "field");
        JVar param2 = method.param(codeModel.ref(Object.class), "value");
        JBlock body = method.body();

        JSwitch _switch = body._switch(param);
        for (Map.Entry<String, JType> entry : fields.entrySet()) {
            JBlock bodyCase = _switch._case(JExpr.ref(entry.getKey().toUpperCase())).body();
            JConditional _if = bodyCase._if(param2.eq(JExpr._null()));
            String capitalizeName = JavaGeneratorUtil.getCapitalizeString(entry.getKey());
            _if._then().invoke("unset" + capitalizeName);
            _if._else().invoke("set" + capitalizeName).arg(JExpr.cast(getTypeGetMethodByName(_class, capitalizeName), param2));
            bodyCase._break();
        }

//      JInvocation _newException = JExpr._new(codeModel.ref(IllegalStateException.class));
//      _switch._default().body()._throw(_newException);

    }
项目:android-modules    文件:InjectHandler.java   
@Override
public void process(Element element, EComponentHolder holder) throws Exception {

    // I just copied this block from BeanHandler, I'm not sure I understand it
    TypeMirror typeMirror = annotationHelper.extractAnnotationClassParameter(element);
    if (typeMirror == null) {
        typeMirror = element.asType();
        typeMirror = holder.processingEnvironment().getTypeUtils().erasure(typeMirror);
    }

    JClass injectedClass = refClass(typeMirror.toString());
    JFieldRef injectField = ref(element.getSimpleName().toString());

    final JBlock initBody = holder.getInitBody();
    initBody.assign(injectField, ModuleCodeGenerator.moduleGetInstanceOrAddDefaultIfNeeded(holder, annotationHelper, holder.getGeneratedClass(), holder.getInit(), injectedClass, "", typeHasAnnotation(typeMirror, EBean.class))); // field = Module.getInstance()
}
项目: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;
}