Search in sources :

Example 6 with SqlBoxException

use of com.github.drinkjava2.jsqlbox.SqlBoxException in project jSqlBox by drinkjava2.

the class DynamicCompileEngine method javaCodeToClass.

public Class<?> javaCodeToClass(String fullClassName, String javaCode) {
    if (StrUtils.isEmpty(fullClassName))
        throw new SqlBoxException("Can not compile class with empty name");
    if (StrUtils.isEmpty(javaCode))
        throw new SqlBoxException("Can not compile class " + fullClassName + " with empty Java source code");
    Class<?> result = compiledClassCache.get(fullClassName);
    if (result != null)
        return result;
    // long start = System.currentTimeMillis();
    Object instance = null;
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
    ClassFileManager fileManager = new ClassFileManager(compiler.getStandardFileManager(diagnostics, null, null));
    List<JavaFileObject> jfiles = new ArrayList<JavaFileObject>();
    jfiles.add(new CharSequenceJavaFileObject(fullClassName, javaCode));
    List<String> options = new ArrayList<String>();
    options.add("-encoding");
    options.add("UTF-8");
    options.add("-classpath");
    options.add(this.classpath);
    JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, diagnostics, options, null, jfiles);
    boolean success = task.call();
    if (success) {
        JavaClassObject jco = fileManager.getJavaClassObject();
        DynamicClassLoader dynamicClassLoader = new DynamicClassLoader(this.parentClassLoader);
        try {
            result = dynamicClassLoader.loadClass(fullClassName, jco);
        } catch (Exception e) {
            e.printStackTrace();
            throw new SqlBoxException(" \r\r\r <<< Dynamic Class Loadere Error \r", e);
        }
        if (result != null)
            compiledClassCache.put(fullClassName, result);
        else
            throw new SqlBoxException(" \r\r\r <<< Dynamic Class Loadere Null Error \r" + fullClassName);
        return result;
    } else {
        String error = "";
        for (Diagnostic diagnostic : diagnostics.getDiagnostics()) {
            error = error + compilePrint(diagnostic);
        }
        throw new SqlBoxException(error + " \r\r\r <<< Java Source Code Compile Error \r" + javaCode);
    }
}
Also used : SqlBoxException(com.github.drinkjava2.jsqlbox.SqlBoxException) ArrayList(java.util.ArrayList) JavaCompiler(javax.tools.JavaCompiler) Diagnostic(javax.tools.Diagnostic) IOException(java.io.IOException) InvocationTargetException(java.lang.reflect.InvocationTargetException) SqlBoxException(com.github.drinkjava2.jsqlbox.SqlBoxException) JavaFileObject(javax.tools.JavaFileObject) JavaFileObject(javax.tools.JavaFileObject) DiagnosticCollector(javax.tools.DiagnosticCollector)

Example 7 with SqlBoxException

use of com.github.drinkjava2.jsqlbox.SqlBoxException in project jSqlBox by drinkjava2.

the class DynamicCompileEngine method readFileToString.

private static String readFileToString(String filename) {
    String result = null;
    File file = new File(filename);
    FileReader reader = null;
    try {
        reader = new FileReader(file);
        char[] chars = new char[(int) file.length()];
        reader.read(chars);
        result = new String(chars);
        reader.close();
    } catch (IOException e) {
        throw new SqlBoxException("Error happen when open file '" + filename + "'", e);
    } finally {
        if (reader != null)
            try {
                reader.close();
            } catch (IOException e) {
                throw new SqlBoxException("Error happen when closing file '" + filename + "'", e);
            }
    }
    return result;
}
Also used : SqlBoxException(com.github.drinkjava2.jsqlbox.SqlBoxException) FileReader(java.io.FileReader) IOException(java.io.IOException) File(java.io.File)

Example 8 with SqlBoxException

use of com.github.drinkjava2.jsqlbox.SqlBoxException in project jSqlBox by drinkjava2.

the class EntitySqlMapListHandler method explainNetQuery.

/**
 * Replace .** to all fields, replace .## to all PKey and FKey fields only,
 * for example:
 *
 * <pre>
 * u.**  ==> u.id as u_id, u.userName as u_userName, u.address as u_address...
 * u.##  ==> u.id as u_id
 * </pre>
 */
public String explainNetQuery(SqlBoxContext ctx, String sqlString) {
    // NOSONAR
    SqlBoxException.assureNotEmpty(sqlString, "Sql can not be empty");
    String sql = SqlBoxStrUtils.formatSQL(sqlString);
    TableModel[] configModels = EntityNetUtils.objectConfigsToModels(ctx, netConfigObjects);
    int pos = sql.indexOf(".**");
    if (pos < 0)
        pos = sql.indexOf(".##");
    while (pos >= 0) {
        StringBuilder aliasSB = new StringBuilder();
        for (int i = pos - 1; i >= 0; i--) {
            if (SqlBoxStrUtils.isNormalLetters(sql.charAt(i)))
                aliasSB.insert(0, sql.charAt(i));
            else
                break;
        }
        if (aliasSB.length() == 0)
            throw new SqlBoxException(".** can not put at front");
        String alias = aliasSB.toString();
        // NOSONAR
        sql += " ";
        // alias found, not find the table name
        int posAlias = StrUtils.indexOfIgnoreCase(sql, " as " + alias + " ");
        if (posAlias == -1)
            posAlias = StrUtils.indexOfIgnoreCase(sql, " as " + alias + ",");
        if (posAlias == -1)
            posAlias = StrUtils.indexOfIgnoreCase(sql, " as " + alias + ")");
        if (posAlias == -1)
            posAlias = StrUtils.indexOfIgnoreCase(sql, " " + alias + " ");
        if (posAlias == -1)
            posAlias = StrUtils.indexOfIgnoreCase(sql, " " + alias + ",");
        if (posAlias == -1)
            posAlias = StrUtils.indexOfIgnoreCase(sql, " " + alias + ")");
        if (posAlias == -1)
            throw new SqlBoxException("Alias '" + alias + "' not found");
        StringBuilder tableNameSb = new StringBuilder();
        for (int i = posAlias - 1; i >= 0; i--) {
            char c = sql.charAt(i);
            if (SqlBoxStrUtils.isNormalLetters(c))
                tableNameSb.insert(0, c);
            else if (tableNameSb.length() > 0)
                break;
        }
        if (tableNameSb.length() == 0)
            throw new SqlBoxException("Alias '" + alias + "' not found tablename in SQL");
        String tbStr = tableNameSb.toString();
        sql = replaceStarStarToColumn(sql, alias, tbStr, configModels);
        pos = sql.indexOf(".**");
        if (pos < 0)
            pos = sql.indexOf(".##");
    }
    generatedTableModels = configModels;
    return sql;
}
Also used : SqlBoxException(com.github.drinkjava2.jsqlbox.SqlBoxException) TableModel(com.github.drinkjava2.jdialects.model.TableModel)

Example 9 with SqlBoxException

use of com.github.drinkjava2.jsqlbox.SqlBoxException in project jSqlBox by drinkjava2.

the class ActiveRecordUtils method doGuessPreparedSQL.

protected static PreparedSQL doGuessPreparedSQL(ActiveRecord ac, Object... params) {
    // NOSONAR
    int callerPos = 0;
    StackTraceElement[] stacks = Thread.currentThread().getStackTrace();
    for (StackTraceElement stack : stacks) {
        callerPos++;
        if ("com.github.drinkjava2.jsqlbox.ActiveRecord".equals(stack.getClassName()) && "guessPreparedSQL".equals(stack.getMethodName()))
            break;
    }
    String callerClassName = stacks[callerPos].getClassName();
    String callerMethodName = stacks[callerPos].getMethodName();
    Class<?> callerClass = ClassCacheUtils.checkClassExist(callerClassName);
    if (callerClass == null)
        throw new SqlBoxException("Can not find class '" + callerClassName + "'");
    Method callerMethod = ClassCacheUtils.checkMethodExist(callerClass, callerMethodName);
    if (callerMethod == null)
        throw new SqlBoxException("Can not find method '" + callerMethodName + "' in '" + callerClassName + "'");
    PreparedSQL sp = getPreparedSQLNoParamsFromSrcCode(callerClassName, callerMethodName, callerMethod);
    sp.setParams(params);
    return sp;
}
Also used : PreparedSQL(com.github.drinkjava2.jdbpro.inline.PreparedSQL) Method(java.lang.reflect.Method)

Example 10 with SqlBoxException

use of com.github.drinkjava2.jsqlbox.SqlBoxException in project jSqlBox by drinkjava2.

the class ActiveRecordUtils method doGuess.

/**
 * Execute operation to access database, based on current method @Sql annotated
 * String or Text String and parameters, guess a best fit
 * query/update/delete/execute method to run
 *
 * @param ac
 * @param params
 * @return <T> T
 */
@SuppressWarnings("all")
protected static <T> T doGuess(ActiveRecord ac, Object... params) {
    // NOSONAR
    int callerPos = 0;
    StackTraceElement[] stacks = Thread.currentThread().getStackTrace();
    for (StackTraceElement stack : stacks) {
        callerPos++;
        if ("com.github.drinkjava2.jsqlbox.ActiveRecord".equals(stack.getClassName()) && "guess".equals(stack.getMethodName()))
            break;
    }
    String callerClassName = stacks[callerPos].getClassName();
    String callerMethodName = stacks[callerPos].getMethodName();
    Class<?> callerClass = ClassCacheUtils.checkClassExist(callerClassName);
    if (callerClass == null)
        throw new SqlBoxException("Can not find class '" + callerClassName + "'");
    Method callerMethod = ClassCacheUtils.checkMethodExist(callerClass, callerMethodName);
    if (callerMethod == null)
        throw new SqlBoxException("Can not find method '" + callerMethodName + "' in '" + callerClassName + "'");
    PreparedSQL sp = getPreparedSQLNoParamsFromSrcCode(callerClassName, callerMethodName, callerMethod);
    String sql = sp.getSql().trim();
    Class<?>[] handlerClass = sp.getHandlerClasses();
    char dotype;
    if (StrUtils.startsWithIgnoreCase(sql, "select"))
        dotype = 's';
    else if (StrUtils.startsWithIgnoreCase(sql, "delete"))
        dotype = 'u';
    else if (StrUtils.startsWithIgnoreCase(sql, "update"))
        dotype = 'u';
    else if (StrUtils.startsWithIgnoreCase(sql, "insert"))
        dotype = 'u';
    else
        // execute
        dotype = 'e';
    boolean hasQuestionMark = sql.indexOf('?') > -1;
    boolean useTemplate = sql.indexOf(':') > -1 || sql.indexOf("#{") > -1;
    if (useTemplate && hasQuestionMark)
        throw new SqlBoxException("guess() method can not determine use template or normal style for SQL '" + sql + "'");
    boolean isEntityQuery = sql.indexOf(".**") > -1;
    if (isEntityQuery && 's' != dotype)
        throw new SqlBoxException("'.**' entity query style SQL can only start with 'select'");
    Map<String, Object> map = null;
    if (useTemplate)
        map = buildParamMap(callerClassName, callerMethodName, params);
    Object o = null;
    switch(dotype) {
        case 's':
            {
                ResultSetHandler<T> resultSetHandler = buildResultHandler(handlerClass);
                if (isEntityQuery) {
                    if (useTemplate)
                        return (T) ac.ctx().tQuery(new EntityListHandler(ac.getClass()), sql, map);
                    else
                        return (T) ac.ctx().nQuery(new EntityListHandler(ac.getClass()), sql, params);
                } else {
                    if (useTemplate)
                        return ac.ctx().tQuery(resultSetHandler, sql, map);
                    else
                        return ac.ctx().nQuery(resultSetHandler, sql, params);
                }
            }
        case 'u':
            {
                if (useTemplate)
                    o = ac.ctx().tUpdate(sql, map);
                else
                    o = ac.ctx().nUpdate(sql, params);
                return (T) o;
            }
        case 'e':
            {
                if (handlerClass == null) {
                    if (useTemplate)
                        o = ac.ctx().tExecute(sql, map);
                    else
                        o = ac.ctx().nExecute(sql, params);
                    return (T) o;
                }
                ResultSetHandler<T> resultSetHandler = buildResultHandler(handlerClass);
                if (useTemplate)
                    o = ac.ctx().tExecute(resultSetHandler, sql, map);
                else
                    o = ac.ctx().nExecute(resultSetHandler, sql, params);
                return (T) o;
            }
        default:
            return null;
    }
}
Also used : PreparedSQL(com.github.drinkjava2.jdbpro.inline.PreparedSQL) Method(java.lang.reflect.Method) EntityListHandler(com.github.drinkjava2.jsqlbox.handler.EntityListHandler) ResultSetHandler(org.apache.commons.dbutils.ResultSetHandler)

Aggregations

Method (java.lang.reflect.Method)9 TableModel (com.github.drinkjava2.jdialects.model.TableModel)8 ColumnModel (com.github.drinkjava2.jdialects.model.ColumnModel)6 SqlBoxException (com.github.drinkjava2.jsqlbox.SqlBoxException)6 PreparedSQL (com.github.drinkjava2.jdbpro.inline.PreparedSQL)5 ArrayList (java.util.ArrayList)5 HashMap (java.util.HashMap)3 IOException (java.io.IOException)2 Type (com.github.drinkjava2.jdialects.Type)1 GenerationType (com.github.drinkjava2.jdialects.annotation.jpa.GenerationType)1 IdGenerator (com.github.drinkjava2.jdialects.id.IdGenerator)1 IdentityIdGenerator (com.github.drinkjava2.jdialects.id.IdentityIdGenerator)1 FKeyModel (com.github.drinkjava2.jdialects.model.FKeyModel)1 Sql (com.github.drinkjava2.jsqlbox.annotation.Sql)1 EntityListHandler (com.github.drinkjava2.jsqlbox.handler.EntityListHandler)1 File (java.io.File)1 FileReader (java.io.FileReader)1 Annotation (java.lang.annotation.Annotation)1 InvocationTargetException (java.lang.reflect.InvocationTargetException)1 SQLException (java.sql.SQLException)1