Search in sources :

Example 1 with ConnectionFactoryException

use of com.varsql.core.exception.ConnectionFactoryException in project varsql by varsqlinfo.

the class SQLServiceImpl method sqlData.

/**
 * @Method Name  : sqlData
 * @Method 설명 : 쿼리 데이터 보기.
 * @작성자   : ytkim
 * @작성일   : 2015. 4. 9.
 * @변경이력  :
 * @param sqlExecuteInfo
 * @param req
 * @return
 * @throws Exception
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
public ResponseResult sqlData(SqlExecuteDTO sqlExecuteInfo, HttpServletRequest req) throws Exception {
    Map sqlParamMap = VartechUtils.jsonStringToObject(sqlExecuteInfo.getSqlParam(), HashMap.class);
    DatabaseInfo dbinfo = SecurityUtil.userDBInfo(sqlExecuteInfo.getConuid());
    ResponseResult parseInfo = SqlSourceBuilder.parseResponseResult(sqlExecuteInfo.getSql(), sqlParamMap, DBType.getDBType(sqlExecuteInfo.getDbType()));
    List<SqlSource> sqlList = parseInfo.getItems();
    int limit = sqlExecuteInfo.getLimit();
    if (!SecurityUtil.isAdmin()) {
        sqlExecuteInfo.setLimit(limit > dbinfo.getMaxSelectCount() ? dbinfo.getMaxSelectCount() : limit);
    }
    ArrayList<SqlSourceResultVO> reLst = new ArrayList<SqlSourceResultVO>();
    ResponseResult result = new ResponseResult();
    Connection conn = null;
    SqlSourceResultVO ssrv = null;
    long stddt = System.currentTimeMillis();
    String[] mmddHH = DateUtils.dateformat("MM-dd-HH", stddt).split("-");
    SqlLogInfoDTO sqlLogInfo = new SqlLogInfoDTO();
    sqlLogInfo.setVconnid(sqlExecuteInfo.getVconnid());
    sqlLogInfo.setViewid(sqlExecuteInfo.getViewid());
    sqlLogInfo.setStartTime(stddt);
    sqlLogInfo.setSMm(Integer.valueOf(mmddHH[0]));
    sqlLogInfo.setSDd(Integer.valueOf(mmddHH[1]));
    sqlLogInfo.setSHh(Integer.valueOf(mmddHH[2]));
    sqlLogInfo.setUsrIp(VarsqlUtils.getClientIp(req));
    SqlSource tmpSqlSource = null;
    int sqldx = 0, sqlSize = sqlList.size();
    String errorMsg = "";
    try {
        conn = ConnectionFactory.getInstance().getConnection(sqlExecuteInfo.getVconnid());
        if (!StringUtils.isBlank(sqlExecuteInfo.get_requid_())) {
            SqlExecuteManager.getInstance().setStatementInfo(sqlExecuteInfo.get_requid_(), null);
        }
        conn.setAutoCommit(false);
        List<SqlStatisticsEntity> allSqlStatistics = new LinkedList<SqlStatisticsEntity>();
        for (sqldx = 0; sqldx < sqlSize; sqldx++) {
            tmpSqlSource = sqlList.get(sqldx);
            ssrv = new SqlSourceResultVO();
            reLst.add(ssrv);
            tmpSqlSource.setResult(ssrv);
            ssrv.setStarttime(System.currentTimeMillis());
            getRequestSqlData(sqlExecuteInfo, conn, tmpSqlSource, dbinfo, true);
            ssrv.setEndtime(System.currentTimeMillis());
            ssrv.setDelay((ssrv.getEndtime() - ssrv.getStarttime()) / 1000);
            ssrv.setResultMessage((ssrv.getDelay()) + " SECOND : " + StringUtils.escape(ssrv.getResultMessage(), EscapeType.html));
            sqlLogInfo.setStartTime(ssrv.getStarttime());
            sqlLogInfo.setCommandType(tmpSqlSource.getCommandType());
            sqlLogInfo.setEndTime(ssrv.getEndtime());
            allSqlStatistics.add(SqlStatisticsEntity.builder().vconnid(sqlLogInfo.getVconnid()).viewid(sqlLogInfo.getViewid()).startTime(ConvertUtils.longToLocalDateTime(sqlLogInfo.getStartTime())).endTime(ConvertUtils.longToLocalDateTime(sqlLogInfo.getEndTime())).delayTime(sqlLogInfo.getDelayTime()).sMm(sqlLogInfo.getSMm()).sDd(sqlLogInfo.getSDd()).sHh(sqlLogInfo.getSHh()).resultCount(sqlLogInfo.getResultCount()).commandType(sqlLogInfo.getCommandType()).build());
            if (SqlDataConstants.VIEWTYPE.GRID.val().equals(ssrv.getViewType())) {
                break;
            }
        }
        commonServiceImpl.sqlLogInsert(allSqlStatistics);
        result.setItemList(reLst);
        conn.commit();
    } catch (Throwable e) {
        if (conn != null && !conn.isClosed())
            conn.rollback();
        errorMsg = e.getMessage();
        if (e instanceof ResultSetConvertException) {
            result.setResultCode(VarsqlAppCode.EC_SQL_RESULT_CONVERT);
            ssrv = ((ResultSetConvertException) e).getSsrv();
            if (ssrv != null) {
                ssrv = new SqlSourceResultVO();
            }
            ssrv.setViewType(SqlDataConstants.VIEWTYPE.GRID.val());
        } else {
            boolean ssrvNullFlag = false;
            if (ssrv == null) {
                ssrvNullFlag = true;
                ssrv = new SqlSourceResultVO();
            }
            ssrv.setEndtime(System.currentTimeMillis());
            String tmpMsg = parseInfo.getMessage();
            tmpMsg = (tmpMsg == null || "".equals(tmpMsg) ? "" : StringUtils.escape(parseInfo.getMessage(), EscapeType.html) + "<br/>");
            if (e instanceof ConnectionFactoryException) {
                if (((ConnectionFactoryException) e).getErrorCode() == VarsqlAppCode.EC_DB_POOL_CLOSE) {
                    result.setResultCode(VarsqlAppCode.EC_DB_POOL_CLOSE);
                } else {
                    result.setResultCode(VarsqlAppCode.EC_DB_POOL);
                }
            } else {
                result.setResultCode(VarsqlAppCode.EC_SQL);
            }
            result.setMessage(tmpMsg + StringUtils.escape(ssrv.getResultMessage(), EscapeType.html));
            if (ssrvNullFlag) {
                result.setMessage(errorMsg);
            }
        }
        result.addCustoms("errorLine", sqldx);
        result.setItemOne(tmpSqlSource == null ? sqlList.get(0) : tmpSqlSource);
        LoggerFactory.getLogger("sqlErrorLog").error("sqlData errorLine : {}", sqldx, e);
    } finally {
        if (conn != null && !conn.isClosed()) {
            conn.setAutoCommit(true);
            JdbcUtils.close(conn);
        }
    }
    if (!StringUtils.isBlank(sqlExecuteInfo.get_requid_())) {
        SqlExecuteManager.getInstance().removeStatementInfo(sqlExecuteInfo.get_requid_());
    }
    long enddt = System.currentTimeMillis();
    commonServiceImpl.saveSqlHistory(SqlHistoryEntity.builder().vconnid(sqlLogInfo.getVconnid()).viewid(sqlLogInfo.getViewid()).startTime(ConvertUtils.longToTimestamp(stddt)).endTime(ConvertUtils.longToTimestamp(enddt)).delayTime((int) ((enddt - stddt) / 1000)).logSql(sqlExecuteInfo.getSql()).usrIp(sqlLogInfo.getUsrIp()).errorLog(errorMsg).build());
    return result;
}
Also used : SqlSource(com.varsql.core.sql.builder.SqlSource) DatabaseInfo(com.varsql.core.db.valueobject.DatabaseInfo) ArrayList(java.util.ArrayList) Connection(java.sql.Connection) LinkedList(java.util.LinkedList) ConnectionFactoryException(com.varsql.core.exception.ConnectionFactoryException) SqlStatisticsEntity(com.varsql.web.model.entity.sql.SqlStatisticsEntity) ResultSetConvertException(com.varsql.core.exception.ResultSetConvertException) ResponseResult(com.vartech.common.app.beans.ResponseResult) SqlSourceResultVO(com.varsql.core.sql.builder.SqlSourceResultVO) SqlLogInfoDTO(com.varsql.web.dto.sql.SqlLogInfoDTO) ParamMap(com.vartech.common.app.beans.ParamMap) Map(java.util.Map) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap)

Example 2 with ConnectionFactoryException

use of com.varsql.core.exception.ConnectionFactoryException in project varsql by varsqlinfo.

the class ConnectionFactory method init.

private void init() {
    try {
        Reflections reflections = new Reflections(new ConfigurationBuilder().setUrls(ClasspathHelper.forPackage("com.varsql")).setScanners(new TypeAnnotationsScanner(), new SubTypesScanner()));
        Set<Class<?>> types = reflections.getTypesAnnotatedWith(ConnectionInfoConfig.class);
        StringBuffer sb = new StringBuffer();
        for (Class<?> type : types) {
            ConnectionInfoConfig annoInfo = type.getAnnotation(ConnectionInfoConfig.class);
            sb.append("beanType : [").append(annoInfo.beanType());
            sb.append("] beanName : [").append(annoInfo.beanName()).append("]");
            if (BeanType.JAVA.equals(annoInfo.beanType())) {
                connectionInfoDao = (ConnectionInfoDao) type.getDeclaredConstructor().newInstance(new Object[] {});
            } else {
                connectionInfoDao = VarsqlSpringBeanUtils.getBean(annoInfo.beanName(), ConnectionInfoDao.class);
            }
            if (annoInfo.primary() == true) {
                break;
            }
        }
        if (connectionInfoDao == null) {
            throw new ConnectionFactoryException(VarsqlAppCode.EC_FACTORY_CONNECTION_INFO, "ConnectionInfoDao bean null; config info : " + sb.toString());
        }
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        throw new ConnectionFactoryException("ConnectionInfoDao bean: " + e.getMessage());
    }
}
Also used : ConfigurationBuilder(org.reflections.util.ConfigurationBuilder) SubTypesScanner(org.reflections.scanners.SubTypesScanner) TypeAnnotationsScanner(org.reflections.scanners.TypeAnnotationsScanner) ConnectionFactoryException(com.varsql.core.exception.ConnectionFactoryException) ConnectionFactoryException(com.varsql.core.exception.ConnectionFactoryException) InvocationTargetException(java.lang.reflect.InvocationTargetException) SQLException(java.sql.SQLException) Reflections(org.reflections.Reflections)

Example 3 with ConnectionFactoryException

use of com.varsql.core.exception.ConnectionFactoryException in project varsql by varsqlinfo.

the class ConnectionFactory method createConnectionInfo.

/**
 * @Method Name  : createConnectionInfo
 * @Method 설명 : connection info 생성.
 * @작성일   : 2018. 2. 13.
 * @작성자   : ytkim
 * @변경이력  :
 * @param connid
 * @return
 * @throws Exception
 */
private synchronized ConnectionInfo createConnectionInfo(String connid) throws ConnectionFactoryException {
    try {
        ConnectionInfo connInfo = connectionInfoDao.getConnectionInfo(connid);
        getPoolBean().createDataSource(connInfo);
        this.connectionConfig.put(connid, connInfo);
        return connInfo;
    } catch (Exception e) {
        this.logger.error("empty connection info", e);
        throw new ConnectionFactoryException("empty connection info : [" + connid + "]", e);
    }
}
Also used : ConnectionInfo(com.varsql.core.connection.beans.ConnectionInfo) ConnectionFactoryException(com.varsql.core.exception.ConnectionFactoryException) InvocationTargetException(java.lang.reflect.InvocationTargetException) SQLException(java.sql.SQLException) ConnectionFactoryException(com.varsql.core.exception.ConnectionFactoryException)

Example 4 with ConnectionFactoryException

use of com.varsql.core.exception.ConnectionFactoryException in project varsql by varsqlinfo.

the class ConnectionDBCP2 method createDataSource.

@Override
public void createDataSource(ConnectionInfo connInfo) throws ConnectionFactoryException {
    logger.info("!!!!!!!!!!!!!!!!! connection create start  !!!!!!!!!!!!!!!!!!!!!!!!!!!");
    try {
        String poolName = connInfo.getConnid();
        Properties properties = setConnectionOption(connInfo);
        Driver dbDriver = JdbcDriverLoader.getInstance().load(connInfo.getJdbcDriverInfo());
        ConnectionFactory connectionFactory;
        if (dbDriver == null) {
            connectionFactory = new DriverManagerConnectionFactory(connInfo.getUrl(), properties);
        } else {
            connectionFactory = new DriverConnectionFactory(dbDriver, connInfo.getUrl(), properties);
        }
        // DBCP가 커넥션 풀에 커넥션을 보관할때 사용하는 PoolableConnectionFactory 생성
        // 실제로 내부적으로 커넥션을 담고있고 커넥션을 관리하는데 기능을 제공한다. ex)커넥션을 close하면 종료하지 않고 커넥션 풀에 반환
        PoolableConnectionFactory poolableConnFactory = new PoolableConnectionFactory(connectionFactory, null);
        poolableConnFactory.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
        // 커넥션이 유효한지 확인할때 사용하는 쿼리를 설정한다.
        poolableConnFactory.setValidationQuery(connInfo.getValidationQuery());
        // 커넥션 풀의 설정 정보를 생성한다.
        GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
        // 유휴 커넥션 검사 주기
        poolConfig.setTimeBetweenEvictionRuns(Duration.ofMillis(1000L * 60L * 1L));
        if (connInfo.isTestWhileIdle()) {
            poolConfig.setTestWhileIdle(true);
        }
        // 커넥션 최소갯수 설정
        poolConfig.setMinIdle(connInfo.getMinIdle());
        // 커넥션 최대 갯수 설정
        poolConfig.setMaxTotal(connInfo.getMaxActive());
        // 커넥션 풀 생성. 인자로는 위에서 생성한  PoolabeConnectionFactory와 GenericObjectPoolConfig를 사용한다.
        GenericObjectPool<PoolableConnection> connectionPool = new GenericObjectPool<PoolableConnection>(poolableConnFactory, poolConfig);
        // PoolabeConnectionFactory에도 커넥션 풀을 연결
        poolableConnFactory.setPool(connectionPool);
        // 위에서 커넥션 풀 드라이버에 생성한 커넥션 풀을 등룍한다. 이름은 cp이다.
        driver.registerPool(poolName, connectionPool);
        logger.debug("poolName : {}", poolName);
        logger.debug("poolConfig : {}", poolConfig);
    } catch (Exception e) {
        throw new ConnectionFactoryException(e.getMessage(), e);
    }
    logger.info("!!!!!!!!!!!!!!!!! connection create  end !!!!!!!!!!!!!!!!!!!!!!!!!!!");
}
Also used : DriverManagerConnectionFactory(org.apache.commons.dbcp2.DriverManagerConnectionFactory) PoolingDriver(org.apache.commons.dbcp2.PoolingDriver) Driver(java.sql.Driver) Properties(java.util.Properties) GenericObjectPool(org.apache.commons.pool2.impl.GenericObjectPool) ConnectionFactoryException(com.varsql.core.exception.ConnectionFactoryException) SQLException(java.sql.SQLException) ConnectionFactoryException(com.varsql.core.exception.ConnectionFactoryException) ConnectionFactory(org.apache.commons.dbcp2.ConnectionFactory) PoolableConnectionFactory(org.apache.commons.dbcp2.PoolableConnectionFactory) DriverManagerConnectionFactory(org.apache.commons.dbcp2.DriverManagerConnectionFactory) DriverConnectionFactory(org.apache.commons.dbcp2.DriverConnectionFactory) GenericObjectPoolConfig(org.apache.commons.pool2.impl.GenericObjectPoolConfig) PoolableConnection(org.apache.commons.dbcp2.PoolableConnection) DriverConnectionFactory(org.apache.commons.dbcp2.DriverConnectionFactory) PoolableConnectionFactory(org.apache.commons.dbcp2.PoolableConnectionFactory)

Example 5 with ConnectionFactoryException

use of com.varsql.core.exception.ConnectionFactoryException in project varsql by varsqlinfo.

the class ConnectionHIKARI method createDataSource.

@Override
public void createDataSource(ConnectionInfo connInfo) throws ConnectionFactoryException {
    try {
        log.info("!!!!!!!!!!!!!!!!! connection create start !!!!!!!!!!!!!!!!!!!!!!!!!!!");
        String poolName = connInfo.getConnid();
        HikariConfig config = new HikariConfig();
        config.setJdbcUrl(connInfo.getUrl());
        config.setUsername(connInfo.getUsername());
        config.setPassword(connInfo.getPassword());
        config.setMaximumPoolSize(connInfo.getMaxActive());
        config.setConnectionTestQuery(connInfo.getValidationQuery());
        config.setConnectionTimeout(connInfo.getConnectionTimeOut() * 1000);
        /*
	        config.addDataSourceProperty( "cachePrepStmts" , "true" );
	        config.addDataSourceProperty( "prepStmtCacheSize" , "250" );
	        config.addDataSourceProperty( "prepStmtCacheSqlLimit" , "2048" );
	        */
        config.setPoolName(poolName);
        log.info("openConnectionPool.Config : {}", config);
        poolShutdown(connInfo);
        connInfo.setDatasource(new HikariDataSource(config));
        log.info("poolName : {}", poolName);
        log.info("connInfo : {}", connInfo);
        log.info("!!!!!!!!!!!!!!!!! connection end !!!!!!!!!!!!!!!!!!!!!!!!!!!");
    } catch (Exception e) {
        throw new ConnectionFactoryException(e.getMessage(), e);
    }
}
Also used : HikariDataSource(com.zaxxer.hikari.HikariDataSource) HikariConfig(com.zaxxer.hikari.HikariConfig) ConnectionFactoryException(com.varsql.core.exception.ConnectionFactoryException) ConnectionFactoryException(com.varsql.core.exception.ConnectionFactoryException)

Aggregations

ConnectionFactoryException (com.varsql.core.exception.ConnectionFactoryException)6 SQLException (java.sql.SQLException)3 ConnectionInfo (com.varsql.core.connection.beans.ConnectionInfo)2 InvocationTargetException (java.lang.reflect.InvocationTargetException)2 Connection (java.sql.Connection)2 ArrayList (java.util.ArrayList)2 FileInfo (com.varsql.core.common.beans.FileInfo)1 JDBCDriverInfo (com.varsql.core.connection.beans.JDBCDriverInfo)1 DatabaseInfo (com.varsql.core.db.valueobject.DatabaseInfo)1 ResultSetConvertException (com.varsql.core.exception.ResultSetConvertException)1 SqlSource (com.varsql.core.sql.builder.SqlSource)1 SqlSourceResultVO (com.varsql.core.sql.builder.SqlSourceResultVO)1 SqlLogInfoDTO (com.varsql.web.dto.sql.SqlLogInfoDTO)1 SqlStatisticsEntity (com.varsql.web.model.entity.sql.SqlStatisticsEntity)1 ParamMap (com.vartech.common.app.beans.ParamMap)1 ResponseResult (com.vartech.common.app.beans.ResponseResult)1 EncryptDecryptException (com.vartech.common.crypto.EncryptDecryptException)1 HikariConfig (com.zaxxer.hikari.HikariConfig)1 HikariDataSource (com.zaxxer.hikari.HikariDataSource)1 Driver (java.sql.Driver)1