List of usage examples for com.google.gwt.core.ext.typeinfo JParameter getAnnotation
<T extends Annotation> T getAnnotation(Class<T> annotationClass);
null if it is not. From source file:com.google.code.gwt.rest.rebind.RestRequestFactoryGenerator.java
License:Apache License
@Override public String generate(TreeLogger logger, GeneratorContext context, String typeName) throws UnableToCompleteException { TypeOracle oracle = context.getTypeOracle(); JClassType type = oracle.findType(typeName); logger.log(logLevel, "create type " + type); String packageName = type.getPackage().getName(); String simpleSourceName = type.getName().replace('.', '_') + "Impl"; PrintWriter pw = context.tryCreate(logger, packageName, simpleSourceName); if (pw == null) { return packageName + "." + simpleSourceName; }// ww w .j av a 2 s .co m ClassSourceFileComposerFactory factory = createClassSourceFileComposerFactory(typeName, packageName, simpleSourceName); SourceWriter sw = factory.createSourceWriter(context, pw); Map<String, Object> contextMap = createContextMethod(); StringBuilder converters = new StringBuilder(); StringBuilder factoryMethods = new StringBuilder(); for (JMethod method : type.getMethods()) { if (method.getParameters().length != 0) { logger.log(Type.ERROR, " Factory Method must be zero paraemeter method. " + method); return null; } JClassType requestClass = method.getReturnType().isInterface(); String implClassName = requestClass.getSimpleSourceName() + "_Impl"; contextMap.put("returnType", requestClass.getQualifiedSourceName()); contextMap.put("methodName", method.getName()); contextMap.put("implClassName", implClassName); StringBuilder methods = new StringBuilder(); String baseUrl = resolveBaseUrl(requestClass); for (JMethod requestClassMethod : requestClass.getMethods()) { URLMapping mapping = requestClassMethod.getAnnotation(URLMapping.class); if (mapping == null) { logger.log(Type.ERROR, "method " + requestClassMethod + " don't have " + URLMapping.class.getSimpleName() + " annotation."); throw new IllegalArgumentException(); } SimpleTemplate requestClassMethodTemplate = selectRequestMethodTemplate( requestClassMethod.getReturnType().isInterface()); String url = baseUrl + mapping.value(); String restMethod = mapping.method().name().toLowerCase(); contextMap.put("url", url); contextMap.put("restMethod", restMethod); JParameterizedType jtype = requestClassMethod.getReturnType().isParameterized(); if (jtype != null) { contextMap.put("implReturnType", jtype.getQualifiedSourceName()); } else { contextMap.put("implReturnType", JavaScriptObject.class.getName()); } contextMap.put("beanType", requestClassMethod.getReturnType().isParameterized().getTypeArgs()[0] .getQualifiedSourceName()); contextMap.put("impleMethodName", requestClassMethod.getName()); String parameters = ""; String bindingLogic = ""; int i = 0; for (JParameter parameter : requestClassMethod.getParameters()) { if (i != 0) { parameters += ","; } parameters += parameter.getType().getQualifiedSourceName() + " arg" + i; if (parameter.isAnnotationPresent(URLParam.class)) { contextMap.put("key", parameter.getAnnotation(URLParam.class).value()); contextMap.put("parameter", "arg" + i); bindingLogic += CALL_PATH_BINDING.resolve(contextMap); } else if (parameter.isAnnotationPresent(QueryParam.class)) { contextMap.put("key", parameter.getAnnotation(QueryParam.class).value()); contextMap.put("parameter", "arg" + i); bindingLogic += CALL_QUERY_BINDING.resolve(contextMap); } else { contextMap.put("parameter", "arg" + i); contextMap.put("parameterType", parameter.getType().getQualifiedSourceName()); bindingLogic += CALL_CONVERTER.resolve(contextMap); converters.append(CONVERTER.resolve(contextMap)); } i++; } contextMap.put("parameters", parameters); contextMap.put("bindingLogic", bindingLogic); methods.append(requestClassMethodTemplate.resolve(contextMap)); } contextMap.put("methods", methods); String classImpl; if (method.getReturnType().getQualifiedSourceName().equals(RestRequestClient.class.getName())) { } classImpl = REQUEST_CLASS.resolve(contextMap); contextMap.put("classImpl", classImpl); factoryMethods.append(FACTORY_METHOD.resolve(contextMap)); } contextMap.put("factoryMethods", factoryMethods.toString()); contextMap.put("converters", converters.toString()); logger.log(logLevel, "create class \n" + MAIN_CLASS.resolve(contextMap)); sw.print(MAIN_CLASS.resolve(contextMap)); sw.commit(logger); return packageName + "." + simpleSourceName; }
From source file:com.guit.rebind.binder.GuitBinderGenerator.java
License:Apache License
private void printViewFieldBindings(SourceWriter writer, JClassType presenterType, String viewTypeName, HashMap<String, JType> validBindingFieldsType, ArrayList<JField> fields) throws UnableToCompleteException { Set<String> validBindingFields = validBindingFieldsType.keySet(); JClassType viewAccesorType = getType(ViewAccesor.class.getCanonicalName()); ArrayList<JField> superFields = new ArrayList<JField>(); collectAllFields(presenterType.getSuperclass(), superFields); JClassType elementDomType = getType(com.guit.client.dom.Element.class.getCanonicalName()); for (JField f : fields) { if (f.isAnnotationPresent(ViewField.class)) { // Check for repetided fields if (f.getType().isClassOrInterface().isAssignableTo(elementDomType)) { if (superFields.contains(f)) { }/*from w w w . j av a2s.c o m*/ } String name = f.getName(); ViewField viewField = f.getAnnotation(ViewField.class); String viewName = viewField.name(); if (viewName.isEmpty()) { viewName = name; } if (!validBindingFields.contains(viewName)) { error("The field '%s' do not exists. Found: %s.%s", viewName, presenterType.getQualifiedSourceName(), name); } JClassType type = f.getType().isClassOrInterface(); // if (type.isInterface() == null && !viewField.provided()) { // error("A ViewField must be an interface. Found: %s.%s", presenterType // .getQualifiedSourceName(), name); // } if (type.isAssignableTo(viewAccesorType)) { writer.println("{"); writer.indent(); if (!type.isAnnotationPresent(Implementation.class)) { writer.println(type.getQualifiedSourceName() + " accesor = " + GinOracle.getProvidedInstance(type.getQualifiedSourceName()) + ".get();"); } else { JClassType implementation = getType( type.getAnnotation(Implementation.class).value().getCanonicalName()); // If they are parameterized look for the base type JParameterizedType implementationParameterized = implementation.isParameterized(); if (implementationParameterized != null) { implementation = implementationParameterized.getBaseType(); } JParameterizedType typeParameterized = type.isParameterized(); if (typeParameterized != null) { type = typeParameterized.getBaseType(); } // Verify that they are assignable if (!implementation.isAssignableTo(type)) { error("An implementation of a ViewAccesor must implement the ViewAccesor interface. Found: %s", implementation.getQualifiedSourceName()); } writer.println(type.getQualifiedSourceName() + " accesor = new " + implementation.getQualifiedSourceName() + "();"); } writer.println("accesor.setTarget(view." + viewName + ");"); writer.println("presenter." + name + " = accesor;"); writer.outdent(); writer.print("}"); writer.println(); } else if (type == null || type.isAssignableFrom(validBindingFieldsType.get(viewName).isClassOrInterface()) || type.getQualifiedSourceName().startsWith("elemental.")) { String qualifiedSourceName = f.getType().getQualifiedSourceName(); writer.println("presenter." + name + " = (" + qualifiedSourceName + ") view." + viewName + ";"); writer.println(); } else { // Interface emulation (without exceptions) writer.println( "presenter." + name + " = new " + type.getParameterizedQualifiedSourceName() + "() {"); writer.indent(); ArrayList<JMethod> methods = new ArrayList<JMethod>(); findAllMethods(type, methods); for (JMethod m : methods) { writer.print(m.getReadableDeclaration(false, true, true, true, true)); writer.println("{"); writer.indent(); // Find the parameters StringBuilder callParameters = new StringBuilder(); for (JParameter p : m.getParameters()) { if (callParameters.length() > 0) { callParameters.append(", "); } if (p.isAnnotationPresent(ImplicitCast.class)) { callParameters.append("("); callParameters .append(p.getAnnotation(ImplicitCast.class).value().getCanonicalName()); callParameters.append(") "); } callParameters.append(p.getName()); } JType returnType = m.getReturnType(); if (!returnType.equals(JPrimitiveType.VOID)) { writer.print("return "); // Implicit cast writer.print("(" + returnType.getParameterizedQualifiedSourceName() + ")"); } writer.indent(); writer.println(createdClassName + ".this.view." + viewName + "." + m.getName() + "(" + callParameters.toString() + ");"); writer.outdent(); writer.outdent(); writer.println("}"); writer.println(); } // Get .equals working on emulated interfaces for // event.getSource() comparations writer.println("@Override"); writer.println("public boolean equals(Object obj) {"); writer.indent(); writer.println("return view." + viewName + ".equals(obj);"); writer.outdent(); writer.println("}"); writer.println(); writer.outdent(); writer.println("};"); } } } }
From source file:com.gwtplatform.dispatch.rebind.RestActionGenerator.java
License:Apache License
private <T extends Annotation> void buildParamList(JParameter[] parameters, Class<T> annotationClass, AnnotationValueResolver<T> annotationValueResolver, List<AnnotatedMethodParameter> destination) throws UnableToCompleteException { List<Class<? extends Annotation>> restrictedAnnotations = getRestrictedAnnotations(annotationClass); for (JParameter parameter : parameters) { T parameterAnnotation = parameter.getAnnotation(annotationClass); if (parameterAnnotation != null) { if (hasAnnotationFrom(parameter, restrictedAnnotations)) { getLogger()//from ww w. j a v a2 s . c o m .die(String.format(MANY_REST_ANNOTATIONS, actionMethod.getName(), parameter.getName())); throw new UnableToCompleteException(); } String value = annotationValueResolver.resolve(parameterAnnotation); destination.add(new AnnotatedMethodParameter(parameter, value)); } } }
From source file:com.gwtplatform.dispatch.rest.rebind.ActionGenerator.java
License:Apache License
private <T extends Annotation> void buildParamList(List<JParameter> parameters, Class<T> annotationClass, AnnotationValueResolver<T> annotationValueResolver, List<AnnotatedMethodParameter> destination) throws UnableToCompleteException { List<Class<? extends Annotation>> restrictedAnnotations = getRestrictedAnnotations(annotationClass); for (JParameter parameter : parameters) { T parameterAnnotation = parameter.getAnnotation(annotationClass); if (parameterAnnotation != null) { if (hasAnnotationFrom(parameter, restrictedAnnotations)) { getLogger()/*from ww w. j a va2 s . c o m*/ .die(String.format(MANY_REST_ANNOTATIONS, actionMethod.getName(), parameter.getName())); } if (parameter.isAnnotationPresent(DateFormat.class) && !isDate(parameter)) { getLogger() .die(String.format(DATE_FORMAT_NOT_DATE, actionMethod.getName(), parameter.getName())); } String value = annotationValueResolver.resolve(parameterAnnotation); destination.add(new AnnotatedMethodParameter(parameter, value)); } } }
From source file:com.gwtplatform.dispatch.rest.rebind.parameter.HttpParameterFactory.java
License:Apache License
private String extractName(JParameter parameter, HttpParameterType type) { switch (type) { case HEADER://from ww w . j av a 2s .com return headerParamValueResolver.resolve(parameter.getAnnotation(HeaderParam.class)); case PATH: return pathParamValueResolver.resolve(parameter.getAnnotation(PathParam.class)); case QUERY: return queryParamValueResolver.resolve(parameter.getAnnotation(QueryParam.class)); case FORM: return formParamValueResolver.resolve(parameter.getAnnotation(FormParam.class)); default: return null; } }
From source file:com.gwtplatform.dispatch.rest.rebind.parameter.HttpParameterFactory.java
License:Apache License
private String extractDateFormat(JParameter parameter) { String format = null;// ww w. ja v a 2 s.c o m if (parameter.isAnnotationPresent(DateFormat.class)) { format = parameter.getAnnotation(DateFormat.class).value(); } return format; }
From source file:com.hiramchirino.restygwt.rebind.RestServiceClassCreator.java
License:Apache License
private void writeMethodImpl(JMethod method) throws UnableToCompleteException { if (method.getReturnType().isPrimitive() != JPrimitiveType.VOID) { error("Invalid rest method. Method must have void return type: " + method.getReadableDeclaration()); }/* www.j a v a 2 s . c om*/ Json jsonAnnotation = source.getAnnotation(Json.class); final Style classStyle = jsonAnnotation != null ? jsonAnnotation.style() : Style.DEFAULT; p(method.getReadableDeclaration(false, false, false, false, true) + " {").i(1); { String restMethod = getRestMethod(method); LinkedList<JParameter> args = new LinkedList<JParameter>(Arrays.asList(method.getParameters())); // the last arg should be the callback. if (args.isEmpty()) { error("Invalid rest method. Method must declare at least a callback argument: " + method.getReadableDeclaration()); } JParameter callbackArg = args.removeLast(); JClassType callbackType = callbackArg.getType().isClassOrInterface(); JClassType methodCallbackType = METHOD_CALLBACK_TYPE; if (callbackType == null || !callbackType.isAssignableTo(methodCallbackType)) { error("Invalid rest method. Last argument must be a " + methodCallbackType.getName() + " type: " + method.getReadableDeclaration()); } JClassType resultType = getCallbackTypeGenericClass(callbackType); String pathExpression = null; Path pathAnnotation = method.getAnnotation(Path.class); if (pathAnnotation != null) { pathExpression = wrap(pathAnnotation.value()); } JParameter contentArg = null; HashMap<String, JParameter> queryParams = new HashMap<String, JParameter>(); HashMap<String, JParameter> headerParams = new HashMap<String, JParameter>(); for (JParameter arg : args) { PathParam paramPath = arg.getAnnotation(PathParam.class); if (paramPath != null) { if (pathExpression == null) { error("Invalid rest method. Invalid @PathParam annotation. Method is missing the @Path annotation: " + method.getReadableDeclaration()); } pathExpression = pathExpression.replaceAll(Pattern.quote("{" + paramPath.value() + "}"), "\"+" + toStringExpression(arg.getType(), arg.getName()) + "+\""); continue; } QueryParam queryParam = arg.getAnnotation(QueryParam.class); if (queryParam != null) { queryParams.put(queryParam.value(), arg); continue; } HeaderParam headerParam = arg.getAnnotation(HeaderParam.class); if (headerParam != null) { headerParams.put(headerParam.value(), arg); continue; } if (contentArg != null) { error("Invalid rest method. Only one content paramter is supported: " + method.getReadableDeclaration()); } contentArg = arg; } String acceptTypeBuiltIn = null; if (callbackType.equals(TEXT_CALLBACK_TYPE)) { acceptTypeBuiltIn = "CONTENT_TYPE_TEXT"; } else if (callbackType.equals(JSON_CALLBACK_TYPE)) { acceptTypeBuiltIn = "CONTENT_TYPE_JSON"; } else if (callbackType.equals(XML_CALLBACK_TYPE)) { acceptTypeBuiltIn = "CONTENT_TYPE_XML"; } if (acceptTypeBuiltIn == null) { p("final " + METHOD_CLASS + " __method ="); } p("this.resource"); if (pathExpression != null) { // example: .resolve("path/"+arg0+"/id") p(".resolve(" + pathExpression + ")"); } for (Map.Entry<String, JParameter> entry : queryParams.entrySet()) { String expr = entry.getValue().getName(); p(".addQueryParam(" + wrap(entry.getKey()) + ", " + toStringExpression(entry.getValue().getType(), expr) + ")"); } // example: .get() p("." + restMethod + "()"); for (Map.Entry<String, JParameter> entry : headerParams.entrySet()) { String expr = entry.getValue().getName(); p(".header(" + wrap(entry.getKey()) + ", " + toStringExpression(entry.getValue().getType(), expr) + ")"); } if (contentArg != null) { if (contentArg.getType() == STRING_TYPE) { p(".text(" + contentArg.getName() + ")"); } else if (contentArg.getType() == JSON_VALUE_TYPE) { p(".json(" + contentArg.getName() + ")"); } else if (contentArg.getType() == DOCUMENT_TYPE) { p(".xml(" + contentArg.getName() + ")"); } else { JClassType contentClass = contentArg.getType().isClass(); if (contentClass == null) { error("Content argument must be a class."); } jsonAnnotation = contentArg.getAnnotation(Json.class); Style style = jsonAnnotation != null ? jsonAnnotation.style() : classStyle; // example: .json(Listings$_Generated_JsonEncoder_$.INSTANCE.encode(arg0) ) p(".json(" + locator.encodeExpression(contentClass, contentArg.getName(), style) + ")"); } } if (acceptTypeBuiltIn != null) { p(".header(" + RESOURCE_CLASS + ".HEADER_ACCEPT, " + RESOURCE_CLASS + "." + acceptTypeBuiltIn + ");"); p(".send(" + callbackArg.getClass() + ");"); } else { p(".header(" + RESOURCE_CLASS + ".HEADER_ACCEPT, " + RESOURCE_CLASS + ".CONTENT_TYPE_JSON);"); p("try {").i(1); { p("__method.send(new " + ABSTRACT_REQUEST_CALLBACK_CLASS + "<" + resultType.getParameterizedQualifiedSourceName() + ">(__method, " + callbackArg.getName() + ") {").i(1); { p("protected " + resultType.getParameterizedQualifiedSourceName() + " parseResult() throws Exception {").i(1); { p("try {").i(1); { jsonAnnotation = method.getAnnotation(Json.class); Style style = jsonAnnotation != null ? jsonAnnotation.style() : classStyle; p("return " + locator.decodeExpression(resultType, JSON_PARSER_CLASS + ".parse(__method.getResponse().getText())", style) + ";"); } i(-1).p("} catch (Throwable __e) {").i(1); { p("throw new " + RESPONSE_FORMAT_EXCEPTION_CLASS + "(\"Response was NOT a valid JSON document\", __e);"); } i(-1).p("}"); } i(-1).p("}"); } i(-1).p("});"); } i(-1).p("} catch (" + REQUEST_EXCEPTION_CLASS + " __e) {").i(1); { p("callback.onFailure(__method,__e);"); } i(-1).p("}"); } } i(-1).p("}"); }
From source file:com.seanchenxi.resteasy.autobean.generator.RESTServiceGenerator.java
License:Apache License
private String getMethodRestPath(String rootPath, JMethod method) { String methodPath = rootPath + getRestPath(method.getAnnotation(Path.class)); for (JParameter param : method.getParameters()) { if (param.isAnnotationPresent(PathParam.class)) { String paramPath = param.getAnnotation(PathParam.class).value(); methodPath = methodPath.replace("{" + paramPath + "}", "\"+" + param.getName() + "+\""); }/* www . j a va 2 s . c o m*/ } methodPath = ("\"" + methodPath.trim() + "\"").replace("+\"\"+", "+").replaceAll("(\"|\\+)\\1", "$1"); if (methodPath.endsWith("+\"")) { methodPath = methodPath.substring(0, methodPath.length() - 2); } return methodPath; }
From source file:fr.onevu.gwt.uibinder.rebind.JClassTypeAdapter.java
License:Apache License
/** * Creates an array of mock GWT parameters for the given array of java * parameters./* w ww . ja va 2 s . c om*/ * * @param parameterTypes the types of the parameters * @param parameterAnnotations the list of annotations for each parameter * @param method the method or constructor to which the parameters belong * @return an array of GWT parameters */ @SuppressWarnings("unchecked") protected JParameter[] adaptParameters(Class<?>[] parameterTypes, Annotation[][] parameterAnnotations, JAbstractMethod method) { JParameter[] parameters = new JParameter[parameterTypes.length]; for (int i = 0; i < parameterTypes.length; i++) { final Class<?> realParameterType = parameterTypes[i]; JParameter parameter = createMock(JParameter.class); parameters[i] = parameter; // TODO(rdamazio): getName() has no plain java equivalent. // Perhaps compiling with -g:vars ? expect(parameter.getEnclosingMethod()).andStubReturn(method); expect(parameter.getType()).andStubAnswer(new IAnswer<JType>() { public JType answer() throws Throwable { return adaptType(realParameterType); } }); // Add annotation behaviour final Annotation[] annotations = parameterAnnotations[i]; expect(parameter.isAnnotationPresent(isA(Class.class))).andStubAnswer(new IAnswer<Boolean>() { public Boolean answer() throws Throwable { Class<? extends Annotation> annotationClass = (Class<? extends Annotation>) EasyMock .getCurrentArguments()[0]; for (Annotation annotation : annotations) { if (annotation.equals(annotationClass)) { return true; } } return false; } }); expect(parameter.getAnnotation(isA(Class.class))).andStubAnswer(new IAnswer<Annotation>() { public Annotation answer() throws Throwable { Class<? extends Annotation> annotationClass = (Class<? extends Annotation>) EasyMock .getCurrentArguments()[0]; for (Annotation annotation : annotations) { if (annotation.equals(annotationClass)) { return annotation; } } return null; } }); EasyMock.replay(parameter); } return parameters; }
From source file:net.sf.mmm.util.nls.impl.rebind.AbstractNlsBundleGenerator.java
License:Apache License
/** * Generates an the body of an {@link NlsBundle}-method. * //from w w w . java 2 s . c o m * @param sourceWriter is the {@link SourceWriter}. * @param logger is the {@link TreeLogger}. * @param context is the {@link GeneratorContext}. * @param method is the {@link NlsBundle}-method to generate an implementation for. */ protected void generateMethodBody(SourceWriter sourceWriter, TreeLogger logger, GeneratorContext context, JMethod method) { JParameter[] methodParameters = method.getParameters(); if (methodParameters.length > 0) { sourceWriter.print("Map<String, Object> "); sourceWriter.print(VARIABLE_ARGUMENTS); sourceWriter.println(" = new HashMap<String, Object>();"); // loop over parameters and generate code that puts the parameters into the arguments map for (JParameter parameter : methodParameters) { String name; Named namedAnnotation = parameter.getAnnotation(Named.class); if (namedAnnotation == null) { name = parameter.getName(); } else { name = namedAnnotation.value(); } sourceWriter.print(VARIABLE_ARGUMENTS); sourceWriter.print(".put(\""); sourceWriter.print(escape(name)); sourceWriter.print("\", "); sourceWriter.print(parameter.getName()); sourceWriter.println(");"); } } sourceWriter.print("String "); generateMethodMessageBlock(sourceWriter, logger, context, method.getName()); generateCreateMessageBlock(sourceWriter, methodParameters.length > 0); }