Define javadoc for content uri.

@param builder
the builder
@param method
the method
5708
private void defineJavadocForContentUri(MethodSpec.Builder builder, SQLiteModelMethod method) {
		String contentUri = method.contentProviderUri().replace("*", "[*]");

		classBuilder.addJavadoc("<tr><td><pre>$L</pre></td><td>{@link $LImpl#$L}</td></tr>\n", contentUri, method.getParent().getName(), method.contentProviderMethodName);
		builder.addJavadoc("<tr><td><pre>$L</pre></td><td>{@link $LImpl#$L}</td></tr>\n", contentUri, method.getParent().getName(), method.contentProviderMethodName);

	}
370528
public void addMethod(final String resource, final ResourceMethod method) {
        resources.putIfAbsent(resource, new HashSet<>());
        resources.get(resource).add(method);
    }
1305103
@Override
    public void newDoc() throws IOException {
        sb = new StringBuilder();
        baos = new ByteArrayOutputStream();
        generator = jsonFactory.createJsonGenerator(baos);
        generator.writeStartObject(); 
    }
1006768
public void doGeneric(String method, HttpServletRequest request, HttpServletResponse response) {
    try {
      ServletUtils.startTransaction(request.getHeader("User-Agent"));

      // Note that getServletPath does an un-escape so that the %24 of job id's are turned into $ characters.
      String uri = request.getServletPath();

      Properties headers = new Properties();
      Enumeration<String> en = request.getHeaderNames();
      while (en.hasMoreElements()) {
        String key = en.nextElement();
        String value = request.getHeader(key);
        headers.put(key, value);
      }

      final String contentType = request.getContentType();
      Properties parms = new Properties();
      String postBody = null;
      if (System.getProperty(H2O.OptArgs.SYSTEM_PROP_PREFIX + "debug.cors") != null) {
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type");
      }

      if (contentType != null && contentType.startsWith(MIME_JSON)) {
        StringBuffer jb = new StringBuffer();
        String line = null;
        try {
          BufferedReader reader = request.getReader();
          while ((line = reader.readLine()) != null)
            jb.append(line);
        } catch (Exception e) {
          throw new H2OIllegalArgumentException("Exception reading POST body JSON for URL: " + uri);
        }
        postBody = jb.toString();
      } else {
        // application/x-www-form-urlencoded
        Map<String, String[]> parameterMap;
        parameterMap = request.getParameterMap();
        for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
          String key = entry.getKey();
          String[] values = entry.getValue();

          if (values.length == 1) {
            parms.put(key, values[0]);
          } else if (values.length > 1) {
            StringBuilder sb = new StringBuilder();
            sb.append("[");
            boolean first = true;
            for (String value : values) {
              if (!first) sb.append(",");
              sb.append("\"").append(value).append("\"");
              first = false;
            }
            sb.append("]");
            parms.put(key, sb.toString());
          }
        }
      }

      // Make serve() call.
      NanoResponse resp = serve(uri, method, headers, parms, postBody);

      // Un-marshal Nano response back to Jetty.
      String choppedNanoStatus = resp.status.substring(0, 3);
      assert (choppedNanoStatus.length() == 3);
      int sc = Integer.parseInt(choppedNanoStatus);
      ServletUtils.setResponseStatus(response, sc);

      response.setContentType(resp.mimeType);

      Properties header = resp.header;
      Enumeration<Object> en2 = header.keys();
      while (en2.hasMoreElements()) {
        String key = (String) en2.nextElement();
        String value = header.getProperty(key);
        response.setHeader(key, value);
      }

      resp.writeTo(response.getOutputStream());

    } catch (IOException e) {
      e.printStackTrace();
      ServletUtils.setResponseStatus(response, 500);
      Log.err(e);
      // Trying to send an error message or stack trace will produce another IOException...
    } finally {
      ServletUtils.logRequest(method, request, response);
      // Handle shutdown if it was requested.
      if (H2O.getShutdownRequested()) {
        (new Thread() {
          public void run() {
            boolean [] confirmations = new boolean[H2O.CLOUD.size()];
            if (H2O.SELF.index() >= 0) {
              confirmations[H2O.SELF.index()] = true;
            }
            for(H2ONode n:H2O.CLOUD._memary) {
              if(n != H2O.SELF)
                new RPC<>(n, new UDPRebooted.ShutdownTsk(H2O.SELF,n.index(), 1000, confirmations, 0)).call();
            }
            try { Thread.sleep(2000); }
            catch (Exception ignore) {}
            int failedToShutdown = 0;
            // shutdown failed
            for(boolean b:confirmations)
              if(!b) failedToShutdown++;
            Log.info("Orderly shutdown: " + (failedToShutdown > 0? failedToShutdown + " nodes failed to shut down! ":"") + " Shutting down now.");
            H2O.closeAll();
            H2O.exit(failedToShutdown);
          }
        }).start();
      }
      ServletUtils.endTransaction();
    }
  }
995174
public void buildReturnCode(MethodSpec.Builder methodBuilder, boolean updateMode, SQLiteModelMethod method, TypeName returnType) {
		if (returnType == TypeName.VOID) {

		} else if (isTypeIncludedIn(returnType, Boolean.TYPE, Boolean.class)) {
			methodBuilder.addJavadoc("\n");
			if (updateMode)
				methodBuilder.addJavadoc("@return <code>true</code> if record is updated, <code>false</code> otherwise");
			else
				methodBuilder.addJavadoc("@return <code>true</code> if record is deleted, <code>false</code> otherwise");
			methodBuilder.addJavadoc("\n");

			methodBuilder.addCode("return result!=0;\n");
		} else if (isTypeIncludedIn(returnType, Long.TYPE, Long.class, Integer.TYPE, Integer.class, Short.TYPE, Short.class)) {
			methodBuilder.addJavadoc("\n");
			if (updateMode) {
				methodBuilder.addJavadoc("@return number of updated records");
			} else {
				methodBuilder.addJavadoc("@return number of deleted records");
			}
			methodBuilder.addJavadoc("\n");

			methodBuilder.addCode("return result;\n");
		} else {
			// more than one listener found
			throw (new InvalidMethodSignException(method, "invalid return type"));
		}
	}
559007
public static void generate(TypeSpec.Builder classBuilder, SQLiteModelMethod method) {
		InsertType insertResultType = detectInsertType(method);

		// if true, field must be associate to ben attributes
		TypeName returnType = method.getReturnClass();

		AssertKripton.failWithInvalidMethodSignException(insertResultType == null, method);

		// generate method code
		MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder(method.getName()).addAnnotation(Override.class)
				.addModifiers(Modifier.PUBLIC);

		ParameterSpec parameterSpec;
		for (Pair<String, TypeName> item : method.getParameters()) {
			parameterSpec = ParameterSpec.builder(item.value1, item.value0).build();
			methodBuilder.addParameter(parameterSpec);
		}
		methodBuilder.returns(returnType);

		// fail if we use jql to INSERT_BEAN with operation of INSERT-FOR-SELECT
		// AssertKripton.failWithInvalidMethodSignException(insertResultType ==
		// InsertType.INSERT_BEAN && method.jql.containsSelectOperation, method,
		// "INSERT-FROM-SELECT SQL can not be used with method sign");

		// generate inner code
		methodBuilder.addComment("Specialized Insert - $L - BEGIN", insertResultType.getClass().getSimpleName());
		insertResultType.generate(classBuilder, methodBuilder, method, returnType);
		methodBuilder.addComment("Specialized Insert - $L - END", insertResultType.getClass().getSimpleName());

		MethodSpec methodSpec = methodBuilder.build();
		classBuilder.addMethod(methodSpec);

		if (method.contentProviderEntryPathEnabled) {
			// we need to generate insert for content provider to
			generateInsertForContentProvider(classBuilder, method, insertResultType);
		}

	}
928314
public RequestBuilder request(String method, URL url) {
        try {
            RequestBuilder req = new RequestBuilder();
            req.host = url.getHost();
            req.port = url.getPort() < 0 ? url.getDefaultPort() : url.getPort();
            HttpURI httpURI = new HttpURI(url.toURI());
            if (!StringUtils.hasText(httpURI.getPath().trim())) {
                httpURI.setPath("/");
            }
            req.request = new MetaData.Request(method, httpURI, HttpVersion.HTTP_1_1, new HttpFields());
            return req;
        } catch (URISyntaxException e) {
            log.error("url exception", e);
            throw new IllegalArgumentException(e);
        }
    }
1364522
public static void generateWhereCondition(MethodSpec.Builder methodBuilder, SQLiteModelMethod method, Pair<String, List<Pair<String, TypeName>>> where) {
		boolean nullable;

		// methodBuilder.addStatement("$T<String>
		// _sqlWhereParams=getWhereParamsArray()", ArrayList.class);

		for (Pair<String, TypeName> item : where.value1) {
			String resolvedParamName = method.findParameterNameByAlias(item.value0);
			// methodBuilder.addCode("_sqlWhereParams.add(");
			methodBuilder.addCode("_contentValues.addWhereArgs(");

			nullable = isNullable(item.value1);

			if (nullable && !method.hasAdapterForParam(item.value0)) {
				// transform null in ""
				methodBuilder.addCode("($L==null?\"\":", resolvedParamName);
			}

			// check for string conversion
			TypeUtility.beginStringConversion(methodBuilder, item.value1);

			SQLTransformer.javaMethodParam2WhereConditions(methodBuilder, method, resolvedParamName, item.value1);
			// check for string conversion
			TypeUtility.endStringConversion(methodBuilder, item.value1);

			if (nullable && !method.hasAdapterForParam(item.value0)) {
				methodBuilder.addCode(")");
			}

			methodBuilder.addCode(");\n");
		}
	}
1133570
static void generateLogForContentProviderBeginning(SQLiteModelMethod method, MethodSpec.Builder methodBuilder) {
		if (method.getParent().isLogEnabled()) {
			methodBuilder.addStatement("$T.info($S, uri.toString())", Logger.class, "Execute " + method.jql.operationType + " for URI %s");
		}

	}
1026055
private void addMethodInfo(MethodDoc method, Content dl) {
        ClassDoc[] intfacs = method.containingClass().interfaces();
        MethodDoc overriddenMethod = method.overriddenMethod();
        // Check whether there is any implementation or overridden info to be
        // printed. If no overridden or implementation info needs to be
        // printed, do not print this section.
        if ((intfacs.length > 0 &&
                new ImplementedMethods(method, this.configuration).build().length > 0) ||
                overriddenMethod != null) {
            MethodWriterImpl.addImplementsInfo(this, method, dl);
            if (overriddenMethod != null) {
                MethodWriterImpl.addOverridden(this,
                        method.overriddenType(), overriddenMethod, dl);
            }
        }
    }
332743
protected MethodSpec.Builder generateMethodBuilder(SQLiteModelMethod method) {
		MethodSpec.Builder methodBuilder;
		if (method.hasLiveData()) {
			methodBuilder = MethodSpec.methodBuilder(method.getName() + LIVE_DATA_PREFIX).addModifiers(Modifier.PROTECTED);
		} else {
			methodBuilder = MethodSpec.methodBuilder(method.getName()).addAnnotation(Override.class).addModifiers(Modifier.PUBLIC);
		}

		return methodBuilder;
	}
33353
public static void generateJavadocGeneratedBy(Builder builder) {
		if (!BindDataSourceSubProcessor.JUNIT_TEST_MODE) {
			builder.addJavadoc("<p><strong>This class is generated by Kripton Annotation Processor - v. $L</strong></p>\n", Version.getVersion());
			builder.addJavadoc("<p><strong>Generation-time: $L</strong></p>\n\n", (new Date()).toString());
		}
	}
1357659
public AnnotatedTypeBuilder<X> addToMethod(Method method, Annotation annotation) {
       if (methods.get(method) == null) {
           methods.put(method, new AnnotationBuilder());
       }
       methods.get(method).add(annotation);
       return this;
   }
529144
public static void generateLog(final SQLiteModelMethod method, MethodSpec.Builder methodBuilder) {
		SQLiteDaoDefinition daoDefinition = method.getParent();

		// log is enabled
		if (daoDefinition.isLogEnabled()) {
			// generate log section - BEGIN
			methodBuilder.addComment("log section BEGIN");
			methodBuilder.beginControlFlow("if (_context.isLogEnabled())");

			methodBuilder.addCode("// log for insert -- BEGIN \n");

			JQLChecker checker = JQLChecker.getInstance();
			final One<Boolean> inWhere = new One<Boolean>(false);

			String sql = checker.replace(method, method.jql, new JQLReplacerListenerImpl(method) {

				@Override
				public String onBindParameter(String bindParameterName, boolean inStatement) {
					if (inWhere.value0) {
						return "?";
					}

					return null;
				}

				@Override
				public void onWhereStatementBegin(Where_stmtContext ctx) {
					super.onWhereStatementBegin(ctx);

					inWhere.value0 = true;
				}

				@Override
				public void onWhereStatementEnd(Where_stmtContext ctx) {
					super.onWhereStatementEnd(ctx);

					inWhere.value0 = false;
				}
			});

			if (method.jql.containsSelectOperation) {
				// log
				// manage log
				methodBuilder.addCode("\n");
				methodBuilder.addStatement("$T.info($S)", Logger.class, sql);
			} else {
				sql = checker.replaceVariableStatements(method, sql, new JQLReplaceVariableStatementListenerImpl() {

					@Override
					public String onColumnNameSet(String statement) {
						return "%s";
					}

					@Override
					public String onColumnValueSet(String statement) {
						return "%s";
					}
				});

				methodBuilder.addStatement("$T _columnNameBuffer=new $T()", StringBuffer.class, StringBuffer.class);
				methodBuilder.addStatement("$T _columnValueBuffer=new $T()", StringBuffer.class, StringBuffer.class);
				methodBuilder.addStatement("String _columnSeparator=$S", "");

				SqlBuilderHelper.forEachColumnInContentValue(methodBuilder, method, "_contentValues.keys()", false, new OnColumnListener() {

					@Override
					public void onColumnCheck(MethodSpec.Builder methodBuilder, String columNameVariable) {
						methodBuilder.addStatement("_columnNameBuffer.append(_columnSeparator+$L)", columNameVariable);
						methodBuilder.addStatement("_columnValueBuffer.append(_columnSeparator+$S+$L)", ":", columNameVariable);
						methodBuilder.addStatement("_columnSeparator=$S", ", ");

					}
				});

				methodBuilder.addStatement("$T.info($S, _columnNameBuffer.toString(), _columnValueBuffer.toString())", Logger.class, sql);
			}
			generateLogForContentValues(method, methodBuilder);

			methodBuilder.addCode("// log for insert -- END \n\n");
			SqlBuilderHelper.generateLogForWhereParameters(method, methodBuilder);

			// generate log section - END
			methodBuilder.endControlFlow();
			methodBuilder.addComment("log section END");
		}
	}
976759
private static void generateInsertForContentProvider(TypeSpec.Builder classBuilder, final SQLiteModelMethod method,
			InsertType insertResultType) {
		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);
		}

		ParameterSpec parameterSpec;
		parameterSpec = ParameterSpec.builder(Uri.class, "uri").build();
		methodBuilder.addParameter(parameterSpec);
		parameterSpec = ParameterSpec.builder(ContentValues.class, "contentValues").build();
		methodBuilder.addParameter(parameterSpec);
		methodBuilder.returns(Long.TYPE);

		SqlBuilderHelper.generateLogForContentProviderBeginning(method, methodBuilder);

		// just detect which columns are admitted
		JQLChecker.getInstance().replace(method, method.jql, new JQLReplacerListenerImpl(method) {

			@Override
			public String onColumnName(String columnName) {
				SQLProperty tempProperty = entity.get(columnName);
				AssertKripton.assertTrueOrUnknownPropertyInJQLException(tempProperty != null, method, columnName);

				columns.add(tempProperty.columnName);

				return tempProperty.columnName;

			}

			@Override
			public String onColumnFullyQualifiedName(String tableName, String columnName) {
				AssertKripton.fail("Inconsistent state");
				return null;
			}

		});

		// generate columnCheckSet
		SqlBuilderHelper.generateColumnCheckSet(classBuilder, method, columns);

		// retrieve content values
		methodBuilder.addStatement("$T _contentValues=contentValuesForContentProvider(contentValues)",
				KriptonContentValues.class);

		// generate column check
		SqlBuilderHelper.forEachColumnInContentValue(methodBuilder, method, "_contentValues.values().keySet()", true,
				null);

		methodBuilder.addCode("\n");

		String rxIdGetter = "result";

		// extract pathVariables
		// generate get uri variables in content values
		// every controls was done in constructor of SQLiteModelMethod
		for (ContentUriPlaceHolder variable : method.contentProviderUriVariables) {
			SQLProperty entityProperty = entity.get(variable.value);

			if (entityProperty != null) {
				methodBuilder.addCode("// Add parameter $L at path segment $L\n", variable.value,
						variable.pathSegmentIndex);
				TypeName entityPropertyType = entityProperty.getPropertyType().getTypeName();
				if (TypeUtility.isString(entityPropertyType)) {
					methodBuilder.addStatement("contentValues.put($S, uri.getPathSegments().get($L))",
							entityProperty.columnName, variable.pathSegmentIndex);
				} else {
					methodBuilder.addStatement("contentValues.put($S, Long.valueOf(uri.getPathSegments().get($L)))",
							entityProperty.columnName, variable.pathSegmentIndex);
				}
			}

			if (entityProperty.isPrimaryKey()) {
				rxIdGetter = PropertyUtility.getter(entityProperty);
			}
		}

		// generate log for inser operation
		SqlBuilderHelper.generateLogForContentValuesContentProvider(method, methodBuilder);

		ConflictAlgorithmType conflictAlgorithmType = InsertBeanHelper.getConflictAlgorithmType(method);
		String conflictString1 = "";
		String conflictString2 = "";
		if (conflictAlgorithmType != ConflictAlgorithmType.NONE) {
			conflictString1 = "WithOnConflict";
			conflictString2 = ", " + conflictAlgorithmType.getConflictAlgorithm();
			methodBuilder.addCode("// conflict algorithm $L\n", method.jql.conflictAlgorithmType);
		}

		methodBuilder.addComment("insert operation");
		methodBuilder.addStatement("long result = database().insert$L($S, null, _contentValues.values()$L)",
				conflictString1, entity.getTableName(), conflictString2);
		if (method.getParent().getParent().generateRx) {
			SQLProperty primaryKey = entity.getPrimaryKey();
			if (primaryKey.columnType == ColumnType.PRIMARY_KEY) {
				// long autogenerated
				rxIdGetter = "result";
			} else {

				if (primaryKey.isType(String.class)) {
					rxIdGetter = String.format("contentValues.getAsString(\"%s\")", primaryKey.columnName);
				} else {
					rxIdGetter = String.format("contentValues.getAsLong(\"%s\")", primaryKey.columnName);
				}
			}

			GenericSQLHelper.generateSubjectNext(entity, methodBuilder, SubjectType.INSERT, rxIdGetter);
		}

		// support for livedata
		if (daoDefinition.hasLiveData()) {
			methodBuilder.addComment("support for livedata");
			methodBuilder.addStatement(BindDaoBuilder.METHOD_NAME_REGISTRY_EVENT + "(result>0?1:0)");
		}

		methodBuilder.addStatement("return result");

		// javadoc
		// 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 contentValues content values\n");

		methodBuilder.addJavadoc("@return new row's id\n");

		classBuilder.addMethod(methodBuilder.build());
	}
908361
public void setMethod(String method) {
	method = method.toLowerCase();
	if (method.equals("loop")) this.method = MODE_LOOP;
	else if (method.equals("exittag")) this.method = MODE_EXIT_TAG;
	else if (method.equals("exittemplate")) this.method = MODE_EXIT_TEMPLATE;
    }
1195269
public void buildMethodSubHeader(XMLNode node, Content methodsContentTree)  {
        methodWriter.addMemberHeader((ExecutableElement)currentMember, methodsContentTree);
    }