List of usage examples for com.google.gwt.core.ext.typeinfo JMethod getReadableDeclaration
String getReadableDeclaration();
From source file:com.gafactory.core.rebind.PropertyAccessGenerator.java
License:sencha.com license
@Override public String generate(TreeLogger logger, GeneratorContext context, String typeName) throws UnableToCompleteException { // make sure it is an interface TypeOracle oracle = context.getTypeOracle(); propertyAccessInterface = oracle.findType(Name.getSourceNameForClass(PropertyAccess.class)); modelKeyProviderInterface = oracle.findType(Name.getSourceNameForClass(ModelKeyProvider.class)); valueProviderInterface = oracle.findType(Name.getSourceNameForClass(ValueProvider.class)); labelProviderInterface = oracle.findType(Name.getSourceNameForClass(LabelProvider.class)); JClassType toGenerate = oracle.findType(typeName).isInterface(); if (toGenerate == null) { logger.log(TreeLogger.ERROR, typeName + " is not an interface type"); throw new UnableToCompleteException(); }/*from w w w. j a va 2 s . c o m*/ if (!toGenerate.isAssignableTo(propertyAccessInterface)) { logger.log(Type.ERROR, "This isn't a PropertyAccess subtype..."); throw new UnableToCompleteException(); } // Get the name of the new type String packageName = toGenerate.getPackage().getName(); String simpleSourceName = toGenerate.getName().replace('.', '_') + "Impl"; PrintWriter pw = context.tryCreate(logger, packageName, simpleSourceName); if (pw == null) { return packageName + "." + simpleSourceName; } // start making the class, with basic imports ClassSourceFileComposerFactory factory = new ClassSourceFileComposerFactory(packageName, simpleSourceName); factory.addImplementedInterface(typeName); SourceWriter sw = factory.createSourceWriter(context, pw); // for each method, for (JMethod m : toGenerate.getOverridableMethods()) { TreeLogger l = logger.branch(Type.DEBUG, "Building method: " + m.getReadableDeclaration()); // no support for params at this time if (m.getParameters().length != 0) { l.log(Type.ERROR, "Method " + m.toString() + " must not have parameters."); throw new UnableToCompleteException(); } // ask for the types that provide the property data JClassType ret = m.getReturnType().isClassOrInterface(); final AbstractCreator c; if (ret.isAssignableTo(valueProviderInterface)) { c = new ValueProviderCreator(context, l, m); } else if (ret.isAssignableTo(modelKeyProviderInterface)) { c = new ModelKeyProviderCreator(context, l, m); } else if (ret.isAssignableTo(labelProviderInterface)) { c = new LabelProviderCreator(context, l, m); } else { logger.log(Type.ERROR, "Method uses a return type that cannot be generated"); throw new UnableToCompleteException(); } c.create(); // build the method // public ValueProvider<T, V> name() { return NameValueProvider.instance; // } sw.println("public %1$s %2$s() {", m.getReturnType().getQualifiedSourceName(), m.getName()); sw.indentln("return %1$s;", c.getInstanceExpression()); sw.println("}"); } sw.commit(logger); return factory.getCreatedClassName(); }
From source file:com.google.web.bindery.requestfactory.gwt.rebind.model.RequestFactoryModel.java
License:Apache License
private EntityProxyModel getEntityProxyType(JClassType entityProxyType) throws UnableToCompleteException { entityProxyType = ModelUtils.ensureBaseType(entityProxyType); EntityProxyModel toReturn = peers.get(entityProxyType); if (toReturn == null) { EntityProxyModel.Builder inProgress = peerBuilders.get(entityProxyType); if (inProgress != null) { toReturn = inProgress.peek(); }//ww w . ja v a 2s . co m } if (toReturn == null) { EntityProxyModel.Builder builder = new EntityProxyModel.Builder(); peerBuilders.put(entityProxyType, builder); // Validate possible super-proxy types first for (JClassType supertype : entityProxyType.getFlattenedSupertypeHierarchy()) { List<EntityProxyModel> superTypes = new ArrayList<EntityProxyModel>(); if (supertype != entityProxyType && shouldAttemptProxyValidation(supertype)) { superTypes.add(getEntityProxyType(supertype)); } builder.setSuperProxyTypes(superTypes); } builder.setQualifiedBinaryName(ModelUtils.getQualifiedBaseBinaryName(entityProxyType)); builder.setQualifiedSourceName(ModelUtils.getQualifiedBaseSourceName(entityProxyType)); if (entityProxyInterface.isAssignableFrom(entityProxyType)) { builder.setType(Type.ENTITY); } else if (valueProxyInterface.isAssignableFrom(entityProxyType)) { builder.setType(Type.VALUE); } else { poison("The type %s is not assignable to either %s or %s", entityProxyInterface.getQualifiedSourceName(), valueProxyInterface.getQualifiedSourceName()); // Cannot continue, since knowing the behavior is crucial die(poisonedMessage()); } // Get the server domain object type ProxyFor proxyFor = entityProxyType.getAnnotation(ProxyFor.class); ProxyForName proxyForName = entityProxyType.getAnnotation(ProxyForName.class); JsonRpcProxy jsonRpcProxy = entityProxyType.getAnnotation(JsonRpcProxy.class); if (proxyFor == null && proxyForName == null && jsonRpcProxy == null) { poison("The %s type does not have a @%s, @%s, or @%s annotation", entityProxyType.getQualifiedSourceName(), ProxyFor.class.getSimpleName(), ProxyForName.class.getSimpleName(), JsonRpcProxy.class.getSimpleName()); } // Look at the methods declared on the EntityProxy List<RequestMethod> requestMethods = new ArrayList<RequestMethod>(); Map<String, JMethod> duplicatePropertyGetters = new HashMap<String, JMethod>(); for (JMethod method : entityProxyType.getInheritableMethods()) { if (method.getEnclosingType().equals(entityProxyInterface)) { // Ignore methods on EntityProxy continue; } RequestMethod.Builder methodBuilder = new RequestMethod.Builder(); methodBuilder.setDeclarationMethod(entityProxyType, method); JType transportedType; String name = method.getName(); if (JBeanMethod.GET.matches(method)) { transportedType = method.getReturnType(); String propertyName = JBeanMethod.GET.inferName(method); JMethod previouslySeen = duplicatePropertyGetters.get(propertyName); if (previouslySeen == null) { duplicatePropertyGetters.put(propertyName, method); } else { poison("Duplicate accessors for property %s: %s() and %s()", propertyName, previouslySeen.getName(), method.getName()); } } else if (JBeanMethod.SET.matches(method) || JBeanMethod.SET_BUILDER.matches(method)) { transportedType = method.getParameters()[0].getType(); } else if (name.equals("stableId") && method.getParameters().length == 0) { // Ignore any overload of stableId continue; } else { poison("The method %s is neither a getter nor a setter", method.getReadableDeclaration()); continue; } validateTransportableType(methodBuilder, transportedType, false); RequestMethod requestMethod = methodBuilder.build(); requestMethods.add(requestMethod); } builder.setExtraTypes(checkExtraTypes(entityProxyType, false)).setRequestMethods(requestMethods); toReturn = builder.build(); peers.put(entityProxyType, toReturn); peerBuilders.remove(entityProxyType); } return toReturn; }
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()); }/*from w w w . j av a 2s . 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.hiramchirino.restygwt.rebind.RestServiceClassCreator.java
License:Apache License
private String getRestMethod(JMethod method) throws UnableToCompleteException { String restMethod = null;/*from www.j a v a 2s .c o m*/ if (method.getAnnotation(DELETE.class) != null) { restMethod = METHOD_DELETE; } else if (method.getAnnotation(GET.class) != null) { restMethod = METHOD_GET; } else if (method.getAnnotation(HEAD.class) != null) { restMethod = METHOD_HEAD; } else if (method.getAnnotation(OPTIONS.class) != null) { restMethod = METHOD_OPTIONS; } else if (method.getAnnotation(POST.class) != null) { restMethod = METHOD_POST; } else if (method.getAnnotation(PUT.class) != null) { restMethod = METHOD_PUT; } else { restMethod = method.getName(); if (!REST_METHODS.contains(restMethod)) { error("Invalid rest method. It must either have a lower case rest method name or have a javax rs method annotation: " + method.getReadableDeclaration()); } } return restMethod; }
From source file:com.seanchenxi.gwt.storage.rebind.StorageKeyProviderModel.java
License:Apache License
private StorageKeyProviderMethod buildKeyMethod(JMethod method) throws UnableToCompleteException { logger.branch(TreeLogger.Type.DEBUG, "buildKeyMethod with method=" + method.getReadableDeclaration()); StorageKeyProviderMethod.Builder builder = new StorageKeyProviderMethod.Builder(); builder.setMethod(method);/* w w w . ja v a2 s . c o m*/ if (method.isAnnotationPresent(KEY_ANNOTATION)) { builder.setKeyAnnotation(method.getAnnotation(KEY_ANNOTATION)); } return builder.build(); }
From source file:com.seanchenxi.gwt.storage.rebind.StorageKeyProviderModel.java
License:Apache License
private boolean validateMethodDef(JMethod method) throws UnableToCompleteException { if (!method.getEnclosingType().equals(providerType)) { return false; }/*from ww w . j ava 2 s .co m*/ JParameterizedType returnType = method.getReturnType().isParameterized(); boolean isCorrectReturnType = returnType != null && returnType.isAssignableTo(storageKeyGenericType); JClassType valueType = isCorrectReturnType ? returnType.getTypeArgs()[0] : null; if (!isValideType(valueType)) { logger.branch(TreeLogger.Type.ERROR, "method " + method.getReadableDeclaration() + "'s returned store type is not extends to IsSerializable nor Serializable"); throw new UnableToCompleteException(); } int length = method.getParameters().length; if (length > 1) { logger.branch(TreeLogger.Type.WARN, "method " + method.getReadableDeclaration() + " should only have one or zero parameter"); throw new UnableToCompleteException(); } return true; }
From source file:com.sencha.gxt.core.rebind.XTemplatesGenerator.java
License:sencha.com license
@Override public String generate(TreeLogger logger, GeneratorContext context, String typeName) throws UnableToCompleteException { // make sure it is an interface TypeOracle oracle = context.getTypeOracle(); this.logger = logger; this.xTemplatesInterface = oracle.findType(Name.getSourceNameForClass(XTemplates.class)); this.listInterface = oracle.findType(Name.getSourceNameForClass(List.class)); JClassType toGenerate = oracle.findType(typeName).isInterface(); if (toGenerate == null) { logger.log(TreeLogger.ERROR, typeName + " is not an interface type"); throw new UnableToCompleteException(); }/*from www .ja va2s . co m*/ if (!toGenerate.isAssignableTo(xTemplatesInterface)) { logger.log(Type.ERROR, "This isn't a XTemplates subtype..."); throw new UnableToCompleteException(); } // Get the name of the new type String packageName = toGenerate.getPackage().getName(); String simpleSourceName = toGenerate.getName().replace('.', '_') + "Impl"; PrintWriter pw = context.tryCreate(logger, packageName, simpleSourceName); if (pw == null) { return packageName + "." + simpleSourceName; } ClassSourceFileComposerFactory factory = new ClassSourceFileComposerFactory(packageName, simpleSourceName); factory.addImplementedInterface(typeName); // imports factory.addImport(Name.getSourceNameForClass(GWT.class)); factory.addImport(Name.getSourceNameForClass(SafeHtml.class)); factory.addImport(Name.getSourceNameForClass(SafeHtmlBuilder.class)); // Loop through the formatters declared for this type and supertypes FormatCollector formatters = new FormatCollector(context, logger, toGenerate); MethodCollector invokables = new MethodCollector(context, logger, toGenerate); SourceWriter sw = factory.createSourceWriter(context, pw); for (JMethod method : toGenerate.getOverridableMethods()) { TreeLogger l = logger.branch(Type.DEBUG, "Creating XTemplate method " + method.getName()); final String template; XTemplate marker = method.getAnnotation(XTemplate.class); if (marker == null) { l.log(Type.ERROR, "Unable to create template for method " + method.getReadableDeclaration() + ", this may cause other failures."); continue; } else { if (marker.source().length() != 0) { if (marker.value().length() != 0) { l.log(Type.WARN, "Found both source file and inline template, using source file"); } InputStream stream = getTemplateResource(context, method.getEnclosingType(), l, marker.source()); if (stream == null) { l.log(Type.ERROR, "No data could be loaded - no data at path " + marker.source()); throw new UnableToCompleteException(); } template = Util.readStreamAsString(stream); } else if (marker.value().length() != 0) { template = marker.value(); } else { l.log(Type.ERROR, "XTemplate annotation found with no contents, cannot generate method " + method.getName() + ", this may cause other failures."); continue; } } XTemplateParser p = new XTemplateParser( l.branch(Type.DEBUG, "Parsing provided template for " + method.getReadableDeclaration())); TemplateModel m = p.parse(template); SafeHtmlTemplatesCreator safeHtml = new SafeHtmlTemplatesCreator(context, l.branch(Type.DEBUG, "Building SafeHtmlTemplates"), method); sw.println(method.getReadableDeclaration(false, true, true, false, true) + "{"); sw.indent(); Map<String, JType> params = new HashMap<String, JType>(); for (JParameter param : method.getParameters()) { params.put(param.getName(), param.getType()); } Context scopeContext = new Context(context, l, params, formatters); // if there is only one parameter, wrap the scope up so that properties // can be accessed directly if (method.getParameters().length == 1) { JParameter param = method.getParameters()[0]; scopeContext = new Context(scopeContext, param.getName(), param.getType()); } String outerSHVar = scopeContext.declareLocalVariable("outer"); sw.println("SafeHtml %1$s;", outerSHVar); buildSafeHtmlTemplates(outerSHVar, sw, m, safeHtml, scopeContext, invokables); sw.println("return %1$s;", outerSHVar); sw.outdent(); sw.println("}"); safeHtml.create(); } // Save the file and return its type name sw.commit(logger); return factory.getCreatedClassName(); }
From source file:org.cruxframework.crux.core.rebind.database.AbstractDatabaseProxyCreator.java
License:Apache License
protected List<IndexData> getIndexFromAnnotations(JClassType objectStoreTarget, String prefix) { List<IndexData> result = new ArrayList<IndexData>(); List<JMethod> getterMethods = JClassUtils.getGetterMethods(objectStoreTarget); for (JMethod method : getterMethods) { if (JClassUtils.isSimpleType(method.getReturnType())) { Indexed indexed = method.getAnnotation(Indexed.class); if (indexed != null) { String property = JClassUtils.getPropertyForGetterOrSetterMethod(method); if (!isValidTypeForKey(method.getReturnType())) { throw new CruxGeneratorException("Invalid index type for index on method [" + method.getReadableDeclaration() + "]. Crux databases only support Strings, integers, double or dates as part of a key or index"); }//w w w . j a va2s . co m result.add(new IndexData(new String[] { prefix + property }, indexed.unique(), false, prefix + property)); } } else { String property = JClassUtils.getPropertyForGetterOrSetterMethod(method); result.addAll(getIndexFromAnnotations(method.getReturnType().isClassOrInterface(), prefix + property + ".")); } } return result; }
From source file:org.cruxframework.crux.core.rebind.database.AbstractDatabaseProxyCreator.java
License:Apache License
protected String[] getKeyPath(JClassType targetObject) { List<String> keyPath = new ArrayList<String>(); List<Key> keys = new ArrayList<Key>(); List<JMethod> getterMethods = JClassUtils.getGetterMethods(targetObject); for (JMethod method : getterMethods) { Key key = method.getAnnotation(Key.class); if (key != null) { if (!isValidTypeForKey(method.getReturnType())) { throw new CruxGeneratorException("Invalid key type for key on method [" + method.getReadableDeclaration() + "]. Crux databases only support Strings, integers, double or dates as part of a key or index"); }//from www . j a v a 2 s. c om keys.add(key); keyPath.add(JClassUtils.getPropertyForGetterOrSetterMethod(method)); } } for (int i = 0; i < keys.size(); i++) { int orderI = keys.get(i).order(); if (orderI < 0 && keys.size() > 1) { throw new CruxGeneratorException( "Crux object stores with composite keys must declare a valid order for its key's components"); } int pos = i; for (int j = i + 1; j < keys.size(); j++) { int orderJ = keys.get(j).order(); if (orderJ < orderI) { orderI = orderJ; pos = j; } } if (pos != i) { Key key = keys.remove(pos); keys.add(i, key); String path = keyPath.remove(pos); keyPath.add(i, path); } } return keyPath.toArray(new String[keyPath.size()]); }
From source file:org.cruxframework.crux.core.rebind.rest.CruxRestProxyCreatorFromServerMetadata.java
License:Apache License
private void validateImplementationMethod(JMethod method, Method implementationMethod) { if (implementationMethod == null) { throw new CruxGeneratorException( "Invalid signature for rest proxy method. Can not found the implementation method: " + method.getName() + ", on class: " + restImplementationClass.getCanonicalName()); }/* www.j a va 2 s . com*/ if (!Modifier.isPublic(implementationMethod.getModifiers())) { throw new CruxGeneratorException( "Invalid signature for rest proxy method. Implementation method: " + method.getName() + ", on class: " + restImplementationClass.getCanonicalName() + ", is not public."); } Class<?>[] implTypes = implementationMethod.getParameterTypes(); JType[] proxyTypes = method.getParameterTypes(); if ((proxyTypes.length - 1) != implTypes.length) { throw new CruxGeneratorException("Invalid signature for rest proxy method. The implementation method: " + method.getName() + ", on class: " + restImplementationClass.getCanonicalName() + " does not match the parameters list."); } for (int i = 0; i < implTypes.length; i++) { if (!isTypesCompatiblesForSerialization(implTypes[i], proxyTypes[i])) { throw new CruxGeneratorException( "Invalid signature for rest proxy method. Incompatible parameters on method[" + method.getReadableDeclaration() + "]"); } } JClassType lastParameterType = proxyTypes[proxyTypes.length - 1].isClassOrInterface(); if (!isTypesCompatiblesForSerialization(implementationMethod.getReturnType(), JClassUtils.getTypeArgForGenericType(lastParameterType))) { throw new CruxGeneratorException( "Invalid signature for rest proxy method. Return type of implementation method is not compatible with Callback's type. Method[" + method.getReadableDeclaration() + "]"); } }