List of usage examples for com.google.gwt.core.ext.typeinfo JClassType getOverridableMethods
JMethod[] getOverridableMethods();
From source file:com.eleven.rebind.SkinBundleGenerator.java
License:Apache License
@Override public String generate(final TreeLogger logger, final GeneratorContext context, final String typeName) throws UnableToCompleteException { TypeOracle typeOracle = context.getTypeOracle(); // Get metadata describing the user's class. JClassType userType = getValidUserType(logger, typeName, typeOracle); // Write the new class. JMethod[] imgMethods = userType.getOverridableMethods(); String resultName = generateImplClass(logger, context, userType, imgMethods); // Return the complete name of the generated class. return resultName; }
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 v a 2 s . c om*/ 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.gwt.testing.easygwtmock.rebind.MocksControlGenerator.java
License:Apache License
/** * Generates the concrete MocksControl implementation of the {@code typeName} interface and * delegates generation of mock classes to * {@link com.google.gwt.testing.easygwtmock.rebind.MocksGenerator} *//*w w w. jav a2 s.c o m*/ @Override public String generate(TreeLogger logger, GeneratorContext context, String typeName) throws UnableToCompleteException { TypeOracle typeOracle = context.getTypeOracle(); JClassType mockControlInterface = typeOracle.findType(typeName); if (mockControlInterface == null) { logger.log(TreeLogger.ERROR, "Unable to find metadata for type '" + typeName + "'", null); throw new UnableToCompleteException(); } if (mockControlInterface.isInterface() == null) { logger.log(TreeLogger.ERROR, mockControlInterface.getQualifiedSourceName() + " is not an interface", null); throw new UnableToCompleteException(); } JPackage interfacePackage = mockControlInterface.getPackage(); String packageName = interfacePackage == null ? "" : interfacePackage.getName(); String newClassName = mockControlInterface.getName().replace(".", "_") + "Impl"; String fullNewClassName = packageName + "." + newClassName; PrintWriter printWriter = context.tryCreate(logger, packageName, newClassName); if (printWriter == null) { // We generated this before. return fullNewClassName; } ClassSourceFileComposerFactory composer = new ClassSourceFileComposerFactory(packageName, newClassName); composer.setSuperclass(MocksControlBase.class.getCanonicalName()); composer.addImplementedInterface(mockControlInterface.getQualifiedSourceName()); SourceWriter writer = composer.createSourceWriter(context, printWriter); writer.println(); MocksGenerator mocksGenerator = new MocksGenerator(context, logger); JClassType markerInterface = typeOracle.findType(MocksControl.class.getCanonicalName()); Set<String> reservedNames = getMethodNames(composer.getSuperclassName(), logger, typeOracle); // Report one error per method in the control interface. They are likely to be independent, // so it's a bit nicer for the user. boolean failed = false; for (JMethod method : mockControlInterface.getOverridableMethods()) { if (method.getEnclosingType().equals(markerInterface)) { // Method is implemented in MocksControlBase continue; } if (reservedNames.contains(method.getName())) { // Method name is already used in base class and method should not be overwritten! logger.log(TreeLogger.ERROR, method.getName() + " is a reserved name. Do not use it in the extended MocksControl interface", null); failed = true; continue; } JClassType typeToMock = method.getReturnType().isClassOrInterface(); if (typeToMock == null) { logger.log(TreeLogger.ERROR, method.getReturnType().getQualifiedSourceName() + " is not an interface or a class", null); failed = true; continue; } if (typeToMock.isInterface() != null) { if (method.getParameterTypes().length != 0) { String methodName = mockControlInterface.getSimpleSourceName() + "." + method.getName(); logger.log(TreeLogger.ERROR, "This method should not have parameters because it creates Ua mock of an interface: " + methodName, null); failed = true; continue; } } else { JConstructor constructorToCall = typeToMock.findConstructor(method.getParameterTypes()); if (constructorToCall == null) { String methodName = mockControlInterface.getSimpleSourceName() + "." + method.getName(); logger.log(TreeLogger.ERROR, "Cannot find matching constructor to call for " + methodName, null); failed = true; continue; } } String mockClassName = mocksGenerator.generateMock(typeToMock); printFactoryMethod(writer, method, mockControlInterface, mockClassName); } if (failed) { throw new UnableToCompleteException(); } writer.commit(logger); return fullNewClassName; }
From source file:com.google.gwt.testing.easygwtmock.rebind.MocksGenerator.java
License:Apache License
/** * Generates a mock class for {@code interfaceToMock}. *//*from w w w .j av a 2 s. c o m*/ String generateMock(JClassType typeToMock) throws UnableToCompleteException { JPackage interfacePackage = typeToMock.getPackage(); String packageName = interfacePackage == null ? "" : interfacePackage.getName(); String newClassName = typeToMock.getName().replace(".", "_") + "Mock"; // GenericType<Integer> has to generate a different mock implementation than // GenericType<String>, that's what we check and do here if (typeToMock.isParameterized() != null) { StringBuilder typeList = new StringBuilder(); for (JClassType genericArg : typeToMock.isParameterized().getTypeArgs()) { typeList.append(genericArg.getParameterizedQualifiedSourceName()); } newClassName += Integer.toHexString(typeList.toString().hashCode()); } String fullNewClassName = packageName + "." + newClassName; PrintWriter printWriter = this.context.tryCreate(this.logger, packageName, newClassName); if (printWriter == null) { // We generated this before. return fullNewClassName; } ClassSourceFileComposerFactory composer = new ClassSourceFileComposerFactory(packageName, newClassName); composer.addImport(MocksControlBase.class.getCanonicalName()); composer.addImport(Method.class.getCanonicalName()); composer.addImport(Call.class.getCanonicalName()); composer.addImport(UndeclaredThrowableException.class.getCanonicalName()); if (typeToMock.isInterface() != null) { composer.addImplementedInterface(typeToMock.getParameterizedQualifiedSourceName()); } else { composer.setSuperclass(typeToMock.getParameterizedQualifiedSourceName()); } SourceWriter sourceWriter = composer.createSourceWriter(this.context, printWriter); sourceWriter.println(); JMethod[] overridableMethods = typeToMock.getOverridableMethods(); List<JMethod> methodsToMock = new ArrayList<JMethod>(); Set<String> needsDefaultImplementation = new HashSet<String>(); for (JMethod method : overridableMethods) { if (isSpecialMethodOfObject(method)) { needsDefaultImplementation.add(method.getName()); } else if (method.getParameterTypes().length == 0 && method.getName().equals("getClass")) { // ignore, Bug 5026788 in GWT } else { methodsToMock.add(method); } } printFields(sourceWriter, methodsToMock); printConstructors(sourceWriter, newClassName, typeToMock.getConstructors()); printMockMethods(sourceWriter, methodsToMock, newClassName); printDefaultMethods(sourceWriter, typeToMock, needsDefaultImplementation); sourceWriter.commit(this.logger); return fullNewClassName; }
From source file:com.google.web.bindery.autobean.gwt.rebind.model.AutoBeanFactoryModel.java
License:Apache License
public AutoBeanFactoryModel(TreeLogger logger, JClassType factoryType) throws UnableToCompleteException { this.logger = logger; oracle = factoryType.getOracle();/*from w w w. j ava 2s . c o m*/ autoBeanInterface = oracle.findType(AutoBean.class.getCanonicalName()).isGenericType(); autoBeanFactoryInterface = oracle.findType(AutoBeanFactory.class.getCanonicalName()).isInterface(); /* * We want to allow the user to override some of the useful Object methods, * so we'll extract them here. */ JClassType objectType = oracle.getJavaLangObject(); objectMethods = Arrays.asList(objectType.findMethod("equals", new JType[] { objectType }), objectType.findMethod("hashCode", EMPTY_JTYPE), objectType.findMethod("toString", EMPTY_JTYPE)); // Process annotations { Category categoryAnnotation = factoryType.getAnnotation(Category.class); if (categoryAnnotation != null) { categoryTypes = new ArrayList<JClassType>(categoryAnnotation.value().length); processClassArrayAnnotation(categoryAnnotation.value(), categoryTypes); } else { categoryTypes = null; } noWrapTypes = new ArrayList<JClassType>(); noWrapTypes.add(oracle.findType(AutoBean.class.getCanonicalName())); NoWrap noWrapAnnotation = factoryType.getAnnotation(NoWrap.class); if (noWrapAnnotation != null) { processClassArrayAnnotation(noWrapAnnotation.value(), noWrapTypes); } ExtraEnums extraEnumsAnnotation = factoryType.getAnnotation(ExtraEnums.class); if (extraEnumsAnnotation != null) { for (Class<?> clazz : extraEnumsAnnotation.value()) { JEnumType asEnum = oracle.findType(clazz.getCanonicalName()).isEnum(); assert asEnum != null; for (JEnumConstant value : asEnum.getEnumConstants()) { allEnumConstants.put(value, AutoBeanMethod.getEnumName(value)); } } } } for (JMethod method : factoryType.getOverridableMethods()) { if (method.getEnclosingType().equals(autoBeanFactoryInterface)) { // Ignore methods in AutoBeanFactory continue; } JClassType returnType = method.getReturnType().isInterface(); if (returnType == null) { poison("The return type of method %s is a primitive type", method.getName()); continue; } // AutoBean<FooIntf> blah() --> beanType = FooIntf JClassType beanType = ModelUtils.findParameterizationOf(autoBeanInterface, returnType)[0]; if (beanType.isInterface() == null) { poison("The %s parameterization is not an interface", beanType.getQualifiedSourceName()); continue; } // AutoBean<FooIntf> blah(FooIntfSub foo) --> toWrap = FooIntfSub JClassType toWrap; if (method.getParameters().length == 0) { toWrap = null; } else if (method.getParameters().length == 1) { toWrap = method.getParameters()[0].getType().isClassOrInterface(); if (!beanType.isAssignableFrom(toWrap)) { poison("The %s parameterization %s is not assignable from the delegate" + " type %s", autoBeanInterface.getSimpleSourceName(), toWrap.getQualifiedSourceName()); continue; } } else { poison("Unexpecetd parameters in method %s", method.getName()); continue; } AutoBeanType autoBeanType = getAutoBeanType(beanType); // Must wrap things that aren't simple interfaces if (!autoBeanType.isSimpleBean() && toWrap == null) { if (categoryTypes != null) { poison("The %s parameterization is not simple and the following" + " methods did not have static implementations:", beanType.getQualifiedSourceName()); for (AutoBeanMethod missing : autoBeanType.getMethods()) { if (missing.getAction().equals(JBeanMethod.CALL) && missing.getStaticImpl() == null) { poison(missing.getMethod().getReadableDeclaration()); } } } else { poison("The %s parameterization is not simple, but the %s method" + " does not provide a delegate", beanType.getQualifiedSourceName(), method.getName()); } continue; } AutoBeanFactoryMethod.Builder builder = new AutoBeanFactoryMethod.Builder(); builder.setAutoBeanType(autoBeanType); builder.setMethod(method); methods.add(builder.build()); } while (!toCalculate.isEmpty()) { Set<JClassType> examine = toCalculate; toCalculate = new LinkedHashSet<JClassType>(); for (JClassType beanType : examine) { getAutoBeanType(beanType); } } if (poisoned) { die("Unable to complete due to previous errors"); } }
From source file:com.google.web.bindery.requestfactory.gwt.rebind.model.RequestFactoryModel.java
License:Apache License
public RequestFactoryModel(TreeLogger logger, JClassType factoryType) throws UnableToCompleteException { this.logger = logger; this.factoryType = factoryType; this.oracle = factoryType.getOracle(); collectionInterface = oracle.findType(Collection.class.getCanonicalName()); entityProxyInterface = oracle.findType(EntityProxy.class.getCanonicalName()); instanceRequestInterface = oracle.findType(InstanceRequest.class.getCanonicalName()); listInterface = oracle.findType(List.class.getCanonicalName()); mapInterface = oracle.findType(Map.class.getCanonicalName()); requestContextInterface = oracle.findType(RequestContext.class.getCanonicalName()); requestFactoryInterface = oracle.findType(RequestFactory.class.getCanonicalName()); requestInterface = oracle.findType(Request.class.getCanonicalName()); setInterface = oracle.findType(Set.class.getCanonicalName()); splittableType = oracle.findType(Splittable.class.getCanonicalName()); valueProxyInterface = oracle.findType(ValueProxy.class.getCanonicalName()); extraTypes = checkExtraTypes(factoryType, false); for (JMethod method : factoryType.getOverridableMethods()) { if (method.getEnclosingType().equals(requestFactoryInterface)) { // Ignore methods defined an RequestFactory itself continue; }/*from w ww.ja v a 2 s. c o m*/ if (method.getParameters().length > 0) { poison("Unexpected parameter on method %s", method.getName()); continue; } JClassType contextType = method.getReturnType().isInterface(); if (contextType == null || !requestContextInterface.isAssignableFrom(contextType)) { poison("Unexpected return type %s on method %s is not" + " an interface assignable to %s", method.getReturnType().getQualifiedSourceName(), method.getName(), requestContextInterface.getSimpleSourceName()); continue; } ContextMethod.Builder builder = new ContextMethod.Builder(); builder.setDeclaredMethod(method); buildContextMethod(builder, contextType); contextMethods.add(builder.build()); } if (poisoned) { die(poisonedMessage()); } }
From source file:com.gwtmobile.persistence.rebind.GenUtils.java
License:Apache License
public void inspectType(String typeName, List<JMethod> getters, List<JMethod> hasManyRels, List<JMethod> hasOneRels) throws UnableToCompleteException { JClassType classType = getClassType(typeName); for (JMethod method : classType.getOverridableMethods()) { if (!method.isAbstract()) { continue; }//from w w w .java 2 s . c o m String methodName = method.getName(); if (methodName.startsWith("get")) { String propertyName = methodName.substring(3); // getId() is reserved. if (propertyName.equals("Id")) { continue; } JType returnType = method.getReturnType(); String returnTypeName = returnType.getSimpleSourceName(); if (returnType.isPrimitive() != null && !returnTypeName.equals("long") || returnTypeName.equals("String") || returnTypeName.equals("Date") || isSubclassOf(returnType, "JSONValue")) { getters.add(method); continue; } if (returnTypeName.equals("long")) { logger.log(TreeLogger.ERROR, "GWT JSNI does not support 'long' as return type on getter '" + methodName + "'. Use 'double' instead."); throw new UnableToCompleteException(); } if (returnTypeName.startsWith("Collection")) { hasManyRels.add(method); continue; } if (isSubclassOf(returnType, "Persistable")) { hasOneRels.add(method); continue; } logger.log(TreeLogger.ERROR, "Unsupported return type '" + returnTypeName + "' on getter '" + methodName + "'."); throw new UnableToCompleteException(); } else { // TODO: check if method is a setter. ignore if so, error if not. } } }
From source file:com.mvp4g.rebind.config.loader.annotation.EventsAnnotationsLoader.java
License:Apache License
/** * Load events defined by this class//from w w w .j a v a2s. c o m * * @param c * annoted class * @param annotation * annotation of the class * @param configuration * configuration containing loaded elements of the application * @throws Mvp4gAnnotationException * if events are properly described */ private void loadEvents(JClassType c, Events annotation, Mvp4gConfiguration configuration) throws Mvp4gAnnotationException { Event event = null; EventElement element = null; Set<EventElement> events = configuration.getEvents(); JParameter[] params = null; JClassType eventBusWithLookupType = configuration.getOracle() .findType(EventBusWithLookup.class.getCanonicalName()); JClassType eventBusType = configuration.getOracle().findType(EventBus.class.getCanonicalName()); JClassType enclosingType = null; String historyName; Class<?> broadcast; for (JMethod method : c.getOverridableMethods()) { event = method.getAnnotation(Event.class); if (event == null) { enclosingType = method.getEnclosingType(); if (!(eventBusType.equals(enclosingType) || (eventBusWithLookupType.equals(enclosingType)))) { String err = Event.class.getSimpleName() + " annotation missing."; throw new Mvp4gAnnotationException(c.getQualifiedSourceName(), method.getName(), err); } //in this case, it's a method by Mvp4g EventBus interface, no need to create an event continue; } params = method.getParameters(); int nbParams = params.length; String[] paramClasses; if (nbParams > 0) { paramClasses = new String[nbParams]; for (int i = 0; i < nbParams; i++) { paramClasses[i] = params[i].getType().getQualifiedSourceName(); } } else { paramClasses = null; } historyName = event.name(); element = new EventElement(); element.setType(method.getName()); element.setHandlers(buildPresentersAndEventHandlers(c, method, event.handlers(), event.handlerNames(), configuration)); element.setBinds( buildPresentersAndEventHandlers(c, method, event.bind(), event.bindNames(), configuration)); element.setCalledMethod(event.calledMethod()); element.setForwardToModules(buildChildModules(c, method, event, configuration)); element.setForwardToParent(Boolean.toString(event.forwardToParent())); element.setActivate(buildPresentersAndEventHandlers(c, method, event.activate(), event.activateNames(), configuration)); element.setDeactivate(buildPresentersAndEventHandlers(c, method, event.deactivate(), event.deactivateNames(), configuration)); element.setGenerate(buildPresentersAndEventHandlers(c, method, event.generate(), event.generateNames(), configuration)); element.setNavigationEvent(Boolean.toString(event.navigationEvent())); element.setWithTokenGeneration(Boolean .toString(method.getReturnType().getQualifiedSourceName().equals(String.class.getName()))); element.setPassive(Boolean.toString(event.passive())); broadcast = event.broadcastTo(); if (!Event.NoBroadcast.class.equals(broadcast)) { element.setBroadcastTo(broadcast.getCanonicalName()); } if (paramClasses != null) { element.setEventObjectClass(paramClasses); } if (!Event.DEFAULT_NAME.equals(historyName)) { element.setName(historyName); } addElement(events, element, c, method); if (method.getAnnotation(Start.class) != null) { if (configuration.getStart().getEventType() == null) { configuration.getStart().setEventType(method.getName()); } else { String err = "Duplicate value for Start event. It is already defined by another method."; throw new Mvp4gAnnotationException(c.getQualifiedSourceName(), method.getName(), err); } } if (method.getAnnotation(Forward.class) != null) { if (configuration.getStart().getForwardEventType() == null) { configuration.getStart().setForwardEventType(method.getName()); } else { String err = "Duplicate value for Forward event. It is already defined by another method."; throw new Mvp4gAnnotationException(c.getQualifiedSourceName(), method.getName(), err); } } loadHistoryEvent(c, method, configuration); loadHistory(c, method, event, element, configuration); loadEventToLoadChildModuleView(c, method, configuration); loadChildConfig(c, method, configuration); } }
From source file:com.mvp4g.rebind.config.loader.annotation.Mvp4gAnnotationsWithServiceLoader.java
License:Apache License
@Override protected void loadElement(JClassType c, T annotation, Mvp4gConfiguration configuration) throws Mvp4gAnnotationException { Mvp4gWithServicesElement element = loadElementWithServices(c, annotation, configuration); // check if any services need to be injected JParameter[] params = null;//from w w w .j a v a2 s . c om String className = null; String serviceName = null; InjectService serviceAnnotation = null; for (JMethod m : c.getOverridableMethods()) { serviceAnnotation = m.getAnnotation(InjectService.class); if (serviceAnnotation != null) { if (!m.isPublic()) { String err = "Only public setter method can be used to inject a service."; throw new Mvp4gAnnotationException(c.getQualifiedSourceName(), m.getName(), err); } params = m.getParameters(); if (params.length != 1) { String err = "Only setter method with one parameter can be used to inject a service"; throw new Mvp4gAnnotationException(c.getQualifiedSourceName(), m.getName(), err); } serviceName = serviceAnnotation.serviceName(); if ((serviceName == null) || (serviceName.length() == 0)) { className = params[0].getType().getQualifiedSourceName(); serviceName = getServiceName(configuration, className); } element.getInjectedServices().add(new InjectedElement(serviceName, m.getName())); } } }
From source file:com.mvp4g.rebind.Mvp4gRunAsyncGenerator.java
License:Apache License
String getRunAsync(JClassType originalType) { JMethod[] methods = originalType.getOverridableMethods(); for (JMethod method : methods) { if ("load".equals(method.getName())) { return method.getParameters()[0].getType().getQualifiedSourceName(); }//from ww w . j a va 2 s . co m } return null; }