Java Code Examples for com.sun.codemodel.JClass#narrow()

The following examples show how to use com.sun.codemodel.JClass#narrow() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TypeToJTypeConvertingVisitor.java    From jaxb2-basics with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Override
public JType visit(ClassOrInterfaceType type, JCodeModel codeModel) {
	final String name = getName(type);
	final JClass knownClass = this.knownClasses.get(name);
	final JClass jclass = knownClass != null ? knownClass : codeModel
			.ref(name);
	final List<Type> typeArgs = type.getTypeArgs();
	if (typeArgs == null || typeArgs.isEmpty()) {
		return jclass;
	} else {
		final List<JClass> jtypeArgs = new ArrayList<JClass>(
				typeArgs.size());
		for (Type typeArg : typeArgs) {
			final JType jtype = typeArg.accept(this, codeModel);
			if (!(jtype instanceof JClass)) {
				throw new IllegalArgumentException("Type argument ["
						+ typeArg.toString() + "] is not a class.");
			} else {
				jtypeArgs.add((JClass) jtype);
			}
		}
		return jclass.narrow(jtypeArgs);
	}
}
 
Example 2
Source File: PluginImpl.java    From immutable-xjc with MIT License 6 votes vote down vote up
private JExpression getDefensiveCopyExpression(JCodeModel codeModel, JType jType, JVar param) {
    List<JClass> typeParams = ((JClass) jType).getTypeParameters();
    JClass typeParameter = null;
    if (typeParams.iterator().hasNext()) {
        typeParameter = typeParams.iterator().next();
    }

    JClass newClass = null;
    if (param.type().erasure().equals(codeModel.ref(Collection.class))) {
        newClass = codeModel.ref(ArrayList.class);
    } else if (param.type().erasure().equals(codeModel.ref(List.class))) {
        newClass = codeModel.ref(ArrayList.class);
    } else if (param.type().erasure().equals(codeModel.ref(Map.class))) {
        newClass = codeModel.ref(HashMap.class);
    } else if (param.type().erasure().equals(codeModel.ref(Set.class))) {
        newClass = codeModel.ref(HashSet.class);
    } else if (param.type().erasure().equals(codeModel.ref(SortedMap.class))) {
        newClass = codeModel.ref(TreeMap.class);
    } else if (param.type().erasure().equals(codeModel.ref(SortedSet.class))) {
        newClass = codeModel.ref(TreeSet.class);
    }
    if (newClass != null && typeParameter != null) {
        newClass = newClass.narrow(typeParameter);
    }
    return newClass == null ? JExpr._null() : JExpr._new(newClass).arg(param);
}
 
Example 3
Source File: RuleHelper.java    From springmvc-raml-plugin with Apache License 2.0 5 votes vote down vote up
private static JClass getResponseEntityNarrow(JCodeModel owner, JClass genericType, JClass callable) {

		JClass responseEntity = owner.ref(ResponseEntity.class);
		JClass returnNarrow = responseEntity.narrow(genericType);

		if (callable != null) {
			returnNarrow = callable.narrow(returnNarrow);
		}
		return returnNarrow;
	}
 
Example 4
Source File: RuleHelper.java    From springmvc-raml-plugin with Apache License 2.0 5 votes vote down vote up
private static JClass updateType(JCodeModel owner, JClass callable, JClass type, boolean useResponseEntity, boolean isArray) {

		JClass arrayType = owner.ref(List.class);
		if (useResponseEntity && isArray) {
			type = getResponseEntityNarrow(owner, arrayType.narrow(type), callable);
		} else if (useResponseEntity) {
			type = getResponseEntityNarrow(owner, type, callable);
		} else if (isArray) {
			type = arrayType.narrow(type);
		}
		return type;
	}
 
Example 5
Source File: MethodParamsRule.java    From springmvc-raml-plugin with Apache License 2.0 5 votes vote down vote up
protected JVar paramObjects(ApiActionMetadata endpointMetadata, CodeModelHelper.JExtMethod generatableType) {

		String requestBodyName = endpointMetadata.getRequestBody().getName();
		String requestBodyFullName = requestBodyName;
		if (BigDecimal.class.getSimpleName().equals(requestBodyName)) {
			requestBodyFullName = BigDecimal.class.getName();
		} else if (BigInteger.class.getSimpleName().equals(requestBodyName)) {
			requestBodyFullName = BigInteger.class.getName();
		}

		boolean array = endpointMetadata.getRequestBody().isArray();

		List<JCodeModel> codeModels = new ArrayList<>();
		if (endpointMetadata.getRequestBody().getCodeModel() != null) {
			codeModels.add(endpointMetadata.getRequestBody().getCodeModel());
		}

		if (generatableType.owner() != null) {
			codeModels.add(generatableType.owner());
		}

		JClass requestBodyType = findFirstClassBySimpleName(codeModels.toArray(new JCodeModel[codeModels.size()]), requestBodyFullName);
		if (allowArrayParameters && array) {
			JClass arrayType = generatableType.owner().ref(List.class);
			requestBodyType = arrayType.narrow(requestBodyType);
		}
		if (addParameterJavadoc) {
			generatableType.get().javadoc().addParam(NamingHelper.getParameterName(requestBodyName) + " The Request Body Payload");
		}
		JVar param = generatableType.get().param(requestBodyType, NamingHelper.getParameterName(requestBodyName));
		if (Config.getPojoConfig().isIncludeJsr303Annotations() && !RamlActionType.PATCH.equals(endpointMetadata.getActionType())) {
			// skip Valid annotation for PATCH actions since it's a partial
			// update so some required fields might be omitted
			param.annotate(Valid.class);
		}
		return param;
	}
 
Example 6
Source File: UntypedListField.java    From hyperjaxb3 with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * @param coreList
 *      A concrete class that implements the List interface.
 *      An instance of this class will be used to store data
 *      for this field.
 */
protected UntypedListField(ClassOutlineImpl context, CPropertyInfo prop, JClass coreList) {
    // the JAXB runtime picks ArrayList if the signature is List,
    // so don't do eager allocation if it's ArrayList.
    // otherwise we need to do eager allocation so that the collection type specified by the user
    // will be used.
    super(context, prop, !coreList.fullName().equals("java.util.ArrayList"));
    this.coreList = coreList.narrow(exposedType.boxify());
    generate();
}
 
Example 7
Source File: Translator.java    From groovy-cps with Apache License 2.0 5 votes vote down vote up
@Override
public JType visitParameterizedType(ParameterizedTypeTree pt, Void __) {
    JClass base = (JClass)visit(pt.getType());
    List<JClass> args = new ArrayList<>();
    for (Tree arg : pt.getTypeArguments()) {
        args.add((JClass)visit(arg));
    }
    return base.narrow(args);
}
 
Example 8
Source File: PluginImpl.java    From immutable-xjc with MIT License 5 votes vote down vote up
private JExpression getNewCollectionExpression(JCodeModel codeModel, JType jType) {
    List<JClass> typeParams = ((JClass) jType).getTypeParameters();
    JClass typeParameter = null;
    if (typeParams.iterator().hasNext()) {
        typeParameter = typeParams.iterator().next();
    }

    JClass newClass = null;
    if (jType.erasure().equals(codeModel.ref(Collection.class))) {
        newClass = codeModel.ref(ArrayList.class);
    } else if (jType.erasure().equals(codeModel.ref(List.class))) {
        newClass = codeModel.ref(ArrayList.class);
    } else if (jType.erasure().equals(codeModel.ref(Map.class))) {
        newClass = codeModel.ref(HashMap.class);
    } else if (jType.erasure().equals(codeModel.ref(Set.class))) {
        newClass = codeModel.ref(HashSet.class);
    } else if (jType.erasure().equals(codeModel.ref(SortedMap.class))) {
        newClass = codeModel.ref(TreeMap.class);
    } else if (jType.erasure().equals(codeModel.ref(SortedSet.class))) {
        newClass = codeModel.ref(TreeSet.class);
    }
    if (newClass != null && typeParameter != null) {
        newClass = newClass.narrow(typeParameter);
    }

    return newClass == null ? JExpr._null() : JExpr._new(newClass);
}
 
Example 9
Source File: SchemaAssistant.java    From avro-fastserde with Apache License 2.0 4 votes vote down vote up
public JClass classFromSchema(Schema schema, boolean abstractType, boolean rawType) {
    JClass outputClass;

    switch (schema.getType()) {

        case RECORD:
            outputClass = useGenericTypes ? codeModel.ref(GenericData.Record.class)
                    : codeModel.ref(schema.getFullName());
            break;

        case ARRAY:
            if (abstractType) {
                outputClass = codeModel.ref(List.class);
            } else {
                if (useGenericTypes) {
                    outputClass = codeModel.ref(GenericData.Array.class);
                } else {
                    outputClass = codeModel.ref(ArrayList.class);
                }
            }
            if (!rawType) {
                outputClass = outputClass.narrow(elementClassFromArraySchema(schema));
            }
            break;
        case MAP:
            if (!abstractType) {
                outputClass = codeModel.ref(HashMap.class);
            } else {
                outputClass = codeModel.ref(Map.class);
            }
            if (!rawType) {
                outputClass = outputClass.narrow(keyClassFromMapSchema(schema), valueClassFromMapSchema(schema));
            }
            break;
        case UNION:
            outputClass = classFromUnionSchema(schema);
            break;
        case ENUM:
            outputClass = useGenericTypes ? codeModel.ref(GenericData.EnumSymbol.class)
                    : codeModel.ref(schema.getFullName());
            break;
        case FIXED:
            outputClass = useGenericTypes ? codeModel.ref(GenericData.Fixed.class)
                    : codeModel.ref(schema.getFullName());
            break;
        case BOOLEAN:
            outputClass = codeModel.ref(Boolean.class);
            break;
        case DOUBLE:
            outputClass = codeModel.ref(Double.class);
            break;
        case FLOAT:
            outputClass = codeModel.ref(Float.class);
            break;
        case INT:
            outputClass = codeModel.ref(Integer.class);
            break;
        case LONG:
            outputClass = codeModel.ref(Long.class);
            break;
        case STRING:

            if (isStringable(schema) && !useGenericTypes) {
                outputClass = codeModel.ref(schema.getProp(SpecificData.CLASS_PROP));
                extendExceptionsFromStringable(schema.getProp(SpecificData.CLASS_PROP));
            } else {
                if (useCharSequence) {
                    outputClass = codeModel.ref(CharSequence.class);
                } else if ("String".equals(schema.getProp(GenericData.STRING_PROP))) {
                    outputClass = codeModel.ref(String.class);
                } else {
                    outputClass = codeModel.ref(Utf8.class);
                }
            }
            break;
        case BYTES:
            outputClass = codeModel.ref(ByteBuffer.class);
            break;
        default:
            throw new SchemaAssistantException("Incorrect request for " + schema.getType().getName() + " class!");
    }

    return outputClass;
}
 
Example 10
Source File: ObjectCodeGenerator.java    From jaxb2-basics with BSD 2-Clause "Simplified" License 4 votes vote down vote up
@Override
public void generate(final JBlock block, JType type,
		Collection<JType> possibleTypes, boolean isAlwaysSet, A arguments) {
	if (possibleTypes.size() <= 1) {
		getImplementor().onObject(arguments, block, isAlwaysSet);
	} else {
		final JClass jaxbElementClass = getCodeModel().ref(
				JAXBElement.class);
		final Set<JType> arrays = new HashSet<JType>();
		final Collection<JClass> jaxbElements = new HashSet<JClass>();
		final Set<JType> otherTypes = new HashSet<JType>();
		for (final JType possibleType : possibleTypes) {
			if (possibleType.isArray()) {
				arrays.add(possibleType);
			} else if (possibleType instanceof JClass
					&& jaxbElementClass
							.isAssignableFrom(((JClass) possibleType)
									.erasure())) {
				jaxbElements.add((JClass) possibleType);
			} else {
				otherTypes.add(possibleType);
			}
		}

		final JConditionable _if = new JConditionable() {

			private JConditional conditional = null;

			@Override
			public JBlock _ifThen(JExpression condition) {
				if (conditional == null) {
					conditional = block._if(condition);
				} else {
					conditional = conditional._elseif(condition);
				}
				return conditional._then();
			}

			@Override
			public JBlock _else() {
				if (conditional == null) {
					return block;
				} else {
					return conditional._else();
				}
			}
		};

		if (!jaxbElements.isEmpty()) {
			final Set<JType> valueTypes = getJAXBElementValueTypes(jaxbElements);
			final JType valueType = TypeUtil.getCommonBaseType(
					getCodeModel(), valueTypes);
			final JClass jaxbElementType = jaxbElementClass
					.narrow(valueType);

			final JBlock jaxbElementBlock = _if._ifThen(arguments
					._instanceof(jaxbElementClass));
			getCodeGenerator().generate(
					jaxbElementBlock,
					jaxbElementType,
					new HashSet<JType>(jaxbElements),
					true,
					arguments.cast("JAXBElement", jaxbElementBlock,
							jaxbElementType, true));

		}

		if (!arrays.isEmpty()) {
			for (JType arrayType : arrays) {
				final JBlock arrayBlock = _if._ifThen(arguments
						._instanceof(arrayType));
				getCodeGenerator().generate(
						arrayBlock,
						arrayType,
						Collections.singleton(arrayType),
						true,
						arguments.cast("Array", arrayBlock, arrayType,
								false));
			}
		}

		if (!otherTypes.isEmpty()) {
			getImplementor().onObject(arguments, _if._else(), false);
		}
	}
}