Example usage for com.google.gwt.user.rebind SourceWriter print

List of usage examples for com.google.gwt.user.rebind SourceWriter print

Introduction

In this page you can find the example usage for com.google.gwt.user.rebind SourceWriter print.

Prototype

void print(String s);

Source Link

Usage

From source file:com.googlecode.gwtx.rebind.PropertyDescriptorsGenerator.java

License:Apache License

/**
 * @param logger/*from w ww.j a  v  a  2s.  c om*/
 * @param w
 * @param typeOracle
 */
private void write(TreeLogger logger, SourceWriter w, JClassType type) {
    Collection<Property> properties = lookupJavaBeanPropertyAccessors(logger, type);

    w.println("// automatically register BeanInfos for bean properties");
    w.println("static {");
    w.indent();
    w.println("GwtBeanInfo beanInfo = new GwtBeanInfo();");
    for (Property property : properties) {
        w.println("try {");
        w.indent();
        w.print("beanInfo.addPropertyDescriptor( ");
        writePropertyDescriptor(w, type, property.name, property.propertyType, property.getter,
                property.setter);
        w.println(" );");
        w.outdent();
        w.println("} catch (Exception e) {}");
    }
    w.println("GwtIntrospector.setBeanInfo( " + type.getName() + ".class, beanInfo );");
    w.outdent();
    w.println("}");
}

From source file:com.googlecode.gwtx.rebind.PropertyDescriptorsGenerator.java

License:Apache License

/**
 * @param sw/*  ww w  . j  av  a2  s .  c  o  m*/
 * @param type
 * @param propertyName
 * @param getter
 * @param setter
 */
private void writePropertyDescriptor(SourceWriter sw, JClassType type, String propertyName, String propertyType,
        JMethod getter, JMethod setter) {
    sw.print("new PropertyDescriptor( \"" + propertyName + "\", " + propertyType + ".class, ");
    if (getter != null) {
        sw.println("new Method() ");
        sw.println("{");
        sw.indent();
        sw.println("public Object invoke( Object bean, Object... args )");
        sw.println("{");
        sw.indent();
        sw.println("return ( (" + type.getName() + ") bean)." + getter.getName() + "();");
        sw.outdent();
        sw.println("}");
        sw.outdent();
        sw.print("}, ");
    } else {
        sw.print("null, ");
    }
    if (setter != null) {
        sw.println("new Method() ");
        sw.println("{");
        sw.indent();
        sw.println("public Object invoke( Object bean, Object... args )");
        sw.println("{");
        sw.indent();
        JType argType = setter.getParameters()[0].getType().getErasedType();
        String argTypeName;
        if (argType.isPrimitive() != null) {
            argTypeName = argType.isPrimitive().getQualifiedBoxedSourceName();
        } else {
            argTypeName = argType.getQualifiedSourceName();
        }
        sw.println(
                "( (" + type.getName() + ") bean)." + setter.getName() + "( (" + argTypeName + ") args[0] );");
        sw.println("return null;");
        sw.outdent();
        sw.println("}");
        sw.outdent();
        sw.print("} )");
    } else {
        sw.print("null )");
    }
}

From source file:com.googlecode.mgwt.css.rebind.StyleSheetUrlHolderGenerator.java

License:Apache License

@Override
public String generate(TreeLogger logger, GeneratorContext context, String typeName)
        throws UnableToCompleteException {
    // get the property oracle
    PropertyOracle propertyOracle = context.getPropertyOracle();
    String enablePropertyValue = getSingleValue(propertyOracle, KEY_ENABLED, logger);

    if (!"true".equals(enablePropertyValue)) {
        return StyleSheetUrlHolderNoopImpl.class.getName();
    }//  w w  w.j  a v  a2 s. com

    List<String> urls = getValues(propertyOracle, KEY_URLS, logger);

    int interval = Integer.parseInt(getSingleValue(propertyOracle, KEY_INTERVAL, logger));

    JClassType classType = null;

    try {
        // get the type we are looking for
        classType = context.getTypeOracle().getType(typeName);
    } catch (NotFoundException e) {
        // if we can`t get it die
        logger.log(TreeLogger.ERROR, "can not find type: '" + typeName + "'", e);
        throw new UnableToCompleteException();
    }

    // get the package name
    String packageName = classType.getPackage().getName();
    // build name for implementation class
    String simpleName = classType.getSimpleSourceName() + "_generated";
    // combine package name and simple name to full qualified
    String fullName = packageName + "." + simpleName;

    PrintWriter printWriter = context.tryCreate(logger, packageName, simpleName);

    if (printWriter == null) {
        return fullName;
    }

    ClassSourceFileComposerFactory composer = new ClassSourceFileComposerFactory(packageName, simpleName);
    composer.setSuperclass(StyleSheetUrlHolderDefaultImpl.class.getName());
    composer.addImport(StyleSheetUrlHolderDefaultImpl.class.getName());

    // start writing the implementation
    SourceWriter writer = composer.createSourceWriter(context, printWriter);

    writer.println("public " + simpleName + "() {");
    writer.print("super(");

    boolean first = true;
    for (String url : urls) {
        if (first) {
            first = false;
        } else {
            writer.print(",");
        }
        writer.print("\"" + url + "\"");
    }
    writer.print(");\n");

    writer.println("}");

    writer.println("public int interval() {");
    writer.println("return " + interval + ";");
    writer.println("}");
    writer.commit(logger);

    return fullName;
}

From source file:com.guit.rebind.appcontroller.AppControllerGenerator.java

License:Apache License

@Override
protected void generate(SourceWriter writer) throws UnableToCompleteException {
    ginInjectorGenerator.generate(logger, context, null);

    List<String> appControllers = getConfigurationProperty("app.controller").getValues();

    writer.println("public void inject() {");
    writer.indent();// www .  j  ava2  s  . c  om

    for (String c : appControllers) {
        writer.println(GinOracle.getInjectedInstance(c) + ";");
    }

    // Force eager instantiation of place manager
    writer.println("getPlaceManager();");

    // Google analytics setup
    String googleAnalyticsUa = getConfigurationProperty("app.google.analytics").getValues().get(0);
    if (!googleAnalyticsUa.isEmpty()) {
        writer.println(GinOracle.getInjectedInstance(GoogleAnalyticsTracker.class.getCanonicalName())
                + ".setAccount(\"" + googleAnalyticsUa + "\");");
    }

    // Fire current history state on load?
    if (getConfigurationProperty("app.fire.current.history.state").getValues().get(0).equals("true")) {
        writer.println(History.class.getCanonicalName() + ".fireCurrentHistoryState();");
    }

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

    writer.println("public " + PlaceManager.class.getCanonicalName() + " getPlaceManager() {");
    writer.indent();
    writer.print("return " + GinOracle.getInjectedInstance(PlaceManager.class.getCanonicalName()) + ";");
    writer.outdent();
    writer.println("}");

    writer.println("public " + CommandService.class.getCanonicalName() + " getCommandService() {");
    writer.indent();
    writer.print("return " + GinOracle.getInjectedInstance(CommandService.class.getCanonicalName()) + ";");
    writer.outdent();
    writer.println("}");

    writer.println("public " + EventBus.class.getCanonicalName() + " getEventBus() {");
    writer.indent();
    writer.println("return " + GinOracle.getInjectedInstance(EventBus.class.getCanonicalName()) + ";");
    writer.outdent();
    writer.println("}");
}

From source file:com.guit.rebind.binder.GuitBinderGenerator.java

License:Apache License

private void printViewBindingMethods(SourceWriter writer, JClassType presenterType, String viewTypeName,
        HashMap<String, JType> validBindingFieldsTypes) throws UnableToCompleteException {

    Set<String> validBindingFields = validBindingFieldsTypes.keySet();

    JPackage contextEventsPackage = getPackage(presenterType.getPackage().getName() + ".event");

    ArrayList<JMethod> methods = new ArrayList<JMethod>();
    findAllMethods(presenterType, methods);

    for (JMethod m : methods) {
        String name = m.getName();
        if (m.isAnnotationPresent(ViewHandler.class)) {
            validateHandler(m, name, presenterType.getQualifiedSourceName());

            String eventName;//from   www .  j av a2  s .  c  o m
            ViewHandler viewHandlerAnnotation = m.getAnnotation(ViewHandler.class);
            JClassType eventType = getType(viewHandlerAnnotation.event().getCanonicalName());

            boolean fieldsAreElements = false;
            Set<String> bindingFields = null;
            boolean addHandlerToView = false;
            if (viewHandlerAnnotation.fields().length == 0) {
                if (name.startsWith("$")) {
                    // Direct view binding
                    eventName = name.substring(1);

                    addHandlerToView = true;
                } else {
                    // View fields binding
                    String[] nameParts = name.split("[$]");

                    // Check the name format
                    if (nameParts.length < 2) {
                        error("The method %s on the class %s have a bad binding format. It should be: "
                                + "'{viewField}${eventName}' or for binding multiple fields: '{viewField1}${viewField2}${eventName}'",
                                name, presenterType.getQualifiedSourceName());
                    }

                    // Check that the binding fields are valid
                    bindingFields = new HashSet<String>();
                    for (int n = 0; n < nameParts.length - 1; n++) {
                        if (!validBindingFields.contains(nameParts[n])) {
                            error("The field %s on the class %s is not a valid binding field. It must be public or protected and not static",
                                    nameParts[n], presenterType);
                        }
                        bindingFields.add(nameParts[n]);
                    }

                    eventName = nameParts[nameParts.length - 1]; // last
                    // token
                }

                // Check the event type and name convention
                if (eventType.equals(gwtEventType)) {
                    eventType = getEventByName(eventName, contextEventsPackage);
                    if (eventType == null) {
                        error("There is no context, dom or shared event with the name '%s'. Binding method: '%s' in class: '%s'",
                                eventName, name, presenterType.getQualifiedSourceName());
                    }
                } else {
                    // Check that the method name correspond to the event
                    // type
                    String eventNameToEventClassName = eventNameToEventClassName(eventName);
                    if (!eventNameToEventClassName.equals(eventType.getSimpleSourceName())) {
                        error("The method '%s' in the class '%s' have a typo in the name. The last token should be : ..$%s() {.. ",
                                name, presenterType.getQualifiedSourceName(), eventName);
                    }
                }
            } else {
                String[] fields = viewHandlerAnnotation.fields();
                bindingFields = new HashSet<String>();
                for (String f : fields) {
                    if (f.isEmpty()) {
                        addHandlerToView = true;
                    } else {
                        if (!validBindingFields.contains(f)) {
                            error("The field %s on the class %s is not a valid binding field. It must be public or protected and not static",
                                    f, presenterType);
                        }
                        bindingFields.add(f);
                    }
                }

                if (eventType.equals(gwtEventType)) {
                    error("When using ViewFields you must specify the event class in the Handler annotation. Found: %s.%s",
                            presenterType.getQualifiedSourceName(), name);
                }

                eventName = eventClassNameToEventName(eventType.getSimpleSourceName());
            }

            // If any field is an element all of them should be otherwise none
            // of them
            int widgetCount = 0;
            JClassType widgetJType = getType(Widget.class.getCanonicalName());
            JClassType isWidgetJType = getType(IsWidget.class.getCanonicalName());
            for (String f : bindingFields) {
                JClassType classOrInterface = validBindingFieldsTypes.get(f).isClassOrInterface();
                if (classOrInterface.isAssignableTo(widgetJType)
                        || classOrInterface.isAssignableTo(isWidgetJType)) {
                    widgetCount++;
                }
            }

            if (widgetCount != bindingFields.size() && widgetCount != 0) {
                error("Not all fields on the class %s.%s are either all elements or all widgets. You cannot bind elements and widgets on the same handler",
                        presenterType, name);
            }
            fieldsAreElements = widgetCount == 0;

            /**
             * Find parameters bindings. The binding can be with the event(cannot have anidation of
             * getters):'getter'->'getGetter()' or with the view:'$getter'->'view.getGetter()' or with a
             * view field '{viewField$getter}'->'view.viewField.getGetter();', this last two ones will
             * support anidation: '{viewField$getter$another}'->'view.viewField.getGetter().getAnother (
             * ) ; '
             **/
            StringBuilder bindingParameters = new StringBuilder();
            JParameter[] parameters = m.getParameters();
            ArrayList<String> parameterStrings = new ArrayList<String>();
            for (JParameter p : parameters) {
                String parameter = p.getName();
                JType parameterType = p.getType();
                if (bindingParameters.length() > 0) {
                    bindingParameters.append(", ");
                }

                int initlenght = bindingParameters.length();

                // Implicit cast
                bindingParameters.append(
                        "(" + parameterType.getErasedType().getParameterizedQualifiedSourceName() + ")");

                String getter = "get";

                // Check if it is a boolean then the getter is 'is' not
                // 'get'
                JPrimitiveType parameterTypeIsPrimitive = parameterType.isPrimitive();
                if (parameterTypeIsPrimitive != null
                        && parameterTypeIsPrimitive.equals(JPrimitiveType.BOOLEAN)) {
                    getter = "is";
                }

                if (p.getName().equals("event")) {
                    bindingParameters.append("event");
                } else if (p.isAnnotationPresent(Attribute.class)) {
                    // Only valid for domEvents
                    if (!eventType.isAssignableTo(hasNativeEventType)) {
                        error("Attributes binding are only valid for DomEvents. Found: %s.%s in parameter: %s",
                                presenterType.getQualifiedSourceName(), name, parameter);
                    }

                    String parameterTypeQualifiedSourceName = parameterType.getQualifiedSourceName();
                    boolean isString = parameterTypeQualifiedSourceName.equals(STRINGCANONICALNAME);
                    if (!isString) {
                        bindingParameters.append(parameterTypeQualifiedSourceName + ".valueOf(");
                    }
                    bindingParameters.append("((" + Element.class.getCanonicalName()
                            + ")event.getNativeEvent().getEventTarget().cast()).getAttribute(\"" + parameter
                            + "\")");
                    if (!isString) {
                        bindingParameters.append(")");
                    }
                } else if (parameter.indexOf("$") == -1) {
                    // Event binding
                    bindingParameters.append("event.");
                    bindingParameters.append(getter);
                    bindingParameters.append(capitalize(parameter));
                    bindingParameters.append("()");
                } else {
                    // Event binding nested binding
                    String[] parameterParts = parameter.split("[$]");

                    bindingParameters.append("event");
                    for (int n = 0; n < parameterParts.length - 1; n++) {
                        bindingParameters.append(".get");
                        bindingParameters.append(capitalize(parameterParts[n]));
                        bindingParameters.append("()");
                    }

                    bindingParameters.append(".");
                    bindingParameters.append(getter);
                    bindingParameters.append(capitalize(parameterParts[parameterParts.length - 1]));
                    bindingParameters.append("()");
                }

                parameterStrings.add(bindingParameters.substring(initlenght, bindingParameters.length()));
            }

            // Get event handler name
            JClassType handlerType = getHandlerForEvent(eventType);
            if (handlerType == null) {
                error("Parameter '%s' is not an event (subclass of GwtEvent).", eventType.getName());
            }

            // Retrieves the single method (usually 'onSomething') related
            // to all
            // handlers. Ex: onClick in ClickHandler, onBlur in BlurHandler
            // ...
            JMethod[] handlerMethods = handlerType.getMethods();
            if (handlerMethods.length != 1) {
                error("'%s' has more than one method defined.", handlerType.getName());
            }

            // 'onSomething' method
            JMethod handlerOnMethod = handlerMethods[0];

            String methodName = name;
            String handlerTypeName = handlerType.getQualifiedSourceName();

            GwtPresenter presenterAnnotation = presenterType.getAnnotation(GwtPresenter.class);
            boolean isElemental = presenterAnnotation != null && presenterAnnotation.elemental();

            // Write handler
            SourceWriter eventHandlerWriter = new StringSourceWriter();
            if (!fieldsAreElements) {
                eventHandlerWriter.println("new " + handlerTypeName + "() {");
                eventHandlerWriter.indent();
                eventHandlerWriter.println("public void " + handlerOnMethod.getName() + "(final "
                        + eventType.getQualifiedSourceName() + " event) {");
                eventHandlerWriter.indent();
            } else if (isElemental) {
                eventHandlerWriter.println("new elemental.events.EventListener() {");
                eventHandlerWriter.println("  @Override");
                eventHandlerWriter.println("  public void handleEvent(elemental.events.Event event) {");
            } else {
                eventHandlerWriter
                        .println("new " + com.guit.client.dom.EventHandler.class.getCanonicalName() + "() {");
                eventHandlerWriter.indent();
                eventHandlerWriter
                        .println("public void onEvent(" + Event.class.getCanonicalName() + " event_) {");
                eventHandlerWriter.println("  " + EventImpl.class.getCanonicalName() + " event = ("
                        + EventImpl.class.getCanonicalName() + ") event_;");
                eventHandlerWriter.indent();
            }

            String bindingParametersString = bindingParameters.toString();

            // Process contributors
            BinderContextImpl binderContext = processMethodContributors(presenterType, null, null, viewTypeName,
                    m, eventType, parameterStrings.toArray(new String[parameterStrings.size()]));

            StringSourceWriter handlerWriter = new StringSourceWriter();

            handlerWriter
                    .println("if (" + LogConfiguration.class.getCanonicalName() + ".loggingIsEnabled()) {");
            handlerWriter.println(Logger.class.getCanonicalName() + ".getLogger(\"Binder\").info(\""
                    + binderContext.getLog() + "\");");
            handlerWriter.println("}");

            handlerWriter.print("presenter." + methodName + "(");
            handlerWriter.print(bindingParametersString);
            handlerWriter.println(");");

            eventHandlerWriter.println(binderContext.build(handlerWriter));

            eventHandlerWriter.outdent();
            eventHandlerWriter.println("}");
            eventHandlerWriter.outdent();
            eventHandlerWriter.print("}");

            if (fieldsAreElements) {
                if (bindingFields != null) {
                    writer.print("final "
                            + (isElemental ? EventListener.class.getCanonicalName()
                                    : com.guit.client.dom.EventHandler.class.getCanonicalName())
                            + " " + methodName + "$" + eventName + " =");
                    writer.print(eventHandlerWriter.toString());
                    writer.println(";");

                    for (String f : bindingFields) {
                        String eventNameLower = eventName.toLowerCase();
                        boolean isTouchStart = eventNameLower.equals("touchstart");
                        boolean isTouchEnd = eventNameLower.equals("touchend");
                        if (isTouchStart || isTouchEnd) {
                            writer.println("if (com.google.gwt.event.dom.client.TouchEvent.isSupported()) {");
                        }
                        if (isElemental) {
                            writer.println("presenter." + f + ".setOn" + eventNameLower + "(" + methodName + "$"
                                    + eventName + ");");
                        } else {
                            writer.println("bindings.add(new " + ElementImpl.class.getCanonicalName() + "(view."
                                    + f + ")." + eventNameLower + "(" + methodName + "$" + eventName + "));");
                        }
                        if (isTouchStart || isTouchEnd) {
                            writer.println("} else {");

                            if (isElemental) {
                                writer.println("presenter." + f + ".setOnmouse" + (isTouchStart ? "down" : "up")
                                        + "(" + methodName + "$" + eventName + ");");
                            } else {
                                writer.println("bindings.add(new " + ElementImpl.class.getCanonicalName()
                                        + "(view." + f + ")." + (isTouchStart ? "mousedown" : "mouseup") + "("
                                        + methodName + "$" + eventName + "));");
                            }

                            writer.print("}");
                        }
                    }
                }
            } else if (viewHandlerAnnotation.force()) {
                String addMethodName = "addDomHandler";
                String eventTypeGetter = eventType.getQualifiedSourceName() + ".";
                JField typeField = eventType.getField("TYPE");
                if (typeField != null && typeField.isStatic() && typeField.isPublic()) {
                    eventTypeGetter += "TYPE";
                } else {
                    eventTypeGetter += "getType()";
                }
                if (bindingFields != null) {
                    writer.print("final " + handlerTypeName + " " + methodName + " =");
                    writer.print(eventHandlerWriter.toString());
                    writer.println(";");

                    for (String f : bindingFields) {
                        writer.println("bindings.add(view." + f + "." + addMethodName + "(" + methodName + ", "
                                + eventTypeGetter + "));");
                    }
                }

                if (addHandlerToView) {
                    writer.print("bindings.add(view." + addMethodName + "(" + eventHandlerWriter.toString()
                            + ", " + eventTypeGetter + "));");
                }
            } else {
                String addMethodName = "add" + eventName.substring(0, 1).toUpperCase() + eventName.substring(1)
                        + "Handler";
                if (bindingFields != null) {
                    writer.print("final " + handlerTypeName + " " + methodName + " =");
                    writer.print(eventHandlerWriter.toString());
                    writer.println(";");

                    for (String f : bindingFields) {

                        // Small patch for touch events
                        if (addMethodName.equals("addTouchStartHandler") && parameters.length == 0) {
                            writer.println("if (!com.google.gwt.event.dom.client.TouchEvent.isSupported()) {");
                            writer.println("bindings.add(view." + f + ".addMouseDownHandler(new "
                                    + MouseDownHandler.class.getCanonicalName() + "(){public void onMouseDown("
                                    + MouseDownEvent.class.getCanonicalName() + " event){presenter."
                                    + methodName + "();} }" + "));");
                            writer.println("}");
                        }

                        if (addMethodName.equals("addTouchEndHandler") && parameters.length == 0) {
                            writer.println("if (!com.google.gwt.event.dom.client.TouchEvent.isSupported()) {");
                            writer.println("bindings.add(view." + f + ".addMouseUpHandler(new "
                                    + MouseUpHandler.class.getCanonicalName() + "(){public void onMouseUp("
                                    + MouseUpEvent.class.getCanonicalName() + " event){presenter." + methodName
                                    + "();} }" + "));");
                            writer.println("}");
                        }
                        writer.println(
                                "bindings.add(view." + f + "." + addMethodName + "(" + methodName + "));");
                    }
                }

                if (addHandlerToView) {
                    writer.print(
                            "bindings.add(view." + addMethodName + "(" + eventHandlerWriter.toString() + "));");
                }
            }
        } else {
            for (Annotation a : m.getAnnotations()) {
                Class<? extends Annotation> annotationType = a.annotationType();
                if (annotationType.isAnnotationPresent(Plugin.class)) {
                    String[] nameParts = name.split("[$]");

                    // Check that the binding fields are valid
                    StringBuilder fields = new StringBuilder();
                    for (int n = 0; n < nameParts.length - 1; n++) {
                        if (!validBindingFields.contains(nameParts[n])) {
                            error("The field %s on the class %s is not a valid binding field. It must be public or protected and not static",
                                    nameParts[n], presenterType);
                        }
                        if (fields.length() > 0) {
                            fields.append(",");
                        }
                        fields.append("view." + nameParts[n]);
                    }

                    Class<?> handler = annotationType.getAnnotation(Plugin.class).value();
                    writer.println("new " + handler.getCanonicalName()
                            + "().install(new com.google.gwt.user.client.Command() {");
                    writer.println("@Override");
                    writer.println("public void execute() {");
                    writer.println("  presenter." + m.getName() + "();");
                    writer.println("}");
                    writer.println("}, new Object[]{");
                    writer.println(fields.toString() + "});");
                }
            }
        }
    }
}

From source file:com.guit.rebind.binder.GuitBinderGenerator.java

License:Apache License

private void printViewFieldBindings(SourceWriter writer, JClassType presenterType, String viewTypeName,
        HashMap<String, JType> validBindingFieldsType, ArrayList<JField> fields)
        throws UnableToCompleteException {

    Set<String> validBindingFields = validBindingFieldsType.keySet();

    JClassType viewAccesorType = getType(ViewAccesor.class.getCanonicalName());

    ArrayList<JField> superFields = new ArrayList<JField>();
    collectAllFields(presenterType.getSuperclass(), superFields);

    JClassType elementDomType = getType(com.guit.client.dom.Element.class.getCanonicalName());

    for (JField f : fields) {
        if (f.isAnnotationPresent(ViewField.class)) {
            // Check for repetided fields
            if (f.getType().isClassOrInterface().isAssignableTo(elementDomType)) {
                if (superFields.contains(f)) {

                }/*  w w w. j  av a2s.com*/
            }

            String name = f.getName();
            ViewField viewField = f.getAnnotation(ViewField.class);
            String viewName = viewField.name();
            if (viewName.isEmpty()) {
                viewName = name;
            }
            if (!validBindingFields.contains(viewName)) {
                error("The field '%s' do not exists. Found: %s.%s", viewName,
                        presenterType.getQualifiedSourceName(), name);
            }

            JClassType type = f.getType().isClassOrInterface();
            // if (type.isInterface() == null && !viewField.provided()) {
            // error("A ViewField must be an interface. Found: %s.%s", presenterType
            // .getQualifiedSourceName(), name);
            // }

            if (type.isAssignableTo(viewAccesorType)) {
                writer.println("{");
                writer.indent();
                if (!type.isAnnotationPresent(Implementation.class)) {
                    writer.println(type.getQualifiedSourceName() + " accesor = "
                            + GinOracle.getProvidedInstance(type.getQualifiedSourceName()) + ".get();");
                } else {

                    JClassType implementation = getType(
                            type.getAnnotation(Implementation.class).value().getCanonicalName());

                    // If they are parameterized look for the base type
                    JParameterizedType implementationParameterized = implementation.isParameterized();
                    if (implementationParameterized != null) {
                        implementation = implementationParameterized.getBaseType();
                    }
                    JParameterizedType typeParameterized = type.isParameterized();
                    if (typeParameterized != null) {
                        type = typeParameterized.getBaseType();
                    }

                    // Verify that they are assignable
                    if (!implementation.isAssignableTo(type)) {
                        error("An implementation of a ViewAccesor must implement the ViewAccesor interface. Found: %s",
                                implementation.getQualifiedSourceName());
                    }
                    writer.println(type.getQualifiedSourceName() + " accesor = new "
                            + implementation.getQualifiedSourceName() + "();");
                }

                writer.println("accesor.setTarget(view." + viewName + ");");
                writer.println("presenter." + name + " = accesor;");
                writer.outdent();
                writer.print("}");
                writer.println();
            } else if (type == null
                    || type.isAssignableFrom(validBindingFieldsType.get(viewName).isClassOrInterface())
                    || type.getQualifiedSourceName().startsWith("elemental.")) {
                String qualifiedSourceName = f.getType().getQualifiedSourceName();
                writer.println("presenter." + name + " = (" + qualifiedSourceName + ") view." + viewName + ";");
                writer.println();
            } else {
                // Interface emulation (without exceptions)
                writer.println(
                        "presenter." + name + " = new " + type.getParameterizedQualifiedSourceName() + "() {");
                writer.indent();

                ArrayList<JMethod> methods = new ArrayList<JMethod>();
                findAllMethods(type, methods);
                for (JMethod m : methods) {
                    writer.print(m.getReadableDeclaration(false, true, true, true, true));
                    writer.println("{");
                    writer.indent();

                    // Find the parameters
                    StringBuilder callParameters = new StringBuilder();
                    for (JParameter p : m.getParameters()) {
                        if (callParameters.length() > 0) {
                            callParameters.append(", ");
                        }
                        if (p.isAnnotationPresent(ImplicitCast.class)) {
                            callParameters.append("(");
                            callParameters
                                    .append(p.getAnnotation(ImplicitCast.class).value().getCanonicalName());
                            callParameters.append(") ");
                        }
                        callParameters.append(p.getName());
                    }

                    JType returnType = m.getReturnType();
                    if (!returnType.equals(JPrimitiveType.VOID)) {
                        writer.print("return ");

                        // Implicit cast
                        writer.print("(" + returnType.getParameterizedQualifiedSourceName() + ")");
                    }

                    writer.indent();
                    writer.println(createdClassName + ".this.view." + viewName + "." + m.getName() + "("
                            + callParameters.toString() + ");");
                    writer.outdent();

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

                // Get .equals working on emulated interfaces for
                // event.getSource() comparations
                writer.println("@Override");
                writer.println("public boolean equals(Object obj) {");
                writer.indent();
                writer.println("return view." + viewName + ".equals(obj);");
                writer.outdent();
                writer.println("}");
                writer.println();

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

From source file:com.guit.rebind.jsorm.JsonSerializerUtil.java

License:Apache License

public static String generate(TreeLogger logger, GeneratorContext context, JClassType pojoType)
        throws UnableToCompleteException {
    JsonSerializerUtil.logger = logger;/*from ww  w .ja va2  s .c o m*/

    // We cannot serialize java.lang.Object
    String pojoQualifiedName = pojoType.getQualifiedSourceName();
    if (pojoQualifiedName.equals(Object.class.getCanonicalName())) {
        error("You cannot serialize Object... we either");
    }

    if (exceptions == null) {
        exceptions = new HashMap<String, String>();
        try {
            List<String> ormExceptions = context.getPropertyOracle()
                    .getConfigurationProperty("json.orm.exception").getValues();
            for (String e : ormExceptions) {
                String[] parts = e.split(" ");
                if (parts.length != 2) {
                    error("Bad json orm exception format. i.e 'java.util.List java.util.ArrayList<%s>. Found: %s'",
                            e);
                }
                exceptions.put(parts[0], parts[1]);
            }
        } catch (BadPropertyValueException e) {
            throw new IllegalStateException(e);
        }
    }

    String parameterizedQualifiedSourceName = pojoType.getParameterizedQualifiedSourceName();
    String typeName = parameterizedQualifiedSourceName;

    // Basic types
    if (typeName.equals(Void.class.getCanonicalName())) {
        return VoidSerializer.class.getCanonicalName();
    } else if (typeName.equals(String.class.getCanonicalName())) {
        return StringSerializer.class.getCanonicalName();
    } else if (typeName.equals(Integer.class.getCanonicalName())) {
        return IntegerSerializer.class.getCanonicalName();
    } else if (typeName.equals(Long.class.getCanonicalName())) {
        return LongSerializer.class.getCanonicalName();
    } else if (typeName.equals(Double.class.getCanonicalName())) {
        return DoubleSerializer.class.getCanonicalName();
    } else if (typeName.equals(Float.class.getCanonicalName())) {
        return FloatSerializer.class.getCanonicalName();
    } else if (typeName.equals(Date.class.getCanonicalName())) {
        return DateSerializer.class.getCanonicalName();
    } else if (typeName.equals(Boolean.class.getCanonicalName())) {
        return BooleanSerializer.class.getCanonicalName();
    }

    // Build name avoiding generics collitions
    StringBuilder implName = new StringBuilder();
    makeImplName(pojoType, implName);
    implName.append("_GuitJsonSerializer");

    String packageName = pojoType.getPackage().getName();
    if (packageName.startsWith("java.")) {
        packageName = "com.guit.java." + packageName.substring(5);
    }

    String implNameString = implName.toString();

    if (getClass(packageName, implNameString)) {
        return packageName + "." + implNameString;
    }

    ClassSourceFileComposerFactory composer = new ClassSourceFileComposerFactory(packageName, implNameString);
    composer.addImplementedInterface(TypeJsonSerializer.class.getCanonicalName() + "<" + typeName + ">");
    PrintWriter printWriter = context.tryCreate(logger, packageName, implNameString);
    String createdName = composer.getCreatedClassName();
    if (printWriter != null) {
        SourceWriter writer = composer.createSourceWriter(context, printWriter);

        JType iterableParameterType = null;
        JPrimitiveType iterableParameterPrimitiveType = null;

        // Iterable
        JGenericType iterableType = context.getTypeOracle().findType(Iterable.class.getCanonicalName())
                .isGenericType();
        boolean isIterable = false;
        if (iterableType.isAssignableFrom(pojoType)) {
            isIterable = true;
            iterableParameterType = pojoType.asParameterizationOf(iterableType).getTypeArgs()[0];
            iterableParameterPrimitiveType = iterableParameterType.isPrimitive();

            // Find if theres any exception
            String qualifiedSourceName = pojoQualifiedName;
            if (exceptions.containsKey(qualifiedSourceName)) {
                parameterizedQualifiedSourceName = exceptions.get(qualifiedSourceName) + "<"
                        + iterableParameterType.getParameterizedQualifiedSourceName() + ">";
            }
        }

        // Map
        JGenericType mapType = context.getTypeOracle().findType(Map.class.getCanonicalName()).isGenericType();
        boolean isMap = false;
        JClassType mapKeyType = null;
        JClassType mapValueType = null;
        if (mapType.isAssignableFrom(pojoType)) {
            isMap = true;
            JParameterizedType pojoMap = pojoType.asParameterizationOf(mapType);
            JClassType[] args = pojoMap.getTypeArgs();
            mapKeyType = args[0];
            mapValueType = args[1];

            // Find if theres any exception
            String qualifiedSourceName = pojoQualifiedName;
            if (exceptions.containsKey(qualifiedSourceName)) {
                parameterizedQualifiedSourceName = exceptions.get(qualifiedSourceName) + "<"
                        + mapKeyType.getParameterizedQualifiedSourceName() + ","
                        + mapValueType.getParameterizedQualifiedSourceName() + ">";
            }
        }

        // Array
        boolean isArray = false;
        JArrayType pojoArray = pojoType.isArray();
        if (pojoArray != null) {
            isArray = true;
            iterableParameterType = pojoArray.getComponentType();
            iterableParameterPrimitiveType = iterableParameterType.isPrimitive();
        }

        // For pojos
        ArrayList<JField> fields = null;

        writer.println("public static " + createdName + " singleton;");

        writer.println("public static " + createdName + " getSingleton() {");
        writer.indent();
        writer.println("return singleton == null ? (singleton = new " + createdName + "()) : singleton;");
        writer.outdent();
        writer.println("}");

        writer.println("@Override");
        writer.println("public " + JSONValue.class.getCanonicalName() + " serialize(" + typeName + " data) {");
        writer.indent();

        if (isMap) {
            writer.println("if (data != null) {");
            writer.indent();
            writer.println(JSONArray.class.getCanonicalName() + " array = new "
                    + JSONArray.class.getCanonicalName() + "();");
            writer.println("int n = 0;");
            writer.println("for (" + Entry.class.getCanonicalName() + "<"
                    + mapKeyType.getParameterizedQualifiedSourceName() + ", "
                    + mapValueType.getParameterizedQualifiedSourceName() + ">" + " entry : data.entrySet()) {");
            writer.indent();

            writer.print("array.set(n, ");
            JPrimitiveType mapKeyPrimitive = mapKeyType.isPrimitive();
            if (mapKeyPrimitive == null) {
                printValueSerialized(logger, context, writer, "entry.getKey()", mapKeyType, pojoType);
            } else {
                printPrimitiveSerialized(typeName, writer, "entry.getKey()", mapKeyPrimitive);
            }
            writer.println(");");
            writer.println("n++;");

            writer.print("array.set(n, ");
            JPrimitiveType mapValuePrimitive = mapValueType.isPrimitive();
            if (mapValuePrimitive == null) {
                printValueSerialized(logger, context, writer, "entry.getValue()", mapValueType, pojoType);
            } else {
                printPrimitiveSerialized(typeName, writer, "entry.getValue()", mapValuePrimitive);
            }
            writer.println(");");
            writer.println("n++;");

            writer.outdent();
            writer.println("}");
            writer.println("return array;");
            writer.outdent();
            writer.println("}");
            writer.println("return " + JSONNull.class.getCanonicalName() + ".getInstance();");
        } else if (isIterable || isArray) {
            writer.println("if (data != null) {");
            writer.indent();
            writer.println(JSONArray.class.getCanonicalName() + " array = new "
                    + JSONArray.class.getCanonicalName() + "();");
            writer.println("int n = 0;");
            writer.println(
                    "for (" + iterableParameterType.getParameterizedQualifiedSourceName() + " item : data) {");
            writer.indent();

            writer.print("array.set(n, ");
            if (iterableParameterPrimitiveType == null) {
                printValueSerialized(logger, context, writer, "item", iterableParameterType, pojoType);
            } else {
                printPrimitiveSerialized(typeName, writer, "item", iterableParameterPrimitiveType);
            }
            writer.println(");");
            writer.println("n++;");

            writer.outdent();
            writer.println("}");
            writer.println("return array;");
            writer.outdent();
            writer.println("}");
            writer.println("return " + JSONNull.class.getCanonicalName() + ".getInstance();");
        } else if (pojoType.isEnum() != null) {
            writer.println("if (data != null) {");
            writer.indent();
            writer.println("return new " + JSONString.class.getCanonicalName() + "(data.name());");
            writer.outdent();
            writer.println("}");
            writer.println("return " + JSONNull.class.getCanonicalName() + ".getInstance();");
        } else {
            // Assert the type have an empty constructor
            try {
                pojoType.getConstructor(emptyParameter);
            } catch (NotFoundException e) {
                error("The data type of the place does not have an empty constructor. Found %s", typeName);
            }

            writer.println(jsonObject + " json = new " + jsonObject + "();");

            fields = new ArrayList<JField>();
            getFields(fields, pojoType);
            for (JField f : fields) {
                String fieldName = f.getName();
                String getterName = fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
                JType fieldType = f.getType();
                JPrimitiveType primitive = fieldType.isPrimitive();
                String fieldTypeQualifiedType = fieldType.getQualifiedSourceName();

                if (primitive != null) {
                    writer.print("json.put(\"" + fieldName + "\",");
                    printPrimitiveSerialized(typeName, writer, "get" + getterName + "(data)", primitive);
                    writer.println(");");
                } else {
                    writer.println(
                            fieldTypeQualifiedType + " " + fieldName + " = get" + getterName + "(data);");
                    writer.println("if (" + fieldName + " != null) {");
                    writer.indent();

                    writer.print("json.put(\"" + fieldName + "\",");
                    printValueSerialized(logger, context, writer, fieldName, fieldType, pojoType);
                    writer.println(");");

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

            writer.println("return json;");
        }

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

        // Getters and setters
        printJsniGettersAndSetters(writer, pojoType);

        writer.println("@Override");
        writer.println(
                "public " + typeName + " deserialize(" + JSONValue.class.getCanonicalName() + " jsonValue) {");
        writer.indent();

        if (isMap) {
            writer.println("if (jsonValue.isNull() == null) {");
            writer.indent();

            writer.println(JSONArray.class.getCanonicalName() + " jsonArray = jsonValue.isArray();");
            writer.println("int jsonArraySize = jsonArray.size();");

            writer.println(parameterizedQualifiedSourceName + " map = new " + parameterizedQualifiedSourceName
                    + "();");

            writer.println("for (int n = 0; n < jsonArraySize; n+=2) {");
            writer.indent();
            writer.println(JSONValue.class.getCanonicalName() + " key = jsonArray.get(n);");
            writer.println(JSONValue.class.getCanonicalName() + " value = jsonArray.get(n + 1);");

            writer.print("map.put(");
            JPrimitiveType mapKeyPrimitive = mapKeyType.isPrimitive();
            if (mapKeyPrimitive == null) {
                printValueDeserialized(logger, context, writer, "key", mapKeyType);
            } else {
                printPrimitiveDeserialized(typeName, writer, "key", mapKeyPrimitive);
            }
            writer.print(",");
            JPrimitiveType mapValuePrimitive = mapValueType.isPrimitive();
            if (mapValuePrimitive == null) {
                printValueDeserialized(logger, context, writer, "value", mapValueType);
            } else {
                printPrimitiveDeserialized(typeName, writer, "value", mapValuePrimitive);
            }
            writer.println(");");

            writer.outdent();
            writer.println("}");
            writer.println("return map;");
            writer.outdent();
            writer.println("} else { return null; }");
        } else if (isIterable || isArray) {
            writer.println("if (jsonValue.isNull() == null) {");
            writer.indent();

            writer.println(JSONArray.class.getCanonicalName() + " jsonArray = jsonValue.isArray();");
            writer.println("int jsonArraySize = jsonArray.size();");

            if (isIterable) {
                writer.println(parameterizedQualifiedSourceName + " array = new "
                        + parameterizedQualifiedSourceName + "();");
            } else {
                JArrayType array = iterableParameterType.isArray();
                if (array != null) {
                    String arrayName = array.getQualifiedSourceName() + "[]";
                    int index = arrayName.indexOf("[");
                    String arrayDeclaration = arrayName.substring(0, index + 1) + "jsonArraySize"
                            + arrayName.substring(index + 1);
                    writer.println(arrayName + " array = new " + arrayDeclaration + ";");
                } else {
                    String parameterQualifiedName = iterableParameterType.getQualifiedSourceName();
                    writer.println(parameterQualifiedName + "[] array = new " + parameterQualifiedName
                            + "[jsonArraySize];");
                }
            }

            writer.println("for (int n = 0; n < jsonArraySize; n++) {");
            writer.indent();
            writer.println(JSONValue.class.getCanonicalName() + " item = jsonArray.get(n);");

            if (isIterable) {
                writer.print("array.add(");
            } else {
                writer.print("array[n] = ");
            }

            if (iterableParameterPrimitiveType == null) {
                printValueDeserialized(logger, context, writer, "item", iterableParameterType);
            } else {
                printPrimitiveDeserialized(typeName, writer, "item", iterableParameterPrimitiveType);
            }

            if (isIterable) {
                writer.println(");");
            } else {
                writer.println(";");
            }

            writer.outdent();
            writer.println("}");
            writer.println("return array;");
            writer.outdent();
            writer.println("} else { return null; }");
        } else if (pojoType.isEnum() != null) {
            writer.println("if (jsonValue.isNull() == null) {");
            writer.indent();
            writer.println("return " + typeName + ".valueOf(jsonValue.isString().stringValue());");
            writer.outdent();
            writer.println("} else { return null; }");

        } else {
            // Assert the type have an empty constructor
            try {
                pojoType.getConstructor(emptyParameter);
            } catch (NotFoundException e) {
                error("The data type of the place does not have an empty constructor. Found %s", typeName);
            }

            writer.println(JSONObject.class.getCanonicalName() + " json = jsonValue.isObject();");
            writer.println(typeName + " instance = new " + typeName + "();");

            for (JField f : fields) {
                String fieldName = f.getName();
                String setterName = fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
                JType fieldType = f.getType();
                JPrimitiveType primitive = fieldType.isPrimitive();
                if (primitive != null) {
                    writer.print("set" + setterName + "(instance,");
                    printPrimitiveDeserialized(typeName, writer, "json.get(\"" + fieldName + "\")", primitive);
                    writer.println(");");
                } else {
                    writer.println("if (json.containsKey(\"" + fieldName + "\")) {");
                    writer.indent();

                    writer.print("set" + setterName + "(instance,");
                    printValueDeserialized(logger, context, writer, "json.get(\"" + fieldName + "\")",
                            fieldType);
                    writer.println(");");

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

            writer.println("return instance;");
        }

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

        writer.commit(logger);
    }

    return createdName;
}

From source file:com.guit.rebind.jsorm.JsonSerializerUtil.java

License:Apache License

private static void printPrimitiveSerialized(String typeName, SourceWriter writer, String fieldName,
        JPrimitiveType primitive) throws UnableToCompleteException {
    if (primitive.equals(JPrimitiveType.BOOLEAN)) {
        writer.print(JSONBoolean.class.getCanonicalName() + ".getInstance(" + fieldName + ")");
    } else if (primitive.equals(JPrimitiveType.DOUBLE)) {
        writer.print("new " + JSONNumber.class.getCanonicalName() + "(" + fieldName + ")");
    } else if (primitive.equals(JPrimitiveType.FLOAT)) {
        writer.print("new " + JSONNumber.class.getCanonicalName() + "(" + fieldName + ")");
    } else if (primitive.equals(JPrimitiveType.LONG)) {
        writer.print("new " + JSONNumber.class.getCanonicalName() + "(" + fieldName + ")");
    } else if (primitive.equals(JPrimitiveType.INT)) {
        writer.print("new " + JSONNumber.class.getCanonicalName() + "(" + fieldName + ")");
    } else {//w  ww  .  jav a  2 s  . com
        error("The type %s is not a valid type for the place data. Found %s", primitive.getSimpleSourceName(),
                typeName);
    }
}

From source file:com.guit.rebind.jsorm.JsonSerializerUtil.java

License:Apache License

private static void printValueDeserialized(TreeLogger logger, GeneratorContext context, SourceWriter writer,
        String fieldName, JType fieldType) throws UnableToCompleteException {
    String fieldTypeName = fieldType.getQualifiedSourceName();
    if (fieldTypeName.equals(String.class.getCanonicalName())) {
        writer.print(fieldName + ".isString().stringValue()");
    } else if (fieldTypeName.equals(Integer.class.getCanonicalName())) {
        writer.print("(int)" + fieldName + ".isNumber().doubleValue()");
    } else if (fieldTypeName.equals(Long.class.getCanonicalName())) {
        writer.print("(long)" + fieldName + ".isNumber().doubleValue()");
    } else if (fieldTypeName.equals(Double.class.getCanonicalName())) {
        writer.print(fieldName + ".isNumber().doubleValue()");
    } else if (fieldTypeName.equals(Float.class.getCanonicalName())) {
        writer.print("(float)" + fieldName + ".isNumber().doubleValue()");
    } else if (fieldTypeName.equals(Date.class.getCanonicalName())) {
        writer.print(//from  www  . j  ava 2 s .c om
                "new " + Date.class.getCanonicalName() + "((long)" + fieldName + ".isNumber().doubleValue())");
    } else if (fieldTypeName.equals(Boolean.class.getCanonicalName())) {
        writer.print(fieldName + ".isBoolean().booleanValue()");
    } else {
        JClassType classOrInterface = fieldType.isClassOrInterface();
        writer.print(
                generate(logger, context, (classOrInterface != null ? classOrInterface : fieldType.isArray()))
                        + ".getSingleton().deserialize(" + fieldName + ")");
    }
}

From source file:com.guit.rebind.jsorm.JsonSerializerUtil.java

License:Apache License

private static void printValueSerialized(TreeLogger logger, GeneratorContext context, SourceWriter writer,
        String fieldName, JType fieldType, JClassType pojoType) throws UnableToCompleteException {

    String fieldTypeName = fieldType.getQualifiedSourceName();
    if (fieldTypeName.equals(String.class.getCanonicalName())) {
        writer.print("new " + JSONString.class.getCanonicalName() + "(" + fieldName + ")");
    } else if (fieldTypeName.equals(Integer.class.getCanonicalName())) {
        writer.print("new " + JSONNumber.class.getCanonicalName() + "(" + fieldName + ")");
    } else if (fieldTypeName.equals(Long.class.getCanonicalName())) {
        writer.print("new " + JSONNumber.class.getCanonicalName() + "(" + fieldName + ")");
    } else if (fieldTypeName.equals(Double.class.getCanonicalName())) {
        writer.print("new " + JSONNumber.class.getCanonicalName() + "(" + fieldName + ")");
    } else if (fieldTypeName.equals(Float.class.getCanonicalName())) {
        writer.print("new " + JSONNumber.class.getCanonicalName() + "(" + fieldName + ")");
    } else if (fieldTypeName.equals(Date.class.getCanonicalName())) {
        writer.print("new " + JSONNumber.class.getCanonicalName() + "(" + fieldName + ".getTime())");
    } else if (fieldTypeName.equals(Boolean.class.getCanonicalName())) {
        writer.print(JSONBoolean.class.getCanonicalName() + ".getInstance(" + fieldName + ")");
    } else {/*from  w ww .j a  v a  2s  .  com*/
        // We cannot serialize java.lang.Object
        if (fieldType.getQualifiedSourceName().equals(Object.class.getCanonicalName())) {
            error("You cannot serialize Object... we either. Found: %s.%s", pojoType.getQualifiedSourceName(),
                    fieldName);
        }

        JClassType classOrInterface = fieldType.isClassOrInterface();
        writer.print(
                generate(logger, context, (classOrInterface != null ? classOrInterface : fieldType.isArray()))
                        + ".getSingleton().serialize(" + fieldName + ")");
    }
}