Java Code Examples for com.sun.codemodel.JClass

The following are top voted examples for showing how to use com.sun.codemodel.JClass. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: GitHub   File: DefaultRule.java   View source code 7 votes vote down vote up
/**
 * 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;

}
 
Example 2
Project: GitHub   File: DynamicPropertiesRule.java   View source code 6 votes vote down vote up
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;
}
 
Example 3
Project: GitHub   File: DynamicPropertiesRule.java   View source code 6 votes vote down vote up
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;
}
 
Example 4
Project: GitHub   File: DefaultRule.java   View source code 6 votes vote down vote up
/**
 * 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;

}
 
Example 5
Project: GitHub   File: ObjectRule.java   View source code 6 votes vote down vote up
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);
}
 
Example 6
Project: GitHub   File: ObjectRule.java   View source code 6 votes vote down vote up
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);
}
 
Example 7
Project: GitHub   File: SerializableHelper.java   View source code 6 votes vote down vote up
@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);
}
 
Example 8
Project: GitHub   File: TypeRuleTest.java   View source code 6 votes vote down vote up
@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));
}
 
Example 9
Project: GitHub   File: ArrayRuleTest.java   View source code 6 votes vote down vote up
@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()));
}
 
Example 10
Project: GitHub   File: ArrayRuleTest.java   View source code 6 votes vote down vote up
@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()));
}
 
Example 11
Project: GitHub   File: ArrayRuleTest.java   View source code 6 votes vote down vote up
@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()));
}
 
Example 12
Project: GitHub   File: ArrayRuleTest.java   View source code 6 votes vote down vote up
@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)));
}
 
Example 13
Project: beanvalidation-benchmark   File: Jsr303Annotator.java   View source code 6 votes vote down vote up
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);
    }
}
 
Example 14
Project: dremio-oss   File: ClassGenerator.java   View source code 6 votes vote down vote up
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;
}
 
Example 15
Project: libraries   File: AbstractSourceFactory.java   View source code 6 votes vote down vote up
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);
}
 
Example 16
Project: libraries   File: CreatorFactory.java   View source code 6 votes vote down vote up
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;
  }
 
Example 17
Project: libraries   File: EqualsFactory.java   View source code 6 votes vote down vote up
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);
}
 
Example 18
Project: aml   File: Types.java   View source code 6 votes vote down vote up
/**
 * <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;
    }
}
 
Example 19
Project: aml   File: Types.java   View source code 6 votes vote down vote up
/**
 * <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);
    
}
 
Example 20
Project: aml   File: Types.java   View source code 6 votes vote down vote up
/**
 * <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);
    }
}
 
Example 21
Project: aml   File: Context.java   View source code 6 votes vote down vote up
/**
 * <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;
}
 
Example 22
Project: aml   File: ImplementationGenerator.java   View source code 6 votes vote down vote up
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));
}
 
Example 23
Project: aml   File: Generator.java   View source code 6 votes vote down vote up
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;
}
 
Example 24
Project: aml   File: AbstractGenerator.java   View source code 6 votes vote down vote up
/**
 * <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);
		}
	}
}
 
Example 25
Project: aml   File: Types.java   View source code 6 votes vote down vote up
/**
 * <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;
    }
}
 
Example 26
Project: aml   File: Types.java   View source code 6 votes vote down vote up
/**
 * <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);
    
}
 
Example 27
Project: aml   File: Types.java   View source code 6 votes vote down vote up
/**
 * <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);
    }
}
 
Example 28
Project: aml   File: Context.java   View source code 6 votes vote down vote up
/**
 * <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;
}
 
Example 29
Project: aml   File: AbstractGenerator.java   View source code 6 votes vote down vote up
/**
 * <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);
		}
	}
}
 
Example 30
Project: aml   File: InterfaceGenerator.java   View source code 6 votes vote down vote up
@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;
}
 
Example 31
Project: jaxb2-namespace-prefix   File: NamespacePrefixPlugin.java   View source code 6 votes vote down vote up
@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;
}
 
Example 32
Project: org.ops4j.ramler   File: PojoGeneratingApiVisitor.java   View source code 6 votes vote down vote up
/**
 * @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);
}
 
Example 33
Project: org.ops4j.ramler   File: PojoGeneratingApiVisitor.java   View source code 6 votes vote down vote up
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);
}
 
Example 34
Project: org.ops4j.ramler   File: PojoGeneratingApiVisitor.java   View source code 6 votes vote down vote up
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);
}
 
Example 35
Project: flowable-engine   File: CxfWSDLImporter.java   View source code 6 votes vote down vote up
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);
        }
    }
 
Example 36
Project: map-engine   File: MapperEngineCodeGenerator.java   View source code 6 votes vote down vote up
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);
}
 
Example 37
Project: thrift-java-compiler   File: StructCodeGeneratorHelper.java   View source code 6 votes vote down vote up
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);

	}
 
Example 38
Project: android-modules   File: InjectHandler.java   View source code 6 votes vote down vote up
@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()
}
 
Example 39
Project: kb_sdk   File: JsonSchemaToPojoCustomObjectRule.java   View source code 6 votes vote down vote up
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;
}
 
Example 40
Project: alchemy-rest-client-generator   File: ServiceStubGenerator.java   View source code 6 votes vote down vote up
/**
 * 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;
}