List of usage examples for com.google.gwt.core.ext.typeinfo JClassType isDefaultInstantiable
boolean isDefaultInstantiable();
new operation. From source file:com.artemis.gwtref.gen.ReflectionCacheSourceCreator.java
License:Apache License
private static boolean isInstantiableWithNewOperator(JClassType t) { if (!t.isDefaultInstantiable() || t instanceof JArrayType || t instanceof JEnumType) return false; try {/*from w w w. j a v a2 s . c om*/ JConstructor constructor = t.getConstructor(new JType[0]); return constructor != null && constructor.isPublic(); } catch (NotFoundException e) { return false; } }
From source file:com.github.gilbertotorrezan.gwtviews.rebind.NavigationManagerGenerator.java
License:Open Source License
@SuppressWarnings("rawtypes") @Override//from w w w. j ava 2 s .c o m public String generate(TreeLogger logger, GeneratorContext context, String typeName) throws UnableToCompleteException { final TypeOracle typeOracle = context.getTypeOracle(); JClassType mainType = typeOracle.findType(typeName); PrintWriter writer = context.tryCreate(logger, mainType.getPackage().getName(), mainType.getName() + "Impl"); if (writer == null) { return mainType.getQualifiedSourceName() + "Impl"; } ClassSourceFileComposerFactory factory = new ClassSourceFileComposerFactory(mainType.getPackage().getName(), mainType.getName() + "Impl"); factory.addImplementedInterface(typeName); factory.addImport(Presenter.class.getPackage().getName() + ".*"); factory.addImport("com.google.gwt.user.client.History"); factory.addImport("com.google.gwt.user.client.ui.Widget"); factory.addImport("com.google.gwt.user.client.ui.Panel"); factory.addImport("com.google.gwt.http.client.URL"); factory.addImport("com.google.gwt.user.client.rpc.AsyncCallback"); factory.addImport("com.google.gwt.core.client.*"); factory.addImport("com.google.gwt.event.logical.shared.*"); factory.addImport("com.github.gilbertotorrezan.gwtviews.client.analytics.*"); factory.addImport("javax.annotation.Generated"); factory.addImport("java.util.*"); factory.addAnnotationDeclaration("@Generated(" + "value=\"" + NavigationManagerGenerator.class.getName() + "\", " + "date=\"" + new Date() + "\", " + "comments=\"Generated by GWT-Views project.\")"); SourceWriter sourceWriter = factory.createSourceWriter(context, writer); sourceWriter.println("//AUTO GENERATED FILE BY GWT-VIEWS AT " + getClass().getName() + ". DO NOT EDIT!\n"); sourceWriter.println("private Panel rootContainer;"); sourceWriter.println("private UserPresenceManager userPresenceManager;"); sourceWriter.println("private URLTokenFactory tokenFactory = new URLTokenFactory();"); sourceWriter.println("private final Map<String, Presenter<?>> presentersMap = new HashMap<>();"); sourceWriter.println("private URLToken currentToken = tokenFactory.createToken(\"\");"); sourceWriter.println("private URLInterceptor currentInterceptor;\n"); List<ViewPage> viewPages = new ArrayList<>(); Map<String, HasViewPages> viewContainers = new HashMap<>(); Set<ViewPage> viewsInNeedOfPresenters = new LinkedHashSet<>(); Set<HasViewPages> containersInNeedOfPresenters = new LinkedHashSet<>(); ViewPage defaultViewPage = null; ViewPage notFoundViewPage = null; HasViewPages defaultViewContainerPage = null; JClassType containerType = typeOracle.findType(HasViews.class.getName()); JClassType[] types = typeOracle.getTypes(); for (JClassType type : types) { if (type.isAnnotationPresent(View.class)) { View view = type.getAnnotation(View.class); if (shouldForceEmptyConstructor(view) && !type.isDefaultInstantiable()) { logger.log(Type.WARN, type.getName() + " must have an empty constructor to be a valid " + View.class.getSimpleName() + "."); continue; } ViewPage page = new ViewPage(view, type); viewPages.add(page); if (view.defaultView()) { defaultViewPage = page; } if (view.notFoundView()) { notFoundViewPage = page; } } else if (type.isAnnotationPresent(ViewContainer.class)) { if (!type.isAssignableTo(containerType)) { logger.log(Type.WARN, type.getName() + " must implement " + containerType.getName() + " to be a valid " + ViewContainer.class.getSimpleName() + "."); continue; } ViewContainer container = type.getAnnotation(ViewContainer.class); if (shouldForceEmptyConstructor(container) && !type.isDefaultInstantiable()) { logger.log(Type.WARN, type.getName() + " must have an empty constructor to be a valid " + ViewContainer.class.getSimpleName() + "."); continue; } HasViewPages hasViews = new HasViewPages(container, type); viewContainers.put(type.getQualifiedSourceName(), hasViews); if (container.defaultContainer()) { defaultViewContainerPage = hasViews; } } } if (defaultViewPage == null) { logger.log(Type.ERROR, "No default view page defined!"); throw new UnableToCompleteException(); } if (defaultViewContainerPage == null && viewContainers.size() > 1) { logger.log(Type.ERROR, "There are more than one " + ViewContainer.class.getSimpleName() + " but no one is the default!"); throw new UnableToCompleteException(); } if (defaultViewContainerPage == null && !viewContainers.isEmpty()) { defaultViewContainerPage = viewContainers.values().iterator().next(); } sourceWriter.println("public void onValueChange(ValueChangeEvent<String> event){"); sourceWriter.indent(); sourceWriter.println("final URLToken token = tokenFactory.createToken(event.getValue());"); sourceWriter.println("if (currentInterceptor != null){"); sourceWriter.indent(); sourceWriter.println("History.newItem(currentToken.toString(), false);"); sourceWriter.println("currentInterceptor.onUrlChanged(currentToken, token, new URLInterceptorCallback(){"); sourceWriter.indent(); sourceWriter.println("@Override\npublic void proceedTo(URLToken destination){"); sourceWriter.indent(); sourceWriter.println("History.newItem(destination.toString(), false);"); sourceWriter.println("proceedToImpl(destination);"); sourceWriter.outdent(); sourceWriter.println("}"); sourceWriter.outdent(); sourceWriter.println("});"); sourceWriter.println("return;"); sourceWriter.outdent(); sourceWriter.println("}"); sourceWriter.println("this.proceedToImpl(token);"); sourceWriter.outdent(); sourceWriter.println("}\n"); sourceWriter.println("private void proceedToImpl(final URLToken token){"); sourceWriter.indent(); sourceWriter.println("this.currentToken = token;"); sourceWriter.println("switch (token.getId()){"); sourceWriter.indent(); int defaultViewIndex = -1; int notFoundViewIndex = -1; for (int i = 0; i < viewPages.size(); i++) { ViewPage viewPage = viewPages.get(i); final View view = viewPage.getView(); logger.log(Type.DEBUG, "Processing view " + view.value() + "..."); if (view.defaultView()) { defaultViewIndex = i; sourceWriter.println("case \"\":"); } if (view.notFoundView()) { notFoundViewIndex = i; } sourceWriter.println("case \"" + view.value() + "\": {"); sourceWriter.indent(); if (!view.publicAccess()) { sourceWriter.println("if (userPresenceManager != null) {"); sourceWriter.indent(); if (view.rolesAllowed() != null && view.rolesAllowed().length > 0) { String[] roles = view.rolesAllowed(); StringBuilder params = new StringBuilder("new String[]{ "); String sep = ""; for (String role : roles) { params.append(sep).append("\"").append(role).append("\""); sep = ", "; } params.append(" }"); sourceWriter.println("userPresenceManager.isUserInAnyRole(token, " + params.toString() + ", new AsyncCallback<Boolean>(){"); } else { sourceWriter.println( "userPresenceManager.isUserInAnyRole(token, new String[0], new AsyncCallback<Boolean>(){"); } sourceWriter.indent(); sourceWriter.println("@Override"); sourceWriter.println("public void onSuccess(Boolean allowed){"); sourceWriter.indent(); sourceWriter.println("if (allowed == null || !allowed){"); sourceWriter.indent(); sourceWriter.println("URLToken nextToken = tokenFactory.createToken(\"" + defaultViewPage.getView().value() + "\");"); sourceWriter.println("nextToken.setParameter(\"next\", URL.encodeQueryString(token.toString()));"); sourceWriter.println("nextToken.go();"); sourceWriter.outdent(); sourceWriter.println("}"); sourceWriter.println("else {"); sourceWriter.indent(); sourceWriter.println("showPresenter" + i + "(token);"); sourceWriter.outdent(); sourceWriter.println("}"); sourceWriter.outdent(); sourceWriter.println("}"); sourceWriter.println("@Override"); sourceWriter.println("public void onFailure(Throwable error){"); sourceWriter.indent(); sourceWriter.println("GWT.log(\"Error loading view: \" + error, error);"); sourceWriter.println("URLToken nextToken = tokenFactory.createToken(\"" + defaultViewPage.getView().value() + "\");"); sourceWriter.println("nextToken.setParameter(\"next\", URL.encodeQueryString(token.toString()));"); sourceWriter.println("nextToken.go();"); sourceWriter.outdent(); sourceWriter.println("}"); sourceWriter.outdent(); sourceWriter.println("});"); sourceWriter.println("return;"); sourceWriter.outdent(); sourceWriter.println("}"); } sourceWriter.println("showPresenter" + i + "(token);"); sourceWriter.outdent(); sourceWriter.println("}\nbreak;"); } sourceWriter.println("default: {"); sourceWriter.indent(); if (notFoundViewPage != null) { sourceWriter.println("//NotFound View"); sourceWriter.println("showPresenter" + notFoundViewIndex + "(tokenFactory.createToken(\"" + notFoundViewPage.getView().value() + "\"));"); } else { sourceWriter.println("//Default View"); sourceWriter.println("History.newItem(\"" + defaultViewPage.getView().value() + "\", false);"); sourceWriter.println("showPresenter" + defaultViewIndex + "(tokenFactory.createToken(\"" + defaultViewPage.getView().value() + "\"));"); } sourceWriter.outdent(); sourceWriter.println("}\nbreak;"); sourceWriter.outdent(); sourceWriter.println("}"); sourceWriter.outdent(); sourceWriter.println("}\n"); for (int i = 0; i < viewPages.size(); i++) { ViewPage viewPage = viewPages.get(i); final View view = viewPage.getView(); sourceWriter.println("/** Method to show the presenter of the " + view.value() + " view. */"); sourceWriter.println("private void showPresenter" + i + "(final URLToken token) {"); sourceWriter.indent(); sourceWriter.println("GWT.runAsync(new RunAsyncCallback() {"); sourceWriter.indent(); sourceWriter.println("public void onSuccess() {"); sourceWriter.indent(); sourceWriter.println("UniversalAnalyticsTracker.sendPageView(token.toString());"); sourceWriter.println("Presenter<?> presenter = presentersMap.get(\"" + view.value() + "\");"); sourceWriter.println("if (presenter == null) {"); sourceWriter.indent(); Class<? extends Presenter> customPresenter = view.customPresenter(); if (!Presenter.class.equals(customPresenter)) { sourceWriter.println("presenter = GWT.create(" + customPresenter.getName() + ".class);"); } else { viewsInNeedOfPresenters.add(viewPage); sourceWriter.println("presenter = (Presenter<?>) GWT.create(" + viewPage.getType().getName() + "Presenter.class);"); } sourceWriter.println("presentersMap.put(\"" + view.value() + "\", presenter);"); sourceWriter.outdent(); sourceWriter.println("}"); sourceWriter.println("Widget widget = presenter.getView(token);"); Class<? extends URLInterceptor> urlInterceptor = view.urlInterceptor(); if (!URLInterceptor.class.equals(urlInterceptor)) { String interceptorName = urlInterceptor.getName(); if (interceptorName.equals(viewPage.getType().getQualifiedSourceName())) { sourceWriter.println("currentInterceptor = (URLInterceptor) widget;"); } else if (interceptorName.equals(customPresenter.getName())) { sourceWriter.println("currentInterceptor = (URLInterceptor) presenter;"); } else { sourceWriter .println("currentInterceptor = GWT.create(" + urlInterceptor.getName() + ".class);"); } } else { sourceWriter.println("currentInterceptor = null;"); } boolean usesViewContainer = view.usesViewContainer(); if (usesViewContainer && !viewContainers.isEmpty()) { Class<?> viewContainer = view.viewContainer(); HasViewPages hasViews; if (HasViews.class.equals(viewContainer)) { hasViews = defaultViewContainerPage; } else { hasViews = viewContainers.get(viewContainer.getName()); } if (hasViews == null) { logger.log(Type.ERROR, viewContainer.getName() + " is not a valid " + ViewContainer.class.getSimpleName() + " for " + View.class.getSimpleName() + " " + viewPage.getType().getQualifiedSourceName() + "."); throw new UnableToCompleteException(); } sourceWriter.println("Presenter<?> containerPresenter = presentersMap.get(\"" + hasViews.getType().getQualifiedSourceName() + "\");"); sourceWriter.println("if (containerPresenter == null) {"); sourceWriter.indent(); if (!Presenter.class.equals(hasViews.getContainer().customPresenter())) { sourceWriter.println("containerPresenter = GWT.create(" + hasViews.getContainer().customPresenter().getName() + ".class);"); } else { containersInNeedOfPresenters.add(hasViews); sourceWriter.println("containerPresenter = (Presenter<?>) GWT.create(" + hasViews.getType().getName() + "Presenter.class);"); } sourceWriter.println("presentersMap.put(\"" + hasViews.getType().getQualifiedSourceName() + "\", containerPresenter);"); sourceWriter.outdent(); sourceWriter.println("}"); sourceWriter.println("Widget container = containerPresenter.getView(token);"); sourceWriter.println("((" + HasViews.class.getName() + ") container).showView(token, widget);"); sourceWriter.println("if (container.getParent() == null){"); sourceWriter.indent(); sourceWriter.println("rootContainer.clear();"); sourceWriter.println("rootContainer.add(container);"); sourceWriter.outdent(); sourceWriter.println("}"); } else { sourceWriter.println("rootContainer.clear();"); sourceWriter.println("rootContainer.add(widget);"); } sourceWriter.outdent(); sourceWriter.println("}"); sourceWriter.println( "public void onFailure(Throwable reason) { GWT.log(\"Error on loading presenter with token: \"+token, reason); }"); sourceWriter.outdent(); sourceWriter.println("});"); sourceWriter.outdent(); sourceWriter.println("}\n"); } sourceWriter.println("@Override\npublic void clearCache() {"); sourceWriter.indent(); sourceWriter.println("presentersMap.clear();"); sourceWriter.outdent(); sourceWriter.println("}\n"); sourceWriter.println("@Override\npublic void clearCache(String tokenId) {"); sourceWriter.indent(); sourceWriter.println("presentersMap.remove(tokenId);"); sourceWriter.outdent(); sourceWriter.println("}\n"); sourceWriter.println("@Override\npublic void setRootContainer(Panel container) {"); sourceWriter.indent(); sourceWriter.println("this.rootContainer = container;"); sourceWriter.outdent(); sourceWriter.println("}\n"); sourceWriter.println("@Override\npublic void setUserPresenceManager(UserPresenceManager umanager) {"); sourceWriter.indent(); sourceWriter.println("this.userPresenceManager = umanager;"); sourceWriter.outdent(); sourceWriter.println("}\n"); sourceWriter.println("@Override\npublic void setURLTokenFactory(URLTokenFactory tokenFactory) {"); sourceWriter.indent(); sourceWriter.println("this.tokenFactory = tokenFactory;"); sourceWriter.outdent(); sourceWriter.println("}\n"); sourceWriter.println("@Override\npublic URLTokenFactory getURLTokenFactory() {"); sourceWriter.indent(); sourceWriter.println("return this.tokenFactory;"); sourceWriter.outdent(); sourceWriter.println("}\n"); sourceWriter.println("//View presenters"); for (ViewPage viewPage : viewsInNeedOfPresenters) { sourceWriter.println("public static interface " + viewPage.getType().getName() + "Presenter extends AutoPresenter<" + viewPage.getType().getQualifiedSourceName() + ">{}"); } if (!containersInNeedOfPresenters.isEmpty()) { sourceWriter.println("\n//ViewContainer presenters"); for (HasViewPages container : containersInNeedOfPresenters) { sourceWriter.println("public static interface " + container.getType().getName() + "Presenter extends AutoPresenter<" + container.getType().getQualifiedSourceName() + ">{}"); } } sourceWriter.outdent(); sourceWriter.println("}"); context.commit(logger, writer); return factory.getCreatedClassName(); }
From source file:com.github.ludorival.dao.gwt.rebind.EntityManagerGenerator.java
License:Apache License
private BeanMetadata create(GeneratorContext context, TreeLogger logger, String packageName, JClassType type, Class<?> classAdapter, IsEntity anno) throws TypeOracleException { String beanName = anno == null || anno.aliasName().isEmpty() ? type.getName() : anno.aliasName(); Source implementation = null; JClassType implType = type; TypeOracle typeOracle = context.getTypeOracle(); if (type.isInterface() != null) { implType = null;//from w w w . j ava 2s . co m JClassType[] types = type.getSubtypes(); log(logger, Type.DEBUG, "Get all sub types of %s : %s", type, Arrays.toString(types)); if (types != null && types.length > 0) { for (JClassType jClassType : types) { if (isInstantiable(jClassType, logger)) { implType = jClassType; implementation = new Source(implType.getPackage().getName(), implType.getName()); break; } } } if (implType == null) { log(logger, Type.ERROR, "The type %s has not valid subtypes " + "%s !", type, Arrays.toString(types)); return null; } } if (!implType.isDefaultInstantiable()) return null; String prefix = classAdapter.getSimpleName().replace("Adapter", ""); boolean isEntity = anno != null; String className = prefix + beanName; if (parseOnlyInterface && implType != type) className += "Light"; PrintWriter writer = context.tryCreate(logger, packageName, className); if (writer == null) { return new BeanMetadata(type, className, implementation, isEntity); } ClassSourceFileComposerFactory factory = new ClassSourceFileComposerFactory(packageName, className); logger.log(Type.DEBUG, "Create Entity " + factory.getCreatedClassName()); factory.setSuperclass(classAdapter.getSimpleName() + "<" + type.getName() + ">"); factory.addImport(RuntimeException.class.getName()); factory.addImport(classAdapter.getName()); factory.addImport(type.getQualifiedSourceName()); if (isEntity) { factory.addImport(ArrayList.class.getName()); factory.addImport(Collection.class.getName()); } factory.addImport(HashMap.class.getName()); factory.addImport(Property.class.getName()); factory.addImport(Property.class.getName() + ".Kind"); factory.addImport(Index.class.getName()); factory.addImport(implType.getQualifiedSourceName()); factory.addImport("javax.annotation.Generated"); factory.addAnnotationDeclaration("@Generated(" + "value=\"" + AdapterEntity.class.getName() + "\", " + "date=\"" + new Date() + "\", " + "comments=\"Generated by DAO-GWT project.\")"); SourceWriter sourceWriter = factory.createSourceWriter(context, writer); sourceWriter.println("//AUTO GENERATED FILE BY DAO-GWT " + getClass().getName() + ". DO NOT EDIT!\n"); sourceWriter.println("private static HashMap<String,Property<%s,?>> PROPERTIES = " + "new HashMap<String,Property<%s,?>>();", type.getName(), type.getName()); if (isEntity) { factory.addImport(ArrayList.class.getName()); factory.addImport(Index.class.getName()); sourceWriter.println("private static Collection<Index> INDEXES = " + "new ArrayList<Index>();"); } sourceWriter.println("static {"); sourceWriter.indent(); JClassType interfaz = type != implType ? type : null; JMethod[] methods = parseOnlyInterface ? type.getInheritableMethods() : implType.getInheritableMethods(); for (JMethod method : methods) { String name = method.getName(); //Check if the method has a IsIgnored annotation before to continue IsIgnored ignored = method.getAnnotation(IsIgnored.class); if (ignored != null) { log(logger, Type.DEBUG, EXPLICITELY_IGNORED, name, implType); continue; } boolean startsWithGet = name.startsWith("get"); boolean startsWithIs = name.startsWith("is"); if (!startsWithGet && !startsWithIs) { log(logger, Type.DEBUG, IGNORE_METHOD, name, implType); continue; } //check no parameters if (method.getParameterTypes().length != 0) { log(logger, Type.WARN, NO_PARAMETER_GETTER, name, implType); continue; } //check return type JType returnType = method.getReturnType(); if (returnType == null || returnType.getQualifiedSourceName().equals(Void.class.getName()) || returnType.getQualifiedSourceName().equals(void.class.getName())) { log(logger, Type.DEBUG, VOID_GETTER, name + "" + returnType, implType); continue; } //change the format of the name getXyy ==> xyy String getterSetter = name; if (startsWithGet) getterSetter = name.substring(3); else if (startsWithIs) getterSetter = name.substring(2); name = getterSetter.substring(0, 1).toLowerCase() + getterSetter.substring(1); // check if the getter has an annotation IsIndexable indexable = method.getAnnotation(IsIndexable.class); boolean isIndexable = indexable != null; if (isIndexable && !isEntity) log(logger, Type.WARN, ONLY_ENTITY_FOR_INDEX, name, implType, IsEntity.class); isIndexable = isIndexable && isEntity;//only entity can defined indexable element String indexName = isIndexable ? indexable.aliasName() : ""; String[] compositeIndexes = isIndexable ? indexable.compoundWith() : new String[0]; Kind kind = null; JType typeOfCollection = null; String typeOfCollectionString = "null"; if (!isPrimitive(returnType)) { //load complex properties except Key if (returnType.isEnum() != null) { kind = Kind.ENUM; } else { boolean isPrimitive = false; boolean isEnum = false; JParameterizedType pType = returnType.isParameterized(); JType collection = typeOracle.parse(Collection.class.getName()); if (pType != null && pType.getRawType().isAssignableTo(collection.isClassOrInterface())) { JClassType[] types = pType.getTypeArgs(); kind = Kind.COLLECTION_OF_PRIMITIVES; if (types.length > 1) { log(logger, Type.DEBUG, CANNOT_PROCESS_PARAMETERIZED_TYPE, returnType, implType); continue; } typeOfCollection = types[0]; typeOfCollectionString = typeOfCollection.getQualifiedSourceName() + ".class"; log(logger, Type.DEBUG, "The type of the collection is %s", typeOfCollectionString); isPrimitive = isPrimitive(typeOfCollection); isEnum = typeOfCollection.isEnum() != null; } if (!isPrimitive) { if (isEnum && kind != null) { kind = Kind.COLLECTION_OF_ENUMS; } else { JClassType classType = typeOfCollection != null ? typeOfCollection.isClassOrInterface() : returnType.isClassOrInterface(); boolean isBean = isBean(classType); if (isBean) { log(logger, Type.DEBUG, "The property %s is well a type %s", name, classType); if (kind == null) kind = Kind.BEAN; else kind = Kind.COLLECTION_OF_BEANS; } else { log(logger, Type.DEBUG, "The property %s has not a bean type %s", name, classType); continue; } } } } } assert kind != null; boolean isMemo = method.getAnnotation(IsMemo.class) != null; String oldName = "null"; OldName oldNameAnno = method.getAnnotation(OldName.class); if (oldNameAnno != null) oldName = "\"" + oldNameAnno.value() + "\""; //create a property if (kind == Kind.BEAN || kind == Kind.COLLECTION_OF_BEANS) factory.addImport(returnType.getQualifiedSourceName()); String valueType = ""; JClassType classType = returnType.isClassOrInterface(); JPrimitiveType primitiveType = returnType.isPrimitive(); if (classType != null) valueType = classType.getQualifiedSourceName(); else if (primitiveType != null) { valueType = primitiveType.getQualifiedBoxedSourceName(); } sourceWriter.println("{ //Property %s", name); sourceWriter.indent(); sourceWriter.print("Index index ="); if (isIndexable) { if (indexName.isEmpty()) indexName = name; sourceWriter.println("new Index(\"%s\",\"%s\",new String[]{%s});", indexName, name, String.join(",", compositeIndexes)); } else sourceWriter.println("null;"); boolean useKeyAsString = anno != null ? (name.equals(anno.keyName()) ? anno.useKeyAsString() : false) : false; KeyOf keyOf = method.getAnnotation(KeyOf.class); if (keyOf != null) { IsEntity isEntity2 = keyOf.entity().getAnnotation(IsEntity.class); if (isEntity2 == null) { log(logger, Type.ERROR, AdapterEntityManager.KEY_OF_NO_ENTITY, method, keyOf, keyOf.entity(), IsEntity.class); continue; } useKeyAsString = isEntity2.useKeyAsString(); } boolean isHidden = isHidden(method, interfaz); sourceWriter.println( "Property<%s,%s> property = new Property<%s,%s>(\"%s\",%s,%s.class,%s,%s,%s,%s,index,%s){", type.getName(), valueType, type.getName(), valueType, name, oldName, returnType.getQualifiedSourceName(), typeOfCollectionString, kind != null ? "Kind." + kind.name() : "null", useKeyAsString + "", isMemo + "", isHidden + ""); sourceWriter.indent(); sourceWriter.println("@Override"); sourceWriter.println("public %s get(%s instance){", valueType, type.getName()); sourceWriter.indent(); sourceWriter.println("return ((%s)instance).%s();", implType.getName(), startsWithGet ? "get" + getterSetter : "is" + getterSetter); sourceWriter.outdent(); sourceWriter.println("}"); sourceWriter.println("@Override"); sourceWriter.println("public void set(%s instance, %s value){", type.getName(), valueType); sourceWriter.indent(); if (getSetter(implType, getterSetter, returnType) != null) sourceWriter.println("((%s)instance).%s(value);", implType.getName(), "set" + getterSetter); else { logger.log(Type.WARN, " Not found setter for " + getterSetter); sourceWriter.println("throw new RuntimeException(\"No such setter " + getterSetter + " \");"); } sourceWriter.outdent(); sourceWriter.println("}"); sourceWriter.outdent(); sourceWriter.println("};"); sourceWriter.println("PROPERTIES.put(\"%s\",property);", name); if (!oldName.equals("null")) { sourceWriter.println("PROPERTIES.put(%s,property);", oldName); } if (isIndexable) sourceWriter.println("INDEXES.add(index);"); sourceWriter.outdent(); sourceWriter.println("}"); log(logger, Type.DEBUG, SUCCESSFUL_ADD_PROPERTY, name + ":" + valueType, implType); } sourceWriter.outdent(); sourceWriter.println("}"); sourceWriter.println(); sourceWriter.println("public %s(){", className); sourceWriter.indent(); /* * boolean asyncReady, boolean autoGeneratedFlag, String keyName, boolean useKeyAsString, Class<T> type,Class<? extends T> implType, Map<String, Property<T,?>> mapAllProperties, Collection<Index> indexes) { super(type,implType,mapAllProperties); */ if (isEntity) sourceWriter .println(String.format("super(\"%s\",%s,%s,\"%s\",%s,%s.class,%s.class,PROPERTIES,INDEXES);", anno.aliasName().isEmpty() ? type.getName() : anno.aliasName(), anno.asyncReady(), anno.autoGeneratedKey(), anno.keyName(), anno.useKeyAsString(), type.getName(), implType.getName())); else { sourceWriter.println( String.format("super(%s.class,%s.class,PROPERTIES);", type.getName(), implType.getName())); } sourceWriter.outdent(); sourceWriter.println("}"); sourceWriter.println(); sourceWriter.println("@Override"); sourceWriter.println("public %s newInstance(){", type.getName()); sourceWriter.indent(); sourceWriter.println("return new %s();", implType.getName()); sourceWriter.outdent(); sourceWriter.println("}"); sourceWriter.outdent(); sourceWriter.println("}"); context.commit(logger, writer); return new BeanMetadata(type, className, implementation, isEntity); }
From source file:com.google.gerrit.plugin.rebind.PluginGenerator.java
License:Apache License
protected void validateType(TreeLogger logger, JClassType type) throws UnableToCompleteException { if (!type.isDefaultInstantiable()) { logger.log(TreeLogger.ERROR, "Plugin types must be default instantiable", null); throw new UnableToCompleteException(); }// w w w . j a va 2 s.c o m }
From source file:com.hiramchirino.restygwt.rebind.JsonEncoderDecoderClassCreator.java
License:Apache License
public void generate() throws UnableToCompleteException { locator = new JsonEncoderDecoderInstanceLocator(context, logger); JClassType soruceClazz = source.isClass(); if (soruceClazz == null) { error("Type is not a class"); }/*from w w w .j ava 2s. c om*/ if (!soruceClazz.isDefaultInstantiable()) { error("No default constuctor"); } Json jsonAnnotation = source.getAnnotation(Json.class); final Style classStyle = jsonAnnotation != null ? jsonAnnotation.style() : Style.DEFAULT; p(); p("public static final " + shortName + " INSTANCE = new " + shortName + "();"); p(); p("public " + JSON_VALUE_CLASS + " encode(" + source.getParameterizedQualifiedSourceName() + " value) {") .i(1); { p(JSON_OBJECT_CLASS + " rc = new " + JSON_OBJECT_CLASS + "();"); for (final JField field : getFields(source)) { final String getterName = getGetterName(field); // If can ignore some fields right off the back.. if (getterName == null && (field.isStatic() || field.isFinal() || field.isTransient())) { continue; } branch("Processing field: " + field.getName(), new Branch<Void>() { public Void execute() throws UnableToCompleteException { // TODO: try to get the field with a setter or JSNI if (getterName != null || field.isDefaultAccess() || field.isProtected() || field.isPublic()) { String name = field.getName(); String fieldExpr = "value." + name; if (getterName != null) { fieldExpr = "value." + getterName + "()"; } Json jsonAnnotation = field.getAnnotation(Json.class); Style style = jsonAnnotation != null ? jsonAnnotation.style() : classStyle; String expression = locator.encodeExpression(field.getType(), fieldExpr, style); p("{").i(1); { p(JSON_VALUE_CLASS + " v=" + expression + ";"); p("if( v!=null ) {").i(1); { if (field.isAnnotationPresent(ExcludeNull.class)) p("if (v != " + JSONNull.class.getCanonicalName() + ".getInstance())"); p("rc.put(" + wrap(name) + ", v);"); } i(-1).p("}"); } i(-1).p("}"); } else { error("field must not be private: " + field.getEnclosingType().getQualifiedSourceName() + "." + field.getName()); } return null; } }); } p("return rc;"); } i(-1).p("}"); p(); p("public " + source.getName() + " decode(" + JSON_VALUE_CLASS + " value) {").i(1); { p(JSON_OBJECT_CLASS + " object = toObject(value);"); p("" + source.getParameterizedQualifiedSourceName() + " rc = new " + source.getParameterizedQualifiedSourceName() + "();"); for (final JField field : getFields(source)) { final String setterName = getSetterName(field); // If can ignore some fields right off the back.. if (setterName == null && (field.isStatic() || field.isFinal() || field.isTransient())) { continue; } branch("Processing field: " + field.getName(), new Branch<Void>() { public Void execute() throws UnableToCompleteException { // TODO: try to set the field with a setter or JSNI if (setterName != null || field.isDefaultAccess() || field.isProtected() || field.isPublic()) { Json jsonAnnotation = field.getAnnotation(Json.class); Style style = jsonAnnotation != null ? jsonAnnotation.style() : classStyle; String name = field.getName(); String expression = locator.decodeExpression(field.getType(), "object.get(" + wrap(name) + ")", style); if (setterName != null) { p("rc." + setterName + "(" + expression + ");"); } else { p("rc." + name + "=" + expression + ";"); } } else { error("field must not be private."); } return null; } }); } p("return rc;"); } i(-1).p("}"); p(); }
From source file:com.kk_electronic.gwt.rebind.JsonEncoderGenerator.java
License:Open Source License
/** * @param context/*from w ww . j a va2 s . c om*/ * @throws UnableToCompleteException */ private void generateJsonFormatterClasses(GeneratorContext context) throws UnableToCompleteException { if (worklist == null || worklist.size() == 0) { return; } for (JClassType jc : worklist) { if (!jc.isDefaultInstantiable()) { logger.log(TreeLogger.ERROR, "Unable to generate class for " + jc.getSimpleSourceName() + " mising default constructor"); } else { SubClassGenerator gen = new SubClassGenerator(); String implentationClassName; implentationClassName = gen.generateSubClass(context, jc); if (implentationClassName == null) { return; } map.put(jc.getQualifiedSourceName(), implentationClassName); } } }
From source file:com.totsp.gwt.freezedry.rebind.CustomFieldSerializerValidator.java
License:Apache License
/** * Returns a list of error messages associated with the custom field * serializer./*from www. j a v a2s .co m*/ * * @param streamReaderClass * {@link com.google.gwt.user.client.rpc.SerializationStreamReader SerializationStreamReader} * @param streamWriterClass * {@link com.google.gwt.user.client.rpc.SerializationStreamWriter SerializationStreamWriter} * @param serializer the class which performs the serialization * @param serializee the class being serialized * @return list of error messages, if any, associated with the custom field * serializer */ public static List /* <String> */ validate(JClassType streamReaderClass, JClassType streamWriterClass, JClassType serializer, JClassType serializee) { List /* <String> */ reasons = new ArrayList/* <String> */(); JMethod deserialize = serializer.findMethod("deserialize", new JType[] { streamReaderClass, serializee }); if (!isValidCustomFieldSerializerMethod(deserialize, JPrimitiveType.VOID)) { reasons.add( MessageFormat.format(NO_DESERIALIZE_METHOD, new String[] { serializer.getQualifiedSourceName(), streamReaderClass.getQualifiedSourceName(), serializee.getQualifiedSourceName() })); } JMethod serialize = serializer.findMethod("serialize", new JType[] { streamWriterClass, serializee }); if (!isValidCustomFieldSerializerMethod(serialize, JPrimitiveType.VOID)) { reasons.add( MessageFormat.format(NO_SERIALIZE_METHOD, new String[] { serializer.getQualifiedSourceName(), streamWriterClass.getQualifiedSourceName(), serializee.getQualifiedSourceName() })); } if (!serializee.isDefaultInstantiable()) { JMethod instantiate = serializer.findMethod("instantiate", new JType[] { streamReaderClass }); if (!isValidCustomFieldSerializerMethod(instantiate, serializee)) { reasons.add(MessageFormat.format(NO_INSTANTIATE_METHOD, new String[] { serializer.getQualifiedSourceName(), serializee.getQualifiedSourceName(), streamReaderClass.getQualifiedSourceName() })); } } return reasons; }
From source file:com.totsp.gwt.freezedry.rebind.SerializableTypeOracleBuilder.java
License:Apache License
/** * Case 1: Type is automatically serializable a) All fields must be * serializable b) All subtypes must be serializable unless we allow subtypes * that are not serializable c) If inherited automatic serialization * superclass must be serializable/* w ww .ja v a2 s . c o m*/ * * Case 2: Type is manually serializable a) CSF must be valid b) All * automatically and manually serializable fields must be serializable c) Any * field that is not manually or automatically serializable is okay * * Case 3: Type is neither automatically or manually serializable a) If type * has at least one automatically or manually serializable subtype then we are * okay. b) If type has no serializable subtypes then: i) context is * automatically serializable => error ii) context is manually serializable => * warning iii) context is neither manually nor automatically serializable => * warning. */ private void checkClassOrInterface(TreeLogger logger, JClassType type, boolean validateSubtypes) { if (type == stringClass) { // we know that it is serializable return; } if (type == typeOracle.getJavaLangObject()) { // Object is never serializable setUnserializableAndLog(logger, inManualSerializationContext() ? TreeLogger.WARN : TreeLogger.ERROR, "In order to produce smaller client-side code, 'Object' is not allowed; consider using a more specific type", type); return; } JClassType superclass = type.getSuperclass(); if (superclass != null) { MetaTypeInfo smti = getMetaTypeInfo(superclass); if (smti.qualifiesForSerialization()) { checkType(logger.branch(TreeLogger.DEBUG, "Analyzing superclass:", null), superclass, false); } else { logger.branch(TreeLogger.DEBUG, "Not analyzing superclass '" + superclass.getParameterizedQualifiedSourceName() + "' because it is not assignable to '" + IsSerializable.class.getName() + "' or '" + Serializable.class.getName() + "' nor does it have a custom field serializer", null); } } MetaTypeInfo mti = getMetaTypeInfo(type); if (mti.qualifiesForManualSerialization()) { List failures = CustomFieldSerializerValidator.validate(streamReaderClass, streamWriterClass, mti.getManualSerializer(), type); if (!failures.isEmpty()) { setUnserializableAndLog(logger, TreeLogger.ERROR, failures, type); return; } mti.setSerializable(true); checkFields(logger, type); } else if (mti.qualifiesForAutoSerialization()) { if (type.isLocalType()) { setUnserializableAndLog(logger, TreeLogger.WARN, "Is a local type, it will be excluded from the set of serializable types", type); return; } if (type.isMemberType() && !type.isStatic()) { setUnserializableAndLog(logger, TreeLogger.WARN, "Is nested but not static, it will be excluded from the set of serializable types", type); return; } if (type.isClass() != null && !type.isDefaultInstantiable()) { setUnserializableAndLog(logger, TreeLogger.ERROR, "Was not default instantiable (it must have a zero-argument public constructor or no constructors at all)", type); return; } if (type.isAbstract() && type.getSubtypes().length == 0) { setUnserializableAndLog(logger, TreeLogger.ERROR, "Is abstract and it has no serializable subtypes", type); return; } getMetaTypeInfo(type).setSerializable(true); checkMethods(logger, type); checkFields(logger, type); } if (validateSubtypes) { int nSubtypes = 0; int nSerializableSubtypes = 0; JClassType[] subtypes = type.getSubtypes(); if (subtypes.length > 0) { TreeLogger localLogger = logger.branch(TreeLogger.DEBUG, "Analyzing subclasses:", null); for (int i = 0; i < subtypes.length; ++i) { JClassType subtype = subtypes[i]; MetaTypeInfo smti = getMetaTypeInfo(subtype); if (smti.qualifiesForSerialization()) { checkType(localLogger, subtype, false); ++nSubtypes; if (smti.isSerializable()) { ++nSerializableSubtypes; } else { localLogger.branch(TreeLogger.DEBUG, subtype.getParameterizedQualifiedSourceName() + " is not serializable", null); if (subtype.isLocalType() || subtype.isMemberType() && !subtype.isStatic()) { --nSubtypes; } } } else { localLogger.branch(TreeLogger.DEBUG, "Not analyzing subclass '" + subtype.getParameterizedQualifiedSourceName() + "' because it is not assignable to '" + IsSerializable.class.getName() + "' or '" + Serializable.class.getName() + "' nor does it have a custom field serializer", null); } } } if (mti.qualifiesForAutoSerialization()) { if (nSerializableSubtypes < nSubtypes) { if (!allowUnserializableSubtypesOfAutoSerializableTypes || nSerializableSubtypes == 0) { setUnserializableAndLog(logger, TreeLogger.ERROR, "Not all subtypes are serializable", type); } } } else if (!mti.qualifiesForManualSerialization() && nSerializableSubtypes == 0) { /* * The type does not qualify for either serialization and it has no * serializable subtypes; this is only an error if we are not in the * context of a custom field serializer */ String message = MessageFormat.format( "Type ''{0}'' is not assignable to IsSerializable or java.io.Serializable, it does not have a custom field serializer and it does not have any serializable subtypes", new String[] { type.getParameterizedQualifiedSourceName() }); setUnserializableAndLog(logger, inManualSerializationContext() ? TreeLogger.WARN : TreeLogger.ERROR, message, type); } } }
From source file:org.fusesource.restygwt.rebind.JsonEncoderDecoderClassCreator.java
License:Apache License
@Override public void generate() throws UnableToCompleteException { locator = new JsonEncoderDecoderInstanceLocator(context, logger); JClassType soruceClazz = source.isClass(); if (soruceClazz == null) { error("Type is not a class"); }/*from w w w . j a va2 s . c o m*/ if (!soruceClazz.isDefaultInstantiable()) { error("No default constuctor"); } Json jsonAnnotation = source.getAnnotation(Json.class); final Style classStyle = jsonAnnotation != null ? jsonAnnotation.style() : Style.DEFAULT; p(); p("public static final " + shortName + " INSTANCE = new " + shortName + "();"); p(); if (null != soruceClazz.isEnum()) { p(); p("public " + JSON_VALUE_CLASS + " encode(" + source.getParameterizedQualifiedSourceName() + " value) {").i(1); { p("if( value==null ) {").i(1); { p("return com.google.gwt.json.client.JSONNull.getInstance();").i(-1); } p("}"); p("return new com.google.gwt.json.client.JSONString(value.toString());"); } i(-1).p("}"); p(); p("public " + source.getName() + " decode(" + JSON_VALUE_CLASS + " value) {").i(1); { p("if( value == null || value.isNull()!=null ) {").i(1); { p("return null;").i(-1); } p("}"); p("com.google.gwt.json.client.JSONString str = value.isString();"); p("if( null == str ) {").i(1); { p("throw new DecodingException(\"Expected a json string (for enum), but was given: \"+value);") .i(-1); } p("}"); p("return Enum.valueOf(" + source.getParameterizedQualifiedSourceName() + ".class, str.stringValue());").i(-1); } p("}"); p(); return; } p("public " + JSON_VALUE_CLASS + " encode(" + source.getParameterizedQualifiedSourceName() + " value) {") .i(1); { p("if( value==null ) {").i(1); { p("return null;"); } i(-1).p("}"); p(JSON_OBJECT_CLASS + " rc = new " + JSON_OBJECT_CLASS + "();"); for (final JField field : getFields(source)) { final String getterName = getGetterName(field); // If can ignore some fields right off the back.. if (getterName == null && (field.isStatic() || field.isFinal() || field.isTransient())) { continue; } branch("Processing field: " + field.getName(), new Branch<Void>() { public Void execute() throws UnableToCompleteException { // TODO: try to get the field with a setter or JSNI if (getterName != null || field.isDefaultAccess() || field.isProtected() || field.isPublic()) { Json jsonAnnotation = field.getAnnotation(Json.class); String name = field.getName(); String jsonName = name; if (jsonAnnotation != null && jsonAnnotation.name().length() > 0) { jsonName = jsonAnnotation.name(); } String fieldExpr = "value." + name; if (getterName != null) { fieldExpr = "value." + getterName + "()"; } Style style = jsonAnnotation != null ? jsonAnnotation.style() : classStyle; String expression = locator.encodeExpression(field.getType(), fieldExpr, style); p("{").i(1); { if (null != field.getType().isEnum()) { p("if(" + fieldExpr + " == null) {").i(1); p("rc.put(" + wrap(name) + ", null);"); i(-1).p("} else {").i(1); } p(JSON_VALUE_CLASS + " v=" + expression + ";"); p("if( v!=null ) {").i(1); { p("rc.put(" + wrap(jsonName) + ", v);"); } i(-1).p("}"); if (null != field.getType().isEnum()) { i(-1).p("}"); } } i(-1).p("}"); } else { error("field must not be private: " + field.getEnclosingType().getQualifiedSourceName() + "." + field.getName()); } return null; } }); } p("return rc;"); } i(-1).p("}"); p(); p("public " + source.getName() + " decode(" + JSON_VALUE_CLASS + " value) {").i(1); { p(JSON_OBJECT_CLASS + " object = toObject(value);"); p("" + source.getParameterizedQualifiedSourceName() + " rc = new " + source.getParameterizedQualifiedSourceName() + "();"); for (final JField field : getFields(source)) { final String setterName = getSetterName(field); // If can ignore some fields right off the back.. if (setterName == null && (field.isStatic() || field.isFinal() || field.isTransient())) { continue; } branch("Processing field: " + field.getName(), new Branch<Void>() { public Void execute() throws UnableToCompleteException { // TODO: try to set the field with a setter or JSNI if (setterName != null || field.isDefaultAccess() || field.isProtected() || field.isPublic()) { Json jsonAnnotation = field.getAnnotation(Json.class); Style style = jsonAnnotation != null ? jsonAnnotation.style() : classStyle; String name = field.getName(); String jsonName = field.getName(); if (jsonAnnotation != null && jsonAnnotation.name().length() > 0) { jsonName = jsonAnnotation.name(); } String objectGetter = "object.get(" + wrap(jsonName) + ")"; String expression = locator.decodeExpression(field.getType(), objectGetter, style); p("if(" + objectGetter + " != null) {").i(1); if (field.getType().isPrimitive() == null) { p("if(" + objectGetter + " instanceof com.google.gwt.json.client.JSONNull) {").i(1); if (setterName != null) { p("rc." + setterName + "(null);"); } else { p("rc." + name + "=null;"); } i(-1).p("} else {").i(1); } if (setterName != null) { p("rc." + setterName + "(" + expression + ");"); } else { p("rc." + name + "=" + expression + ";"); } i(-1).p("}"); if (field.getType().isPrimitive() == null) { i(-1).p("}"); } } else { error("field must not be private."); } return null; } }); } p("return rc;"); } i(-1).p("}"); p(); }
From source file:org.gwtportlets.portlet.rebind.WidgetFactoryHelperCreator.java
License:Open Source License
public WidgetFactoryHelperCreator(TreeLogger logger, TypeOracle typeOracle, SourceWriter sw) throws NotFoundException { this.logger = logger; this.typeOracle = typeOracle; this.sw = sw; widgetFactory = typeOracle.getType(WIDGET_FACTORY); containerFactory = typeOracle.getType(CONTAINER_FACTORY); int c = 0;// ww w . ja v a 2 s.c om for (JClassType t : typeOracle.getTypes()) { if (t.isClass() != null && !t.isAbstract() && t.isDefaultInstantiable() && t.isStatic() && implementsWidgetFactory(t)) { widgetFactoryMap.put(t, c++); } } }