Resolves user, author, terms and meta for a post.
@param post The post builder.
@return The builder with resolved items.
@throws SQLException on database error.
502871
public Post.Builder resolve(final Post.Builder post) throws SQLException {
      Timer.Context ctx = metrics.resolvePostTimer.time();
      try {
         User author = resolveUser(post.getAuthorId());
         if(author != null) {
            List<Meta> meta = userMetadata(post.getAuthorId());
            if(meta.size() > 0) {
               author = author.withMetadata(meta);
            }
            post.setAuthor(author);
         }

         List<Meta> meta = selectPostMeta(post.getId());
         if(meta.size() > 0) {
            post.setMetadata(meta);
         }

         List<TaxonomyTerm> terms = selectPostTerms(post.getId());
         if(terms.size() > 0) {
            post.setTaxonomyTerms(terms);
         }

         List<Post> children = selectChildren(post.getId(), false);
         if(children.size() > 0) {
            post.setChildren(children);
         }
         return post;
      } finally {
         ctx.stop();
      }
   }
928827
public static void sqluser(StringBuilder buf, List<? extends CharSequence> parsedArgs) throws SQLException {
    zeroArgumentFunctionCall(buf, "user", "user", parsedArgs);
  }
317403
public void generateJavaDoc(MethodSpec.Builder methodBuilder, final SQLiteModelMethod method, TypeName returnType,
			List<SQLProperty> listUsedProperty, ModelProperty primaryKey) {
		// transform JQL to SQL
		String sqlInsert = JQLChecker.getInstance().replace(method, method.jql, new JQLReplacerListenerImpl(method) {

			@Override
			public String onColumnName(String columnName) {
				Set<SQLProperty> property = currentSchema.getPropertyBySimpleName(columnName);

				SQLProperty tempProperty = property.iterator().next();
				AssertKripton.assertTrueOrUnknownPropertyInJQLException(tempProperty != null, method, columnName);

				return tempProperty.columnName;
			}

			@Override
			public String onBindParameter(String bindParameterName, boolean inStatement) {
				String resolvedParamName = method.findParameterNameByAlias(bindParameterName);

				return SqlAnalyzer.PARAM_PREFIX + resolvedParamName + SqlAnalyzer.PARAM_SUFFIX;
			}

		});

		// generate javadoc and result
		{
			String beanNameParameter = method.findParameterAliasByName(method.getParameters().get(0).value0);

			methodBuilder.addJavadoc("<h2>SQL insert</h2>\n");
			methodBuilder.addJavadoc("<pre>$L</pre>\n\n", sqlInsert);
			methodBuilder.addJavadoc(
					"<p><code>$L.$L</code> is automatically updated because it is the primary key</p>\n",
					beanNameParameter, primaryKey.getName());
			methodBuilder.addJavadoc("\n");

			// list of inserted fields
			methodBuilder.addJavadoc("<p><strong>Inserted columns:</strong></p>\n");
			methodBuilder.addJavadoc("<dl>\n");
			for (SQLProperty property : listUsedProperty) {
				methodBuilder.addJavadoc("\t<dt>$L</dt>", property.columnName);
				methodBuilder.addJavadoc("<dd>is mapped to <strong>$L</strong></dd>\n",
						SqlAnalyzer.PARAM_PREFIX + method.findParameterAliasByName(method.getParameters().get(0).value0)
								+ "." + method.findParameterNameByAlias(property.getName()) + SqlAnalyzer.PARAM_SUFFIX);
			}
			methodBuilder.addJavadoc("</dl>\n\n");

			// update bean have only one parameter: the bean to update
			for (Pair<String, TypeName> param : method.getParameters()) {
				methodBuilder.addJavadoc("@param $L", param.value0);
				methodBuilder.addJavadoc("\n\tis mapped to parameter <strong>$L</strong>\n",
						method.findParameterAliasByName(param.value0));
			}

			InsertRawHelper.generateJavaDocReturnType(methodBuilder, returnType);
		}
	}
945921
public <T> List<T> query(String sql, Class<T> beanClass, Object... params) throws SQLException {
		return query(sql, new BeanListHandler<T>(beanClass), params);
	}
1302730
public static void generateGenericExecSQL(MethodSpec.Builder methodBuilder, final SQLiteModelMethod method) {

		boolean nullable;
		final List<String> paramsList = new ArrayList<String>();
		final List<String> contentValueList = new ArrayList<String>();
		final One<Boolean> columnsToUpdate = new One<Boolean>(true);

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

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

				columnsToUpdate.value0 = false;
			}

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

				columnsToUpdate.value0 = true;
			}

			@Override
			public String onColumnName(String columnName) {
				String resolvedName = currentSchema.findColumnNameByPropertyName(method, columnName);
				AssertKripton.assertTrueOrUnknownPropertyInJQLException(resolvedName != null, method, columnName);

				return resolvedName;

			}

			@Override
			public String onBindParameter(String bindParameterName, boolean inStatement) {
				String propertyName = method.findParameterAliasByName(bindParameterName);

				if (columnsToUpdate.value0) {
					contentValueList.add(propertyName);
				} else {
					paramsList.add(propertyName);
				}
				return "?";
			}
		});

		// update/insert columns
		final SQLiteEntity entity = method.getEntity();
		for (String item : contentValueList) {
			// ASSERT: property is always in entity
			String propertyName = method.findParameterNameByAlias(item);
			TypeName paramType = method.findParameterTypeByAliasOrName(item);

			SQLProperty property = entity.get(item);

			if (propertyName == null)
				throw (new PropertyNotFoundException(method, propertyName, paramType));

			Pair<String, TypeName> methodParam = new Pair<String, TypeName>(propertyName, paramType);

			// check same type
			TypeUtility.checkTypeCompatibility(method, methodParam, property);
			// check nullabliity
			// nullable = TypeUtility.isNullable(method, methodParam, property);
			//
			// if (nullable) {
			// // it use raw method param's typeName
			// methodBuilder.beginControlFlow("if ($L!=null)", methodParam.value0);
			// }

			if (method.isLogEnabled()) {
				methodBuilder.addCode("_contentValues.put($S, ", property.columnName);
			} else {
				methodBuilder.addCode("_contentValues.put(");
			}

			// it does not need to be converted in string
			SQLTransformer.javaMethodParam2ContentValues(methodBuilder, method, methodParam.value0, methodParam.value1,
					property);
			methodBuilder.addCode(");\n");
			// if (nullable) {
			// methodBuilder.nextControlFlow("else");
			//
			// if (method.isLogEnabled()) {
			// methodBuilder.addStatement("_contentValues.putNull($S)", property.columnName);
			// } else {
			// methodBuilder.addStatement("_contentValues.putNull()");
			// }
			//
			// methodBuilder.endControlFlow();
			// }

		}

		// where condition
		methodBuilder.addComment("build where condition");
		{
			// String separator = "";
			TypeName paramType;
			String realName;

			for (String item : paramsList) {
				methodBuilder.addCode("_contentValues.addWhereArgs(");

				paramType = method.findParameterTypeByAliasOrName(item);
				realName = method.findParameterNameByAlias(item);

				AssertKripton.assertTrueOrUnknownPropertyInJQLException(paramType != null, method, item);

				// code for query arguments
				nullable = TypeUtility.isNullable(paramType);
				if (nullable) {
					methodBuilder.addCode("($L==null?\"\":", realName);
				}

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

				SQLTransformer.javaMethodParam2ContentValues(methodBuilder, method, realName, paramType, null);

				// check for string conversion
				TypeUtility.endStringConversion(methodBuilder, paramType);

				if (nullable) {
					methodBuilder.addCode(")");
				}

				methodBuilder.addCode(");\n");
			}
		}

		// log for where parames
		SqlBuilderHelper.generateLog(method, methodBuilder);

		// log
		methodBuilder.addCode("\n");
		methodBuilder.addStatement("database().execSQL($S, _contentValues.whereArgsAsArray())", sql);
	}
206172
public static UroboroSQLBuilder builder(final String url, final String user, final String password,
			final String schema) {
		return builder().setConnectionSupplier(new JdbcConnectionSupplierImpl(url, user, password, schema));
	}
1265079
public User get( Connection conn, int id) throws SQLException {
        ResultSetHandler<User> h = new BeanHandler<User>(User.class);
        String sql =
            "SELECT id,username,fullname,type,emailaddress,registered_ts,invited_by,enabled \n"+
            "FROM userbase \n"+
            "WHERE id=?";
        return run.query(conn, sql, h, id);
    }
1162064
public User resolveUser(final long userId) throws SQLException {
      metrics.userCacheTries.mark();
      User user = userCache.getIfPresent(userId);
      if(user != null) {
         metrics.userCacheHits.mark();
         return user;
      } else {
         user = selectUser(userId);
         if(user != null) {
            userCache.put(userId, user);
         }
         return user;
      }
   }
380795
public function getTermsForPost(AbstractPost $post)
    {
        $terms = array();

        if ($dbTerms = get_the_terms($post->getId(), $this->getName())) {
            foreach ($dbTerms as $termData) {
                $terms[] = $this->termFactory->create($termData, $this);
            }
        }

        return $terms;
    }
823466
@Override
    public ResultSet getSuperTables(String catalog, String schemaPattern, String tableNamePattern) throws SQLException
    {
        checkClosed();
        throw SQLError.noSupport();
    }
672152
public boolean addPostTerm(final long postId, final TaxonomyTerm taxonomyTerm) throws SQLException {

      List<TaxonomyTerm> currTerms = selectPostTerms(postId, taxonomyTerm.taxonomy);
      for(TaxonomyTerm currTerm : currTerms) {
         if(currTerm.term.name.equals(taxonomyTerm.term.name)) {
            return false;
         }
      }

      Connection conn = null;
      PreparedStatement stmt = null;
      Timer.Context ctx = metrics.postTermsSetTimer.time();
      try {
         conn = connectionSupplier.getConnection();
         stmt = conn.prepareStatement(insertPostTermSQL);
         stmt.setLong(1, postId);
         stmt.setLong(2, taxonomyTerm.id);
         stmt.setInt(3, currTerms.size()); //Add at the last position...
         return stmt.executeUpdate() > 0;
      } finally {
         ctx.stop();
         SQLUtil.closeQuietly(conn, stmt);
      }
   }
894764
@Override
	protected void handleException(final SqlContext sqlContext, final SQLException ex) throws SQLException {
		SQLException cause = ex;

		while (cause.getNextException() != null) {
			cause = cause.getNextException();
		}

		if (LOG.isErrorEnabled() && isOutputExceptionLog()) {
			StringBuilder builder = new StringBuilder();
			builder.append(System.lineSeparator()).append("Exception occurred in SQL execution.")
					.append(System.lineSeparator());
			builder.append("Executed SQL[").append(sqlContext.getExecutableSql()).append("]")
					.append(System.lineSeparator());
			if (sqlContext instanceof SqlContextImpl) {
				Parameter[] bindParameters = ((SqlContextImpl) sqlContext).getBindParameters();
				for (int i = 0; i < bindParameters.length; i++) {
					Parameter parameter = getSqlFilterManager().doParameter(bindParameters[i]);
					builder.append("Bind Parameter.[INDEX[").append(i + 1).append("], ").append(parameter.toString())
							.append("]").append(System.lineSeparator());
				}
			}
			LOG.error(builder.toString(), cause);
		}

		throw cause;
	}
633458
public void touchPost(final long postId, final TimeZone tz) throws SQLException {
      if(postId < 1L) {
         throw new SQLException("The post id must be specified for update");
      }

      long modifiedTimestamp = System.currentTimeMillis();

      int offset = tz.getOffset(modifiedTimestamp);
      Connection conn = null;
      PreparedStatement stmt = null;
      Timer.Context ctx = metrics.updatePostTimer.time();
      try {
         conn = connectionSupplier.getConnection();
         stmt = conn.prepareStatement(updatePostModifiedSQL);
         stmt.setTimestamp(1, new Timestamp(modifiedTimestamp));
         stmt.setTimestamp(2, new Timestamp(modifiedTimestamp - offset));
         stmt.setLong(3, postId);
         stmt.executeUpdate();
      } finally {
         ctx.stop();
         SQLUtil.closeQuietly(conn, stmt);
      }
   }
815799
void resolveTypeVariable(SQLiteModelMethod value) {
		// before proceed, we need to resolve typeVariables
		for (Pair<String, TypeName> item : value.getParameters()) {
			item.value1 = typeVariableResolver.resolve(item.value1);
		}

		value.setReturnClass(typeVariableResolver.resolve(value.getReturnClass()));

	}
361956
@Override
    public E resolve(ExtensionId extensionId) throws ResolveException
    {
        E extension = this.extensions.get(extensionId);

        if (extension == null) {
            throw new ExtensionNotFoundException("Can't find extension [" + extensionId + "]");
        }

        return extension;
    }
678309
@Override
    public void postConstruct(Object instance, Object creationMetaData) throws InjectionProviderException
    {
        // TODO the servlet spec is not clear about searching in superclass??
        Class clazz = instance.getClass();
        Method[] methods = getDeclaredMethods(clazz);
        if (methods == null)
        {
            methods = clazz.getDeclaredMethods();
            Map<Class,Method[]> declaredMethodBeansMap = getDeclaredMethodBeansMap();
            synchronized(declaredMethodBeansMap)
            {
                declaredMethodBeansMap.put(clazz, methods);
            }
        }
        Method postConstruct = null;
        for (int i = 0; i < methods.length; i++)
        {
            Method method = methods[i];
            if (method.isAnnotationPresent(PostConstruct.class))
            {
                // a method that does not take any arguments
                // the method must not be static
                // must not throw any checked expections
                // the return value must be void
                // the method may be public, protected, package private or private

                if ((postConstruct != null)
                        || (method.getParameterTypes().length != 0)
                        || (Modifier.isStatic(method.getModifiers()))
                        || (method.getExceptionTypes().length > 0)
                        || (!method.getReturnType().getName().equals("void")))
                {
                    throw new IllegalArgumentException("Invalid PostConstruct annotation");
                }
                postConstruct = method;
            }
        }
        try
        {
            invokeAnnotatedMethod(postConstruct, instance);
        }
        catch (IllegalAccessException ex)
        {
            throw new InjectionProviderException(ex);
        }
        catch (InvocationTargetException ex)
        {
            throw new InjectionProviderException(ex);
        }
    }
390962
public boolean updatePostContent(long postId, final String content) throws SQLException {
      Connection conn = null;
      PreparedStatement stmt = null;
      Timer.Context ctx = metrics.updatePostTimer.time();
      try {
         conn = connectionSupplier.getConnection();
         stmt = conn.prepareStatement(updatePostContentSQL);
         stmt.setString(1, content);
         stmt.setLong(2, postId);
         return stmt.executeUpdate() > 0;
      } finally {
         ctx.stop();
         SQLUtil.closeQuietly(conn, stmt);
      }
   }