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

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

Introduction

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

Prototype

void outdent();

Source Link

Usage

From source file:com.googlecode.mgwt.useragent.rebind.UserAgentGenerator.java

License:Apache License

@Override
public String generate(TreeLogger logger, GeneratorContext context, String typeName)
        throws UnableToCompleteException {
    TypeOracle typeOracle = context.getTypeOracle();

    JClassType userType;/*from  w  ww.  j a  va  2  s. co  m*/
    try {
        userType = typeOracle.getType(typeName);
    } catch (NotFoundException e) {
        logger.log(TreeLogger.ERROR, "Unable to find metadata for type: " + typeName, e);
        throw new UnableToCompleteException();
    }
    String packageName = userType.getPackage().getName();
    String className = userType.getName();
    className = className.replace('.', '_');

    if (userType.isInterface() == null) {
        logger.log(TreeLogger.ERROR, userType.getQualifiedSourceName() + " is not an interface", null);
        throw new UnableToCompleteException();
    }

    PropertyOracle propertyOracle = context.getPropertyOracle();

    String userAgentValue;
    SelectionProperty selectionProperty;
    try {
        selectionProperty = propertyOracle.getSelectionProperty(logger, PROPERTY_USER_AGENT);
        userAgentValue = selectionProperty.getCurrentValue();
    } catch (BadPropertyValueException e) {
        logger.log(TreeLogger.ERROR, "Unable to find value for '" + PROPERTY_USER_AGENT + "'", e);
        throw new UnableToCompleteException();
    }

    String userAgentValueInitialCap = userAgentValue.substring(0, 1).toUpperCase(Locale.ENGLISH)
            + userAgentValue.substring(1);
    className = className + "Impl" + userAgentValueInitialCap;

    ClassSourceFileComposerFactory composerFactory = new ClassSourceFileComposerFactory(packageName, className);
    composerFactory.addImplementedInterface(userType.getQualifiedSourceName());

    PrintWriter pw = context.tryCreate(logger, packageName, className);
    if (pw != null) {
        SourceWriter sw = composerFactory.createSourceWriter(context, pw);

        sw.println();
        sw.println("public native String getRuntimeValue() /*-{");
        sw.indent();
        UserAgentPropertyGenerator.writeUserAgentPropertyJavaScript(sw, selectionProperty.getPossibleValues(),
                null);
        sw.outdent();
        sw.println("}-*/;");
        sw.println();

        sw.println();
        sw.println("public String getCompileTimeValue() {");
        sw.indent();
        sw.println("return \"" + userAgentValue.trim() + "\";");
        sw.outdent();
        sw.println("}");

        sw.commit(logger);
    }
    return composerFactory.getCreatedClassName();
}

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();// w  ww  .ja  v a2  s.  co  m

    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

@Override
protected void generate(SourceWriter writer) throws UnableToCompleteException {
    // Do we need to check this?
    JClassType presenterType = baseClass.getImplementedInterfaces()[0].isParameterized().getTypeArgs()[0];

    // Presenter or controller
    boolean isPresenter = checkIsPresenter(presenterType);

    hasNativeEventType = hasNativeEventType == null ? getType(HasNativeEvent.class.getCanonicalName())
            : hasNativeEventType;//w w w.  jav a  2s. c o m

    // If it is a parameterized type we need to find the base type to get
    // the right method names
    while (presenterType.isParameterized() != null || presenterType.isRawType() != null) {
        if (presenterType.isParameterized() != null) {
            presenterType = presenterType.isParameterized().getBaseType();
        } else {
            presenterType = presenterType.isRawType().getBaseType();
        }
    }

    checkForRepetition(presenterType);

    writer.println(bindingsDeclaration);
    writer.println(eventBusbindingsDeclaration);

    String viewTypeName = null;
    HashMap<String, JType> validBindingFieldsTypes = null;
    if (isPresenter) {
        viewTypeName = guitViewGenerator.generate(logger, context, presenterType.getQualifiedSourceName());
        writer.println(viewTypeName + " view;");

        // Field -> Type (for validation purpose)
        validBindingFieldsTypes = getValidGuitViewBindingFields(presenterType);

        // View pool
        writer.println("private static " + ViewPool.class.getCanonicalName() + " pool = new "
                + ViewPool.class.getCanonicalName() + "();");
    }

    // If is an editor generate the driver
    boolean isGwtEditor = presenterType.isAnnotationPresent(GwtEditor.class);
    GwtEditor editor = null;
    Class<?> editorDriver = null;
    if (isGwtEditor) {
        editor = presenterType.getAnnotation(GwtEditor.class);
        editorDriver = editor.base();
        writer.println("public static interface Driver extends " + editorDriver.getCanonicalName() + "<"
                + editor.pojo().getCanonicalName() + "," + viewTypeName + "> {}");
    }

    writer.println(presenterType.getQualifiedSourceName() + " presenter;");

    writer.println(EventBus.class.getCanonicalName() + " eventBus;");

    writer.println("boolean isBinded = false;");

    /*
     * Event bus binder.
     */
    writer.println("public void bind(final " + presenterType.getQualifiedSourceName() + " presenter, final "
            + EventBus.class.getCanonicalName() + " eventBus) {");
    writer.indent();

    writer.println("this.presenter = presenter;");
    writer.println("this.eventBus = eventBus != null ? eventBus : " + GuitEntryPoint.class.getCanonicalName()
            + ".getEventBus();");
    printEventBusBindingMethods(writer, presenterType);

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

    /*
     * View binder.
     */
    writer.println("public " + View.class.getCanonicalName() + " getView() {");
    writer.indent();

    if (isPresenter) {
        // If already binded return the view
        writer.println("if (isBinded) {");
        writer.println("    return view;");
        writer.println("}");

        // Find a view from the pool or create a new one
        writer.println("if (pool.isEmpty()) {");
        writer.println("view = (" + viewTypeName + ") new " + viewTypeName + "();");

        ArrayList<JField> fields = new ArrayList<JField>();
        collectAllFields(presenterType, fields);

        // Provided fields
        printProvidedFields(presenterType, validBindingFieldsTypes, writer, false, fields);

        writer.println("view.bind();");
        writer.println("} else {");
        writer.println("view = (" + viewTypeName + ") pool.pop();");

        // Provided fields
        printProvidedFields(presenterType, validBindingFieldsTypes, writer, true, fields);

        writer.println("}");

        printViewFieldBindings(writer, presenterType, viewTypeName, validBindingFieldsTypes, fields);
        printViewBindingMethods(writer, presenterType, viewTypeName, validBindingFieldsTypes);

        // Initializers
        printPresentersInitilizersCalls(writer, presenterType);

        writer.println("isBinded = true;");

        // GwtEditor
        if (isGwtEditor) {
            writer.println("Driver driver = GWT.create(Driver.class);");

            if (editorDriver.equals(RequestFactoryEditorDriver.class)) {
                JField factoryField = presenterType.getField("factory");
                if (factoryField == null
                        || !factoryField.getType().isClassOrInterface()
                                .isAssignableTo(getType(RequestFactory.class.getCanonicalName()))
                        || factoryField.isPrivate()) {
                    error("The presenter does not have a non-private factory field of the type RequestFactory. Found: "
                            + presenterType.getQualifiedSourceName() + ".factory");
                }
                writer.println("driver.initialize(eventBus, presenter.factory, view);");
            } else {
                writer.println("driver.initialize(view);");
            }

            writer.println("presenter.driver = driver;");
        }

        // Return the view or null
        writer.println("return view;");
    } else {
        writer.println("return null;");
    }

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

    /*
     * Unbind
     */
    writer.println("public void releaseView() {");
    writer.indent();

    if (isPresenter) {
        writer.println("for (" + handlerRegistrationName + " b : bindings) {b.removeHandler();}");
        writer.println("bindings.clear();");
        if (isPresenter) {
            // Recycle the view
            writer.println("if (view != null) {");
            writer.indent();
            writer.println("pool.push(view);");
            writer.println("view = null;");
            writer.outdent();
            writer.println("}");
        }
        writer.println("isBinded = false;");
    }
    writer.outdent();
    writer.println("}");

    /*
     * Destroy.
     */
    writer.println("public void destroy() {");
    writer.indent();
    writer.println("for (" + handlerRegistrationName + " b : eventBusBindings) {b.removeHandler();}");
    if (isPresenter) {
        writer.println("releaseView();");
    }
    writer.println("bindings = null;");
    writer.println("eventBusBindings = null;");
    writer.println("presenter = null;");
    writer.println("eventBus = null;");
    writer.outdent();
    writer.println("}");
}

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

License:Apache License

/**
 * Finds the valid methods and check all the conventions.
 *//*w  w  w  .java 2 s.c  o m*/
protected void printEventBusBindingMethods(SourceWriter writer, JClassType presenterType)
        throws UnableToCompleteException {
    JPackage contextEventsPackage = getPackage(presenterType.getPackage().getName() + ".event");
    for (JMethod m : presenterType.getMethods()) {
        if (m.isAnnotationPresent(EventBusHandler.class)) {

            EventBusHandler eventBusHandler = m.getAnnotation(EventBusHandler.class);

            String name = m.getName();
            String presenterName = presenterType.getQualifiedSourceName();

            validateHandler(m, name, presenterName);

            // Find the event type
            JParameter[] parameters = m.getParameters();

            if (!name.startsWith("$") && !name.startsWith("eventBus$")) {
                error("Bad method name: %s on class: %s, the method should start with '$' or 'eventBus$'", name,
                        presenterName);
            }

            // Clean the name
            if (name.startsWith("$")) {
                name = name.substring(1); // Cut off the $
            } else {
                name = name.substring(9); // Cut off the eventBus$
            }

            JClassType eventType = getType(eventBusHandler.value().getCanonicalName());
            if (eventType.equals(gwtEventType)) {
                eventType = getEventByName(name, contextEventsPackage);
                if (eventType == null) {
                    error("There is no context, dom or shared event with the name '%s'. Binding method: '%s' in class: '%s'",
                            name, m.getName(), presenterType.getQualifiedSourceName());
                }
            }

            StringBuilder bindingParameters = new StringBuilder();
            ArrayList<String> parameterStrings = new ArrayList<String>();
            for (JParameter p : parameters) {
                String parameter = p.getName();

                if (bindingParameters.length() > 0) {
                    bindingParameters.append(", ");
                }

                int initlenght = bindingParameters.length();

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

                String getter = "get";

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

                // Event getter binding
                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()));
            }

            // Find the event name
            String simpleName = eventType.getSimpleSourceName();
            if (!simpleName.endsWith("Event")) {
                error("The event %s does not use the event convention. It should end with 'Event'",
                        eventType.getQualifiedSourceName());
            }
            String eventName = eventClassNameToEventName(simpleName);

            // Check that the name of the event correspond to the method
            // name convention
            if (!eventName.equals(name)) {
                error("The method %s on class %s does not use the event bus handler method convention. "
                        + "It should start with '$' or 'eventBus$' "
                        + "and end with the event name. i.e ValueChangeEvent -> $valueChange. Solve it renaming it to '$%s'",
                        m.getName(), presenterName, eventName);
            }

            // 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[] methods = handlerType.getMethods();
            if (methods.length != 1) {
                error("'%s' has more than one method defined.", handlerType.getName());
            }

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

            // Checks if the method has an Event as parameter. Ex:
            // ClickEvent in onClick, BlurEvent in onBlur ...
            parameters = handlerOnMethod.getParameters();
            if (parameters.length != 1) {
                error("Method '%s' needs '%s' as parameter", handlerOnMethod.getName(), eventType.getName());
            }

            writer.println("eventBusBindings.add(eventBus.addHandler(");

            writer.println(eventType.getQualifiedSourceName() + ".");

            // getType or TYPE ?
            JField typeField = eventType.getField("TYPE");
            if (typeField != null && typeField.isStatic() && typeField.isPublic()) {
                writer.println("TYPE");
            } else {
                writer.println("getType()");
            }
            writer.println(", ");

            writer.println("new " + handlerType.getQualifiedSourceName() + "() {");
            writer.indent();
            writer.println("public void " + handlerOnMethod.getName() + "(final "
                    + eventType.getQualifiedSourceName() + " event) {");
            writer.indent();

            // Process contributors
            String bindingParametersString = bindingParameters.toString();
            BinderContextImpl binderContext = processMethodContributors(presenterType, null, null, null, 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.println("presenter." + m.getName() + "(" + bindingParametersString + ");");

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

            writer.outdent();
            writer.println("}");
            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 w w  w.  j  a  v a2s  . 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)) {

                }/*from  w  w w  .  j  a v  a  2s .  co  m*/
            }

            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   w ww.jav  a2  s  .  co  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.place.PlaceManagerInitializerGenerator.java

License:Apache License

@Override
protected void generate(SourceWriter writer) throws UnableToCompleteException {
    writer.println("public void initialize(" + PlaceManagerImpl.class.getCanonicalName() + " manager) {");
    writer.indent();//from  w ww.ja  v a  2  s  .c  o  m

    boolean encryptAll = !findConfigurationProperty("app.encrypt.place").getValues().get(0).equals("false");

    for (Class<?> p : PlaceGinContributor.places) {
        String canonicalName = p.getCanonicalName();
        String injectedPlace = p.isAnnotationPresent(RunAsync.class)
                ? GinOracle.getAsyncProvidedInstance(canonicalName)
                : GinOracle.getProvidedInstance(p.getCanonicalName());

        String encryptPlace = (encryptAll || p.isAnnotationPresent(PlaceDataEncrypted.class)) ? "true"
                : "false";

        writer.println("manager.addPlace(" + canonicalName + ".class, \"" + getPlaceName(p.getCanonicalName())
                + "\", \"" + getPlaceTitle(p) + "\", " + injectedPlace + ", "
                + generatePlaceData(logger, context, canonicalName) + ".getSingleton(), " + encryptPlace
                + ");");
    }

    ConfigurationProperty configurationProperty = findConfigurationProperty("app.default.place");
    if (configurationProperty != null) {
        List<String> defaultPlaces = configurationProperty.getValues();
        if (defaultPlaces.size() == 1) {
            String defaultPlace = defaultPlaces.get(0);
            if (defaultPlace != null) {
                JClassType type = getType(defaultPlace);
                if (type == null) {
                    error("The default place type does not exists, check your gwt.xml module for typos in 'app.default.place'. Found: %s",
                            defaultPlace);
                }

                writer.println(
                        "manager.setDefaultPlace(\"" + getPlaceName(type.getQualifiedSourceName()) + "\");");
            }
        } else {
            error("You can only have one default place");
        }
    }

    writer.println(History.class.getCanonicalName() + ".addValueChangeHandler(manager);");
    writer.println(Window.class.getCanonicalName() + ".addWindowClosingHandler(manager);");

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

From source file:com.gwtent.gen.aop.AOPCreator.java

License:Apache License

protected void createSource(SourceWriter source, JClassType classType) {

    createInterceptorMap(source, classType);

    source.println("private static final ClassType classType = TypeOracle.Instance.getClassType("
            + classType.getSimpleSourceName() + ".class);");
    source.println();/*  w ww .  ja  v a  2 s  .  c  o m*/

    declareMethodInvocation(source);

    source.println();
    source.println("public " + getSimpleUnitName(classType) + "(){");
    source.indent();
    createMethodInvocation(source);
    source.outdent();
    source.println("}");

    overrideMethods(source, classType);

    source.println();
    createMethodInvocationChain(source);
}

From source file:com.gwtent.gen.aop.AOPCreator.java

License:Apache License

private void createInterceptorMap(SourceWriter source, JClassType classType) {
    source.println("");
    source.println("private static class InterceptorMap{");
    source.indent();/*from w ww. j a  v a  2  s .com*/
    source.println("static Map<Method, List<Method>> interceptors = new HashMap<Method, List<Method>>();");

    source.println("static {");

    source.indent();

    source.println("ClassType aspectClass = null;");
    source.println("Method method = null;");

    for (JMethod sourceMethod : classType.getMethods()) {
        List<JMethod> allMatchedMethods = aspectCollector.allMatches(sourceMethod);
        if (allMatchedMethods.size() > 0) {
            methodCaches.add(new MethodCache(sourceMethod, allMatchedMethods));

            source.println("{");
            source.println("List<Method> matchAdvices = new ArrayList<Method>();");
            for (JMethod matchedMethod : allMatchedMethods) {
                source.println("aspectClass = TypeOracle.Instance.getClassType("
                        + matchedMethod.getEnclosingType().getQualifiedSourceName() + ".class);");
                source.println("method = aspectClass.findMethod(\"" + matchedMethod.getName()
                        + "\", new String[]{" + GenUtils.getParamTypeNames(matchedMethod, '"') + "});");
                source.println("if (method != null)");
                source.println("  matchAdvices.add(method);");
            }
            source.println(
                    "interceptors.put(classType.findMethod(\"" + sourceMethod.getName() + "\", new String[]{"
                            + GenUtils.getParamTypeNames(sourceMethod, '"') + "}), matchAdvices);");
            source.println("}");
        }
    }
    source.outdent();
    source.println("}");

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

    source.outdent();
}