Generate the method that returns the body of the static render functions.

@param exposedTypeGenerator Class generating the ExposedType
@param result The result from compilation using vue-template-compiler
335947
private void generateGetStaticRenderFunctions(ComponentExposedTypeGenerator exposedTypeGenerator,
      VueTemplateCompilerResult result) {
    CodeBlock.Builder staticFunctions = CodeBlock.builder();

    boolean isFirst = true;
    for (String staticRenderFunction : result.getStaticRenderFunctions()) {
      if (!isFirst) {
        staticFunctions.add(", ");
      } else {
        isFirst = false;
      }

      staticFunctions.add("new $T($S)", Function.class, staticRenderFunction);
    }

    MethodSpec.Builder getStaticRenderFunctionsBuilder = MethodSpec
        .methodBuilder("getStaticRenderFunctions")
        .addModifiers(Modifier.PRIVATE)
        .returns(Function[].class)
        .addStatement("return new $T[] { $L }", Function.class, staticFunctions.build());

    exposedTypeGenerator.getClassBuilder().addMethod(getStaticRenderFunctionsBuilder.build());
  }
938115
private Set<String> determineReturnTypes(final MethodResult result) {
        final List<Instruction> visitedInstructions = interpretRelevantInstructions(result.getInstructions());

        // find project defined methods in invoke occurrences
        final Set<ProjectMethod> projectMethods = findProjectMethods(visitedInstructions);

        // add project methods to global method pool
        projectMethods.forEach(MethodPool.getInstance()::addProjectMethod);

        final Element returnedElement = simulator.simulate(visitedInstructions);
        if (returnedElement == null) {
            // happens for abstract methods or if there is no return
            return singleton(result.getOriginalMethodSignature().getReturnType());
        }

        return returnedElement.getTypes();
    }
379129
public VueTemplateCompilerResult compile(String htmlTemplate)
      throws VueTemplateCompilerException {
    ScriptObjectMirror templateCompilerResult;
    try {
      templateCompilerResult =
          (ScriptObjectMirror) engine.invokeFunction("compile", htmlTemplate);
    } catch (ScriptException | NoSuchMethodException e) {
      e.printStackTrace();
      throw new VueTemplateCompilerException(
          "An error occurred while compiling the template: "
              + htmlTemplate
              + " -> "
              + e.getMessage());
    }

    String renderFunction = (String) templateCompilerResult.get("render");
    String[] staticRenderFunctions =
        ((ScriptObjectMirror) templateCompilerResult.get("staticRenderFns")).to(String[].class);

    return new VueTemplateCompilerResult(renderFunction, staticRenderFunctions);
  }
240020
private void generateTemplateExpressionMethod(ComponentExposedTypeGenerator exposedTypeGenerator,
      TemplateExpression expression,
      String templateName) {
    MethodSpec.Builder templateExpressionMethodBuilder = MethodSpec
        .methodBuilder(expression.getId())
        .addModifiers(Modifier.PUBLIC)
        .addAnnotation(JsMethod.class)
        .addAnnotation(getUnusableByJSAnnotation())
        .returns(expression.getType());

    String expressionPosition = templateName;
    if (expression.getLineInHtml() != null) {
      expressionPosition += ", line " + expression.getLineInHtml();
    }

    templateExpressionMethodBuilder.addComment(expressionPosition);

    expression
        .getParameters()
        .forEach(parameter -> templateExpressionMethodBuilder.addParameter(parameter.getType(),
            parameter.getName()));

    if (expression.isReturnString()) {
      templateExpressionMethodBuilder.addStatement("return $T.templateExpressionToString($L)",
          VueGWTTools.class,
          expression.getBody());
    } else if (expression.isReturnVoid()) {
      templateExpressionMethodBuilder.addStatement("$L", expression.getBody());
    } else if (expression.isReturnAny()) {
      templateExpressionMethodBuilder.addStatement("return $T.asAny($L)",
          Js.class,
          expression.getBody());
    } else if (expression.isShouldCast()) {
      templateExpressionMethodBuilder.addStatement("return ($T) ($L)",
          expression.getType(),
          expression.getBody());
    } else {
      templateExpressionMethodBuilder.addStatement("return $L", expression.getBody());
    }

    exposedTypeGenerator.getClassBuilder().addMethod(templateExpressionMethodBuilder.build());
    exposedTypeGenerator.addMethodToProto(expression.getId());
  }
211940
function(result) {
    var oResult = {},
        schema = this.responseSchema;
        
    try {
        // Loop through each data field in each result using the schema
        for(var m = schema.fields.length-1; m >= 0 ; m--) {
            var field = schema.fields[m];
            var key = (lang.isValue(field.key)) ? field.key : field;
            var data = null;

            if(this.useXPath) {
                data = YAHOO.util.DataSource._getLocationValue(field, result);
            }
            else {
                // Values may be held in an attribute...
                var xmlAttr = result.attributes.getNamedItem(key);
                if(xmlAttr) {
                    data = xmlAttr.value;
                }
                // ...or in a node
                else {
                    var xmlNode = result.getElementsByTagName(key);
                    if(xmlNode && xmlNode.item(0)) {
                        var item = xmlNode.item(0);
                        // For IE, then DOM...
                        data = (item) ? ((item.text) ? item.text : (item.textContent) ? item.textContent : null) : null;
                        // ...then fallback, but check for multiple child nodes
                        if(!data) {
                            var datapieces = [];
                            for(var j=0, len=item.childNodes.length; j<len; j++) {
                                if(item.childNodes[j].nodeValue) {
                                    datapieces[datapieces.length] = item.childNodes[j].nodeValue;
                                }
                            }
                            if(datapieces.length > 0) {
                                data = datapieces.join("");
                            }
                        }
                    }
                }
            }
            
            
            // Safety net
            if(data === null) {
                   data = "";
            }
            // Backward compatibility
            if(!field.parser && field.converter) {
                field.parser = field.converter;
                YAHOO.log("The field property converter has been deprecated" +
                        " in favor of parser", "warn", this.toString());
            }
            var parser = (typeof field.parser === 'function') ?
                field.parser :
                DS.Parser[field.parser+''];
            if(parser) {
                data = parser.call(this, data);
            }
            // Safety measure
            if(data === undefined) {
                data = null;
            }
            oResult[key] = data;
        }
    }
    catch(e) {
        YAHOO.log("Error while parsing XML result: " + e.message);
    }

    return oResult;
}
390726
private static void generateSelectForContentProvider(Builder builder, final SQLiteModelMethod method, SelectType selectResultType) {
		final SQLiteDaoDefinition daoDefinition = method.getParent();
		final SQLiteEntity entity = method.getEntity();
		final Set<String> columns = new LinkedHashSet<>();

		MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder(method.contentProviderMethodName);
		if (!method.getParent().hasSamePackageOfSchema()) {
			methodBuilder.addModifiers(Modifier.PUBLIC);
		}

		// params
		methodBuilder.addParameter(ParameterSpec.builder(Uri.class, "uri").build());
		methodBuilder.addParameter(ParameterSpec.builder(ArrayTypeName.of(String.class), "projection").build());
		methodBuilder.addParameter(ParameterSpec.builder(String.class, "selection").build());
		methodBuilder.addParameter(ParameterSpec.builder(ArrayTypeName.of(String.class), "selectionArgs").build());
		methodBuilder.addParameter(ParameterSpec.builder(String.class, "sortOrder").build());

		methodBuilder.returns(Cursor.class);

		SqlBuilderHelper.generateLogForContentProviderBeginning(method, methodBuilder);

		JQLChecker jqlChecker = JQLChecker.getInstance();
		SplittedSql splittedSql = generateSQL(method, methodBuilder, true);

		List<JQLPlaceHolder> placeHolders = jqlChecker.extractFromVariableStatement(method, splittedSql.sqlWhereStatement);
		// remove placeholder for dynamic where, we are not interested here
		placeHolders = SqlBuilderHelper.removeDynamicPlaceHolder(placeHolders);
		AssertKripton.assertTrue(placeHolders.size() == method.contentProviderUriVariables.size(),
				"In '%s.%s' content provider URI path variables and variables in where conditions are different. If SQL uses parameters, they must be defined in URI path.", daoDefinition.getName(),
				method.getName());

		Set<JQLProjection> projectedColumns = jqlChecker.extractProjections(method, method.jql.value, entity);
		for (JQLProjection item : projectedColumns) {
			if (item.type == ProjectionType.COLUMN) {
				if (item.alias != null) {
					columns.add(entity.get(item.alias.trim()).columnName);
				} else {
					columns.add(entity.get(item.column.trim()).columnName);
				}
			} else {
				columns.add(item.expression.trim());
			}
		}

		methodBuilder.addStatement("$T _contentValues=contentValues()", KriptonContentValues.class);
		methodBuilder.addStatement("$T _sqlBuilder=sqlBuilder()", StringBuilder.class);
		SqlModifyBuilder.generateInitForDynamicWhereVariables(method, methodBuilder, "selection", "selectionArgs");

		methodBuilder.addStatement("$T _projectionBuffer=new $T()", StringBuilder.class, StringBuilder.class);
		if (method.jql.isOrderBy()) {
			methodBuilder.addStatement("String _sortOrder=sortOrder");
		}

		methodBuilder.addStatement("_sqlBuilder.append($S)", splittedSql.sqlBasic);

		SqlBuilderHelper.generateWhereCondition(methodBuilder, method, false);

		generateDynamicPartOfQuery(method, methodBuilder, splittedSql, false);

		// generate and check columns
		{
			methodBuilder.addCode("\n// manage projected columns\n");
			methodBuilder.addStatement("String _columnSeparator=\"\"");
			methodBuilder.beginControlFlow("if (projection!=null && projection.length>0)");
			// generate projected column check
			String columnCheckSetName = SqlBuilderHelper.generateColumnCheckSet(builder, method, columns);
			SqlBuilderHelper.forEachColumnInContentValue(methodBuilder, method, "projection", true, new OnColumnListener() {

				@Override
				public void onColumnCheck(MethodSpec.Builder methodBuilder, String projectedColumnVariable) {
					methodBuilder.addStatement("_projectionBuffer.append(_columnSeparator + $L)", projectedColumnVariable);
					methodBuilder.addStatement("_columnSeparator=\", \"");
				}
			});
			methodBuilder.nextControlFlow("else");
			methodBuilder.beginControlFlow("for (String column: $L)", columnCheckSetName);
			methodBuilder.addStatement("_projectionBuffer.append(_columnSeparator + column)");
			methodBuilder.addStatement("_columnSeparator=\", \"");
			methodBuilder.endControlFlow();
			methodBuilder.endControlFlow();

			int i = 0;
			// extract pathVariables
			// every controls was done in constructor of SQLiteModelMethod
			for (ContentUriPlaceHolder variable : method.contentProviderUriVariables) {
				AssertKripton.assertTrue(SqlBuilderHelper.validate(variable.value, placeHolders, i), "In '%s.%s' content provider URI path and where conditions must use same set of variables",
						daoDefinition.getName(), method.getName());

				SQLProperty entityProperty = entity.get(variable.value);
				TypeName methodParameterType = method.findParameterTypeByAliasOrName(variable.value);

				methodBuilder.addCode("// Add parameter $L at path segment $L\n", variable.value, variable.pathSegmentIndex);
				// methodBuilder.addStatement("_sqlWhereParams.add(uri.getPathSegments().get($L))",
				// variable.pathSegmentIndex);
				methodBuilder.addStatement("_contentValues.addWhereArgs(uri.getPathSegments().get($L))", variable.pathSegmentIndex);

				if (entityProperty != null) {

					AssertKripton.assertTrue(TypeUtility.isTypeIncludedIn(entityProperty.getPropertyType().getTypeName(), String.class, Long.class, Long.TYPE),
							"In '%s.%s' content provider URI path variables %s must be String of Long type", daoDefinition.getName(), method.getName(), entityProperty.getName());
				} else if (methodParameterType != null) {
					AssertKripton.assertTrue(TypeUtility.isTypeIncludedIn(methodParameterType, String.class, Long.class, Long.TYPE),
							"In '%s.%s' content provider URI path variables %s must be String of Long type", daoDefinition.getName(), method.getName(),
							method.findParameterNameByAlias(variable.value));
				}

				i++;
			}
		}

		// _sql must be always defined
		methodBuilder.addStatement("String _sql=String.format(_sqlBuilder.toString(), _projectionBuffer.toString())");
		SqlBuilderHelper.generateLogForSQL(method, methodBuilder);

		SqlBuilderHelper.generateLogForWhereParameters(method, methodBuilder);

		methodBuilder.addCode("\n// execute query\n");
		// methodBuilder.addStatement("Cursor _result =
		// database().rawQuery(_sql, _sqlWhereParams.toArray(new
		// String[_sqlWhereParams.size()]))");
		methodBuilder.addStatement("Cursor _result = database().rawQuery(_sql, _contentValues.whereArgsAsArray())");

		methodBuilder.addStatement("return _result");

		// we add at last javadoc, because need info is built at last.
		SqlBuilderHelper.generateJavaDocForContentProvider(method, methodBuilder);

		methodBuilder.addJavadoc("@param uri $S\n", method.contentProviderUriTemplate.replace("*", "[*]"));
		methodBuilder.addJavadoc("@param selection dynamic part of <code>where</code> statement $L\n", method.hasDynamicWhereConditions() ? "" : "<b>NOT USED</b>");
		methodBuilder.addJavadoc("@param selectionArgs arguments of dynamic part of <code>where</code> statement $L\n", method.hasDynamicWhereConditions() ? "" : "<b>NOT USED</b>");

		methodBuilder.addJavadoc("@return number of effected rows\n");

		builder.addMethod(methodBuilder.build());
	}
983041
void analyze(final MethodResult methodResult) {
        lock.lock();
        try {
            buildPackagePrefix(methodResult.getParentResource().getOriginalClass());

            final List<Instruction> visitedInstructions = interpretRelevantInstructions(methodResult.getInstructions());

            // find project defined methods in invoke occurrences
            final Set<ProjectMethod> projectMethods = findProjectMethods(visitedInstructions);

            // add project methods to global method pool
            projectMethods.forEach(MethodPool.getInstance()::addProjectMethod);

            Element returnedElement = new MethodSimulator().simulate(visitedInstructions);
            final String returnType = methodResult.getOriginalMethodSignature().getReturnType();

            // void resource methods are interpreted later; stop analyzing on error
            if (Types.PRIMITIVE_VOID.equals(returnType)) {
                return;
            }

            if (returnedElement == null) {
                // happens for abstract methods or if there is no return
                return;
            }

            final Set<Object> possibleObjects = returnedElement.getPossibleValues().stream().filter(o -> !(o instanceof HttpResponse))
                    .collect(Collectors.toSet());

            // for non-Response methods add a default if there are non-Response objects or none objects at all
            if (!Types.RESPONSE.equals(returnType)) {
                final HttpResponse defaultResponse = new HttpResponse();

                if (Types.OBJECT.equals(returnType))
                    defaultResponse.getEntityTypes().addAll(returnedElement.getTypes());
                else
                    defaultResponse.getEntityTypes().add(returnType);

                possibleObjects.stream().filter(o -> o instanceof JsonValue).map(o -> (JsonValue) o).forEach(defaultResponse.getInlineEntities()::add);

                defaultResponse.getContentTypes().addAll(methodResult.getResponseMediaTypes());

                methodResult.getResponses().add(defaultResponse);
            }

            // add Response results as well
            returnedElement.getPossibleValues().stream().filter(o -> o instanceof HttpResponse).map(o -> (HttpResponse) o).forEach(methodResult.getResponses()::add);
        } finally {
            lock.unlock();
        }
    }
1075723
public OmdbBuilder setResultType(final ResultType resultType) {
        if (!ResultType.isDefault(resultType)) {
            params.add(Param.RESULT, resultType);
        }
        return this;
    }
550562
void outputStaticInjectionMethods(Class<?> type, FragmentMap fragments,
      NameGenerator nameGenerator, SourceWriteUtil sourceWriteUtil) {
    String methodName = nameGenerator.convertToValidMemberName("injectStatic_" + type.getName());
    SourceSnippetBuilder body = new SourceSnippetBuilder();
    for (InjectionPoint injectionPoint : InjectionPoint.forStaticMethodsAndFields(type)) {
      Member member = injectionPoint.getMember();
      try {
        List<InjectorMethod> staticInjectionHelpers = new ArrayList<InjectorMethod>();

        if (member instanceof Method) {
          MethodLiteral<?, Method> method =
              MethodLiteral.get((Method) member, TypeLiteral.get(member.getDeclaringClass()));
          body.append(methodCallUtil.createMethodCallWithInjection(method, null, nameGenerator,
              staticInjectionHelpers));
        } else if (member instanceof Field) {
          FieldLiteral<?> field =
              FieldLiteral.get((Field) member, TypeLiteral.get(member.getDeclaringClass()));
          body.append(sourceWriteUtil.createFieldInjection(field, null, nameGenerator,
              staticInjectionHelpers));
        }

        outputMethods(staticInjectionHelpers, fragments);
      } catch (NoSourceNameException e) {
        errorManager.logError(e.getMessage(), e);
      }
    }

    // Note that the top-level method that performs static injection will only
    // invoke a bunch of other injector methods.  Therefore, it doesn't matter
    // which package it goes in, and we don't need to invoke getUserPackageName
    // (which is good, because in practice users statically inject types that
    // have no user package name because they're private inner classes!)
    String packageName = type.getPackage().getName();
    InjectorMethod method = SourceSnippets.asMethod(false, "private void " + methodName + "()",
        packageName, body.build());
    GinjectorFragmentOutputter fragment =
        fragments.get(fragmentPackageNameFactory.create(packageName));
    fragment.outputMethod(method);
    fragment.invokeInInitializeStaticInjections(methodName);
  }
1174003
private static List<SFStatementType> getResultTypes(JsonNode result)
  {
    JsonNode resultTypes = result.path("data").path("resultTypes");
    if (resultTypes.isNull() ||
        resultTypes.isMissingNode() ||
        resultTypes.asText().isEmpty())
    {
      return Collections.emptyList();
    }

    String[] typeStrs = resultTypes.asText().split(",");

    List<SFStatementType> res = new ArrayList<>();
    for (String typeStr : typeStrs)
    {
      long typeId = Long.valueOf(typeStr);
      res.add(SFStatementType.lookUpTypeById(typeId));
    }
    return res;
  }
80727
private Class<?> resolveResultJavaType(Class<?> resultType, String property, Class<?> javaType) {
    if (javaType == null && property != null) {
      try {
        MetaClass metaResultType = MetaClass.forClass(resultType, REFLECTOR_FACTORY);
        javaType = metaResultType.getSetterType(property);
      } catch (Exception ignored) {
        // ignore, following null check statement will deal with the
        // situation
      }
    }
    if (javaType == null) {
      javaType = Object.class;
    }
    return javaType;
  }
573661
public void doHttpPut(String url, String templateName, Object model, HttpResponse result) {
        doHttpPut(url, templateName, model, result, null, XmlHttpResponse.CONTENT_TYPE_XML_TEXT_UTF8);
    }
541793
@Override
  public GeneratedCode generate(ClassTemplateSpec templateSpec) {

    String code;
    TSProperties TSProperties = globalConfig.lookupTSProperties(templateSpec);
    if (TSProperties.omit) return null;

    TSSyntax syntax = new TSSyntax(TSProperties);
    try {
      if (templateSpec instanceof RecordTemplateSpec) {
        code = engine.render("rythm-ts/record.txt", syntax.new TSRecordSyntax((RecordTemplateSpec) templateSpec));
      } else if (templateSpec instanceof EnumTemplateSpec) {
        code = engine.render("rythm-ts/enum.txt", syntax.new TSEnumSyntax((EnumTemplateSpec) templateSpec));
      } else if (templateSpec instanceof UnionTemplateSpec) {
        code = engine.render("rythm-ts/union.txt", syntax.new TSUnionSyntax((UnionTemplateSpec) templateSpec));
      } else if (templateSpec instanceof TyperefTemplateSpec) {
        TyperefTemplateSpec typerefSpec = (TyperefTemplateSpec) templateSpec;
        code = engine.render("rythm-ts/typeref.txt", syntax.TSTyperefSyntaxCreate(typerefSpec));
      } else if (templateSpec instanceof FixedTemplateSpec) {
        code = engine.render("rythm-ts/fixed.txt", syntax.TSFixedSyntaxCreate((FixedTemplateSpec) templateSpec));
      } else {
        return null; // Indicates that we are declining to generate code for the type (e.g. map or array)
      }
    } catch (RythmException e) {
      throw new RuntimeException(
        "Internal error in generator while processing " + templateSpec.getFullName(), e);
    }
    TSCompilationUnit compilationUnit =
        new TSCompilationUnit(
            templateSpec.getFullName(), "");
    code = formatter.format(code);
    return new GeneratedCode(compilationUnit, code);
  }
258684
@Override
  public GeneratedCode generate(ClassTemplateSpec templateSpec) {

    String code;
    SwiftProperties swiftProperties = globalConfig.lookupSwiftProperties(templateSpec);
    if (swiftProperties.omit) return null;

    SwiftSyntax syntax = new SwiftSyntax(templateSpec, swiftProperties, globalConfig);
    SwiftyJSON swifty = new SwiftyJSON(syntax);

    try {
      if (templateSpec instanceof RecordTemplateSpec) {
        code = engine.render("rythm-swift/record.txt", templateSpec, syntax, swifty);
      } else if (templateSpec instanceof EnumTemplateSpec) {
        code = engine.render("rythm-swift/enum.txt", templateSpec);
      } else if (templateSpec instanceof UnionTemplateSpec) {
        code = engine.render("rythm-swift/union.txt", templateSpec, syntax, swifty);
      } else {
        return null; // Indicates that we are declining to generate code for the type (e.g. map or array)
      }
    } catch (RythmException e) {
      throw new RuntimeException(
        "Internal error in generator while processing " + templateSpec.getFullName(), e);
    }
    SwiftCompilationUnit compilationUnit =
        new SwiftCompilationUnit(
            templateSpec.getClassName(), "");
    code = formatter.format(code);
    return new GeneratedCode(compilationUnit, code);
  }
1172003
void analyze(final MethodResult methodResult) {
        lock.lock();
        try {
            buildPackagePrefix(methodResult.getParentResource().getOriginalClass());

            determineReturnTypes(methodResult).stream()
                    // FEATURE handle several sub-resource impl's
                    .reduce((l, r) -> JavaUtils.determineMostSpecificType(l, r))
                    .ifPresent(t -> registerSubResourceJob(t, methodResult.getSubResource()));
        } finally {
            lock.unlock();
        }
    }
654366
public static void check(final Object result, final Class<?> targetType) {
        if (result != null && !targetType.isAssignableFrom(result.getClass())) {
            // note: conversion logic may go wrong (e.g. because converter expect collection input mostly and may
            // not work correctly for single element), but anyway overall conversion would be considered failed.
            throw new ResultConversionException(String.format("Failed to convert %s to %s",
                    toStringType(result), targetType.getSimpleName()));
        }
    }
432934
@Override
    public void handleResult(RHI result) {
        if (wrappedResultHandler != null) {
            wrappedResultHandler.handleResult(resultTransformer.transform(result));
        }
    }