Java Code Examples for com.sun.codemodel.JCodeModel#ref()

The following examples show how to use com.sun.codemodel.JCodeModel#ref() . 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: ConnectPlugin.java    From kafka-connect-transform-xml with Apache License 2.0 6 votes vote down vote up
void processToStruct(JFieldVar schemaField, JCodeModel codeModel, ClassOutline classOutline) {
  final Map<String, JFieldVar> fields = classOutline.implClass.fields();
  final JClass structClass = codeModel.ref(Struct.class);
  final JMethod method = classOutline.implClass.method(JMod.PUBLIC, structClass, "toStruct");
  final JBlock methodBody = method.body();
  final JVar structVar = methodBody.decl(structClass, "struct", JExpr._new(structClass).arg(schemaField));

  for (final Map.Entry<String, JFieldVar> field : fields.entrySet()) {
    log.trace("processSchema() - processing name = '{}' type = '{}'", field.getKey(), field.getValue().type().name());
    if (schemaField.name().equals(field.getKey())) {
      log.trace("processSchema() - skipping '{}' cause we added it.", field.getKey());
      continue;
    }

    methodBody.invoke(structVar, "put")
        .arg(field.getKey())
        .arg(JExpr.ref(JExpr._this(), field.getKey()));
  }

  methodBody._return(structVar);
}
 
Example 2
Source File: InExpression.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
public JClass getListType(JCodeModel model) {
  final CompleteType type = eval.getCompleteType();
  if(CompleteType.BIGINT.equals(type)) {
    return model.ref(LongSet.class);
  }else if(CompleteType.INT.equals(type)) {
    return model.ref(IntSet.class);
  }else if(CompleteType.DATE.equals(type)) {
    return model.ref(LongSet.class);
  }else if(CompleteType.TIME.equals(type)) {
    return model.ref(IntSet.class);
  }else if(CompleteType.TIMESTAMP.equals(type)) {
    return model.ref(LongSet.class);
  }else if(CompleteType.VARCHAR.equals(type)) {
    return model.ref(BytesSet.class);
  }else if(CompleteType.VARBINARY.equals(type)) {
    return model.ref(BytesSet.class);
  } else {
    throw new UnsupportedOperationException(type.toString() + " does not support in list optimizations.");
  }
}
 
Example 3
Source File: RamlJavaClientGenerator.java    From raml-java-client-generator with Apache License 2.0 6 votes vote down vote up
private JType getOrGeneratePojoFromJsonSchema(JCodeModel cm, String resourcePath, MimeType mimeType, String className) throws IOException {
    JType type = null;

    if (StringUtils.isNotBlank(mimeType.getSchema())) {
        if (globalTypes.containsKey(mimeType.getSchema())) {
            type = globalTypes.get(mimeType.getSchema());
        } else {
            type = generatePojoFromSchema(cm, className, getModelPackage(resourcePath), mimeType.getSchema(), mimeType.getSchemaPath(), SourceType.JSONSCHEMA);
        }
    } else if (StringUtils.isNotBlank(mimeType.getExample())) {
        type = generatePojoFromSchema(cm, className, getModelPackage(resourcePath), mimeType.getExample(), SourceType.JSON);
    }

    if (type != null && type.fullName().equals("java.lang.Object") && StringUtils.isNotBlank(mimeType.getExample())) {
        type = generatePojoFromSchema(cm, className, getModelPackage(resourcePath), mimeType.getExample(), SourceType.JSON);
    }

    if (type == null) {
        type = cm.ref(Object.class);
    }

    return type;
}
 
Example 4
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 5
Source File: RuleHelper.java    From springmvc-raml-plugin with Apache License 2.0 6 votes vote down vote up
private static JClass narrow(ApiActionMetadata endpointMetadata, JCodeModel owner, boolean useCallable, boolean checkBody,
		boolean useWildcard, boolean useDeferredResult) {

	JClass callable = null;
	if (useCallable) {
		callable = owner.ref(Callable.class);
	}
	if (useDeferredResult) {
		callable = owner.ref(DeferredResult.class);
	}
	if (checkBody && endpointMetadata.getResponseBody().isEmpty()) {
		if (useWildcard || useDeferredResult) {
			return getResponseEntityNarrow(owner, owner.wildcard(), callable);
		} else {
			return owner.ref(Object.class);
		}
	}

	return getReturnEntity(endpointMetadata, owner, callable, useWildcard);
}
 
Example 6
Source File: CodeModelUtils.java    From jaxb2-basics with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public static JType ref(JCodeModel codeModel, String className) {
	try {
		// try the context class loader first
		return codeModel.ref(Thread.currentThread().getContextClassLoader()
				.loadClass(className));
	} catch (ClassNotFoundException e) {
		// fall through
	}
	// then the default mechanism.
	try {
		return codeModel.ref(Class.forName(className));
	} catch (ClassNotFoundException e1) {
		// fall through
	}

	{
		JDefinedClass _class = _getClass(codeModel, className);
		if (_class != null) {
			return _class;
		}
	}
	return codeModel.ref(className.replace('$', '.'));
}
 
Example 7
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 8
Source File: OperationProcessor.java    From jpmml-evaluator with GNU Affero General Public License v3.0 5 votes vote down vote up
static
private JInvocation createReportInvocation(JDefinedClass clazz, String operation, List<JVar> parameters, JPrimitiveType type){
	JCodeModel codeModel = clazz.owner();

	JClass stringBuilderClazz = codeModel.ref(StringBuilder.class);

	return createReportInvocation(clazz, JExpr._new(stringBuilderClazz).arg(JExpr.lit(256)), operation, parameters, type);
}
 
Example 9
Source File: SchemaAssistant.java    From avro-util with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public SchemaAssistant(JCodeModel codeModel, boolean useGenericTypes, Class defaultStringClass) {
  this.codeModel = codeModel;
  this.useGenericTypes = useGenericTypes;
  /**
   * Use {@link TreeSet} here to make sure the code gen is deterministic.
   */
  this.exceptionsFromStringable = new TreeSet<>(Comparator.comparing(Class::getCanonicalName));
  this.defaultStringType = codeModel.ref(defaultStringClass);
}
 
Example 10
Source File: OperationProcessor.java    From jpmml-evaluator with GNU Affero General Public License v3.0 5 votes vote down vote up
static
private void createNewReportMethod(JDefinedClass clazz){
	JCodeModel codeModel = clazz.owner();

	JClass reportClazz = codeModel.ref(Report.class);

	JMethod method = clazz.method(JMod.ABSTRACT | JMod.PROTECTED, reportClazz, "newReport");
}
 
Example 11
Source File: OperationProcessor.java    From jpmml-evaluator with GNU Affero General Public License v3.0 5 votes vote down vote up
static
private void createReportingConstructor(JDefinedClass clazz, ExecutableElement executableElement, String operation, String initialOperation, JPrimitiveType type){
	JCodeModel codeModel = clazz.owner();

	JMethod constructor = clazz.constructor(JMod.PUBLIC);

	List<? extends VariableElement> parameterElements = executableElement.getParameters();
	for(VariableElement parameterElement : parameterElements){
		constructor.param(toType(codeModel, parameterElement.asType()), String.valueOf(parameterElement.getSimpleName()));
	}

	JBlock body = constructor.body();

	body.add(createSuperInvocation(clazz, constructor));

	if((clazz.name()).endsWith("Value")){
		JClass reportClazz = codeModel.ref(Report.class);

		JVar reportParameter = constructor.param(reportClazz, "report");

		body.add(JExpr.invoke("setReport").arg(reportParameter));
	} // End if

	if(initialOperation != null){
		throw new RuntimeException();
	}

	body.add(JExpr.invoke("report").arg(createReportInvocation(clazz, operation, constructor.params(), type)));
}
 
Example 12
Source File: MetaPlugin.java    From jaxb2-rich-contract-plugin with MIT License 5 votes vote down vote up
private JMethod generateVisitMethod(final ClassOutline classOutline) {
	final JDefinedClass definedClass = classOutline.implClass;
	final JMethod visitMethod = definedClass.method(JMod.PUBLIC, definedClass, this.visitMethodName);
	final JCodeModel codeModel = definedClass.owner();
	final JClass visitorType = codeModel.ref(PropertyVisitor.class);
	final JVar visitorParam = visitMethod.param(JMod.FINAL, visitorType, "_visitor_");
	if (classOutline.getSuperClass() != null) {
		visitMethod.body().add(JExpr._super().invoke(this.visitMethodName).arg(visitorParam));
	} else {
		visitMethod.body().add(visitorParam.invoke("visit").arg(JExpr._this()));
	}
	return visitMethod;
}
 
Example 13
Source File: JTypeUtils.java    From hyperjaxb3 with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public static JType[] getTemporalTypes(final JCodeModel codeModel) {
	final JType[] basicTypes = new JType[] {
			codeModel.ref(java.util.Date.class),
			codeModel.ref(java.util.Calendar.class),
			codeModel.ref(java.sql.Date.class),
			codeModel.ref(java.sql.Time.class),
			codeModel.ref(java.sql.Timestamp.class) };
	return basicTypes;
}
 
Example 14
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 15
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 16
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 17
Source File: RamlJavaClientGenerator.java    From raml-java-client-generator with Apache License 2.0 5 votes vote down vote up
private List<JTypeWithMimeType> buildBodyType(JCodeModel cm, ActionType actionType, Action action, String resourcePath, String resourceName)
        throws IOException, JClassAlreadyExistsException {
    final List<JTypeWithMimeType> result = new ArrayList<>();

    if (action.getBody() != null) {
        for (MimeType mimeType : action.getBody().values()) {
            final JType bodyType;
            final MimeType body = mimeType;
            final String className = NameHelper.toValidClassName(resourceName) + NameHelper.toCamelCase(actionType.name(), false) + BODY_CLASS_SUFFIX;
            if (MimeTypeHelper.isJsonType(body)) {
                bodyType = getOrGeneratePojoFromJsonSchema(cm, resourcePath, body, className);
            } else if (MimeTypeHelper.isTextType(body)) {
                bodyType = cm.ref(String.class);
            } else if (MimeTypeHelper.isBinaryType(body)) {
                bodyType = cm.ref(InputStream.class);
            } else if (MimeTypeHelper.isMultiPartType(body) || MimeTypeHelper.isFormUrlEncodedType(body)) {
                final Map<String, TypeFieldDefinition> formParameters = body.getFormParameters();
                bodyType = toParametersJavaBean(cm, className, formParameters, resourcePath);
            } else {
                bodyType = cm.ref(Object.class);
            }
            if (bodyType != null) {
                result.add(new JTypeWithMimeType(bodyType, mimeType));
            } else {
                logger.info("No type was inferred for body type at " + resourcePath + " on method " + action.getType());
            }
        }
    }
    return result;
}
 
Example 18
Source File: RamlJavaClientGenerator.java    From raml-java-client-generator with Apache License 2.0 5 votes vote down vote up
private JTypeWithMimeType buildReturnType(JCodeModel cm, ActionType actionType, Response response, String resourcePath, String resourceName) throws IOException {
    JTypeWithMimeType returnType = new JTypeWithMimeType(cm.VOID, null);
    if (response != null) {

        if (response.getBody() != null) {
            final Iterator<Map.Entry<String, MimeType>> bodies = response.getBody().entrySet().iterator();
            if (bodies.hasNext()) {
                final Map.Entry<String, MimeType> bodyEntry = bodies.next();
                final MimeType mimeType = bodyEntry.getValue();
                if (MimeTypeHelper.isJsonType(mimeType)) {
                    String className = NameHelper.toValidClassName(resourceName) + NameHelper.toCamelCase(actionType.name(), false) + RESPONSE_CLASS_SUFFIX;
                    if (outputVersion.ordinal() >= OutputVersion.v2.ordinal()) {
                        className = className + BODY_CLASS_SUFFIX;
                    }
                    returnType = new JTypeWithMimeType(getOrGeneratePojoFromJsonSchema(cm, resourcePath, mimeType, className), mimeType);

                } else if (MimeTypeHelper.isTextType(mimeType)) {
                    returnType = new JTypeWithMimeType(cm.ref(String.class), mimeType);
                } else if (MimeTypeHelper.isBinaryType(mimeType)) {
                    returnType = new JTypeWithMimeType(cm.ref(InputStream.class), mimeType);
                } else {
                    returnType = new JTypeWithMimeType(cm.ref(Object.class), mimeType);
                }
            }
        }
    }
    return returnType;
}
 
Example 19
Source File: OperationProcessor.java    From jpmml-evaluator with GNU Affero General Public License v3.0 4 votes vote down vote up
static
private void createFormatMethod(JDefinedClass clazz, JPrimitiveType type){
	JCodeModel codeModel = clazz.owner();

	JClass numberClazz = codeModel.ref(Number.class);
	JClass stringBuilderClazz = codeModel.ref(StringBuilder.class);

	JMethod method = clazz.method(JMod.STATIC | JMod.PRIVATE, String.class, "format");

	JVar valuesParameter = method.varParam(numberClazz, "values");

	JBlock body = method.body();

	JVar sbVariable = body.decl(stringBuilderClazz, "sb", JExpr._new(stringBuilderClazz).arg(valuesParameter.ref("length").mul(JExpr.lit(32))));

	JForEach forStatement = body.forEach(numberClazz, "value", valuesParameter);

	JBlock forBody = forStatement.body();

	forBody.add(createReportInvocation(clazz, sbVariable, "${0}", Collections.singletonList(forStatement.var()), type));

	body._return(sbVariable.invoke("toString"));
}
 
Example 20
Source File: CodeModelArrowHelper.java    From dremio-oss with Apache License 2.0 4 votes vote down vote up
public static JClass getHolderType(CompleteType type, final JCodeModel model) {
  return model.ref(type.getHolderClass());
}