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

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

Introduction

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

Prototype

void commit(TreeLogger logger);

Source Link

Usage

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

License:Apache License

public String doGenerate(TreeLogger logger, GeneratorContext context, String typeName) throws Exception {
    TypeOracle typeOracle = context.getTypeOracle();
    JClassType type = typeOracle.getType(typeName);
    String packageName = type.getPackage().getName();
    String simpleClassName = type.getSimpleSourceName();

    String className = simpleClassName + "Introspector";
    String qualifiedBeanClassName = packageName + "." + className;
    SourceWriter sourceWriter = getSourceWriter(logger, context, packageName, className, type);
    if (sourceWriter == null) {
        return qualifiedBeanClassName;
    }//w w w . ja  va 2 s.  c o  m
    write(logger, sourceWriter, type);
    sourceWriter.commit(logger);
    return qualifiedBeanClassName;
}

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.c  o  m

    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.googlecode.mgwt.ui.generator.DeviceDensityGenerator.java

License:Apache License

protected void writeImplementation(TreeLogger logger, SelectionProperty property, SourceWriter writer) {
    writer.println("public boolean isMidDPI() {");
    writer.println("return " + property.getCurrentValue().equals("mid") + ";");
    writer.println("}");

    writer.println("public boolean isHighDPI() {");
    writer.println("return " + property.getCurrentValue().equals("high") + ";");
    writer.println("}");

    writer.println("public boolean isXHighDPI() {");
    writer.println("return " + property.getCurrentValue().equals("xhigh") + ";");
    writer.println("}");

    writer.commit(logger);
}

From source file:com.googlecode.mgwt.ui.generator.FormFactorGenerator.java

License:Apache License

@Override
protected void writeImplementation(TreeLogger logger, SelectionProperty property, SourceWriter writer) {
    writer.println("public boolean isPhone() {");
    writer.println("return " + property.getCurrentValue().equals("phone") + ";");
    writer.println("}");

    writer.println("public boolean isTablet() {");
    writer.println("return " + property.getCurrentValue().equals("tablet") + ";");
    writer.println("}");

    writer.println("public boolean isDesktop() {");
    writer.println("return " + property.getCurrentValue().equals("desktop") + ";");
    writer.println("}");

    writer.commit(logger);
}

From source file:com.googlecode.mgwt.ui.generator.OsDetectionGenerator.java

License:Apache License

@Override
protected void writeImplementation(TreeLogger logger, SelectionProperty property, SourceWriter writer) {
    writer.println("public boolean isAndroid() {");
    writer.println("return isAndroidTablet() || isAndroidPhone();");
    writer.println("}");

    writer.println("public boolean isIPhone() {");
    writer.println("return " + property.getCurrentValue().equals("iphone") + " || "
            + property.getCurrentValue().equals("retina") + ";");
    writer.println("}");

    writer.println("public boolean isIPad() {");
    writer.println("return " + property.getCurrentValue().equals("ipad") + " || "
            + property.getCurrentValue().equals("ipad_retina") + ";");
    writer.println("}");

    writer.println("public boolean isIOs() {");
    writer.println("return isIPhone() || isIPad();");
    writer.println("}");

    writer.println("public boolean isDesktop() {");
    writer.println("return " + property.getCurrentValue().equals("desktop") + ";");
    writer.println("}");

    writer.println("public boolean isBlackBerry() {");
    writer.println("return false;");
    writer.println("}");

    writer.println("public boolean isTablet() {");
    writer.println("return isDesktop() || isIPad() || isAndroidTablet();");
    writer.println("}");

    writer.println("public boolean isPhone() {");
    writer.println("return isIPhone() || isAndroidPhone() || isBlackBerry();");
    writer.println("}");

    writer.println("public boolean isAndroidTablet() {");
    writer.println("return " + property.getCurrentValue().equals("android_tablet") + ";");
    writer.println("}");

    writer.println("public boolean isAndroidPhone() {");
    writer.println("return " + property.getCurrentValue().equals("android") + ";");
    writer.println("}");

    writer.println("public boolean isRetina() {");
    writer.println("return " + property.getCurrentValue().equals("retina") + ";");
    writer.println("}");

    writer.println("public boolean isIPadRetina() {");
    writer.println("return " + property.getCurrentValue().equals("ipad_retina") + ";");
    writer.println("}");

    writer.commit(logger);
}

From source file:com.googlecode.mgwt.ui.generator.SuperDevModeGenerator.java

License:Apache License

private String buildOnImplementation(TreeLogger logger, GeneratorContext context, JClassType classType,
        String typeName, ConfigurationProperty superDevModeServer) {

    if (superDevModeServer.getValues().get(0) == null) {
        //use default impl!
        return "com.googlecode.mgwt.ui.client.util.impl.SuperDevModeHelperOnDefaultImpl";
    }/*from w  w  w.j  a  va 2 s . c  o m*/

    // 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;

    ClassSourceFileComposerFactory composer = new ClassSourceFileComposerFactory(packageName, simpleName);
    composer.setSuperclass("com.googlecode.mgwt.ui.client.util.impl.SuperDevModeHelperOnImpl");
    composer.addImport("com.googlecode.mgwt.ui.client.util.impl.SuperDevModeHelperOnImpl");

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

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

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

    writer.println("protected String getServerUrl() {");
    writer.println("return \"" + superDevModeServer.getValues().get(0) + "\";");
    writer.println("}");
    writer.commit(logger);

    return fullName;
}

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 w  w . j  a va2 s  . c  om*/
    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.common.AbstractGenerator.java

License:Apache License

@Override
public RebindResult generateIncrementally(TreeLogger logger, GeneratorContext context, String typeName)
        throws UnableToCompleteException {
    saveVariables(logger, context, typeName);

    baseClass = getType(typeName);//from  ww  w  .j  ava  2s.  c  o  m
    generatedPackage = baseClass.getPackage().getName();
    implName = baseClass.getSimpleSourceName() + implementationPostfix;
    implName = processImplName(implName);
    JClassType enclosingType = baseClass.getEnclosingType();
    if (enclosingType != null) {
        implName = enclosingType.getSimpleSourceName() + implName;
    }

    RebindMode rebindMode = context.isGeneratorResultCachingEnabled() ? rebindMode()
            : RebindMode.USE_ALL_NEW_WITH_NO_CACHING;
    if (rebindMode.equals(RebindMode.USE_ALL_CACHED) || rebindMode.equals(RebindMode.USE_EXISTING)) {
        return new RebindResult(rebindMode, generatedPackage + "." + implName);
    }

    ClassSourceFileComposerFactory composer = createComposer();
    processComposer(composer);
    createdClassName = composer.getCreatedClassName();
    PrintWriter printWriter = createPrintWriter();
    if (printWriter != null) {
        SourceWriter writer = composer.createSourceWriter(context, printWriter);
        generate(writer);

        writer.commit(logger);
    }

    RebindResult result = new RebindResult(rebindMode, composer.getCreatedClassName());
    saveClientData(result);
    return result;
}

From source file:com.guit.rebind.gin.GinInjectorGenerator.java

License:Apache License

@Override
public RebindResult generateIncrementally(TreeLogger logger, GeneratorContext context, String typeName)
        throws UnableToCompleteException {
    saveVariables(logger, context, typeName);
    if (typeOracle.findType(GinOracle.packageName, GinOracle.className) != null) {
        return new RebindResult(RebindMode.USE_EXISTING, GinOracle.packageName + "." + GinOracle.className);
    }/*from w  w w.  j  a  v a 2 s. c o m*/

    // Clear
    injectedClasses.clear();
    providedClasses.clear();
    asyncProvidedClasses.clear();
    gmodules.clear();

    // Call gin contributors
    List<String> contributors = getConfigurationProperty("app.gin.contributor").getValues();
    for (String c : contributors) {
        GinContributor contributor = instantiateContributor(c);
        contributor.collaborate(this, logger, context);
    }

    // Generate the modules string
    StringBuilder sb = new StringBuilder();
    sb.append("({");
    for (Class<?> m : gmodules) {
        if (sb.length() > 2) {
            sb.append(", ");
        }
        sb.append(m.getCanonicalName() + ".class");
    }
    sb.append("})");

    GinOracle.setModules(gmodules);

    ClassSourceFileComposerFactory composer = new ClassSourceFileComposerFactory(GinOracle.packageName,
            GinOracle.className);
    composer.makeInterface();
    composer.addImplementedInterface(Ginjector.class.getCanonicalName());
    composer.addAnnotationDeclaration("@" + GinModules.class.getCanonicalName() + sb.toString());
    PrintWriter printWriter = context.tryCreate(logger, GinOracle.packageName, GinOracle.className);

    // Convert to linked to remove possible duplicated entries
    injectedClasses = findClassOrLinkedInjectionKey(injectedClasses);
    providedClasses = findClassOrLinkedInjectionKey(providedClasses);
    asyncProvidedClasses = findClassOrLinkedInjectionKey(asyncProvidedClasses);

    if (printWriter != null) {
        SourceWriter writer = composer.createSourceWriter(context, printWriter);

        writer.println(SINGLETON_DECLARATION);

        for (String classType : injectedClasses) {
            load(classType);
            writer.println(classType + " " + GinOracle.getGetterMethodName(classType) + "();");
        }

        for (String classType : providedClasses) {
            load(classType);
            writer.println(Provider.class.getCanonicalName() + "<" + classType + "> "
                    + GinOracle.getProviderGetterMethodName(classType) + "();");
        }

        for (String classType : asyncProvidedClasses) {
            load(classType);
            writer.println(AsyncProvider.class.getCanonicalName() + "<" + classType + "> "
                    + GinOracle.getAsyncProviderGetterMethodName(classType) + "();");
        }

        writer.commit(logger);
    }

    return new RebindResult(RebindMode.USE_PARTIAL_CACHED, GinOracle.packageName + "." + GinOracle.className);
}

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  www.jav  a2  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;
}