Example usage for com.google.gwt.core.ext.typeinfo JMethod isAbstract

List of usage examples for com.google.gwt.core.ext.typeinfo JMethod isAbstract

Introduction

In this page you can find the example usage for com.google.gwt.core.ext.typeinfo JMethod isAbstract.

Prototype

boolean isAbstract();

Source Link

Usage

From source file:ch.unifr.pai.twice.comm.serverPush.rebind.RemoteEventSerializerGenerator.java

License:Apache License

@Override
public String generate(TreeLogger logger, GeneratorContext context, String typeName)
        throws UnableToCompleteException {
    // Build a new class, that implements a "paintScreen" method
    JClassType classType;//from  w w w  . j a va 2  s  .  c  om

    try {
        classType = context.getTypeOracle().getType(typeName);
        JClassType superClass = classType.getSuperclass();
        JClassType[] generics = superClass.isParameterized().getTypeArgs();
        JClassType eventHandlerClass = generics[0];

        // Here you would retrieve the metadata based on typeName for this
        // Screen
        SourceWriter src = getSourceWriter(classType, context, logger);
        if (src != null) {
            src.println("@Override");
            src.println("public " + String.class.getName() + " getEventType(){");
            src.println("return " + classType.getQualifiedSourceName() + ".class.getName();");
            src.println("}");

            if (superClass.getQualifiedSourceName().equals(RemoteEventWrapper.class.getName())
                    || superClass.getQualifiedSourceName().equals(UndoableRemoteEventWrapper.class.getName())) {
                JClassType eventClass = generics[1];
                src.println("@Override");
                src.println("public void wrap(" + eventClass.getQualifiedSourceName() + " event){");
                for (JMethod method : classType.getMethods()) {
                    String realMethodName = method.getName().replaceAll("_", "().");
                    src.println("setProperty(\"" + method.getName() + "\", " + String.class.getName()
                            + ".valueOf(event." + realMethodName + "()));");
                }
                src.println("}");

                for (JMethod method : classType.getMethods()) {
                    if (method.isAbstract()) {
                        src.println();
                        src.println("@Override");
                        src.println("public " + String.class.getName() + " " + method.getName() + "(){");
                        src.println(
                                JSONValue.class.getName() + " value = json.get(\"" + method.getName() + "\");");
                        src.println(
                                "return value!=null && value.isString()!=null ? value.isString().stringValue() : null;");
                        src.println("}");
                    }
                }

                src.println();
            }

            src.println("@Override");
            src.println("public " + GwtEvent.class.getName() + "." + Type.class.getSimpleName() + "<"
                    + eventHandlerClass.getQualifiedSourceName() + "> getAssociatedType() {");
            src.println("\treturn " + classType.getQualifiedSourceName() + ".TYPE;");
            src.println("}");

            src.println();

            src.println("@Override");
            src.println(
                    "protected void dispatch(" + eventHandlerClass.getQualifiedSourceName() + " handler) {");
            // for (JMethod m : eventHandlerClass.getMethods()) {
            // if(!m.getName().equals("undo")){
            boolean undoable = classType
                    .isAssignableTo(context.getTypeOracle().getType(UndoableRemoteEvent.class.getName()));
            if (undoable) {
                src.println("if(isUndo())");
                src.println("handler.undo(this);");
                src.println("else {");
                src.println("handler.saveState(this);");
            }
            src.println("\t handler.onEvent(this);");
            if (undoable) {
                src.println("}");
            }

            // }
            // }
            src.println("}");
            src.println();
            src.println("@Override");
            src.println("public String serialize(" + TWICESecurityManager.class.getName() + " security) throws "
                    + MessagingException.class.getName() + "{");
            for (JField field : classType.getFields()) {
                if (!field.isStatic() && !field.isTransient()) {
                    src.println("if(" + field.getName() + "!=null){");
                    src.println("setProperty(\"" + field.getName() + "\", String.valueOf(" + field.getName()
                            + "));}");

                }
            }
            src.println("return super.serialize(security);");
            src.println("}");
            src.println();
            src.println("@Override");
            src.println(
                    "public " + RemoteEvent.class.getName() + "<" + eventHandlerClass.getQualifiedSourceName()
                            + "> deserialize(String string, " + TWICESecurityManager.class.getName()
                            + " security) throws " + MessagingException.class.getName() + "{");
            src.println(RemoteEvent.class.getName() + " result = super.deserialize(string, security);");
            for (JField field : classType.getFields()) {
                if (!field.isStatic()) {
                    if (String.class.getName().equals(field.getType().getQualifiedSourceName()))
                        src.println(field.getName() + " = getProperty(\"" + field.getName() + "\");");
                    else {
                        src.println("String " + field.getName() + "Tmp = getProperty(\"" + field.getName()
                                + "\");");
                        src.println(field.getName() + " = " + field.getName() + "Tmp!=null ? "
                                + field.getType().getQualifiedSourceName() + ".valueOf(" + field.getName()
                                + "Tmp) : null;");
                    }
                }
            }
            src.println("return result;");
            src.println("}");
            src.commit(logger);

        }
        return typeName + "Impl";

    } catch (NotFoundException e) {
        e.printStackTrace();
    }
    return null;
}

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 www. j  a  va  2s . 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.vaadin.server.widgetsetutils.ConnectorBundleLoaderFactory.java

License:Apache License

private void writeProxys(SplittingSourceWriter w, ConnectorBundle bundle) {
    Set<JClassType> needsProxySupport = bundle.getNeedsProxySupport();
    for (JClassType type : needsProxySupport) {
        w.print("store.setProxyHandler(");
        writeClassLiteral(w, type);/*from  ww  w. j ava  2 s .c  o m*/
        w.print(", new ");
        w.print(ProxyHandler.class.getCanonicalName());
        w.println("() {");
        w.indent();

        w.println("public Object createProxy(final " + InvokationHandler.class.getName() + " handler) {");
        w.indent();

        w.print("return new ");
        w.print(type.getQualifiedSourceName());
        w.println("() {");
        w.indent();

        JMethod[] methods = type.getOverridableMethods();
        for (JMethod method : methods) {
            if (method.isAbstract()) {
                w.print("public ");
                w.print(method.getReturnType().getQualifiedSourceName());
                w.print(" ");
                w.print(method.getName());
                w.print("(");

                JType[] types = method.getParameterTypes();
                for (int i = 0; i < types.length; i++) {
                    if (i != 0) {
                        w.print(", ");
                    }
                    w.print(types[i].getQualifiedSourceName());
                    w.print(" p");
                    w.print(Integer.toString(i));
                }

                w.println(") {");
                w.indent();

                if (!method.getReturnType().getQualifiedSourceName().equals("void")) {
                    w.print("return ");
                }

                w.print("handler.invoke(this, ");
                w.print(TypeData.class.getCanonicalName());
                w.print(".getType(");
                writeClassLiteral(w, type);
                w.print(").getMethod(\"");
                w.print(escape(method.getName()));
                w.print("\"), new Object [] {");
                for (int i = 0; i < types.length; i++) {
                    w.print("p" + i + ", ");
                }
                w.println("});");

                w.outdent();
                w.println("}");
            }
        }

        w.outdent();
        w.println("};");

        w.outdent();
        w.println("}");

        w.outdent();
        w.println("});");

        w.splitIfNeeded();
    }
}

From source file:org.jsonmaker.gwt.rebind.BeanProperty.java

License:Apache License

private static boolean isCandidateAccessor(JMethod method) {
    return !method.isAnnotationPresent(Transient.class) && method.isPublic() && !method.isAbstract()
            && !method.isStatic();
}

From source file:org.rstudio.core.rebind.command.CommandBundleGenerator.java

License:Open Source License

private JMethod[] getMethods(boolean includeCommands, boolean includeMenus, boolean includeShortcuts)
        throws UnableToCompleteException {
    ArrayList<JMethod> methods = new ArrayList<JMethod>();
    for (JMethod method : bundleType_.getMethods()) {
        if (!method.isAbstract())
            continue;
        validateMethod(method);/*from w ww  . ja v  a  2 s.  co  m*/
        if (!includeCommands && isCommandMethod(method))
            continue;
        if (!includeMenus && isMenuMethod(method))
            continue;
        if (!includeShortcuts && isShortcutsMethod(method))
            continue;
        methods.add(method);
    }
    return methods.toArray(new JMethod[methods.size()]);
}

From source file:org.server.AppGenerator.java

License:Open Source License

protected String writeGetAppSpecificAttribute(String appPackageName, JClassType[] types, JClassType iXholonType,
        TypeOracle oracle) {//from  ww w  .j av  a 2  s  . c o  m
    String xhSimpleName = null;
    StringBuilder sb = new StringBuilder();
    StringBuilder sbt = new StringBuilder();
    for (int i = 0; i < types.length; i++) {
        JClassType type = types[i];
        if ((type.isClass() != null) && (type.isAssignableTo(iXholonType))) {
            //we have determined that the type is an IXholon class (concrete or abstract, not an interface)
            xhSimpleName = type.getName();
            //if (!xhSimpleName.startsWith("App")) {
            // retrieve getter methods that don't return an IXholon
            JMethod[] methods = type.getMethods();
            StringBuilder sbm = new StringBuilder();
            for (int j = 0; j < methods.length; j++) {
                JMethod m = methods[j];
                String mName = m.getName();
                JClassType rType = oracle.findType(m.getReturnType().getQualifiedSourceName());
                // rType = null if oracle is given a primitive type (int etc.)
                if (m.isPublic() && !m.isAbstract() && !m.isStatic() && (m.getParameterTypes().length == 0)
                        && ((rType == null) || !(rType.isAssignableTo(iXholonType)))
                        && (((mName.startsWith("get")) && (mName.length() > 3))
                                || ((mName.startsWith("is")) && (mName.length() > 2)))) {
                    // ex: if ("ADouble".equals(attrName)) {return ((XhTestFsm)node).getADouble();}
                    sbm.append("    if (\"")
                            .append(mName.startsWith("get") ? mName.substring(3) : mName.substring(2))
                            .append("\".equalsIgnoreCase(attrName)) {return ((").append(xhSimpleName)
                            .append(")node).").append(mName).append("();}\n");
                }
            } // end for(j
            if (sbm.length() > 0) {
                sbt.append("  else if (\"").append(appPackageName + "." + xhSimpleName)
                        .append("\".equals(clazz.getName())) {\n")
                        //.append("    System.out.println(\"AppGenerator getAppSpecificAttribute2: \" + clazz.getName());\n")
                        .append(sbm.toString()).append("  }\n");
            }
            //} // end if App
        } // end if
    } // end for(i

    if (sbt.length() > 0) {
        sb.append(
                "public Object getAppSpecificAttribute(IXholon node, Class<IXholon> clazz, String attrName) {\n")
                //.append("  System.out.println(\"AppGenerator getAppSpecificAttribute1: \" + node + \" \" + clazz.getName() + \" \" + attrName);\n")
                .append("  if (node == null) {return null;}\n").append(sbt.toString())
                .append("  Class superclass = clazz.getSuperclass();\n")
                .append("  if ((superclass != null) && superclass.getName().startsWith(\"")
                .append(appPackageName).append("\")) {\n")
                .append("    return getAppSpecificAttribute(node, superclass, attrName);\n").append("  }\n")
                .append("  return super.getAppSpecificAttribute(node, clazz, attrName);\n").append("}\n");
        //System.out.println(sb.toString());
    }
    return sb.toString();
}

From source file:org.server.AppGenerator.java

License:Open Source License

protected String writeSetAppSpecificAttribute(String appPackageName, JClassType[] types, JClassType iXholonType,
        TypeOracle oracle) {/*  w  w  w  . jav a  2 s . c  o  m*/
    String xhSimpleName = null;
    StringBuilder sb = new StringBuilder();
    StringBuilder sbt = new StringBuilder();
    for (int i = 0; i < types.length; i++) {
        JClassType type = types[i];
        if ((type.isClass() != null) && (type.isAssignableTo(iXholonType))) {
            //we have determined that the type is an IXholon class (concrete or abstract, not an interface)
            xhSimpleName = type.getName();
            //if (!xhSimpleName.startsWith("App")) {
            // retrieve getter methods that don't return an IXholon
            JMethod[] methods = type.getMethods();
            StringBuilder sbm = new StringBuilder();
            for (int j = 0; j < methods.length; j++) {
                JMethod m = methods[j];
                String mName = m.getName();
                JType[] paramTypes = m.getParameterTypes();
                if (m.isPublic() && !m.isAbstract() && !m.isStatic() && (paramTypes.length == 1)
                        && (paramTypes[0].isArray() == null) && (mName.startsWith("set"))) {
                    JClassType paramType = paramTypes[0].isClassOrInterface();
                    if ((paramType != null) && (paramType.isAssignableTo(iXholonType))) {
                        // the param is an IXholon, so ignore it
                        continue;
                    }
                    // ex: if ("ADouble".equals(attrName)) {((XhTestFsm)node).setADouble(Double.parseDouble((String)attrVal));return;}
                    sbm.append("      if (\"").append(mName.substring(3))
                            .append("\".equalsIgnoreCase(attrName)) {((").append(xhSimpleName).append(")node).")
                            .append(mName).append("(");
                    String paramTypeStr = paramTypes[0].getQualifiedSourceName();
                    if (paramTypeStr == null) {
                    } else if (paramTypeStr.equals(JPrimitiveType.BOOLEAN.toString())
                            || (paramTypeStr.equals("java.lang.Boolean"))) {
                        sbm.append("Boolean.parseBoolean((String)attrVal));");
                    } else if (paramTypeStr.equals(JPrimitiveType.BYTE.toString())
                            || (paramTypeStr.equals("java.lang.Byte"))) {
                        sbm.append("Byte.parseByte((String)attrVal));");
                    } else if (paramTypeStr.equals(JPrimitiveType.CHAR.toString())
                            || (paramTypeStr.equals("java.lang.Character"))) {
                        sbm.append("((String)attrVal).length() > 0 ? ((String)attrVal).charAt(0) : ' ');");
                    } else if (paramTypeStr.equals(JPrimitiveType.DOUBLE.toString())
                            || (paramTypeStr.equals("java.lang.Double"))) {
                        sbm.append("Double.parseDouble((String)attrVal));");
                    } else if (paramTypeStr.equals(JPrimitiveType.FLOAT.toString())
                            || (paramTypeStr.equals("java.lang.Float"))) {
                        sbm.append("Float.parseFloat((String)attrVal));");
                    } else if (paramTypeStr.equals(JPrimitiveType.INT.toString())
                            || (paramTypeStr.equals("java.lang.Integer"))) {
                        sbm.append("Integer.parseInt((String)attrVal));");
                    } else if (paramTypeStr.equals(JPrimitiveType.LONG.toString())
                            || (paramTypeStr.equals("java.lang.Long"))) {
                        sbm.append("Long.parseLong((String)attrVal));");
                    } else if (paramTypeStr.equals(JPrimitiveType.SHORT.toString())
                            || (paramTypeStr.equals("java.lang.Boolean"))) {
                        sbm.append("Short.parseShort((String)attrVal));");
                    } else if (paramTypeStr.equals("java.lang.String")) {
                        sbm.append("(String)attrVal);");
                    } else if (paramTypeStr.equals("java.lang.Object")) {
                        // it's not clear what to do here
                        sbm.append("attrVal);");
                    } else {
                        // this shouldn't happen
                        sbm.append("null);");
                    }
                    sbm.append("return;}\n");
                }
            } // end for(j
            if (sbm.length() > 0) {
                sbt.append("    else if (\"").append(appPackageName + "." + xhSimpleName)
                        .append("\".equals(clazz.getName())) {\n").append(sbm.toString()).append("    }\n");
            }
            //} // end if APP
        } // end if
    } // end for(i

    if (sbt.length() > 0) {
        sb.append(
                "public void setAppSpecificAttribute(IXholon node, Class<IXholon> clazz, String attrName, Object attrVal) {\n")
                .append("  try {\n").append("    if (node == null) {return;}\n").append(sbt.toString())
                .append("  } catch(java.lang.NumberFormatException e) {return;}\n")
                .append("  Class superclass = clazz.getSuperclass();\n")
                .append("  if (superclass.getName().startsWith(\"").append(appPackageName).append("\")) {\n")
                .append("    setAppSpecificAttribute(node, superclass, attrName, attrVal); return;\n")
                .append("  }\n").append("  super.setAppSpecificAttribute(node, clazz, attrName, attrVal);")
                .append("}\n");
        //System.out.println(sb.toString());
    }
    return sb.toString();
}

From source file:org.server.AppGenerator.java

License:Open Source License

protected String writeGetAppSpecificAttributes(String appPackageName, JClassType[] types,
        JClassType iXholonType, TypeOracle oracle) {
    String xhSimpleName = null;/* w  w  w  .  ja v  a  2 s . c  o  m*/
    StringBuilder sb = new StringBuilder();
    StringBuilder sbt = new StringBuilder();
    for (int i = 0; i < types.length; i++) {
        JClassType type = types[i];
        if ((type.isClass() != null) && (type.isAssignableTo(iXholonType))) {
            //we have determined that the type is an IXholon class (concrete or abstract, not an interface)
            xhSimpleName = type.getName();
            //if (!xhSimpleName.startsWith("App")) {
            // retrieve getter methods that don't return an IXholon
            JMethod[] methods = type.getMethods();
            StringBuilder sbm = new StringBuilder();
            for (int j = 0; j < methods.length; j++) {
                JMethod m = methods[j];
                String mName = m.getName();
                JClassType rType = oracle.findType(m.getReturnType().getQualifiedSourceName());
                // rType = null if oracle is given a primitive type (int etc.)
                if (m.isPublic() && !m.isAbstract() && !m.isStatic() && (m.getParameterTypes().length == 0)
                        && ((rType == null) || !(rType.isAssignableTo(iXholonType)))
                        && ((mName.startsWith("get")) || (mName.startsWith("is")))) {
                    // ex: names.add("ADouble");values.add(((XhTestFsm)node).getADouble());types.add(Double.class);
                    sbm.append("    names.add(\"")
                            .append(mName.startsWith("get") ? mName.substring(3) : mName.substring(2))
                            .append("\");values.add(((").append(xhSimpleName).append(")node).").append(mName)
                            .append("());types.add(");
                    sbm.append(m.getReturnType().getQualifiedSourceName());
                    sbm.append(".class);\n");
                }
            } // end for(j
            if (sbm.length() > 0) {
                sbt.append("  else if (\"").append(appPackageName + "." + xhSimpleName)
                        .append("\".equals(clazz.getName())) {\n").append(sbm.toString()).append("  }\n");
            }
            //} // end if "App"
        } // end if
    } // end for(i

    if (sbt.length() > 0) {
        sb.append(
                "public Object[][] getAppSpecificAttributes(IXholon node, Class<IXholon> clazz, boolean returnAll) {\n")
                .append("  List names = new ArrayList();\n").append("  List values = new ArrayList();\n")
                .append("  List types = new ArrayList();\n")
                .append("  if (node == null) {return new Object[0][0];}\n").append(sbt.toString())
                .append("  if (returnAll) {\n").append("    Class superclass = clazz.getSuperclass();\n")
                .append("    if (superclass.getName().startsWith(\"").append(appPackageName).append("\")) {\n")
                .append("      Object[][] scAttrs = getAppSpecificAttributes(node, superclass, returnAll);\n")
                .append("      if (scAttrs != null) {\n")
                .append("        for (int i = 0; i < scAttrs.length; i++) {\n")
                .append("          names.add(scAttrs[i][0]);values.add(scAttrs[i][1]);types.add(scAttrs[i][2]);\n")
                .append("        }\n").append("      }\n").append("    }\n")

                .append("    else {\n")
                .append("      Object[][] scAttrs = super.getAppSpecificAttributes(node, clazz, returnAll);\n")
                .append("      if (scAttrs != null) {\n")
                .append("        for (int i = 0; i < scAttrs.length; i++) {\n")
                .append("          names.add(scAttrs[i][0]);values.add(scAttrs[i][1]);types.add(scAttrs[i][2]);\n")
                .append("        }\n").append("      }\n").append("    }\n")

                .append("  }\n").append("  Object attributes[][] = new Object[names.size()][3];\n")
                .append("  for (int attrIx = 0; attrIx < names.size(); attrIx++) {\n")
                .append("    attributes[attrIx][0] = names.get(attrIx);\n")
                .append("    attributes[attrIx][1] = values.get(attrIx);\n")
                .append("    attributes[attrIx][2] = types.get(attrIx);\n").append("  }\n")
                .append("  return attributes;\n").append("}\n");
        //System.out.println(sb.toString());
    }
    return sb.toString();
}

From source file:org.server.AppGenerator.java

License:Open Source License

/**
 * Write an isAppSpecificAttribute() method.
 *///from w w w .j  ava  2  s  .  c o  m
protected String writeIsAppSpecificAttribute(String appPackageName, JClassType[] types, JClassType iXholonType,
        TypeOracle oracle) {
    String xhSimpleName = null;
    StringBuilder sb = new StringBuilder();
    StringBuilder sbt = new StringBuilder();
    for (int i = 0; i < types.length; i++) {
        JClassType type = types[i];
        if ((type.isClass() != null) && (type.isAssignableTo(iXholonType))) {
            //we have determined that the type is an IXholon class (concrete or abstract, not an interface)
            xhSimpleName = type.getName();
            //if (!xhSimpleName.startsWith("App")) {
            // retrieve getter methods that don't return an IXholon
            JMethod[] methods = type.getMethods();
            StringBuilder sbm = new StringBuilder();
            for (int j = 0; j < methods.length; j++) {
                JMethod m = methods[j];
                String mName = m.getName();
                JType[] paramTypes = m.getParameterTypes();
                if (m.isPublic() && !m.isAbstract() && !m.isStatic() && (paramTypes.length == 1)
                        && (paramTypes[0].isArray() == null) && (mName.startsWith("set"))) {
                    JClassType paramType = paramTypes[0].isClassOrInterface();
                    if ((paramType != null) && (paramType.isAssignableTo(iXholonType))) {
                        // the param is an IXholon, so ignore it
                        continue;
                    }
                    // ex: if ("ADouble".equals(attrName)) {return true;}
                    sbm.append("    if (\"").append(mName.substring(3))
                            .append("\".equalsIgnoreCase(attrName)) {return true;}\n");
                }
            } // end for(j
            if (sbm.length() > 0) {
                sbt.append("  else if (\"").append(appPackageName + "." + xhSimpleName)
                        .append("\".equals(clazz.getName())) {\n").append(sbm.toString()).append("  }\n");
            }
            //} // end if App
        } // end if
    } // end for(i

    if (sbt.length() > 0) {
        sb.append(
                "public boolean isAppSpecificAttribute(IXholon node, Class<IXholon> clazz, String attrName) {\n")
                .append("  if (node == null) {return false;}\n").append(sbt.toString())
                .append("  Class superclass = clazz.getSuperclass();\n")
                .append("  if ((superclass != null) && superclass.getName().startsWith(\"")
                .append(appPackageName).append("\")) {\n")
                .append("    return isAppSpecificAttribute(node, superclass, attrName);\n").append("  }\n")
                .append("  return false;\n").append("}\n");
        //System.out.println(sb.toString());
    }
    return sb.toString();
}

From source file:org.webinit.gwt.rebind.ObservableObjectGenerator.java

License:Apache License

@Override
public String generate(TreeLogger logger, GeneratorContext context, String typeName)
        throws UnableToCompleteException {
    // retrieve the type oracle
    TypeOracle oracle = context.getTypeOracle();
    assert oracle != null;

    // get the implementation name from the type name
    String implementationName;/*  w  w  w .j a  v a 2  s  .  c o  m*/
    if (typeName.lastIndexOf('.') == -1) {
        implementationName = typeName + implementationSuffix;
    } else {
        implementationName = typeName.substring(typeName.lastIndexOf('.') + 1) + implementationSuffix;
    }

    logger.log(TreeLogger.DEBUG, "Generating for " + typeName);

    // try to get java.lang.Object
    try {
        objectType_ = oracle.getType("java.lang.Object");
    } catch (NotFoundException nfe) {
        logger.log(TreeLogger.ERROR, typeName, nfe);
        return null;
    }

    JClassType sourceClass = oracle.findType(typeName);

    if (sourceClass == null) {
        logger.log(TreeLogger.ERROR, "Unable to find metadata for type '" + typeName + "'", null);
        throw new UnableToCompleteException();
    }

    // if target class is an interface and it has one or more unknown methods,
    // we cannot implement this interface because we cannot implement unknown methods.
    if (sourceClass.isInterface() != null) {
        JClassType targetInterface = oracle
                .findType(org.webinit.gwt.client.Observable.class.getCanonicalName());
        JMethod[] targetMethods = targetInterface.getMethods();
        JMethod[] methods = sourceClass.getMethods();
        int known = 0;
        for (JMethod method : methods) {
            for (JMethod targetMethod : targetMethods) {
                if (method.equals(targetMethod)) {
                    known++;
                }
            }
        }
        if (known < methods.length) {
            logger.log(TreeLogger.ERROR,
                    "Unable to implement/extend " + typeName + ", because it has unknown methods.");
            throw new UnableToCompleteException();
        }

    }
    // target class is a class,
    // if it has unknown abstract methods, we cannot implement it.
    // if it has methods with the same signature as the observable interface, we cannot implement it.
    else {
        JClassType targetInterface = oracle
                .findType(org.webinit.gwt.client.Observable.class.getCanonicalName());
        JMethod[] targetMethods = targetInterface.getMethods();

        JMethod[] methods = sourceClass.getMethods();
        for (JMethod method : methods) {
            for (JMethod targetMethod : targetMethods) {
                if (!method.equals(targetMethod) && method.isAbstract()) {
                    logger.log(TreeLogger.ERROR,
                            "Unable to implement/extend " + typeName + ", because it has unknown method");
                    throw new UnableToCompleteException();
                }
                if (method.getReadableDeclaration().equals(targetMethod.getReadableDeclaration())
                        && !method.isAbstract()) {
                    logger.log(TreeLogger.ERROR, "Source class contains a conflict method " + method.getName());
                    throw new UnableToCompleteException();
                }
            }
        }
    }

    // checking done, get the source writers

    ClassSourceFileComposerFactory oocf = new ClassSourceFileComposerFactory(packageName, implementationName);

    // if the source class is a Class, adds it as a superclass
    if (sourceClass.isClass() != null) {
        oocf.setSuperclass(typeName);
    }
    if (sourceClass.isInterface() != null) {
        oocf.addImplementedInterface(sourceClass.getQualifiedSourceName());
        JClassType[] implementedInterfaces = sourceClass.getImplementedInterfaces();
        for (JClassType intf : implementedInterfaces) {
            oocf.addImplementedInterface(intf.getQualifiedSourceName());
        }
    }

    // add imports
    oocf.addImport("java.util.Map");
    oocf.addImport("java.util.Set");
    oocf.addImport("java.util.List");
    oocf.addImport("java.util.HashMap");
    oocf.addImport("java.util.HashSet");
    oocf.addImport("java.util.ArrayList");

    PrintWriter printWriter = context.tryCreate(logger, packageName, implementationName);
    SourceWriter sourceWriter = oocf.createSourceWriter(printWriter);

    writeObservableObjectClass(logger, sourceWriter);
    context.commit(logger, printWriter);

    return packageName + "." + implementationName;
}