diff --git a/base/src/main/java/com/developmentontheedge/be5/base/exceptions/Be5Exception.java b/base/src/main/java/com/developmentontheedge/be5/base/exceptions/Be5Exception.java index f01569c91..53dc565dc 100644 --- a/base/src/main/java/com/developmentontheedge/be5/base/exceptions/Be5Exception.java +++ b/base/src/main/java/com/developmentontheedge/be5/base/exceptions/Be5Exception.java @@ -57,6 +57,11 @@ public static Be5Exception accessDenied() return Be5ErrorCode.ACCESS_DENIED.exception(); } + public static Be5Exception accessDenied(String info) + { + return Be5ErrorCode.ACCESS_DENIED.exception(info); + } + public static Be5Exception accessDeniedToOperation(String entityName, String operationName) { return Be5ErrorCode.ACCESS_DENIED_TO_OPERATION.exception(entityName, operationName); @@ -164,7 +169,7 @@ public static String getMessage(Throwable err) return HtmlUtils.escapeHTML(out.toString()); } - private static String getFullStackTraceLine(StackTraceElement e) + public static String getFullStackTraceLine(StackTraceElement e) { return e.getClassName() + "." + e.getMethodName() + "(" + e.getFileName() + ":" + e.getLineNumber() + ")"; diff --git a/base/src/main/java/com/developmentontheedge/be5/base/exceptions/ErrorTitles.java b/base/src/main/java/com/developmentontheedge/be5/base/exceptions/ErrorTitles.java index 856b0f2bf..b73284848 100644 --- a/base/src/main/java/com/developmentontheedge/be5/base/exceptions/ErrorTitles.java +++ b/base/src/main/java/com/developmentontheedge/be5/base/exceptions/ErrorTitles.java @@ -30,7 +30,7 @@ public class ErrorTitles TITLES.put(UNKNOWN_OPERATION, "Operation not found: $1.$2"); TITLES.put(NOT_FOUND, "Element not found: $1"); - TITLES.put(ACCESS_DENIED, "Access denied"); + TITLES.put(ACCESS_DENIED, "Access denied. $1"); TITLES.put(ACCESS_DENIED_TO_QUERY, "Access denied to query: $1.$2"); TITLES.put(ACCESS_DENIED_TO_OPERATION, "Access denied to operation: $1.$2"); TITLES.put(OPERATION_NOT_ASSIGNED_TO_QUERY, "Operation '$1.$3' not assigned to query: '$2'"); diff --git a/base/src/main/java/com/developmentontheedge/be5/base/services/GroovyRegister.java b/base/src/main/java/com/developmentontheedge/be5/base/services/GroovyRegister.java index 7d7036270..022ba61ef 100644 --- a/base/src/main/java/com/developmentontheedge/be5/base/services/GroovyRegister.java +++ b/base/src/main/java/com/developmentontheedge/be5/base/services/GroovyRegister.java @@ -103,69 +103,6 @@ public static void registerMetaClass(Class metaClazz, Class } } -// public String getErrorCodeLine(Throwable e) -// { -// Set printedGroovyClasses = new HashSet<>(); -// Throwable err = e; -// -// Stack throwables = new Stack<>(); -// throwables.add(err); -// while (err.getCause() != null) -// { -// throwables.add(err.getCause()); -// err = err.getCause(); -// } -// -// StringBuilder sb = new StringBuilder(); -// while (!throwables.empty()) -// { -// err = throwables.pop(); -// -// StackTraceElement[] stackTrace = err.getStackTrace(); -// for (int i = 0; i < stackTrace.length; i++) -// { -// if(stackTrace[i].getFileName() != null && stackTrace[i].getFileName().endsWith(".groovy") -// && !printedGroovyClasses.contains(stackTrace[i].getFileName())) -// { -// printedGroovyClasses.add(stackTrace[i].getFileName()); -// sb.append(getErrorCodeLinesForClass(stackTrace[i])); -// break; -// } -// } -// } -// -// return sb.toString(); -// } -// -// private String getErrorCodeLinesForClass(StackTraceElement e) -// { -// int lineID = e.getLineNumber(); -// StringBuilder sb = new StringBuilder("\n" + Be5Exception.getFullStackTraceLine(e)); -// -// String className = e.getClassName().indexOf('$') == -1 -// ? e.getClassName() -// : e.getClassName().substring(0, e.getClassName().indexOf('$')); -// -// String code = groovyOperationLoaderProvider.get() -// .getByFullName(className + ".groovy") -// .getCode(); -// String lines[] = HtmlUtils.escapeHTML(code).split("\\r?\\n"); -// -// sb.append("\n\n"); -// for (int i = Math.max(0, lineID - 4); i < Math.min(lineID + 3, lines.length); i++) -// { -// String lineNumber = String.format("%4d", i+1)+" | "; -// if(lineID == i+1){ -// sb.append("").append(lineNumber).append(lines[i]).append("\n"); -// }else{ -// sb.append(lineNumber).append(lines[i]).append("\n"); -// } -// } -// sb.append(""); -// -// return sb.toString(); -// } - // // @SuppressWarnings( "unchecked" ) // public static List toCompilationMessages(List errors0) diff --git a/base/src/main/java/com/developmentontheedge/be5/base/services/impl/DataSourceServiceImpl.java b/base/src/main/java/com/developmentontheedge/be5/base/services/impl/DataSourceServiceImpl.java index a498fe6d0..723422b31 100644 --- a/base/src/main/java/com/developmentontheedge/be5/base/services/impl/DataSourceServiceImpl.java +++ b/base/src/main/java/com/developmentontheedge/be5/base/services/impl/DataSourceServiceImpl.java @@ -8,7 +8,7 @@ import com.developmentontheedge.be5.metadata.sql.DatabaseUtils; import com.developmentontheedge.be5.metadata.sql.Rdbms; import com.developmentontheedge.be5.metadata.util.JULLogger; -import com.developmentontheedge.sql.format.Dbms; +import com.developmentontheedge.sql.format.dbms.Dbms; import org.apache.commons.dbcp.BasicDataSource; import javax.inject.Inject; diff --git a/base/src/main/java/com/developmentontheedge/be5/base/services/impl/MetaImpl.java b/base/src/main/java/com/developmentontheedge/be5/base/services/impl/MetaImpl.java index 5d2ef9d80..8abce3daf 100644 --- a/base/src/main/java/com/developmentontheedge/be5/base/services/impl/MetaImpl.java +++ b/base/src/main/java/com/developmentontheedge/be5/base/services/impl/MetaImpl.java @@ -258,7 +258,10 @@ public Locale getLocale(Locale locale) if(locale == null || !languages.contains(locale.getLanguage())) { - return new Locale( languages.get(0) ); + if(languages.size() > 0) + return new Locale( languages.get(0) ); + else + return Locale.US; } else { @@ -418,11 +421,19 @@ public Map getColumns(Entity entity) { BeModelElement scheme = entity.getAvailableElement("Scheme"); if(scheme == null) return new HashMap<>(); - BeCaseInsensitiveCollection columns = (BeCaseInsensitiveCollection) ((TableDef) scheme).get("Columns"); - return StreamSupport.stream(columns.spliterator(), false).collect( - Utils.toLinkedMap(ColumnDef::getName, Function.identity()) - ); + if(scheme instanceof TableDef) + { + BeCaseInsensitiveCollection columns = (BeCaseInsensitiveCollection) ((TableDef) scheme).get("Columns"); + + return StreamSupport.stream(columns.spliterator(), false).collect( + Utils.toLinkedMap(ColumnDef::getName, Function.identity()) + ); + } + else + { + return Collections.emptyMap(); + } } @Override diff --git a/base/src/main/java/com/developmentontheedge/be5/base/util/Utils.java b/base/src/main/java/com/developmentontheedge/be5/base/util/Utils.java index 052b83917..37ebd274f 100644 --- a/base/src/main/java/com/developmentontheedge/be5/base/util/Utils.java +++ b/base/src/main/java/com/developmentontheedge/be5/base/util/Utils.java @@ -21,6 +21,7 @@ import java.util.List; import java.util.Locale; import java.util.Map; +import java.util.Random; import java.util.function.Function; import java.util.stream.Collector; import java.util.stream.Collectors; @@ -719,4 +720,33 @@ public static T ifNull( Object val, T def ) LinkedHashMap::new); } + /** + * Generates random password, containing 8 symbols using english alphabet and numbers. + * + * @param userName user name + * @return generated password + */ + public static String newRandomPassword( String userName ) + { + return newRandomPassword( userName, "abcdefghijklmnopqrstuvwxyz0123456789" ); + } + + /** + * Generates random password, containing 8 symbols from specified symbols array. + * + * @param userName user name + * @param pool symbols to use in password + * @return generated password + */ + public static String newRandomPassword( String userName, String pool ) + { + StringBuffer pass = new StringBuffer(); + Random random = userName == null ? new Random() : new Random( System.currentTimeMillis() + userName.hashCode() ); + for( int i = 0; i < 8; i++ ) + { + pass.append( pool.charAt( random.nextInt( pool.length() ) ) ); + } + return pass.toString(); + } + } diff --git a/base/src/test/java/com/developmentontheedge/be5/base/services/impl/DataSourceServiceImplTest.java b/base/src/test/java/com/developmentontheedge/be5/base/services/impl/DataSourceServiceImplTest.java index b8aff4ca6..2c9620107 100644 --- a/base/src/test/java/com/developmentontheedge/be5/base/services/impl/DataSourceServiceImplTest.java +++ b/base/src/test/java/com/developmentontheedge/be5/base/services/impl/DataSourceServiceImplTest.java @@ -2,7 +2,7 @@ import com.developmentontheedge.be5.base.BaseTest; import com.developmentontheedge.be5.database.DataSourceService; -import com.developmentontheedge.sql.format.Dbms; +import com.developmentontheedge.sql.format.dbms.Dbms; import org.apache.commons.dbcp.BasicDataSource; import org.junit.Test; diff --git a/database/src/main/java/com/developmentontheedge/be5/database/DataSourceService.java b/database/src/main/java/com/developmentontheedge/be5/database/DataSourceService.java index e6185c485..f4f00c366 100644 --- a/database/src/main/java/com/developmentontheedge/be5/database/DataSourceService.java +++ b/database/src/main/java/com/developmentontheedge/be5/database/DataSourceService.java @@ -1,6 +1,6 @@ package com.developmentontheedge.be5.database; -import com.developmentontheedge.sql.format.Dbms; +import com.developmentontheedge.sql.format.dbms.Dbms; import javax.sql.DataSource; diff --git a/database/src/main/java/com/developmentontheedge/be5/database/impl/DbServiceImpl.java b/database/src/main/java/com/developmentontheedge/be5/database/impl/DbServiceImpl.java index b847905c3..3c8f2608a 100644 --- a/database/src/main/java/com/developmentontheedge/be5/database/impl/DbServiceImpl.java +++ b/database/src/main/java/com/developmentontheedge/be5/database/impl/DbServiceImpl.java @@ -6,8 +6,8 @@ import com.developmentontheedge.be5.database.sql.ResultSetParser; import com.developmentontheedge.be5.database.sql.SqlExecutor; import com.developmentontheedge.be5.database.sql.SqlExecutorVoid; -import com.developmentontheedge.sql.format.Context; -import com.developmentontheedge.sql.format.Formatter; +import com.developmentontheedge.sql.format.dbms.Context; +import com.developmentontheedge.sql.format.dbms.Formatter; import com.developmentontheedge.sql.model.DefaultParserContext; import com.developmentontheedge.sql.model.SqlQuery; import org.apache.commons.dbutils.QueryRunner; diff --git a/database/src/test/java/com/developmentontheedge/be5/database/impl/DataSourceServiceTestImpl.java b/database/src/test/java/com/developmentontheedge/be5/database/impl/DataSourceServiceTestImpl.java index 38793f9dd..59fca999e 100644 --- a/database/src/test/java/com/developmentontheedge/be5/database/impl/DataSourceServiceTestImpl.java +++ b/database/src/test/java/com/developmentontheedge/be5/database/impl/DataSourceServiceTestImpl.java @@ -1,7 +1,7 @@ package com.developmentontheedge.be5.database.impl; import com.developmentontheedge.be5.database.DataSourceService; -import com.developmentontheedge.sql.format.Dbms; +import com.developmentontheedge.sql.format.dbms.Dbms; import javax.sql.DataSource; diff --git a/dbms/src/main/java/com/developmentontheedge/dbms/DbmsConnector.java b/dbms/src/main/java/com/developmentontheedge/dbms/DbmsConnector.java index e592fb6d2..b3dd738f1 100644 --- a/dbms/src/main/java/com/developmentontheedge/dbms/DbmsConnector.java +++ b/dbms/src/main/java/com/developmentontheedge/dbms/DbmsConnector.java @@ -20,6 +20,6 @@ public interface DbmsConnector Connection getConnection() throws SQLException; - void releaseConnection( Connection conn ); + //void releaseConnection( Connection conn ); } diff --git a/dbms/src/main/java/com/developmentontheedge/dbms/SimpleConnector.java b/dbms/src/main/java/com/developmentontheedge/dbms/SimpleConnector.java index cf8acb6a2..0bcf5a2f2 100644 --- a/dbms/src/main/java/com/developmentontheedge/dbms/SimpleConnector.java +++ b/dbms/src/main/java/com/developmentontheedge/dbms/SimpleConnector.java @@ -111,33 +111,33 @@ public Connection getConnection() throws SQLException return connection; } - private void returnConnection(Connection conn) - { - try - { - if(!conn.isClosed()) - { - if(!conn.getAutoCommit()) - conn.setAutoCommit(true); - conn.close(); - } - } - catch (SQLException e) - { - throw new RuntimeException(e); - } - } - - @Override - public void releaseConnection( Connection conn ) - { - if ( null == conn ) - { - return; - } - - returnConnection(conn); - } +// private void returnConnection(Connection conn) +// { +// try +// { +// if(!conn.isClosed()) +// { +// if(!conn.getAutoCommit()) +// conn.setAutoCommit(true); +// conn.close(); +// } +// } +// catch (SQLException e) +// { +// throw new RuntimeException(e); +// } +// } +// +// @Override +// public void releaseConnection( Connection conn ) +// { +// if ( null == conn ) +// { +// return; +// } +// +// returnConnection(conn); +// } private RuntimeException propagate(SQLException e) { log.log(Level.SEVERE, e.getMessage(), e); diff --git a/dbms/src/main/java/com/developmentontheedge/dbms/SqlExecutor.java b/dbms/src/main/java/com/developmentontheedge/dbms/SqlExecutor.java index c0d26615b..05d791e2b 100644 --- a/dbms/src/main/java/com/developmentontheedge/dbms/SqlExecutor.java +++ b/dbms/src/main/java/com/developmentontheedge/dbms/SqlExecutor.java @@ -525,10 +525,6 @@ else if( arg instanceof byte[] ) } return null; } - finally - { - connector.releaseConnection( conn ); - } } catch( Exception e ) { diff --git a/maven/src/main/java/com/developmentontheedge/be5/maven/AppDataMojo.java b/maven/src/main/java/com/developmentontheedge/be5/maven/AppDataMojo.java index ab034d7e9..88b1ef5ba 100644 --- a/maven/src/main/java/com/developmentontheedge/be5/maven/AppDataMojo.java +++ b/maven/src/main/java/com/developmentontheedge/be5/maven/AppDataMojo.java @@ -24,6 +24,7 @@ public void execute() .setConnectionPassword(connectionPassword) .setLogPath(logPath) .setLogger(logger) + .setDebug(debug) .setScript(script) .setIgnoreMissing(ignoreMissing) .execute(); diff --git a/maven/src/main/java/com/developmentontheedge/be5/maven/AppDbMojo.java b/maven/src/main/java/com/developmentontheedge/be5/maven/AppDbMojo.java index 8af9e9614..4615442d9 100644 --- a/maven/src/main/java/com/developmentontheedge/be5/maven/AppDbMojo.java +++ b/maven/src/main/java/com/developmentontheedge/be5/maven/AppDbMojo.java @@ -16,6 +16,7 @@ public void execute() .setConnectionPassword(connectionPassword) .setLogPath(logPath) .setLogger(logger) + .setDebug(debug) .execute(); } diff --git a/maven/src/main/java/com/developmentontheedge/be5/maven/AppSyncMojo.java b/maven/src/main/java/com/developmentontheedge/be5/maven/AppSyncMojo.java index 95605f776..041ee744c 100644 --- a/maven/src/main/java/com/developmentontheedge/be5/maven/AppSyncMojo.java +++ b/maven/src/main/java/com/developmentontheedge/be5/maven/AppSyncMojo.java @@ -29,6 +29,7 @@ public void execute() .setConnectionPassword(connectionPassword) .setLogPath(logPath) .setLogger(logger) + .setDebug(debug) .setForceUpdate(forceUpdate) .execute(); } diff --git a/maven/src/main/java/com/developmentontheedge/be5/maven/AppToolsMojo.java b/maven/src/main/java/com/developmentontheedge/be5/maven/AppToolsMojo.java index aa2cadb10..382ede7ab 100644 --- a/maven/src/main/java/com/developmentontheedge/be5/maven/AppToolsMojo.java +++ b/maven/src/main/java/com/developmentontheedge/be5/maven/AppToolsMojo.java @@ -21,6 +21,7 @@ public void execute() throws MojoFailureException .setConnectionPassword(connectionPassword) .setLogPath(logPath) .setLogger(logger) + .setDebug(debug) .setInputStream(inputStream) .execute(); } diff --git a/maven/src/main/java/com/developmentontheedge/be5/maven/AppValidateMojo.java b/maven/src/main/java/com/developmentontheedge/be5/maven/AppValidateMojo.java index 5fee6d758..0ecfb0684 100644 --- a/maven/src/main/java/com/developmentontheedge/be5/maven/AppValidateMojo.java +++ b/maven/src/main/java/com/developmentontheedge/be5/maven/AppValidateMojo.java @@ -12,28 +12,30 @@ public class AppValidateMojo extends Be5Mojo { @Parameter (property = "BE5_RDBMS") - String rdbmsName; + private String rdbmsName; @Parameter (property = "BE5_SKIP_VALIDATION") - boolean skipValidation = false; + private boolean skipValidation = false; @Parameter (property = "BE5_CHECK_QUERY") - String queryPath; + private String queryPath; @Parameter (property = "BE5_CHECK_ROLES") - boolean checkRoles; + private boolean checkRoles; @Parameter (property = "BE5_CHECK_DDL") - String ddlPath; + private String ddlPath; @Parameter (property = "BE5_SAVE_PROJECT") - boolean saveProject; + private boolean saveProject; @Override public void execute() { new AppValidate() + .setLogPath(logPath) .setLogger(logger) + .setDebug(debug) .setBe5ProjectPath(projectPath.toPath()) .setCheckQueryPath(queryPath) .setDdlPath(ddlPath) diff --git a/maven/src/main/java/com/developmentontheedge/be5/maven/Be5Mojo.java b/maven/src/main/java/com/developmentontheedge/be5/maven/Be5Mojo.java index 886a8cdbb..dd4fc4a40 100644 --- a/maven/src/main/java/com/developmentontheedge/be5/maven/Be5Mojo.java +++ b/maven/src/main/java/com/developmentontheedge/be5/maven/Be5Mojo.java @@ -16,13 +16,13 @@ public abstract class Be5Mojo extends AbstractMojo public File projectPath; @Parameter (property = "BE5_UNLOCK_PROTECTED_PROFILE") - boolean unlockProtectedProfile = false; + protected boolean unlockProtectedProfile = false; @Parameter (property = "BE5_DEBUG") - boolean debug = false; + protected boolean debug = false; @Parameter (property = "BE5_LOG_PATH") - File logPath = Paths.get("target/sql").toFile(); + protected File logPath = Paths.get("target/sql").toFile(); @Parameter (property = "BE5_PROFILE") public String connectionProfileName; diff --git a/maven/src/main/java/com/developmentontheedge/be5/maven/generate/GenerateContextMojo.java b/maven/src/main/java/com/developmentontheedge/be5/maven/generate/GenerateContextMojo.java index 2ace7a840..2f284af68 100644 --- a/maven/src/main/java/com/developmentontheedge/be5/maven/generate/GenerateContextMojo.java +++ b/maven/src/main/java/com/developmentontheedge/be5/maven/generate/GenerateContextMojo.java @@ -25,7 +25,9 @@ public void execute() throws MojoFailureException .setConnectionPassword(connectionPassword) .setGenerateContextPath(generateContextPath) .setSkipGenerateContextPath(skipGenerateContextPath) + .setLogPath(logPath) .setLogger(logger) + .setDebug(debug) .execute(); } } \ No newline at end of file diff --git a/maven/src/main/java/com/developmentontheedge/be5/maven/generate/GroovyDSLGeneratorMojo.java b/maven/src/main/java/com/developmentontheedge/be5/maven/generate/GroovyDSLGeneratorMojo.java index 563bebab7..dad072d1b 100644 --- a/maven/src/main/java/com/developmentontheedge/be5/maven/generate/GroovyDSLGeneratorMojo.java +++ b/maven/src/main/java/com/developmentontheedge/be5/maven/generate/GroovyDSLGeneratorMojo.java @@ -22,7 +22,9 @@ public void execute() new GroovyDSLGenerator() .setBe5ProjectPath(projectPath.getPath()) .setProfileName(connectionProfileName) + .setLogPath(logPath) .setLogger(logger) + .setDebug(debug) .setFileName(fileName) .execute(); } diff --git a/metadata/src/main/java/com/developmentontheedge/be5/metadata/model/Project.java b/metadata/src/main/java/com/developmentontheedge/be5/metadata/model/Project.java index 380b63915..1937d3735 100644 --- a/metadata/src/main/java/com/developmentontheedge/be5/metadata/model/Project.java +++ b/metadata/src/main/java/com/developmentontheedge/be5/metadata/model/Project.java @@ -13,9 +13,9 @@ import com.developmentontheedge.be5.metadata.sql.macro.IMacroProcessorStrategy; import com.developmentontheedge.beans.annot.PropertyDescription; import com.developmentontheedge.beans.annot.PropertyName; -import com.developmentontheedge.sql.format.Context; -import com.developmentontheedge.sql.format.Dbms; -import com.developmentontheedge.sql.format.DbmsTransformer; +import com.developmentontheedge.sql.format.dbms.Context; +import com.developmentontheedge.sql.format.dbms.Dbms; +import com.developmentontheedge.sql.format.dbms.DbmsTransformer; import com.developmentontheedge.sql.format.MacroExpander; import com.developmentontheedge.sql.model.AstStart; import com.developmentontheedge.sql.model.SqlParser; diff --git a/metadata/src/main/java/com/developmentontheedge/be5/metadata/scripts/AppDb.java b/metadata/src/main/java/com/developmentontheedge/be5/metadata/scripts/AppDb.java index cdb7fb49b..d1b6ad8e3 100644 --- a/metadata/src/main/java/com/developmentontheedge/be5/metadata/scripts/AppDb.java +++ b/metadata/src/main/java/com/developmentontheedge/be5/metadata/scripts/AppDb.java @@ -71,12 +71,7 @@ public void execute() throws ScriptException } catch ( ProjectElementException | FreemarkerSqlException e ) { - if(debug) { - e.printStackTrace(); - throw new ScriptException("Setup db error", e); - } - - throw new ScriptException(e.getMessage()); + throw new ScriptException("Setup db error", e); } catch(Exception e) { diff --git a/metadata/src/main/java/com/developmentontheedge/be5/metadata/scripts/ScriptSupport.java b/metadata/src/main/java/com/developmentontheedge/be5/metadata/scripts/ScriptSupport.java index 5d5e81b0a..5f3961a6d 100644 --- a/metadata/src/main/java/com/developmentontheedge/be5/metadata/scripts/ScriptSupport.java +++ b/metadata/src/main/java/com/developmentontheedge/be5/metadata/scripts/ScriptSupport.java @@ -279,4 +279,10 @@ public T setConnectionPassword(String connectionPassword) this.connectionPassword = connectionPassword; return me(); } + + public T setDebug(boolean debug) + { + this.debug = debug; + return me(); + } } diff --git a/metadata/src/main/java/com/developmentontheedge/be5/metadata/sql/Rdbms.java b/metadata/src/main/java/com/developmentontheedge/be5/metadata/sql/Rdbms.java index 6a11218b7..6552836c6 100644 --- a/metadata/src/main/java/com/developmentontheedge/be5/metadata/sql/Rdbms.java +++ b/metadata/src/main/java/com/developmentontheedge/be5/metadata/sql/Rdbms.java @@ -23,7 +23,7 @@ import com.developmentontheedge.be5.metadata.sql.type.SqlServerTypeManager; import com.developmentontheedge.dbms.DbmsConnector; import com.developmentontheedge.dbms.DbmsType; -import com.developmentontheedge.sql.format.Dbms; +import com.developmentontheedge.sql.format.dbms.Dbms; import java.util.Map; import java.util.Map.Entry; @@ -32,32 +32,32 @@ public enum Rdbms { - DB2( DbmsType.DB2, - new Db2MacroProcessorStrategy(), - new Db2TypeManager(), - new Db2SchemaReader(), - "org.eclipse.datatools.enablement.ibm.db2.luw.connectionProfile", + DB2( DbmsType.DB2, + new Db2MacroProcessorStrategy(), + new Db2TypeManager(), + new Db2SchemaReader(), + "org.eclipse.datatools.enablement.ibm.db2.luw.connectionProfile", "DriverDefn.org.eclipse.datatools.enablement.ibm.db2.luw.jdbc4.driverTemplate.IBM Data Server Driver for JDBC and SQLJ (JDBC 4.0) Default", "v97" ), - MYSQL( DbmsType.MYSQL, - new MySqlMacroProcessorStrategy(), - new MySqlTypeManager(), - new MySqlSchemaReader(), + MYSQL( DbmsType.MYSQL, + new MySqlMacroProcessorStrategy(), + new MySqlTypeManager(), + new MySqlSchemaReader(), "", "com.mysql.jdbc.Driver", "6" ), - ORACLE( DbmsType.ORACLE, - new OracleMacroProcessorStrategy(), - new OracleTypeManager(), - new OracleSchemaReader(), + ORACLE( DbmsType.ORACLE, + new OracleMacroProcessorStrategy(), + new OracleTypeManager(), + new OracleSchemaReader(), "", "oracle.jdbc.driver.OracleDriver", "11" ), - SQLSERVER( DbmsType.SQLSERVER, + SQLSERVER( DbmsType.SQLSERVER, new SqlServerMacroProcessorStrategy(), - new SqlServerTypeManager(), - new SqlServerSchemaReader(), + new SqlServerTypeManager(), + new SqlServerSchemaReader(), "org.eclipse.datatools.enablement.msft.sqlserver.connectionProfile", "DriverDefn.org.eclipse.datatools.enablement.msft.sqlserver.2008.driverTemplate.Microsoft SQL Server 2008 JDBC Driver", "2008"), - POSTGRESQL( DbmsType.POSTGRESQL, - new PostgresMacroProcessorStrategy(), - new PostgresTypeManager(), - new PostgresSchemaReader(), + POSTGRESQL( DbmsType.POSTGRESQL, + new PostgresMacroProcessorStrategy(), + new PostgresTypeManager(), + new PostgresSchemaReader(), "", "org.postgresql.Driver", "91" ), BESQL(DbmsType.BESQL, new BeSQLMacroProcessorStrategy(), @@ -73,7 +73,7 @@ public enum Rdbms public static Rdbms getRdbms(final String url) { - String realUrl = url.startsWith( "jdbc:" )?url.substring( "jdbc:".length() ):url; + String realUrl = url.startsWith( "jdbc:" )?url.substring( "jdbc:".length() ):url; if(realUrl.startsWith( "mysql:" )) { return Rdbms.MYSQL; @@ -126,7 +126,7 @@ public Dbms getDbms() /////////////////////////////////////////////////////////////////// // RDBMS implementation // - + private final DbmsType type; private final IMacroProcessorStrategy macroProcessor; private final DbmsTypeManager typeManager; @@ -134,7 +134,7 @@ public Dbms getDbms() private final String providerId; private final String driverDefinition; private final String version; - + private Rdbms( DbmsType type, IMacroProcessorStrategy macroProcessor, DbmsTypeManager typeManager, DbmsSchemaReader schemaReader, String providerId, String driverDefinition, String version ) { this.type = type; @@ -145,12 +145,12 @@ private Rdbms( DbmsType type, IMacroProcessorStrategy macroProcessor, DbmsTypeMa this.driverDefinition = driverDefinition; this.version = version; } - + public String getName() { return type.getName(); } - + public String getAntName() { return type.getName().equals( "postgres" ) ? "postgresql" : type.getName(); @@ -175,12 +175,12 @@ public String getProviderId() { return providerId; } - + public String getDriverDefinition() { return driverDefinition; } - + public DbmsType getType() { return type; @@ -221,9 +221,18 @@ public String createConnectionUrl( String host, int port, String database, Map entry : properties.entrySet()) { - url.append( entry.getKey() ).append( '=' ).append( entry.getValue() ).append( ';' ); + if(!first){ + if(this == MYSQL) + url.append( '&' ); + else + url.append( ';' ); + } + first = false; + url.append( entry.getKey() ).append( '=' ).append( entry.getValue() ); } } return url.toString(); diff --git a/metadata/src/main/java/com/developmentontheedge/be5/metadata/sql/schema/DefaultSchemaReader.java b/metadata/src/main/java/com/developmentontheedge/be5/metadata/sql/schema/DefaultSchemaReader.java index ceb8bb7fe..b355807c8 100644 --- a/metadata/src/main/java/com/developmentontheedge/be5/metadata/sql/schema/DefaultSchemaReader.java +++ b/metadata/src/main/java/com/developmentontheedge/be5/metadata/sql/schema/DefaultSchemaReader.java @@ -20,14 +20,8 @@ public String getDefaultSchema( SqlExecutor sql ) throws ExtendedSqlException try { Connection connection = connector.getConnection(); - try - { - return connection.getMetaData().getUserName(); - } - finally - { - connector.releaseConnection( connection ); - } + + return connection.getMetaData().getUserName(); } catch(SQLException ex) { @@ -55,7 +49,6 @@ public Map readTableNames( SqlExecutor sql, String defSchema, Pr finally { connector.close( rs ); - connector.releaseConnection( connection ); } return result; } diff --git a/metadata/src/test/java/com/developmentontheedge/be5/metadata/FreemarkerTest.java b/metadata/src/test/java/com/developmentontheedge/be5/metadata/FreemarkerTest.java index 26c4e8361..913d2cb63 100644 --- a/metadata/src/test/java/com/developmentontheedge/be5/metadata/FreemarkerTest.java +++ b/metadata/src/test/java/com/developmentontheedge/be5/metadata/FreemarkerTest.java @@ -150,18 +150,29 @@ public void testPredefinedMacros() throws ProjectElementException dataModel.put( "project", project ); Entity entity = new Entity( "myTable", project.getApplication(), EntityType.TABLE ); DataElementUtils.saveQuiet( entity ); -//TODO Query query = new Query( "All records", entity ); -// DataElementUtils.saveQuiet( query ); -// query.setQuery( "SELECT * FROM ${entity.getName()}" ); -// Query query2 = new Query("Copy", entity); -// DataElementUtils.saveQuiet( query2 ); -// query2.setQuery( "<@_copyAllRecordsQuery/>" ); -// assertEquals("SELECT * FROM myTable", query2.getQueryCompiled().validate()); -// -// query2.setQuery( "SELECT <@_bold>name FROM myTable" ); -// assertEquals("SELECT CONCAT( '',name,'' ) FROM myTable", query2.getQueryCompiled().validate()); -// query2.setQuery( "SELECT <@_bold><@_italic>name FROM myTable" ); -// assertEquals("SELECT CONCAT( '',CONCAT( '',name,'' ),'' ) FROM myTable", query2.getQueryCompiled().validate()); + + FreemarkerScript script = new FreemarkerScript( FreemarkerCatalog.MAIN_MACRO_LIBRARY, project.getMacroCollection() ); + DataElementUtils.saveQuiet( script ); + script.setSource( + "<#macro _copyQuery name>${entity.getQueries().get(name).getQueryCompiled().validate()}" + + "<#macro _copyAllRecordsQuery><@_copyQuery \"All records\"/>" + + "<#macro _bold><#assign nested><#nested>${concat(''?str, nested, ''?str)}\n" + + "<#macro _italic><#assign nested><#nested>${concat(''?str, nested, ''?str)}" + ); + Query query = new Query( "All records", entity ); + DataElementUtils.saveQuiet( query ); + query.setQuery( "SELECT * FROM ${entity.getName()}" ); + Query query2 = new Query("Copy", entity); + DataElementUtils.saveQuiet( query2 ); + + query2.setQuery( "<@_copyAllRecordsQuery/>" ); + assertEquals("SELECT * FROM myTable", query2.getQueryCompiled().validate()); + + query2.setQuery( "SELECT <@_bold>name FROM myTable" ); + assertEquals("SELECT CONCAT( '',name,'' ) FROM myTable", query2.getQueryCompiled().validate()); + + query2.setQuery( "SELECT <@_bold><@_italic>name FROM myTable" ); + assertEquals("SELECT CONCAT( '',CONCAT( '',name,'' ),'' ) FROM myTable", query2.getQueryCompiled().validate()); } public void testProjectMacros() throws ProjectElementException diff --git a/metadata/src/test/java/com/developmentontheedge/be5/metadata/freemarker/FreemarkerSqlHandlerTest.java b/metadata/src/test/java/com/developmentontheedge/be5/metadata/freemarker/FreemarkerSqlHandlerTest.java index 948b320ef..00fef1f9a 100644 --- a/metadata/src/test/java/com/developmentontheedge/be5/metadata/freemarker/FreemarkerSqlHandlerTest.java +++ b/metadata/src/test/java/com/developmentontheedge/be5/metadata/freemarker/FreemarkerSqlHandlerTest.java @@ -67,11 +67,11 @@ public Connection getConnection() throws SQLException { throw new UnsupportedOperationException(); } - - @Override - public void releaseConnection( Connection conn ) - { - } +// +// @Override +// public void releaseConnection( Connection conn ) +// { +// } } @Test diff --git a/metadata/src/test/java/com/developmentontheedge/be5/metadata/sql/ConnectionUrlTest.java b/metadata/src/test/java/com/developmentontheedge/be5/metadata/sql/ConnectionUrlTest.java index b47dd2c00..4f85ea9a8 100644 --- a/metadata/src/test/java/com/developmentontheedge/be5/metadata/sql/ConnectionUrlTest.java +++ b/metadata/src/test/java/com/developmentontheedge/be5/metadata/sql/ConnectionUrlTest.java @@ -68,5 +68,7 @@ public void testMySQL() assertEquals("convertToNull", url.getProperty( "zeroDateTimeBehavior" )); assertEquals("true", url.getProperty( "useUnicode" )); assertEquals("UTF-8", url.getProperty( "characterEncoding" )); + + assertEquals("jdbc:mysql://localhost:3306/mydb?characterEncoding=UTF-8&useUnicode=true&zeroDateTimeBehavior=convertToNull", url.toString()); } } diff --git a/modules/core/src/include/common.ftl b/modules/core/src/include/common.ftl index 682c42345..3257c5130 100644 --- a/modules/core/src/include/common.ftl +++ b/modules/core/src/include/common.ftl @@ -2,7 +2,15 @@ <#macro _sqlMacro><#assign nested><#nested>${project.addSQLMacro(nested)} -<#-- Macros for using in custom scripts --> +<#macro _copyQuery name>${entity.getQueries().get(name).getQueryCompiled().validate()} + +<#macro _copySelectionQuery><@_copyQuery "*** Selection view ***"/> + +<#macro _copyAllRecordsQuery><@_copyQuery "All records"/> + +<#macro _bold><#assign nested><#nested>${concat(''?str, nested, ''?str)} + +<#macro _italic><#assign nested><#nested>${concat(''?str, nested, ''?str)} <#macro _systemSetting category key value> DELETE FROM systemSettings WHERE section_name = ${category?str} AND setting_name = ${key?str}; diff --git a/modules/core/src/l10n/ru.yaml b/modules/core/src/l10n/ru.yaml index 6fef6a494..793b5fa25 100644 --- a/modules/core/src/l10n/ru.yaml +++ b/modules/core/src/l10n/ru.yaml @@ -11,8 +11,10 @@ ru: - topics: exception entries: - 'Internal error occurred: $1': 'Произошла внутренняя ошибка: $1' + - 'Internal error occurred during operation: $1.$2': 'Произошла внутренняя ошибка в операции: $1.$2' + - 'Internal error occurred during query: $1.$2': 'Произошла внутренняя ошибка в представлении: $1.$2' - 'Entity not found: $1': 'Сущность не найдена: $1' - - 'Access denied': Доступ запрещен + - 'Access denied. $1': 'Доступ запрещен. $1' - Error in operation: Ошибка в операции - Incorrect username or password.: Неправильно указано имя пользователя или пароль. - topics: validation diff --git a/modules/core/src/test/groovy/com/developmentontheedge/be5/modules/core/LoadTest.groovy b/modules/core/src/test/groovy/com/developmentontheedge/be5/modules/core/LoadTest.groovy index 5f6e0c2b7..ac7b3021b 100644 --- a/modules/core/src/test/groovy/com/developmentontheedge/be5/modules/core/LoadTest.groovy +++ b/modules/core/src/test/groovy/com/developmentontheedge/be5/modules/core/LoadTest.groovy @@ -1,8 +1,13 @@ package com.developmentontheedge.be5.modules.core import com.developmentontheedge.be5.base.services.ProjectProvider +import com.developmentontheedge.be5.metadata.exception.ProjectElementException import com.developmentontheedge.be5.metadata.exception.ProjectLoadException +import com.developmentontheedge.be5.metadata.model.DataElementUtils +import com.developmentontheedge.be5.metadata.model.Entity +import com.developmentontheedge.be5.metadata.model.EntityType import com.developmentontheedge.be5.metadata.model.Module +import com.developmentontheedge.be5.metadata.model.Query import com.developmentontheedge.be5.metadata.model.base.BeModelCollection import com.developmentontheedge.be5.metadata.scripts.AppValidate import org.junit.Test @@ -31,4 +36,31 @@ class LoadTest extends CoreBe5ProjectDbMockTest { new AppValidate().setBe5ProjectPath("./").execute() } + + @Test + void testPredefinedMacros() throws ProjectElementException + { + def project = projectProvider.get() + + Map dataModel = new HashMap<>() + dataModel.put( "project", project ) + Entity entity = new Entity( "myTable", project.getApplication(), EntityType.TABLE ) + DataElementUtils.saveQuiet( entity ) + + Query query = new Query( "All records", entity ) + DataElementUtils.saveQuiet( query ) + query.setQuery( "SELECT * FROM ${entity.getName()}" ) + Query query2 = new Query("Copy", entity) + DataElementUtils.saveQuiet( query2 ) + + query2.setQuery( "<@_copyAllRecordsQuery/>" ) + assertEquals("SELECT * FROM myTable", query2.getQueryCompiled().validate()) + + query2.setQuery( "SELECT <@_bold>name FROM myTable" ) + assertEquals("SELECT ( '' || name || '' ) FROM myTable", query2.getQueryCompiled().validate()) + + query2.setQuery( "SELECT <@_bold><@_italic>name FROM myTable" ) + assertEquals("SELECT ( '' || ( '' || name || '' ) || '' ) FROM myTable", + query2.getQueryCompiled().validate()) + } } diff --git a/modules/core/src/test/java/com/developmentontheedge/be5/modules/core/LocalizationTest.java b/modules/core/src/test/java/com/developmentontheedge/be5/modules/core/LocalizationTest.java new file mode 100644 index 000000000..cd9602c7f --- /dev/null +++ b/modules/core/src/test/java/com/developmentontheedge/be5/modules/core/LocalizationTest.java @@ -0,0 +1,19 @@ +package com.developmentontheedge.be5.modules.core; + +import com.developmentontheedge.be5.base.exceptions.Be5Exception; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class LocalizationTest extends CoreBe5ProjectDbMockTest +{ + @Test + public void test_INTERNAL_ERROR_IN_OPERATION() + { + assertEquals("Произошла внутренняя ошибка в операции: users.Login", + userAwareMeta.getLocalizedBe5ErrorMessage( + Be5Exception.internalInOperation( + meta.getOperation("users", "Login"), new RuntimeException("test")))); + } + +} diff --git a/operation/src/main/java/com/developmentontheedge/be5/operation/services/validation/Validator.java b/operation/src/main/java/com/developmentontheedge/be5/operation/services/validation/Validator.java index 29412ebad..fadba03aa 100644 --- a/operation/src/main/java/com/developmentontheedge/be5/operation/services/validation/Validator.java +++ b/operation/src/main/java/com/developmentontheedge/be5/operation/services/validation/Validator.java @@ -111,12 +111,24 @@ else if (property.getType() != property.getValue().getClass()) private void checkValueInTags(DynamicProperty property, Object value) { - Object[][] tags = (Object[][])property.getAttribute(BeanInfoConstants.TAG_LIST_ATTR); - if(tags != null) + Object tagsObject = property.getAttribute(BeanInfoConstants.TAG_LIST_ATTR); + if (tagsObject instanceof Object[][]) { + Object[][] tags = (Object[][])tagsObject; + if(Arrays.stream(tags).noneMatch(item -> (item)[0].toString().equals(value.toString()))) { - setError(property, "Value is not contained in tags"); + setError(property, "Value is not contained in tags: " + value.toString()); + throw new IllegalArgumentException("Value is not contained in tags" + toStringProperty(property)); + } + } + else if (tagsObject instanceof Object[]) + { + Object[] tags = (Object[])tagsObject; + + if(Arrays.stream(tags).noneMatch(item -> item.toString().equals(value.toString()))) + { + setError(property, "Value is not contained in tags: " + value.toString()); throw new IllegalArgumentException("Value is not contained in tags" + toStringProperty(property)); } } diff --git a/operation/src/test/groovy/com/developmentontheedge/be5/operation/services/ValidatorServiceValueInTagsTest.groovy b/operation/src/test/groovy/com/developmentontheedge/be5/operation/services/ValidatorServiceValueInTagsTest.groovy index 21a595283..ac4525fa1 100644 --- a/operation/src/test/groovy/com/developmentontheedge/be5/operation/services/ValidatorServiceValueInTagsTest.groovy +++ b/operation/src/test/groovy/com/developmentontheedge/be5/operation/services/ValidatorServiceValueInTagsTest.groovy @@ -62,7 +62,7 @@ class ValidatorServiceValueInTagsTest extends OperationsSqlMockProjectTest validator.checkErrorAndCast(dps) }catch (RuntimeException e){ assertEquals("error", JsonFactory.dpsMeta(dps).getJsonObject("/test").getString('status')) - assertEquals("Value is not contained in tags", JsonFactory.dpsMeta(dps).getJsonObject("/test").getString('message')) + assertEquals("Value is not contained in tags: 3", JsonFactory.dpsMeta(dps).getJsonObject("/test").getString('message')) throw e } @@ -97,7 +97,7 @@ class ValidatorServiceValueInTagsTest extends OperationsSqlMockProjectTest validator.checkErrorAndCast(dps) }catch (RuntimeException e){ assertEquals("error", JsonFactory.dpsMeta(dps).getJsonObject("/test").getString('status')) - assertEquals("Value is not contained in tags", JsonFactory.dpsMeta(dps).getJsonObject("/test").getString('message')) + assertEquals("Value is not contained in tags: 3", JsonFactory.dpsMeta(dps).getJsonObject("/test").getString('message')) throw e } } diff --git a/query/src/main/java/com/developmentontheedge/be5/query/services/impl/TableModelServiceImpl.java b/query/src/main/java/com/developmentontheedge/be5/query/services/impl/TableModelServiceImpl.java index 8083e6c09..aa8bde0ce 100644 --- a/query/src/main/java/com/developmentontheedge/be5/query/services/impl/TableModelServiceImpl.java +++ b/query/src/main/java/com/developmentontheedge/be5/query/services/impl/TableModelServiceImpl.java @@ -47,16 +47,22 @@ public TableModelServiceImpl(UserAwareMeta userAwareMeta, CoreUtils coreUtils, G @Override public TableModel getTableModel(Query query, Map parameters) { - switch (query.getType()) + try{ + switch (query.getType()) + { + case D1: + case D1_UNKNOWN: + return getSqlTableModel(query, (Map) parameters); + case JAVA: + case GROOVY: + return getFromTableBuilder(query, (Map) parameters); + default: + throw Be5Exception.internal("Unknown action type '" + query.getType() + "'"); + } + } + catch(Throwable e) { - case D1: - case D1_UNKNOWN: - return getSqlTableModel(query, (Map) parameters); - case JAVA: - case GROOVY: - return getFromTableBuilder(query, (Map) parameters); - default: - throw Be5Exception.internal("Unknown action type '" + query.getType() + "'"); + throw Be5Exception.internalInQuery(query, e); } } diff --git a/query/src/test/java/com/developmentontheedge/be5/query/impl/utils/CategoryFilterTest.java b/query/src/test/java/com/developmentontheedge/be5/query/impl/utils/CategoryFilterTest.java index f1d1140af..53e16270f 100644 --- a/query/src/test/java/com/developmentontheedge/be5/query/impl/utils/CategoryFilterTest.java +++ b/query/src/test/java/com/developmentontheedge/be5/query/impl/utils/CategoryFilterTest.java @@ -1,8 +1,8 @@ package com.developmentontheedge.be5.query.impl.utils; -import com.developmentontheedge.sql.format.Context; -import com.developmentontheedge.sql.format.Dbms; -import com.developmentontheedge.sql.format.Formatter; +import com.developmentontheedge.sql.format.dbms.Context; +import com.developmentontheedge.sql.format.dbms.Dbms; +import com.developmentontheedge.sql.format.dbms.Formatter; import com.developmentontheedge.sql.model.AstStart; import com.developmentontheedge.sql.model.DefaultParserContext; import com.developmentontheedge.sql.model.SqlQuery; diff --git a/server/pom.xml b/server/pom.xml index 96dec3138..e3b776d91 100644 --- a/server/pom.xml +++ b/server/pom.xml @@ -52,6 +52,12 @@ 1.1 + + javax.mail + mail + 1.4.3 + + org.thymeleaf thymeleaf diff --git a/server/src/main/java/com/developmentontheedge/be5/server/ServerModule.java b/server/src/main/java/com/developmentontheedge/be5/server/ServerModule.java index 05f96e57a..3ed07ce35 100644 --- a/server/src/main/java/com/developmentontheedge/be5/server/ServerModule.java +++ b/server/src/main/java/com/developmentontheedge/be5/server/ServerModule.java @@ -27,6 +27,7 @@ import com.developmentontheedge.be5.server.services.impl.FormGeneratorImpl; import com.developmentontheedge.be5.server.services.impl.QuerySessionImpl; import com.developmentontheedge.be5.server.services.impl.UserInfoProviderImpl; +import com.developmentontheedge.be5.server.services.mail.MailService; import com.developmentontheedge.be5.web.Request; import com.developmentontheedge.be5.web.Response; import com.developmentontheedge.be5.web.Session; @@ -73,6 +74,7 @@ protected void configureServlets() bind(ColumnsHelper.class).in(Scopes.SINGLETON); bind(MenuHelper.class).in(Scopes.SINGLETON); bind(JsonApiResponseHelper.class).in(Scopes.SINGLETON); + bind(MailService.class).in(Scopes.SINGLETON); bind(DocumentGenerator.class).to(DocumentGeneratorImpl.class).in(Scopes.SINGLETON); bind(FormGenerator.class).to(FormGeneratorImpl.class).in(Scopes.SINGLETON); diff --git a/server/src/main/java/com/developmentontheedge/be5/server/controllers/FormController.java b/server/src/main/java/com/developmentontheedge/be5/server/controllers/FormController.java index 70696defa..2b8806f25 100644 --- a/server/src/main/java/com/developmentontheedge/be5/server/controllers/FormController.java +++ b/server/src/main/java/com/developmentontheedge/be5/server/controllers/FormController.java @@ -2,6 +2,7 @@ import com.developmentontheedge.be5.base.exceptions.Be5Exception; import com.developmentontheedge.be5.base.services.UserInfoProvider; +import com.developmentontheedge.be5.base.util.HashUrl; import com.developmentontheedge.be5.operation.util.OperationUtils; import com.developmentontheedge.be5.server.RestApiConstants; import com.developmentontheedge.be5.server.helpers.JsonApiResponseHelper; @@ -14,8 +15,12 @@ import com.google.inject.Stage; import javax.inject.Inject; +import java.util.Collections; import java.util.Map; +import java.util.logging.Level; +import static com.developmentontheedge.be5.base.FrontendConstants.FORM_ACTION; +import static com.developmentontheedge.be5.server.RestApiConstants.SELF_LINK; import static com.google.common.base.Strings.nullToEmpty; @@ -79,7 +84,11 @@ public void generate(Request req, Response res, String requestSubUrl) } catch(Be5Exception e) { - responseHelper.sendErrorAsJson(e, req); + String url = new HashUrl(FORM_ACTION, entityName, queryName, operationName).named(operationParams).toString(); + + log.log(Level.SEVERE, "Error in operation: " + url + ", on requestSubUrl = '" + requestSubUrl + "'", e); + + responseHelper.sendErrorAsJson(responseHelper.getErrorModel(e, Collections.singletonMap(SELF_LINK, url)), req); } } diff --git a/server/src/main/java/com/developmentontheedge/be5/server/controllers/QueryBuilderController.java b/server/src/main/java/com/developmentontheedge/be5/server/controllers/QueryBuilderController.java index 21c444f9c..4a3c83113 100644 --- a/server/src/main/java/com/developmentontheedge/be5/server/controllers/QueryBuilderController.java +++ b/server/src/main/java/com/developmentontheedge/be5/server/controllers/QueryBuilderController.java @@ -156,9 +156,9 @@ public void generate(Request req, Response res, String requestSubUrl) else { responseHelper.sendErrorAsJson( - responseHelper.getErrorModel(Be5Exception.accessDenied(), "Role " + RoleType.ROLE_SYSTEM_DEVELOPER + " required.", + responseHelper.getErrorModel(Be5Exception.accessDenied("Role " + RoleType.ROLE_SYSTEM_DEVELOPER + " required."), Collections.singletonMap(SELF_LINK, "queryBuilder")), - responseHelper.getDefaultMeta(req) + req ); } } diff --git a/server/src/main/java/com/developmentontheedge/be5/server/helpers/JsonApiResponseHelper.java b/server/src/main/java/com/developmentontheedge/be5/server/helpers/JsonApiResponseHelper.java index 4568f5aec..a14024551 100644 --- a/server/src/main/java/com/developmentontheedge/be5/server/helpers/JsonApiResponseHelper.java +++ b/server/src/main/java/com/developmentontheedge/be5/server/helpers/JsonApiResponseHelper.java @@ -1,7 +1,10 @@ package com.developmentontheedge.be5.server.helpers; import com.developmentontheedge.be5.base.exceptions.Be5Exception; +import com.developmentontheedge.be5.base.services.UserAwareMeta; import com.developmentontheedge.be5.base.services.UserInfoProvider; +import com.developmentontheedge.be5.base.util.HtmlUtils; +import com.developmentontheedge.be5.operation.services.GroovyOperationLoader; import com.developmentontheedge.be5.server.model.jsonapi.ErrorModel; import com.developmentontheedge.be5.server.model.jsonapi.JsonApiModel; import com.developmentontheedge.be5.server.model.jsonapi.ResourceData; @@ -13,7 +16,10 @@ import java.io.PrintWriter; import java.io.StringWriter; import java.util.Collections; +import java.util.HashSet; import java.util.Map; +import java.util.Set; +import java.util.Stack; import java.util.logging.Logger; import static com.developmentontheedge.be5.server.RestApiConstants.TIMESTAMP_PARAM; @@ -24,13 +30,18 @@ public class JsonApiResponseHelper public final Logger log = Logger.getLogger(JsonApiResponseHelper.class.getName()); private final UserInfoProvider userInfoProvider; + private final GroovyOperationLoader groovyOperationLoader; private final Provider responseProvider; + private final UserAwareMeta userAwareMeta; @Inject - public JsonApiResponseHelper(UserInfoProvider userInfoProvider, Provider responseProvider) + public JsonApiResponseHelper(UserInfoProvider userInfoProvider, GroovyOperationLoader groovyOperationLoader, + Provider responseProvider, UserAwareMeta userAwareMeta) { this.userInfoProvider = userInfoProvider; + this.groovyOperationLoader = groovyOperationLoader; this.responseProvider = responseProvider; + this.userAwareMeta = userAwareMeta; } public void sendAsJson(JsonApiModel jsonApiModel) @@ -58,24 +69,24 @@ public void sendErrorAsJson(Be5Exception e, Request req) responseProvider.get().sendAsJson(JsonApiModel.error(getErrorModel(e), getDefaultMeta(req))); } - public void sendErrorAsJson(ErrorModel error, Object meta) + public void sendErrorAsJson(ErrorModel error, Request req) { - responseProvider.get().sendAsJson(JsonApiModel.error(error, meta)); + responseProvider.get().sendAsJson(JsonApiModel.error(error, getDefaultMeta(req))); } - public void sendErrorAsJson(ErrorModel error, ResourceData[] included, Object meta) - { - responseProvider.get().sendAsJson(JsonApiModel.error(error, included, meta)); - } +// public void sendErrorAsJson(ErrorModel error, ResourceData[] included, Object meta) +// { +// responseProvider.get().sendAsJson(JsonApiModel.error(error, included, meta)); +// } - public void sendErrorAsJson(ErrorModel error, ResourceData[] included, Object meta, Map links) - { - responseProvider.get().sendAsJson(JsonApiModel.error(error, included, meta, links)); - } +// public void sendErrorAsJson(ErrorModel error, ResourceData[] included, Object meta, Map links) +// { +// responseProvider.get().sendAsJson(JsonApiModel.error(error, included, meta, links)); +// } public void sendUnknownActionError(Request req) { - sendErrorAsJson( new ErrorModel("404", "Unknown component action."), getDefaultMeta(req)); + sendErrorAsJson( Be5Exception.notFound("route" + req.getRequestUri()), req); } private String exceptionAsString(Throwable e) @@ -98,19 +109,24 @@ private String exceptionAsString(Throwable e) public ErrorModel getErrorModel(Be5Exception e) { - return getErrorModel(e, "", null); + return getErrorModel(e, null); } - public ErrorModel getErrorModel(Be5Exception e, String additionalMessage, Map links) + public ErrorModel getErrorModel(Be5Exception e, Map links) { if(userInfoProvider.isSystemDeveloper()) { - return new ErrorModel(e.getHttpStatusCode(), e.getMessage(), Be5Exception.getMessage(e) + additionalMessage, - exceptionAsString(e), links); + return new ErrorModel( + e.getHttpStatusCode(), + userAwareMeta.getLocalizedBe5ErrorMessage(e), + Be5Exception.getMessage(e) + getErrorCodeLine(e), + exceptionAsString(e), + links + ); } else { - return new ErrorModel(e.getHttpStatusCode(), e.getMessage(), links); + return new ErrorModel(e.getHttpStatusCode(), userAwareMeta.getLocalizedBe5ErrorMessage(e), links); } } @@ -119,4 +135,66 @@ public Object getDefaultMeta(Request request) return Collections.singletonMap(TIMESTAMP_PARAM, request.get(TIMESTAMP_PARAM)); } + private String getErrorCodeLine(Throwable e) + { + Set printedGroovyClasses = new HashSet<>(); + Throwable err = e; + + Stack throwables = new Stack<>(); + throwables.add(err); + while (err.getCause() != null) + { + throwables.add(err.getCause()); + err = err.getCause(); + } + + StringBuilder sb = new StringBuilder(); + while (!throwables.empty()) + { + err = throwables.pop(); + + StackTraceElement[] stackTrace = err.getStackTrace(); + for (int i = 0; i < stackTrace.length; i++) + { + if(stackTrace[i].getFileName() != null && stackTrace[i].getFileName().endsWith(".groovy") + && !printedGroovyClasses.contains(stackTrace[i].getFileName())) + { + printedGroovyClasses.add(stackTrace[i].getFileName()); + sb.append(getErrorCodeLinesForClass(stackTrace[i])); + break; + } + } + } + + return sb.toString(); + } + + private String getErrorCodeLinesForClass(StackTraceElement e) + { + int lineID = e.getLineNumber(); + StringBuilder sb = new StringBuilder("\n" + Be5Exception.getFullStackTraceLine(e)); + + String className = e.getClassName().indexOf('$') == -1 + ? e.getClassName() + : e.getClassName().substring(0, e.getClassName().indexOf('$')); + + String code = groovyOperationLoader + .getByFullName(className + ".groovy") + .getCode(); + String lines[] = HtmlUtils.escapeHTML(code).split("\\r?\\n"); + + sb.append("\n\n"); + for (int i = Math.max(0, lineID - 4); i < Math.min(lineID + 3, lines.length); i++) + { + String lineNumber = String.format("%4d", i+1)+" | "; + if(lineID == i+1){ + sb.append("").append(lineNumber).append(lines[i]).append("\n"); + }else{ + sb.append(lineNumber).append(lines[i]).append("\n"); + } + } + sb.append(""); + + return sb.toString(); + } } diff --git a/server/src/main/java/com/developmentontheedge/be5/server/services/impl/DocumentGeneratorImpl.java b/server/src/main/java/com/developmentontheedge/be5/server/services/impl/DocumentGeneratorImpl.java index 062079b55..66fa484bd 100644 --- a/server/src/main/java/com/developmentontheedge/be5/server/services/impl/DocumentGeneratorImpl.java +++ b/server/src/main/java/com/developmentontheedge/be5/server/services/impl/DocumentGeneratorImpl.java @@ -245,9 +245,9 @@ public JsonApiModel queryJsonApiFor(String entityName, String queryName, Map + *

Same as, + * {@link #sendEmail(InternetAddress, InternetAddress[], String, String, String)} + * only parameter "from" - "MAIL_FROM_ADDRESS" or "MAIL_FROM_NAME", parameter "to" as string. + * + * @param to + * @param subject + * @param body + * @throws Exception + */ + public void sendPlainEmail(String to, String subject, String body) + throws Exception + { + sendEmail(null, + new InternetAddress[]{new InternetAddress(to)}, subject, body, "text/plain"); + } + + /** + * Send email with parameter type="text/html". + *

+ *

Same as, + * {@link #sendEmail(InternetAddress, InternetAddress[], String, String, String)} + * only parameter "from" - "MAIL_FROM_ADDRESS" or "MAIL_FROM_NAME", parameter "to" as string. + * + * @param to + * @param subject + * @param body + * @throws Exception + */ + public void sendHtmlEmail(String to, String subject, String body) + throws Exception + { + sendEmail(null, + new InternetAddress[]{new InternetAddress(to)}, subject, body, "text/html"); + } + + /** + * Same as, + * {@link #sendEmailReal(InternetAddress, InternetAddress[], String, String, String, Map) sendEmailReal(InternetAddress, InternetAddress[], String, String, String, Map, Locale)} + * only map of localized messages extract from a current operation. + * + * @param from + * @param to + * @param subject + * @param body + * @param type + * @throws Exception + */ + public void sendEmail(InternetAddress from, InternetAddress[] to, String subject, String body, String type) + throws Exception + { +// Map locMessages = Utils.readLocalizedMessages( +// userInfo.getLocale(), entity, getName() ); + + sendEmailReal(from, to, subject, body, type, Collections.emptyMap()); + } + + /** + * Send email passed localized. + * + * @param from + * @param to + * @param subject + * @param body + * @param type + * @param locMessages + * @throws Exception + */ + public void sendEmailReal(InternetAddress from, InternetAddress[] to, String subject, String body, String type, + Map locMessages) + throws Exception + { + String enc = "UTF-8"; + MimeMessage2 message = createMimeMessage(); + + + StringWriter writer = new StringWriter(); + //LocalizingWriter lWriter = new LocalizingWriter( locale, writer, locMessages ); + +// if( subject != null && subject.indexOf( LOC_MSG_PREFIX ) >= 0 ) +// { +// writer.write( subject ); +// writer.flush(); +// writer.close(); +// subject = writer.getBuffer().toString(); +// +// writer = new StringWriter(); +// lWriter = new LocalizingWriter( locale, writer, locMessages ); +// } +// else +// { +// subject = Utils.getMessage( locMessages, subject ); +// } + +// lWriter.write( body ); +// lWriter.flush(); +// lWriter.close(); + + if(from != null) + { + message.setFrom(from); + } + + message.setSubject(subject, enc); + message.addRecipients(Message.RecipientType.TO, to); + + message.setDataHandler( + getEmailBodyDataHandler( + writer.getBuffer().toString().getBytes(enc), + type + "; charset=" + enc) + ); + + Transport.send(message); + } + + /** + * Retrieves data handler for the Mime message. + * + * @param bodyBytes message body, as byte array + * @param mimeType body text parameter + * @return + */ + public static DataHandler getEmailBodyDataHandler(final byte[] bodyBytes, final String mimeType) + { + return new DataHandler( + new DataSource() + { + @Override + public String getContentType() + { + return mimeType; + } + + @Override + public String getName() + { + return ""; + } + + @Override + public OutputStream getOutputStream() throws IOException + { + throw new UnknownServiceException(); + } + + @Override + public InputStream getInputStream() + { + return new ByteArrayInputStream(bodyBytes); + } + }); + } + + static class SmtpAuthenticator extends Authenticator + { + private String user = null; + private String pwd = null; + + public SmtpAuthenticator(String user, String pwd) + { + this.user = user; + this.pwd = pwd; + } + + @Override + protected PasswordAuthentication getPasswordAuthentication() + { + return new PasswordAuthentication(this.user, this.pwd); + } + } + + /** + * Creates session for the mail host. Mail host is passed parameter "host" or host is fetching from the system settings + * ( {@link CoreUtils#getSystemSetting(String) getSystemSetting(DatabaseConnector, String)} ), parameter "MAIL_HOST". + * If mail host wasn't specified or is empty, then "localhost" will be taken instead. + * + * @param host mail host + * @return + */ + public Session getMailSession(String host) + { + Properties props = new Properties(); + props.setProperty("mail.transport.protocol", "smtp"); + + if(host == null) + { + host = coreUtils.getSystemSetting("MAIL_HOST"); + if(Utils.isEmpty(host)) + { + host = "localhost"; + log.warning("No mail host defined (MAIL_HOST). Using localhost."); + } + } + props.setProperty("mail.host", host); + + String login = coreUtils.getSystemSetting("SMTP_AUTH_USER"); + String password = coreUtils.getSystemSetting("SMTP_AUTH_PASSWORD"); + if(!Utils.isEmpty(login) && !Utils.isEmpty(password)) + { + props.put("mail.smtp.user", login); + props.put("mail.smtp.auth", "true"); + if(host.endsWith(".gmail.com")) + { + props.put("mail.smtp.port", "587"); + props.put("mail.smtp.starttls.enable", "true"); + } + SmtpAuthenticator auth = new SmtpAuthenticator(login, password); + Session session = Session.getInstance(props, auth); + if(Boolean.parseBoolean(coreUtils.getSystemSetting("SMTP_DEBUG", "false"))) + { + session.setDebug(true); + session.setDebugOut(new MimeMessage2.PrintStream2(new ByteArrayOutputStream(), true)); + } + return session; + } + return Session.getInstance(props); + } + + /** + * Use {@link #createMimeMessage(String, InputStream) createMimeMessage(DatabaseConnector, String, InputStream)}, + * with host=null and stream=null + * + * @return created mime message + * @throws MessagingException + * @throws UnsupportedEncodingException + */ + public MimeMessage2 createMimeMessage() + throws MessagingException, UnsupportedEncodingException + { + return createMimeMessage(null, null); + } + + /** + * Creates mime message from passed stream, for sending it as letter with the specified host. If system settings contains parameter + * "MAIL_FROM_ADDRESS" or "MAIL_FROM_NAME", then mime message will contain from address and name. + * + * @param host smtp host + * @param stream message body + * @return created mime message + * @throws MessagingException + * @throws UnsupportedEncodingException + */ + public MimeMessage2 createMimeMessage(String host, InputStream stream) + throws MessagingException, UnsupportedEncodingException + { + MimeMessage2 message = stream == null + ? new MimeMessage2(getMailSession(host)) + : new MimeMessage2(getMailSession(host), stream); + + if(stream != null) + { + return message; + } + + String fromAddr = coreUtils.getSystemSetting("MAIL_FROM_ADDRESS"); + String fromName = coreUtils.getSystemSetting("MAIL_FROM_NAME"); + + if(Utils.isEmpty(fromAddr)) + { + return message; + } + + if(!Utils.isEmpty(fromName)) + { + message.setFrom(new InternetAddress(fromAddr, fromName, "UTF-8")); + } else + { + message.setFrom(new InternetAddress(fromAddr)); + } + + return message; + } + +} diff --git a/server/src/main/java/com/developmentontheedge/be5/server/services/mail/MimeMessage2.java b/server/src/main/java/com/developmentontheedge/be5/server/services/mail/MimeMessage2.java new file mode 100644 index 000000000..887b12a58 --- /dev/null +++ b/server/src/main/java/com/developmentontheedge/be5/server/services/mail/MimeMessage2.java @@ -0,0 +1,42 @@ +package com.developmentontheedge.be5.server.services.mail; + +import javax.mail.MessagingException; +import javax.mail.Session; +import javax.mail.internet.MimeMessage; +import java.io.ByteArrayOutputStream; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.PrintStream; + + +public class MimeMessage2 extends MimeMessage +{ + public static class PrintStream2 extends PrintStream + { + public PrintStream2(OutputStream outputStream, boolean autoFlush ) + { + super( outputStream, autoFlush ); + } + + public ByteArrayOutputStream getOutput() + { + return (ByteArrayOutputStream)out; + } + } + + public MimeMessage2( Session session ) + { + super( session ); + } + + public MimeMessage2( Session session, InputStream is ) + throws MessagingException + { + super( session, is ); + } + + public Session getSession() + { + return session; + } +} diff --git a/sql/src/main/java/com/developmentontheedge/sql/format/Context.java b/sql/src/main/java/com/developmentontheedge/sql/format/dbms/Context.java similarity index 86% rename from sql/src/main/java/com/developmentontheedge/sql/format/Context.java rename to sql/src/main/java/com/developmentontheedge/sql/format/dbms/Context.java index d4281e241..591debd5b 100644 --- a/sql/src/main/java/com/developmentontheedge/sql/format/Context.java +++ b/sql/src/main/java/com/developmentontheedge/sql/format/dbms/Context.java @@ -1,29 +1,30 @@ -package com.developmentontheedge.sql.format; +package com.developmentontheedge.sql.format.dbms; public class Context { + protected Dbms dbms; + protected DbmsTransformer dbmsTransformer; + public Context(Dbms dbms) { this.dbms = dbms; switch(dbms) { - case DB2: dbmsTransformer = new DB2Transformer(); break; - case MYSQL: dbmsTransformer = new MySqlTransformer(); break; - case ORACLE: dbmsTransformer = new OracleTransformer(); break; - case POSTGRESQL: dbmsTransformer = new PostgreSqlTransformer(); break; + case DB2: dbmsTransformer = new DB2Transformer(); break; + case MYSQL: dbmsTransformer = new MySqlTransformer(); break; + case ORACLE: dbmsTransformer = new OracleTransformer(); break; + case POSTGRESQL: dbmsTransformer = new PostgreSqlTransformer(); break; case SQLSERVER: dbmsTransformer = new SqlServerTransformer(); break; case H2: dbmsTransformer = new PostgreSqlTransformer(); break; } } - protected Dbms dbms; public Dbms getDbms() { return dbms; } - - protected DbmsTransformer dbmsTransformer; + public DbmsTransformer getDbmsTransformer() { return dbmsTransformer; diff --git a/sql/src/main/java/com/developmentontheedge/sql/format/DB2Transformer.java b/sql/src/main/java/com/developmentontheedge/sql/format/dbms/DB2Transformer.java similarity index 99% rename from sql/src/main/java/com/developmentontheedge/sql/format/DB2Transformer.java rename to sql/src/main/java/com/developmentontheedge/sql/format/dbms/DB2Transformer.java index 3f42c88a5..53b8d073e 100644 --- a/sql/src/main/java/com/developmentontheedge/sql/format/DB2Transformer.java +++ b/sql/src/main/java/com/developmentontheedge/sql/format/dbms/DB2Transformer.java @@ -1,4 +1,4 @@ -package com.developmentontheedge.sql.format; +package com.developmentontheedge.sql.format.dbms; import com.developmentontheedge.sql.model.AstBetweenPredicate; import com.developmentontheedge.sql.model.AstCast; diff --git a/sql/src/main/java/com/developmentontheedge/sql/format/DateFormat.java b/sql/src/main/java/com/developmentontheedge/sql/format/dbms/DateFormat.java similarity index 95% rename from sql/src/main/java/com/developmentontheedge/sql/format/DateFormat.java rename to sql/src/main/java/com/developmentontheedge/sql/format/dbms/DateFormat.java index becf1c1e0..99f29806b 100644 --- a/sql/src/main/java/com/developmentontheedge/sql/format/DateFormat.java +++ b/sql/src/main/java/com/developmentontheedge/sql/format/dbms/DateFormat.java @@ -1,7 +1,8 @@ -package com.developmentontheedge.sql.format; +package com.developmentontheedge.sql.format.dbms; -public enum DateFormat { +public enum DateFormat +{ FORMAT_DATE("'YYYY-MM-DD'", "'%Y-%m-%d'"), FORMAT_DATETIME("'YYYY-MM-DD HH24:MI:SS'", "'%Y-%m-%d %H:%i:%S'"), FORMAT_DATE_RUS("'DD.MM.YYYY'", "'%d.%m.%Y'"), diff --git a/sql/src/main/java/com/developmentontheedge/sql/format/Dbms.java b/sql/src/main/java/com/developmentontheedge/sql/format/dbms/Dbms.java similarity index 86% rename from sql/src/main/java/com/developmentontheedge/sql/format/Dbms.java rename to sql/src/main/java/com/developmentontheedge/sql/format/dbms/Dbms.java index d241d1b15..4d41edc48 100644 --- a/sql/src/main/java/com/developmentontheedge/sql/format/Dbms.java +++ b/sql/src/main/java/com/developmentontheedge/sql/format/dbms/Dbms.java @@ -1,4 +1,4 @@ -package com.developmentontheedge.sql.format; +package com.developmentontheedge.sql.format.dbms; public enum Dbms { diff --git a/sql/src/main/java/com/developmentontheedge/sql/format/DbmsTransformer.java b/sql/src/main/java/com/developmentontheedge/sql/format/dbms/DbmsTransformer.java similarity index 56% rename from sql/src/main/java/com/developmentontheedge/sql/format/DbmsTransformer.java rename to sql/src/main/java/com/developmentontheedge/sql/format/dbms/DbmsTransformer.java index 2edacdc36..cadfa6489 100644 --- a/sql/src/main/java/com/developmentontheedge/sql/format/DbmsTransformer.java +++ b/sql/src/main/java/com/developmentontheedge/sql/format/dbms/DbmsTransformer.java @@ -1,4 +1,4 @@ -package com.developmentontheedge.sql.format; +package com.developmentontheedge.sql.format.dbms; import com.developmentontheedge.sql.model.AstQuery; import com.developmentontheedge.sql.model.AstStart; @@ -11,10 +11,9 @@ */ public interface DbmsTransformer { - public void transformAst(AstStart start); - public void transformQuery(AstQuery start); - - public ParserContext getParserContext(); - public void setParserContext(ParserContext parserContext); + void transformAst(AstStart start); + void transformQuery(AstQuery start); + ParserContext getParserContext(); + void setParserContext(ParserContext parserContext); } diff --git a/sql/src/main/java/com/developmentontheedge/sql/format/Formatter.java b/sql/src/main/java/com/developmentontheedge/sql/format/dbms/Formatter.java similarity index 94% rename from sql/src/main/java/com/developmentontheedge/sql/format/Formatter.java rename to sql/src/main/java/com/developmentontheedge/sql/format/dbms/Formatter.java index 93bff4e66..8dd6db203 100644 --- a/sql/src/main/java/com/developmentontheedge/sql/format/Formatter.java +++ b/sql/src/main/java/com/developmentontheedge/sql/format/dbms/Formatter.java @@ -1,4 +1,4 @@ -package com.developmentontheedge.sql.format; +package com.developmentontheedge.sql.format.dbms; import com.developmentontheedge.sql.model.AstQuery; import com.developmentontheedge.sql.model.AstStart; diff --git a/sql/src/main/java/com/developmentontheedge/sql/format/GenericDbmsTransformer.java b/sql/src/main/java/com/developmentontheedge/sql/format/dbms/GenericDbmsTransformer.java similarity index 99% rename from sql/src/main/java/com/developmentontheedge/sql/format/GenericDbmsTransformer.java rename to sql/src/main/java/com/developmentontheedge/sql/format/dbms/GenericDbmsTransformer.java index 077116d9f..9e0bd7991 100644 --- a/sql/src/main/java/com/developmentontheedge/sql/format/GenericDbmsTransformer.java +++ b/sql/src/main/java/com/developmentontheedge/sql/format/dbms/GenericDbmsTransformer.java @@ -1,4 +1,4 @@ -package com.developmentontheedge.sql.format; +package com.developmentontheedge.sql.format.dbms; import com.developmentontheedge.sql.model.AstCase; import com.developmentontheedge.sql.model.AstCaseElse; diff --git a/sql/src/main/java/com/developmentontheedge/sql/format/MySqlTransformer.java b/sql/src/main/java/com/developmentontheedge/sql/format/dbms/MySqlTransformer.java similarity index 99% rename from sql/src/main/java/com/developmentontheedge/sql/format/MySqlTransformer.java rename to sql/src/main/java/com/developmentontheedge/sql/format/dbms/MySqlTransformer.java index f96d93bde..593590890 100644 --- a/sql/src/main/java/com/developmentontheedge/sql/format/MySqlTransformer.java +++ b/sql/src/main/java/com/developmentontheedge/sql/format/dbms/MySqlTransformer.java @@ -1,4 +1,4 @@ -package com.developmentontheedge.sql.format; +package com.developmentontheedge.sql.format.dbms; import com.developmentontheedge.sql.model.AstCase; import com.developmentontheedge.sql.model.AstCaseElse; diff --git a/sql/src/main/java/com/developmentontheedge/sql/format/OracleTransformer.java b/sql/src/main/java/com/developmentontheedge/sql/format/dbms/OracleTransformer.java similarity index 99% rename from sql/src/main/java/com/developmentontheedge/sql/format/OracleTransformer.java rename to sql/src/main/java/com/developmentontheedge/sql/format/dbms/OracleTransformer.java index 5fe78d694..f5d352355 100644 --- a/sql/src/main/java/com/developmentontheedge/sql/format/OracleTransformer.java +++ b/sql/src/main/java/com/developmentontheedge/sql/format/dbms/OracleTransformer.java @@ -1,4 +1,4 @@ -package com.developmentontheedge.sql.format; +package com.developmentontheedge.sql.format.dbms; import com.developmentontheedge.sql.model.AstCast; import com.developmentontheedge.sql.model.AstConcatExpression; diff --git a/sql/src/main/java/com/developmentontheedge/sql/format/PostgreSqlTransformer.java b/sql/src/main/java/com/developmentontheedge/sql/format/dbms/PostgreSqlTransformer.java similarity index 99% rename from sql/src/main/java/com/developmentontheedge/sql/format/PostgreSqlTransformer.java rename to sql/src/main/java/com/developmentontheedge/sql/format/dbms/PostgreSqlTransformer.java index 74954416f..1afdba0c1 100644 --- a/sql/src/main/java/com/developmentontheedge/sql/format/PostgreSqlTransformer.java +++ b/sql/src/main/java/com/developmentontheedge/sql/format/dbms/PostgreSqlTransformer.java @@ -1,4 +1,4 @@ -package com.developmentontheedge.sql.format; +package com.developmentontheedge.sql.format.dbms; import com.developmentontheedge.sql.model.AstCase; import com.developmentontheedge.sql.model.AstCaseElse; diff --git a/sql/src/main/java/com/developmentontheedge/sql/format/SqlServerTransformer.java b/sql/src/main/java/com/developmentontheedge/sql/format/dbms/SqlServerTransformer.java similarity index 99% rename from sql/src/main/java/com/developmentontheedge/sql/format/SqlServerTransformer.java rename to sql/src/main/java/com/developmentontheedge/sql/format/dbms/SqlServerTransformer.java index edc3277c6..b646fd4e2 100644 --- a/sql/src/main/java/com/developmentontheedge/sql/format/SqlServerTransformer.java +++ b/sql/src/main/java/com/developmentontheedge/sql/format/dbms/SqlServerTransformer.java @@ -1,4 +1,4 @@ -package com.developmentontheedge.sql.format; +package com.developmentontheedge.sql.format.dbms; import com.developmentontheedge.sql.model.AstBetweenPredicate; import com.developmentontheedge.sql.model.AstCase; diff --git a/sql/src/main/java/com/developmentontheedge/sql/model/AstBeDbmsTransform.java b/sql/src/main/java/com/developmentontheedge/sql/model/AstBeDbmsTransform.java index 8c1309400..88574222c 100644 --- a/sql/src/main/java/com/developmentontheedge/sql/model/AstBeDbmsTransform.java +++ b/sql/src/main/java/com/developmentontheedge/sql/model/AstBeDbmsTransform.java @@ -1,6 +1,6 @@ package com.developmentontheedge.sql.model; -import com.developmentontheedge.sql.format.Dbms; +import com.developmentontheedge.sql.format.dbms.Dbms; import java.util.EnumSet; import java.util.Map; diff --git a/sql/src/main/java/com/developmentontheedge/sql/model/DbSpecificFunction.java b/sql/src/main/java/com/developmentontheedge/sql/model/DbSpecificFunction.java index dd7b593b2..8db90e021 100644 --- a/sql/src/main/java/com/developmentontheedge/sql/model/DbSpecificFunction.java +++ b/sql/src/main/java/com/developmentontheedge/sql/model/DbSpecificFunction.java @@ -1,6 +1,6 @@ package com.developmentontheedge.sql.model; -import com.developmentontheedge.sql.format.Dbms; +import com.developmentontheedge.sql.format.dbms.Dbms; import java.util.Arrays; import java.util.Collections; diff --git a/sql/src/main/java/com/developmentontheedge/sql/model/DefaultParserContext.java b/sql/src/main/java/com/developmentontheedge/sql/model/DefaultParserContext.java index 9b9e40a75..ac8fa4ca0 100644 --- a/sql/src/main/java/com/developmentontheedge/sql/model/DefaultParserContext.java +++ b/sql/src/main/java/com/developmentontheedge/sql/model/DefaultParserContext.java @@ -1,7 +1,7 @@ package com.developmentontheedge.sql.model; -import com.developmentontheedge.sql.format.DateFormat; -import com.developmentontheedge.sql.format.Dbms; +import com.developmentontheedge.sql.format.dbms.DateFormat; +import com.developmentontheedge.sql.format.dbms.Dbms; import one.util.streamex.StreamEx; import java.util.HashMap; diff --git a/sql/src/test/java/com/developmentontheedge/sql/CloneTest.java b/sql/src/test/java/com/developmentontheedge/sql/CloneTest.java index 4d61c714d..5a3a32cfc 100644 --- a/sql/src/test/java/com/developmentontheedge/sql/CloneTest.java +++ b/sql/src/test/java/com/developmentontheedge/sql/CloneTest.java @@ -1,8 +1,8 @@ package com.developmentontheedge.sql; -import com.developmentontheedge.sql.format.Context; -import com.developmentontheedge.sql.format.Dbms; -import com.developmentontheedge.sql.format.Formatter; +import com.developmentontheedge.sql.format.dbms.Context; +import com.developmentontheedge.sql.format.dbms.Dbms; +import com.developmentontheedge.sql.format.dbms.Formatter; import com.developmentontheedge.sql.model.AstSelect; import com.developmentontheedge.sql.model.AstStart; import com.developmentontheedge.sql.model.DefaultParserContext; diff --git a/sql/src/test/java/com/developmentontheedge/sql/FilterApplierTest.java b/sql/src/test/java/com/developmentontheedge/sql/FilterApplierTest.java index b8837aea2..c659698da 100644 --- a/sql/src/test/java/com/developmentontheedge/sql/FilterApplierTest.java +++ b/sql/src/test/java/com/developmentontheedge/sql/FilterApplierTest.java @@ -1,10 +1,10 @@ package com.developmentontheedge.sql; import com.developmentontheedge.sql.format.ColumnRef; -import com.developmentontheedge.sql.format.Context; -import com.developmentontheedge.sql.format.Dbms; +import com.developmentontheedge.sql.format.dbms.Context; +import com.developmentontheedge.sql.format.dbms.Dbms; import com.developmentontheedge.sql.format.FilterApplier; -import com.developmentontheedge.sql.format.Formatter; +import com.developmentontheedge.sql.format.dbms.Formatter; import com.developmentontheedge.sql.model.AstStart; import com.developmentontheedge.sql.model.DefaultParserContext; import com.developmentontheedge.sql.model.SqlQuery; diff --git a/sql/src/test/java/com/developmentontheedge/sql/LimitsApplierTest.java b/sql/src/test/java/com/developmentontheedge/sql/LimitsApplierTest.java index a685907f6..507c01508 100644 --- a/sql/src/test/java/com/developmentontheedge/sql/LimitsApplierTest.java +++ b/sql/src/test/java/com/developmentontheedge/sql/LimitsApplierTest.java @@ -1,8 +1,8 @@ package com.developmentontheedge.sql; -import com.developmentontheedge.sql.format.Context; -import com.developmentontheedge.sql.format.Dbms; -import com.developmentontheedge.sql.format.Formatter; +import com.developmentontheedge.sql.format.dbms.Context; +import com.developmentontheedge.sql.format.dbms.Dbms; +import com.developmentontheedge.sql.format.dbms.Formatter; import com.developmentontheedge.sql.format.LimitsApplier; import com.developmentontheedge.sql.model.AstStart; import com.developmentontheedge.sql.model.DefaultParserContext; diff --git a/sql/src/test/java/com/developmentontheedge/sql/MacroTest.java b/sql/src/test/java/com/developmentontheedge/sql/MacroTest.java index 545338c1d..5fcbd603c 100644 --- a/sql/src/test/java/com/developmentontheedge/sql/MacroTest.java +++ b/sql/src/test/java/com/developmentontheedge/sql/MacroTest.java @@ -1,8 +1,8 @@ package com.developmentontheedge.sql; -import com.developmentontheedge.sql.format.Context; -import com.developmentontheedge.sql.format.Dbms; -import com.developmentontheedge.sql.format.Formatter; +import com.developmentontheedge.sql.format.dbms.Context; +import com.developmentontheedge.sql.format.dbms.Dbms; +import com.developmentontheedge.sql.format.dbms.Formatter; import com.developmentontheedge.sql.format.MacroExpander; import com.developmentontheedge.sql.model.AstStart; import com.developmentontheedge.sql.model.ParserContext; diff --git a/sql/src/test/java/com/developmentontheedge/sql/OrderByFilterTest.java b/sql/src/test/java/com/developmentontheedge/sql/OrderByFilterTest.java index b77d1a57e..7fef44b34 100644 --- a/sql/src/test/java/com/developmentontheedge/sql/OrderByFilterTest.java +++ b/sql/src/test/java/com/developmentontheedge/sql/OrderByFilterTest.java @@ -1,8 +1,8 @@ package com.developmentontheedge.sql; -import com.developmentontheedge.sql.format.Context; -import com.developmentontheedge.sql.format.Dbms; -import com.developmentontheedge.sql.format.Formatter; +import com.developmentontheedge.sql.format.dbms.Context; +import com.developmentontheedge.sql.format.dbms.Dbms; +import com.developmentontheedge.sql.format.dbms.Formatter; import com.developmentontheedge.sql.format.OrderByFilter; import com.developmentontheedge.sql.model.AstStart; import com.developmentontheedge.sql.model.DefaultParserContext; diff --git a/sql/src/test/java/com/developmentontheedge/sql/ParserTarget.java b/sql/src/test/java/com/developmentontheedge/sql/ParserTarget.java index bbaf5cf37..974c2fd0a 100644 --- a/sql/src/test/java/com/developmentontheedge/sql/ParserTarget.java +++ b/sql/src/test/java/com/developmentontheedge/sql/ParserTarget.java @@ -1,11 +1,11 @@ package com.developmentontheedge.sql; import com.developmentontheedge.sql.format.BasicQueryContext; -import com.developmentontheedge.sql.format.Context; +import com.developmentontheedge.sql.format.dbms.Context; import com.developmentontheedge.sql.format.ContextApplier; import com.developmentontheedge.sql.format.CountApplier; -import com.developmentontheedge.sql.format.Dbms; -import com.developmentontheedge.sql.format.Formatter; +import com.developmentontheedge.sql.format.dbms.Dbms; +import com.developmentontheedge.sql.format.dbms.Formatter; import com.developmentontheedge.sql.format.LimitsApplier; import com.developmentontheedge.sql.format.MacroExpander; import com.developmentontheedge.sql.model.AstStart; diff --git a/test-base/src/main/java/com/developmentontheedge/be5/test/BaseTestUtils.java b/test-base/src/main/java/com/developmentontheedge/be5/test/BaseTestUtils.java index 39b208aae..92f984ee3 100644 --- a/test-base/src/main/java/com/developmentontheedge/be5/test/BaseTestUtils.java +++ b/test-base/src/main/java/com/developmentontheedge/be5/test/BaseTestUtils.java @@ -10,8 +10,10 @@ import com.developmentontheedge.be5.database.DataSourceService; import com.developmentontheedge.be5.database.DbService; import com.developmentontheedge.be5.database.sql.ResultSetParser; +import com.developmentontheedge.be5.metadata.model.BeConnectionProfile; import com.developmentontheedge.be5.metadata.model.Project; import com.developmentontheedge.be5.metadata.scripts.AppDb; +import com.developmentontheedge.be5.metadata.sql.Rdbms; import com.developmentontheedge.be5.metadata.util.JULLogger; import com.developmentontheedge.be5.test.mocks.Be5CachesForTest; import com.developmentontheedge.be5.test.mocks.ConnectionServiceMock; @@ -21,6 +23,7 @@ import com.developmentontheedge.beans.DynamicProperty; import com.developmentontheedge.beans.DynamicPropertySet; import com.developmentontheedge.beans.DynamicPropertySetSupport; +import com.developmentontheedge.dbms.SimpleConnector; import com.google.common.collect.ImmutableMap; import com.google.inject.AbstractModule; import com.google.inject.Guice; @@ -162,6 +165,9 @@ protected static void initDb(Injector injector) profileForIntegrationTests.equals(project.getConnectionProfileName())) { log.info(JULLogger.infoBlock("Execute be5:create-db")); + + dropAllTables(project.getConnectionProfile()); + new AppDb() .setLogger(new JULLogger(log)) .setBe5Project(project) @@ -173,6 +179,21 @@ protected static void initDb(Injector injector) } } + private static void dropAllTables(BeConnectionProfile profile) + { + SimpleConnector connector = new SimpleConnector(Rdbms.getRdbms(profile.getConnectionUrl()).getType(), + profile.getConnectionUrl(), profile.getUsername(), profile.getPassword()); + + try + { + connector.executeUpdate("DROP ALL OBJECTS"); + } + catch(SQLException e) + { + e.printStackTrace(); + } + } + public static class BaseDbMockTestModule extends AbstractModule { @Override diff --git a/test-base/src/main/java/com/developmentontheedge/be5/test/mocks/DataSourceServiceMock.java b/test-base/src/main/java/com/developmentontheedge/be5/test/mocks/DataSourceServiceMock.java index 476cf06f0..8f67ad791 100644 --- a/test-base/src/main/java/com/developmentontheedge/be5/test/mocks/DataSourceServiceMock.java +++ b/test-base/src/main/java/com/developmentontheedge/be5/test/mocks/DataSourceServiceMock.java @@ -1,7 +1,7 @@ package com.developmentontheedge.be5.test.mocks; import com.developmentontheedge.be5.database.DataSourceService; -import com.developmentontheedge.sql.format.Dbms; +import com.developmentontheedge.sql.format.dbms.Dbms; import javax.sql.DataSource; diff --git a/test/src/main/java/com/developmentontheedge/be5/test/TestUtils.java b/test/src/main/java/com/developmentontheedge/be5/test/TestUtils.java index 1e03c2a34..81238859a 100644 --- a/test/src/main/java/com/developmentontheedge/be5/test/TestUtils.java +++ b/test/src/main/java/com/developmentontheedge/be5/test/TestUtils.java @@ -11,6 +11,7 @@ import com.developmentontheedge.be5.operation.model.OperationContext; import com.developmentontheedge.be5.operation.model.OperationInfo; import com.developmentontheedge.be5.operation.model.OperationResult; +import com.developmentontheedge.be5.operation.model.OperationStatus; import com.developmentontheedge.be5.operation.services.OperationExecutor; import com.developmentontheedge.be5.operation.services.OperationService; import com.developmentontheedge.be5.operation.util.Either; @@ -66,8 +67,9 @@ public abstract class TestUtils extends BaseTestUtils public ShowCreatedOperations showCreatedOperations = new ShowCreatedOperations(); @Inject private OperationService operationService; - @Inject private Meta meta; @Inject private OperationExecutor operationExecutor; + + @Inject protected Meta meta; @Inject protected UserAwareMeta userAwareMeta; @Inject protected DatabaseModel database; @Inject protected DbService db; @@ -197,7 +199,12 @@ protected Either generateOperation(Operation operation) protected Either generateOperation(Operation operation, Map presetValues) { - return operationService.generate(operation, replaceEmptyStringToNull(presetValues)); + Either resultEither = operationService.generate(operation, replaceEmptyStringToNull(presetValues)); + if(operation.getStatus() == OperationStatus.ERROR) + { + throw (RuntimeException)operation.getResult().getDetails(); + } + return resultEither; } protected Either executeOperation(String entityName, String queryName, String operationName, @@ -230,7 +237,12 @@ protected Either executeOperation(Operation operation) protected Either executeOperation(Operation operation, Map presetValues) { - return operationService.execute(operation, replaceEmptyStringToNull(presetValues)); + Either resultEither = operationService.execute(operation, replaceEmptyStringToNull(presetValues)); + if(operation.getStatus() == OperationStatus.ERROR) + { + throw (RuntimeException)operation.getResult().getDetails(); + } + return resultEither; } protected Operation createOperation(String entityName, String operationName, OperationContext context)