下面列出了javax.persistence.metamodel.StaticMetamodel#com.squareup.javapoet.ClassName 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private List<MethodSpec> buildCommonPropertyDeserializerMethods( PropertyInfo property, JDeserializerType deserializerType )
throws UnableToCompleteException {
List<MethodSpec> result = new ArrayList<MethodSpec>();
result.add( MethodSpec.methodBuilder( "newDeserializer" )
.addModifiers( Modifier.PROTECTED )
.addAnnotation( Override.class )
.returns( ParameterizedTypeName.get( ClassName.get( JsonDeserializer.class ), DEFAULT_WILDCARD ) )
.addStatement( "return $L", deserializerType.getInstance() )
.build() );
Optional<MethodSpec> paramMethod = buildPropertyDeserializerParameters( property, deserializerType );
if ( paramMethod.isPresent() ) {
result.add( paramMethod.get() );
}
return result;
}
private static void addResourceField(TypeSpec.Builder resourceType, VariableDeclarator variable,
ClassName annotation) {
String fieldName = variable.getNameAsString();
String fieldValue = variable.getInitializer()
.map(Node::toString)
.orElseThrow(
() -> new IllegalStateException("Field " + fieldName + " missing initializer"));
FieldSpec.Builder fieldSpecBuilder = FieldSpec.builder(int.class, fieldName)
.addModifiers(PUBLIC, STATIC, FINAL)
.initializer(fieldValue);
if (annotation != null) {
fieldSpecBuilder.addAnnotation(annotation);
}
resourceType.addField(fieldSpecBuilder.build());
}
/**
* Instantiates a new model property.
*
* @param entity the entity
* @param element the element
* @param modelAnnotations the model annotations
*/
@SuppressWarnings("rawtypes")
public ModelProperty(ModelEntity<?> entity, Element element, List<ModelAnnotation> modelAnnotations) {
super((element != null) ? element.getSimpleName().toString() : null, element);
this.parent = new WeakReference<ModelEntity>(entity);
if (element != null) {
TypeName temp1=TypeName.get(element.asType());
LiteralType temp2 = LiteralType.of(element.asType().toString());
AssertKripton.fail((temp1 instanceof ClassName) && temp2.isCollection(), "In bean '%s' property '%s' can not use Object as parameter", entity.getElement().asType().toString() ,element.getSimpleName().toString());
propertyType = new ModelType(element.asType());
publicField = element.getModifiers().contains(Modifier.PUBLIC);
}
this.annotations = new ArrayList<ModelAnnotation>();
if (modelAnnotations != null) {
this.annotations.addAll(modelAnnotations);
}
this.typeAdapter = new TypeAdapter();
}
@Test
public void addValueSpaceCheck() throws Exception {
ParameterSpec paramS = ParameterSpec.builder(ClassName.get(String.class), "s")
.build();
MethodSpec.Builder method = MethodSpec.methodBuilder("foo")
.addModifiers(Modifier.PUBLIC)
.addParameter(paramS)
.returns(void.class);
NotNullValidator validator = new NotNullValidator();
validator.addValueSpaceCheck(method, paramS, rdfsClazz);
String code = method.build().code.toString();
Matcher matcher = Pattern.compile("if\\s*\\((s\\s*==\\s*null|null\\s*==\\s*s)\\)").matcher(code);
assertTrue(matcher.find());
}
private CodeBlock buildViewSchemaCreations(GenClassesManagerStep managerStep) {
final CodeBlock.Builder builder = CodeBlock.builder();
final List<ViewElement> allViewElements = managerStep.getAllViewElements();
if (!allViewElements.isEmpty()) {
addDebugLogging(builder, "Creating views");
for (ViewElement viewElement : allViewElements) {
final ClassName viewDao = EntityEnvironment.getGeneratedDaoClassName(viewElement);
builder.addStatement("$T.createView(db, $T.$L, $S)",
SQL_UTIL,
viewDao,
FIELD_VIEW_QUERY,
viewElement.getViewName());
}
}
return builder.build();
}
private MethodSpec mergeServiceDefaultsMethod() {
boolean crc32FromCompressedDataEnabled = model.getCustomizationConfig().isCalculateCrc32FromCompressedData();
MethodSpec.Builder builder = MethodSpec.methodBuilder("mergeServiceDefaults")
.addAnnotation(Override.class)
.addModifiers(PROTECTED, FINAL)
.returns(SdkClientConfiguration.class)
.addParameter(SdkClientConfiguration.class, "config")
.addCode("return config.merge(c -> c.option($T.SIGNER, defaultSigner())\n",
SdkAdvancedClientOption.class)
.addCode(" .option($T"
+ ".CRC32_FROM_COMPRESSED_DATA_ENABLED, $L)",
SdkClientOption.class, crc32FromCompressedDataEnabled);
String clientConfigClassName = model.getCustomizationConfig().getServiceSpecificClientConfigClass();
if (StringUtils.isNotBlank(clientConfigClassName)) {
builder.addCode(".option($T.SERVICE_CONFIGURATION, $T.builder().build())",
SdkClientOption.class, ClassName.bestGuess(clientConfigClassName));
}
builder.addCode(");");
return builder.build();
}
/**
* Generate a simple method for operations with streaming input and output members.
* Streaming input member takes a {@link Path} containing the data to upload and
* the streaming output member takes a {@link Path} where data will be downloaded to.
*/
private MethodSpec streamingInputOutputFileSimpleMethod(OperationModel opModel) {
ClassName requestType = ClassName.get(modelPackage, opModel.getInput().getVariableType());
return interfaceMethodSignature(opModel)
.returns(completableFutureType(getPojoResponseType(opModel)))
.addJavadoc(opModel.getDocs(model, ClientType.ASYNC, SimpleMethodOverload.FILE))
.addParameter(requestType, opModel.getInput().getVariableName())
.addParameter(ClassName.get(Path.class), "sourcePath")
.addParameter(ClassName.get(Path.class), "destinationPath")
.addStatement("return $L($L, $T.fromFile(sourcePath), $T.toFile(destinationPath))",
opModel.getMethodName(),
opModel.getInput().getVariableName(),
ClassName.get(AsyncRequestBody.class),
ClassName.get(AsyncResponseTransformer.class))
.build();
}
@Test
public void createInteger() throws Exception {
when(integerDeclaration.name()).thenReturn("Time");
when(integerDeclaration.enumValues()).thenReturn(Arrays.<Number>asList(1, 2, 3));
EnumerationTypeHandler handler = new EnumerationTypeHandler("time", integerDeclaration);
GenerationContextImpl generationContext = new GenerationContextImpl(PluginManager.NULL, api, TypeFetchers.fromTypes(), "bar.pack", Collections.<String>emptyList());
generationContext.newExpectedType("Time", new CreationResult("bar.pack", ClassName.get("bar.pack", "Time"), null));
CreationResult result = handler.create(generationContext, new CreationResult("bar.pack", ClassName.get("bar.pack", "Time"), null)).get();
assertThat(result.getInterface(), allOf(
name(equalTo("Time")),
fields(Matchers.contains(
FieldSpecMatchers.fieldName(equalTo("name"))
)
)
));
System.err.println(result.getInterface().toString());
}
private ClassName className( JClassType type ) {
JClassType enclosingType = type.getEnclosingType();
if ( null == enclosingType ) {
return ClassName.get( type.getPackage()
.getName(), type.getSimpleSourceName() );
}
// We look for all enclosing types and add them at the head.
List<String> types = new ArrayList<String>();
types.add( type.getSimpleSourceName() );
while ( null != enclosingType ) {
types.add( 0, enclosingType.getSimpleSourceName() );
enclosingType = enclosingType.getEnclosingType();
}
// The parent type is the first one. We remove it to keep only the childs.
String parentType = types.remove( 0 );
String[] childs = types.toArray( new String[types.size()] );
return ClassName.get( type.getPackage()
.getName(), parentType, childs );
}
private TypeSpec getInterceptorInitializer(Set<? extends Element> interceptorElements) throws ClassNotFoundException {
ClassName interceptor = ClassName.get("com.android.easyrouter.intercept", "IInterceptor");
ClassName list = ClassName.get("java.util", "List");
TypeName interceptorList = ParameterizedTypeName.get(list, interceptor);
MethodSpec.Builder routerInitBuilder = MethodSpec
.methodBuilder("initModuleInterceptor")
.returns(interceptorList)
.addModifiers(Modifier.PUBLIC)
.addModifiers(Modifier.STATIC);
routerInitBuilder.addStatement("List<IInterceptor> list = new java.util.ArrayList()");
for (Element element : interceptorElements) {
routerInitBuilder.addStatement("list.add(new $T())",
ClassName.get((TypeElement) element));
}
routerInitBuilder.addStatement("return list");
return TypeSpec.classBuilder(CompilerConstant.AutoCreateInterceptorPrefix + moduleName)
.addModifiers(Modifier.PUBLIC)
.addMethod(routerInitBuilder.build())
.build();
}
private MethodSpec generateOnActivityResultMethod() {
MethodSpec.Builder builder = MethodSpec.methodBuilder("onActivityResult")
.addAnnotation(Override.class)
.addModifiers(Modifier.PUBLIC)
.returns(void.class)
.addParameter(TypeVariableName.get("T"), "target", Modifier.FINAL)
.addParameter(int.class, "requestCode", Modifier.FINAL)
.addParameter(int.class, "resultCode", Modifier.FINAL)
.addParameter(ClassName.get("android.content", "Intent"), "data", Modifier.FINAL);
final Map<Integer, MethodBinding> methodBindings = bindings.get(MethodBinding.onActivityResult);
if (methodBindings != null && !methodBindings.isEmpty()) {
boolean first = true;
for (MethodBinding binding : methodBindings.values()) {
if (first) {
builder.beginControlFlow("if (requestCode == $L)", binding.requestCode);
first = false;
} else {
builder.nextControlFlow("else if (requestCode == $L)", binding.requestCode);
}
builder.addStatement("target.$L(resultCode, data)", binding.name);
}
builder.endControlFlow();
}
return builder.build();
}
public BundlerClassInfo(TypeElement te) {
typeElement = te;
className = ClassName.get(typeElement);
for (Element e : te.getEnclosedElements()) {
if (e.getKind() == ElementKind.FIELD) {
VariableElement ve = (VariableElement) e;
fields.add(ve);
}
if (e.getKind() == ElementKind.METHOD) {
ExecutableElement ee = (ExecutableElement) e;
methods.add(ee);
}
}
}
private static List<AnnotationSpec> getExternalAnnotations(VariableElement param) {
final List<? extends AnnotationMirror> annotationMirrors = param.getAnnotationMirrors();
final List<AnnotationSpec> annotations = new ArrayList<>();
for (AnnotationMirror annotationMirror : annotationMirrors) {
if (annotationMirror.getAnnotationType().toString().startsWith(COMPONENTS_PACKAGE)) {
continue;
}
final AnnotationSpec.Builder annotationSpec =
AnnotationSpec.builder(
ClassName.bestGuess(annotationMirror.getAnnotationType().toString()));
Map<? extends ExecutableElement, ? extends AnnotationValue> elementValues =
annotationMirror.getElementValues();
for (Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> elementValue :
elementValues.entrySet()) {
annotationSpec.addMember(
elementValue.getKey().getSimpleName().toString(), elementValue.getValue().toString());
}
annotations.add(annotationSpec.build());
}
return annotations;
}
public static Matcher<TypeName> typeName(final Matcher<? super ClassName> matcher) {
final Matcher<? super ClassName> subMatcher = matcher;
return new TypeSafeMatcher<TypeName>() {
@Override
protected boolean matchesSafely(TypeName item) {
return subMatcher.matches(item);
}
@Override
public void describeTo(Description description) {
description.appendText("typename ").appendDescriptionOf(subMatcher);
}
};
}
@Test
public void simplest() throws Exception {
Api api = RamlLoader.load(this.getClass().getResourceAsStream("simplest-type.raml"), ".");
RamlToPojo ramlToPojo = new RamlToPojoBuilder(api).fetchTypes(TypeFetchers.fromAnywhere()).findTypes(TypeFinders.everyWhere()).build(Arrays.asList("core.constructor"));
CreationResult r = ramlToPojo.buildPojos().creationResults().stream().filter(x -> x.getJavaName(EventType.INTERFACE).simpleName().equals("Foo")).findFirst().get();
assertThat(r.getInterface()).hasName("Foo");
System.err.println(r.getInterface().toString());
System.err.println(r.getImplementation().toString());
assertThat(r.getImplementation().get(), is(allOf(
name(equalTo("FooImpl")),
methods(containsInAnyOrder(
allOf(methodName(equalTo("<init>"))),
allOf(methodName(equalTo("<init>")), parameters(contains(type(equalTo(ClassName.get(String.class))), type(equalTo(ClassName.INT))))),
allOf(methodName(equalTo("getName")), returnType(equalTo(ClassName.get(String.class)))),
allOf(methodName(equalTo("setName")), parameters(contains(type(equalTo(ClassName.get(String.class)))))),
allOf(methodName(equalTo("getAge")), returnType(equalTo(ClassName.INT))),
allOf(methodName(equalTo("setAge")), parameters(contains(type(equalTo(ClassName.INT)))))
))
)));
}
private MethodSpec optionalSetter(final Descriptor d, final ExecutableElement field) {
String fieldName = fieldName(field);
TypeName valueType = genericArgument(d, field, 0);
ClassName optionalType = ClassName.bestGuess(optionalType(field));
TypeName parameterType = ParameterizedTypeName.get(optionalType, subtypeOf(valueType));
AnnotationSpec suppressUncheckedAnnotation = AnnotationSpec.builder(SuppressWarnings.class)
.addMember("value", "$S", "unchecked")
.build();
MethodSpec.Builder setter = MethodSpec.methodBuilder(fieldName)
.addAnnotation(suppressUncheckedAnnotation)
.addModifiers(PUBLIC)
.addParameter(parameterType, fieldName)
.returns(builderType(d));
if (shouldEnforceNonNull(field)) {
assertNotNull(setter, fieldName);
}
setter.addStatement("this.$N = ($T)$N", fieldName, fieldType(d, field), fieldName);
return setter.addStatement("return this").build();
}
private ApiContract<ClassName> getApiClassNameContract(TypeElement apiImplElement) {
String apiClassSymbol = null;
List<? extends AnnotationMirror> annotationMirrors = apiImplElement.getAnnotationMirrors();
for (AnnotationMirror annotationMirror : annotationMirrors) {
Map<? extends ExecutableElement, ? extends AnnotationValue> elementValues = annotationMirror.getElementValues();
for (Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> entry : elementValues.entrySet()) {
apiClassSymbol = entry.getValue().accept(annotationValueVisitor, null);
}
}
ClassName apiName = ClassName.get(elements.getTypeElement(apiClassSymbol));
ClassName apiImplName = ClassName.get(apiImplElement);
return new ApiContract<>(apiName, apiImplName);
}
private TypeName unboundedValueType(final Descriptor d) {
final ClassName raw = rawValueType(d);
if (!d.isGeneric()) {
return raw;
}
return ParameterizedTypeName.get(raw, wildcards(d.typeVariables().size()));
}
protected TypeName getParamType(ParamInjectionTarget paramInjectionTarget) {
if (paramInjectionTarget.kind == ParamInjectionTarget.Kind.INSTANCE) {
return TypeName.get(typeUtil.erasure(paramInjectionTarget.memberClass.asType()));
} else {
return ParameterizedTypeName.get(
ClassName.get(paramInjectionTarget.memberClass),
ClassName.get(typeUtil.erasure(paramInjectionTarget.kindParamClass.asType())));
}
}
private void parseDiscriminator(TypeSpec.Builder typeSpecBuilder, Discriminator discriminator, String targetPackage,
boolean generateDiscriminatorProperty) {
if (discriminator.getPropertyName() != null) {
AnnotationSpec.Builder annotationSpecBuilder = AnnotationSpec.builder(JsonTypeInfo.class)
.addMember("use", "JsonTypeInfo.Id.NAME")
.addMember("include", "JsonTypeInfo.As.PROPERTY")
.addMember("property", "$S", discriminator.getPropertyName());
if (generateDiscriminatorProperty) {
annotationSpecBuilder.addMember("visible", "true");
}
typeSpecBuilder.addAnnotation(annotationSpecBuilder.build());
}
if (discriminator.getMapping() != null) {
List<AnnotationSpec> annotationSpecs = discriminator.getMapping().entrySet().stream()
.map(discriminatorMappingEntry ->
AnnotationSpec.builder(Type.class)
.addMember("value", "$T.class", ClassName.get(targetPackage, discriminatorMappingEntry.getValue()))
.addMember("name", "$S", discriminatorMappingEntry.getKey())
.build())
.collect(Collectors.toList());
AnnotationSpec jsonSubTypesAnnotation = AnnotationSpec.builder(JsonSubTypes.class)
.addMember("value", wrapAnnotationsIntoArray(annotationSpecs))
.build();
typeSpecBuilder.addAnnotation(jsonSubTypesAnnotation);
}
}
private void generateLoadCompositeReferences() {
// generate method 'generateLoadCompositeReferences()'
MethodSpec.Builder loadCompositesMethodBuilder = MethodSpec.methodBuilder("loadCompositeReferences")
.addModifiers(Modifier.PUBLIC)
.addAnnotation(Override.class)
.addStatement("$T sb01 = new $T()",
ClassName.get(StringBuilder.class),
ClassName.get(StringBuilder.class))
.addStatement("sb01.append(\"load composite references\")")
.addStatement("$T.get().logDetailed(sb01.toString(), 2)",
ClassName.get(ClientLogger.class));
for (ControllerModel controllerModel : this.metaModel.getControllers()) {
for (ControllerCompositeModel controllerCompositeModel : controllerModel.getComposites()) {
loadCompositesMethodBuilder.addStatement("this.compositeControllerReferences.add(new $T($S, $S, $S, $S, $L))",
ClassName.get(CompositeControllerReference.class),
controllerModel.getProvider()
.getClassName(),
controllerCompositeModel.getName(),
controllerCompositeModel.getComposite()
.getClassName(),
controllerCompositeModel.getSelector(),
controllerCompositeModel.isScopeGlobal())
.addStatement("sb01.setLength(0)")
.addStatement("sb01.append(\"register composite >>$L<< for controller >>$L<< in selector >>$L<<\")",
controllerCompositeModel.getName(),
controllerModel.getProvider()
.getClassName(),
controllerCompositeModel.getSelector())
.addStatement("$T.get().logDetailed(sb01.toString(), 3)",
ClassName.get(ClientLogger.class));
}
}
typeSpec.addMethod(loadCompositesMethodBuilder.build());
}
static String noSupportedOverloadingMethod(ClassName className, String methodName) {
String message = "When checking %s 2 methods with name '%s' were found.\n"
+ "But method overloading is not supported by Mockery interfaces.\n"
+ "To fix it, rename one of the previous methods.\n";
return String.format(message, className, methodName);
}
private void emitGetTargetScope(TypeSpec.Builder builder) {
CodeBlock.Builder getParentScopeCodeBlockBuilder = getParentScopeCodeBlockBuilder();
MethodSpec.Builder getScopeBuilder =
MethodSpec.methodBuilder("getTargetScope")
.addAnnotation(Override.class)
.addModifiers(Modifier.PUBLIC)
.addParameter(ClassName.get(Scope.class), "scope")
.returns(ClassName.get(Scope.class))
.addStatement("return scope$L", getParentScopeCodeBlockBuilder.build().toString());
builder.addMethod(getScopeBuilder.build());
}
private TypeName valueImplType(final Descriptor d) {
final ClassName raw = rawValueImplType(d);
if (!d.isGeneric()) {
return raw;
}
return ParameterizedTypeName.get(raw, d.typeArguments());
}
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
Set<? extends Element> candidates = roundEnv.getElementsAnnotatedWith(Component.class);
for (Element candidate : candidates) {
TypeElement component = (TypeElement) candidate;
ClassName componentName = ClassName.get(component);
TypeElement builder = findBuilder(component);
ClassName builderName = builder != null ? ClassName.get(builder) : null;
TypeElement factory = findFactory(component);
ClassName factoryName = factory != null ? ClassName.get(factory) : null;
TypeSpec.Builder typeBuilder =
createComponent(componentName, builderName, factoryName)
.toBuilder()
.addOriginatingElement(component);
if (generatedAnnotation != null) {
typeBuilder.addAnnotation(generatedAnnotation);
}
JavaFile file =
JavaFile.builder(componentName.packageName(), typeBuilder.build())
.addFileComment("Generated by Dagger's reflect-compiler. Do not modify!")
.build();
try {
file.writeTo(filer);
} catch (Exception e) {
messager.printMessage(ERROR, "Unable to write component implementation: " + e, component);
}
}
return false;
}
private static String createMessage(Optional<ClassName> generatedClassName, String message) {
return String.format("Could not generate %s: %s.",
generatedClassName.isPresent()
? generatedClassName.get()
: "unknown file",
message);
}
private ClassName exceptionBaseClass() {
String customExceptionBase = intermediateModel.getCustomizationConfig()
.getSdkModeledExceptionBaseClassName();
if (customExceptionBase != null) {
return poetExtensions.getModelClass(customExceptionBase);
}
return poetExtensions.getModelClass(intermediateModel.getSdkModeledExceptionBaseClassName());
}
@Test
public void buildSupportTypeSpec() throws Exception {
TypeSpec typeSpec = clazz.buildSupportTypeSpec(generationConfig);
// Test @Partial annotation:
AnnotationSpec partialAnnotation = AnnotationSpec.builder(Partial.class).build();
assertEquals(1, typeSpec.annotations.size());
assertEquals(partialAnnotation, typeSpec.annotations.get(0));
// Test superclass:
TypeName sanitizingObjectSupport = ClassName.get(SchemaSanitizingObjectSupport.class);
assertEquals(sanitizingObjectSupport, typeSpec.superclass);
// Test superinterface:
ClassName superInterface = clazz.getJavaPoetClassName(generationConfig);
assertEquals(1, typeSpec.superinterfaces.size());
assertEquals(superInterface, typeSpec.superinterfaces.get(0));
// Test methods:
Set<String> methodNames = getMethodNames(typeSpec);
assertEquals(5, methodNames.size());
assertTrue(methodNames.contains("setFoos"));
assertTrue(methodNames.contains("addFoo"));
assertTrue(methodNames.contains("addAllFoos"));
assertTrue(methodNames.contains("removeFoo"));
assertTrue(methodNames.contains("removeAllFoos"));
}
private void response(ClassName className, Method method, boolean expectError,
MethodSpec.Builder builder) {
builder.addCode("\n // Perform and validate response \n");
String params = "";
List<Object> args = new ArrayList<>();
args.add(method.returnType);
args.add(Introspector
.decapitalize(className.simpleName()));
args.add(method.name);
for (int i = 0; i < method.params.size(); i++) {
Param param = method.params.get(i);
if (i == method.params.size() -1) params += param.name;
else params += param.name + ", ";
}
args.add(params);
builder.addStatement("$T response = $L().$L($L)",
args.toArray(new Object[args.size()]));
if (expectError) {
builder.addStatement("exception.expect($T.class)", AssertionError.class);
}
builder.addStatement("robot.validateResponse(response)");
}
private MethodSpec createIntentMethodSpec(Elements elementUtils, Types typeUtils, ExtraClassesGrouped extraClassesGrouped) {
final String activityQualifiedClassName = extraClassesGrouped.getExtraAnnotatedClassName();
final TypeElement typeElement = elementUtils.getTypeElement(activityQualifiedClassName);
final String activityName = typeElement.getSimpleName().toString();
// Declare method name.
final MethodSpec.Builder methodSpecBuilder = MethodSpec.methodBuilder("create" + activityName + "Intent")
.addModifiers(Modifier.PUBLIC, Modifier.STATIC)
.returns(Androids.intentClass());
// Build parameters.
// Add Context object.
methodSpecBuilder.addParameter(Androids.contextClass(), "context");
buildParameters(methodSpecBuilder, extraClassesGrouped);
ClassName bundleClass = ClassName.get("android.os", "Bundle");
// Declare bundle object.
methodSpecBuilder.addStatement("$T bundle = new $T()", bundleClass, bundleClass);
// Put extras base on key, value to bundle.
bindExtras(methodSpecBuilder, extraClassesGrouped, "bundle");
// Build and return Intent.
return methodSpecBuilder.addStatement("$T intent = new $T(context, $L)", Androids.intentClass(), Androids.intentClass(), extraClassesGrouped.getExtraAnnotatedClassName() + ".class")
.addStatement("intent.putExtras(bundle)")
.addStatement("return intent")
.build();
}