Ejemplo n.º 1
0
public class ResponseProcessor {
  private static final org.slf4j.Logger logger = LoggerFactory.getLogger(ResponseProcessor.class);
  private final Map<String, byte[]> uriMap = new HashMap<>();
  private final ControllerConfig config;

  public ResponseProcessor(ControllerConfig config) {
    this.config = config;
  }

  public void requestResponse(
      HttpServletRequest httpRequest, HttpServletResponse httpResponse, ExecuteResult executeResult)
      throws IOException, ServletException {
    ControllerContext context = HttpBaseController.getControllerContext();
    if (executeResult.getException() != null) {
      PrintWriter print = httpResponse.getWriter();
      if (executeResult.getException() instanceof AjaxException) {
        AjaxException ajaxException = (AjaxException) executeResult.getException();
        print.write(ajaxException.getJsonData());
        print.close();
      } else {
        if (executeResult.getException().getMessage() != null) {
          print.write(executeResult.getException().getMessage());
          print.close();
        } else {
          throw new ServletException(executeResult.getException());
        }
      }
    } else {
      if (executeResult.getResult() != null) {
        PrintWriter print = httpResponse.getWriter();
        if (context.getExecuteMethod() == null
            || context.getExecuteMethod().getAnnotation(Ajax.class) != null) {
          httpResponse.setContentType("application/json;charset=UTF-8");
          print.write(JsonUtil.toJson(executeResult.getResult()));
          print.close();
        } else {
          Iterator<String> keyIterator = context.getModel().keySet().iterator();
          while (keyIterator.hasNext()) {
            String key = keyIterator.next();
            httpRequest.setAttribute(key, context.getModel().get(key));
          }
          if (executeResult.getResult() != null && executeResult.getResult() instanceof String) {
            StringBuilder sb = new StringBuilder();
            sb.append(config.getPrefix());
            sb.append(executeResult.getResult());
            sb.append(config.getSuffix());
            RequestDispatcher dispatcher = httpRequest.getRequestDispatcher(sb.toString());
            dispatcher.forward(httpRequest, httpResponse);
            logger.debug("response = " + sb.toString());
          }
        }
      } else {
        String uri = httpRequest.getRequestURI();
        byte[] bf = uriMap.get(uri);
        if (bf == null) {
          String name = httpRequest.getContextPath();
          String path = uri;
          if (StringUtils.isNotEmpty(name)) {
            path = path.replaceFirst(name, "");
          }
          try {
            InputStream is = httpRequest.getServletContext().getResourceAsStream(path);
            if (is != null) {
              bf = new byte[is.available()];
              is.read(bf);
              is.close();
              uriMap.put(uri, bf);
            }
          } catch (Exception e) {
            logger.error(e.getMessage(), e);
          }
        }
        if (bf != null) {
          if (uri != null && (uri.endsWith(".html"))) {
            httpResponse.getWriter().write(new String(bf, config.getCharacterEncoding()));
          } else {
            if (uri.endsWith(".js")) {
              httpResponse.setHeader("Content-Type", "application/javascript");
            } else if (uri.endsWith(".css")) {
              httpResponse.setHeader("Content-Type", "text/css");
            }
            httpResponse.getOutputStream().write(bf);
          }
        }
      }
    }
  }
}
class Table extends AbstractTableModel {
  private static final Logger logger = LoggerFactory.getLogger(DBConnectionInfoPanel.class);
  private static final long serialVersionUID = 1L;

  private List<DBConnectionInfo> dbConnectionInfoList = new ArrayList<>();;

  private String[] title = {
    "标识", "地址", "端口", "数据库类型", "数据库名称", "用户名", "密码", "连接测试用SQL", "最大连接数", "最小连接数", "驱动类", "连接字符串"
  };

  public void addRow(DBConnectionInfo dbConnectionInfo) {
    dbConnectionInfoList.add(dbConnectionInfo);
  }

  public void removeRow(int[] ids) {
    if (dbConnectionInfoList == null || dbConnectionInfoList.size() < 1) {
      return;
    }
    List<DBConnectionInfo> tmpList = new ArrayList<DBConnectionInfo>();
    for (int i = 0; i < ids.length; i++) {
      tmpList.add(dbConnectionInfoList.get(ids[i]));
    }
    dbConnectionInfoList.removeAll(tmpList);
  }

  public void removeRows() {
    dbConnectionInfoList.clear();
  }

  public boolean saveList(String path) {
    Properties properties = LocalResourcesUtil.getProperties(path);
    Iterator<Object> dbsKeys = properties.keySet().iterator();
    String dbsPath = path.substring(0, path.lastIndexOf(File.separator) + 1);
    while (dbsKeys.hasNext()) {
      String key = dbsKeys.next().toString().trim();
      String value = properties.getProperty(key).trim();
      FileUtils.deleteFile(StringUtils.unite(dbsPath, value));
    }
    for (int i = 0; i < dbConnectionInfoList.size(); i++) {
      DBConnectionInfo dbConnectionInfo = dbConnectionInfoList.get(i);
      String key = dbConnectionInfo.getDbCode();
      try {
        String name = StringUtils.unite(key, "DBConfig.properties");
        if (properties.get(key) != null) {
          name = properties.getProperty(key);
        }
        FileOutputStream fos = new FileOutputStream(StringUtils.unite(dbsPath, name));
        fos.write(dbConnectionInfo.toString().getBytes());
        fos.close();
      } catch (IOException e) {
        logger.error(e.getMessage(), e);
      }
    }
    return true;
  }

  @Override
  public boolean isCellEditable(int rowIndex, int columnIndex) {
    if (columnIndex == 10 || columnIndex == 11) {
      return false;
    }
    return true;
  }

  @Override
  public void setValueAt(Object value, int row, int col) {
    DBConnectionInfo tmp = dbConnectionInfoList.get(row);
    if (tmp == null || value == null) {
      return;
    }
    switch (col) {
      case 0:
        tmp.setDbCode(value.toString());
        break;
      case 1:
        tmp.setDbAddress(value.toString());
        break;
      case 2:
        tmp.setDbPort(value.toString());
        break;
      case 3:
        tmp.setDbType(DBType.valueOf(value.toString()));
        break;
      case 4:
        tmp.setDbName(value.toString());
        break;
      case 5:
        tmp.setDbUsername(value.toString());
        break;
      case 6:
        tmp.setDbPassword(value.toString());
        break;
      case 7:
        tmp.setDbTestSQL(value.toString());
        break;
      case 8:
        tmp.setMaxConnectionNum(Integer.valueOf(value.toString()));
        break;
      case 9:
        tmp.setMinConnectionNum(Integer.valueOf(value.toString()));
        break;
    }
    DBType dbtype = tmp.getDbType() == null ? DBType.MYSQL : tmp.getDbType();
    tmp.initConnectionString(ConfigDbUtil.init().getConnectionStringFormat(dbtype));
    for (int i = 0; i < title.length; i++) {
      this.fireTableCellUpdated(row, i);
    }
  }

  @Override
  public String getColumnName(int col) {
    return title[col];
  }

  @Override
  public int getColumnCount() {
    return title.length;
  }

  @Override
  public int getRowCount() {
    return dbConnectionInfoList.size();
  }

  @Override
  public Object getValueAt(int row, int col) {
    Object tmp = new Object();
    switch (col) {
      case 0:
        tmp = dbConnectionInfoList.get(row).getDbCode();
        break;
      case 1:
        tmp = dbConnectionInfoList.get(row).getDbAddress();
        break;
      case 2:
        tmp = dbConnectionInfoList.get(row).getDbPort();
        break;
      case 3:
        tmp = dbConnectionInfoList.get(row).getDbType();
        break;
      case 4:
        tmp = dbConnectionInfoList.get(row).getDbName();
        break;
      case 5:
        tmp = dbConnectionInfoList.get(row).getDbUsername();
        break;
      case 6:
        tmp = dbConnectionInfoList.get(row).getDbPassword();
        break;
      case 7:
        tmp = dbConnectionInfoList.get(row).getDbTestSQL();
        break;
      case 8:
        tmp = dbConnectionInfoList.get(row).getMaxConnectionNum();
        break;
      case 9:
        tmp = dbConnectionInfoList.get(row).getMinConnectionNum();
        break;
      case 10:
        tmp = dbConnectionInfoList.get(row).getDriveClass();
        break;
      case 11:
        tmp = dbConnectionInfoList.get(row).getDbConnectionString();
        break;
    }
    return tmp;
  }

  @Override
  public Class<?> getColumnClass(int col) {
    Class<?> clazz = Object.class;
    switch (col) {
      case 3:
        clazz = DBType.class;
        break;
      case 8:
      case 9:
        clazz = Integer.class;
        break;
      default:
        clazz = String.class;
    }
    return clazz;
  }
}
Ejemplo n.º 3
0
public class ClassUtil {
  private static final Logger logger = LoggerFactory.getLogger(ClassUtil.class);

  @SuppressWarnings("unchecked")
  public static <T> Class<T> forName(String name) {
    Class<T> clazz = null;
    try {
      clazz = (Class<T>) Class.forName(name);
    } catch (Exception e) {
      logger.error(e.getMessage(), e);
    }
    return clazz;
  }

  public static <T> T newInstance(String className, Object... parameters) {
    Class<T> clazz = null;
    try {
      if (StringUtils.isNotEmpty(className)) {
        clazz = forName(className);
      }
    } catch (Exception e) {
      logger.error(e.getMessage(), e);
    }
    return newInstance(clazz, parameters);
  }

  public static <T> T newInstance(Class<T> clazz, Object... parameters) {
    T objetc = null;
    try {
      if (StringUtils.isNotEmpty(clazz)) {
        if (parameters != null && parameters.length > 0) {
          Class<?>[] classs = new Class<?>[parameters.length];
          for (int i = 0; i < classs.length; i++) {
            classs[i] = parameters[i].getClass();
          }
          Constructor<T> constructor = clazz.getConstructor(classs);
          objetc = constructor.newInstance(parameters);
        } else {
          objetc = clazz.newInstance();
        }
      }
    } catch (Exception e) {
      logger.error(e.getMessage(), e);
    }
    return objetc;
  }

  public static String getMethodKey(Method method) {
    StringBuilder sb = new StringBuilder(method.getReturnType().getName());
    sb.append(" ");
    sb.append(method.getName());
    sb.append("(");
    Class<?>[] parameterTypes = method.getParameterTypes();
    for (int i = 0; i < parameterTypes.length; i++) {
      sb.append(parameterTypes[i].getName());
      sb.append(",");
    }
    sb.append(")");
    return sb.toString();
  }

  public static boolean isJavaType(Class<?> classInfo) {
    boolean isJavaType = false;
    isJavaType = classInfo == Object.class || classInfo == Object[].class ? true : isJavaType;
    isJavaType = classInfo == Byte.class || classInfo == Byte[].class ? true : isJavaType;
    isJavaType = classInfo == byte.class || classInfo == byte[].class ? true : isJavaType;
    isJavaType = classInfo == Short.class || classInfo == Short[].class ? true : isJavaType;
    isJavaType = classInfo == short.class || classInfo == short[].class ? true : isJavaType;
    isJavaType = classInfo == Integer.class || classInfo == Integer[].class ? true : isJavaType;
    isJavaType = classInfo == int.class || classInfo == int[].class ? true : isJavaType;
    isJavaType = classInfo == Long.class || classInfo == Long[].class ? true : isJavaType;
    isJavaType = classInfo == long.class || classInfo == long[].class ? true : isJavaType;
    isJavaType = classInfo == Float.class || classInfo == Float[].class ? true : isJavaType;
    isJavaType = classInfo == float.class || classInfo == float[].class ? true : isJavaType;
    isJavaType = classInfo == Double.class || classInfo == Double[].class ? true : isJavaType;
    isJavaType = classInfo == double.class || classInfo == double[].class ? true : isJavaType;
    isJavaType = classInfo == String.class || classInfo == String[].class ? true : isJavaType;
    return isJavaType;
  }

  public static Class<?> getSingleGenerics(Object object) {
    Class<?>[] clazzs = getGenerics(object);
    if (clazzs != null && clazzs.length > 0) {
      return clazzs[0];
    }
    return null;
  }

  public static Class<?>[] getGenerics(Object object) {
    Type[] types = object.getClass().getGenericInterfaces();
    if (types != null && types.length > 0) {
      Type type = types[0];
      if (type instanceof ParameterizedType) {
        ParameterizedType pt = (ParameterizedType) type;
        types = pt.getActualTypeArguments();
        Class<?>[] clazzs = new Class<?>[types.length];
        for (int i = 0; i < types.length; i++) {
          if (types[i] instanceof Class<?>) {
            clazzs[i] = (Class<?>) types[i];
          } else {
            clazzs[i] = types[i].getClass();
          }
        }
        return clazzs;
      }
    }
    return null;
  }

  public static Annotation getAnnotation(Annotation[] annotations, Class<?> annotationClass) {
    for (int i = 0; i < annotations.length; i++) {
      if (annotations[i].annotationType() == annotationClass) {
        return annotations[i];
      }
    }
    return null;
  }

  public static Set<Class<?>> getClassSet(String[] paths) {
    Set<Class<?>> classSet = new HashSet<>();
    for (int i = 0; i < paths.length; i++) {
      List<String> tmpList = getClassListInPackage(paths[i]);
      for (int t = 0; t < tmpList.size(); t++) {
        Class<?> tmpClass = forName(tmpList.get(t));
        if (tmpClass != null) {
          classSet.add(tmpClass);
        }
      }
    }
    return classSet;
  }

  public static List<String> getClassListInPackage(String packageName) {
    String packagePath = packageName.replace('.', '/') + "/";
    List<String> reClassList = new ArrayList<String>();
    Set<String> pathSet = new HashSet<>();
    URL resource = LocalResourcesUtil.class.getClassLoader().getResource(packagePath);
    if (resource != null) {
      String filePath = resource.getPath();
      if (filePath.indexOf("jar!") > -1) {
        filePath = filePath.replaceFirst("!/" + packagePath, "");
        pathSet.add(filePath);
      } else {
        addLocalClass(reClassList, packageName, filePath);
        if (reClassList.size() > 0) {
          return reClassList;
        }
      }
    } else {
      pathSet = getClassOrJarPaths();
    }
    Iterator<String> paths = pathSet.iterator();
    while (paths.hasNext()) {
      String path = paths.next();
      try {
        File classPath;
        if (path.startsWith("file:")) {
          classPath = new File(new URI(path));
        } else {
          classPath = new File(path);
        }
        if (!classPath.exists()) {
          continue;
        }
        if (classPath.isDirectory()) {
          File dir = new File(classPath, packagePath);
          if (!dir.exists()) {
            continue;
          }
          File[] files = dir.listFiles();
          for (int f = 0; f < files.length; f++) {
            if (files[f].isFile()) {
              String clsName = files[f].getName();
              clsName = packageName + "." + clsName.substring(0, clsName.length() - 6);
              reClassList.add(clsName);
            }
          }
        } else {
          FileInputStream fis = new FileInputStream(classPath);
          JarInputStream jis = new JarInputStream(fis, false);
          JarEntry entry = null;
          while ((entry = jis.getNextJarEntry()) != null) {
            String eName = entry.getName();
            if (eName.startsWith(packagePath) && !eName.endsWith("/")) {
              reClassList.add(eName.replace('/', '.').substring(0, eName.length() - 6));
            }
            jis.closeEntry();
          }
          jis.close();
        }
      } catch (IOException e) {
        logger.error(e.getMessage(), e);
      } catch (URISyntaxException e) {
        logger.error(e.getMessage(), e);
      }
    }
    return reClassList;
  }

  public static Set<String> getClassOrJarPaths() {
    Set<String> pathSet = new HashSet<>();
    URL url = CentralController.class.getClassLoader().getResource("");
    if (url != null) {
      String path = url.getPath();
      if (path.endsWith("/")) {
        path = path.substring(0, path.lastIndexOf("/"));
      }
      path = path.substring(0, path.lastIndexOf("/") + 1);
      addJarPath(pathSet, new File(path));
    }
    String[] paths = new String[] {"java.class.path", "java.ext.dirs", "sun.boot.class.path"};
    String delim = ":";
    if (System.getProperty("os.name").indexOf("Windows") != -1) {
      delim = ";";
    }
    for (int p = 0; p < paths.length; p++) {
      String[] jarPaths = System.getProperty(paths[p]).split(delim);
      for (int i = 0; i < jarPaths.length; i++) {
        pathSet.add(jarPaths[i]);
      }
    }
    return pathSet;
  }

  public static Map<String, Field> getClassAllFields(Class<?> classInfo) {
    Class<?> tmpClass = classInfo;
    if (!tmpClass.isInterface() && !ClassUtil.isJavaType(tmpClass)) {
      Map<String, Field> fieldMap = new HashMap<>();
      do {
        Field[] fields = tmpClass.getDeclaredFields();
        for (int f = 0; f < fields.length; f++) {
          fieldMap.put(fields[f].getName(), fields[f]);
        }
      } while ((tmpClass = tmpClass.getSuperclass()) != Object.class);
      return fieldMap;
    }
    return null;
  }

  private static void addLocalClass(List<String> classList, String packageName, String path) {
    try {
      File file = new File(path);
      if (file.isDirectory()) {
        String[] paths = file.list();
        for (int i = 0; i < paths.length; i++) {
          if (path.endsWith("/")) {
            addLocalClass(classList, packageName + "." + paths[i], path + paths[i]);
          } else {
            addLocalClass(classList, packageName + "." + paths[i], path + "/" + paths[i]);
          }
        }
      } else {
        if (file.getName().endsWith(".class")) {
          if (file.getName().indexOf("$") == -1) {
            if (packageName.endsWith(".class")) {
              packageName = packageName.replaceFirst("." + file.getName(), "");
            }
            classList.add(
                packageName + "." + file.getName().substring(0, file.getName().length() - 6));
          }
        }
      }
    } catch (Exception e) {
      logger.error(e.getMessage(), e);
    }
  }

  private static void addJarPath(Set<String> set, File file) {
    String[] names = file.list();
    if (names != null) {
      for (int i = 0; i < names.length; i++) {
        File f = new File(StringUtils.unite(file.getPath(), File.separator, names[i]));
        if (f.isFile() && f.getName().endsWith(".jar")) {
          set.add(f.getPath());
        } else {
          addJarPath(set, f);
        }
      }
    }
  }
}
Ejemplo n.º 4
0
/**
 * @ClassName: Session @Description: 数据库会话类
 *
 * @author cloud
 * @date 2014年5月5日 下午2:47:38
 */
public class SimpleDBSession implements DBSession {

  private static final Logger logger = LoggerFactory.getLogger(SimpleDBSession.class);

  private Connection dbConnection = null;

  private PreparedStatement pstm = null;

  private ResultSet rs = null;

  private CallableStatement call = null;

  private boolean autoCommit = false;

  public SimpleDBSession(Connection connection) {
    dbConnection = connection;
  }

  /**
   * @Title: isClose @Description: 连接是否关闭
   *
   * @return boolean
   * @throws SQLException
   * @since 1.0
   */
  public boolean isClosed() throws SQLException {
    if (dbConnection == null || dbConnection.isClosed()) return true;
    else return false;
  }

  /**
   * @Title getConnection @Description 创建数据库连接(默认手动提交事务)
   *
   * @throws SQLException
   */
  public Connection getConnection() throws SQLException {
    clear();
    if (!isClosed()) {
      if (dbConnection.getAutoCommit() != autoCommit) {
        dbConnection.setAutoCommit(autoCommit);
      }
    }
    return dbConnection;
  }

  /**
   * @title closeResultSet @Description 关闭结果集
   * @param result 要关闭的结果集对象
   */
  public void closeResultSet() {
    try {
      if (rs != null) {
        rs.close();
        rs = null;
      }
    } catch (Exception e) {
      logger.error("Close the ResultSet error···", e);
    }
  }

  /** @title closeCallStatement @Description 关闭CallableStatement */
  public void closeCallStatement() {
    try {
      if (call != null) {
        call.close();
        call = null;
      }
    } catch (Exception e) {
      logger.error("Close the CallableStatement error···", e);
    }
  }

  /** @title closePreparedStatement @Description 关闭PreparedStatement对象 */
  public void closePreparedStatement() {
    try {
      if (pstm != null) {
        pstm.close();
        pstm = null;
      }
    } catch (Exception e) {
      logger.error("Close the PreparedStatement error···", e);
    }
  }

  /**
   * @title setAutoCommit
   * @description 更改当前conn事务为自动提交(谨慎使用)
   */
  public void setAutoCommit() {
    autoCommit = true;
  }

  /**
   * @title setAutoCommit
   * @description 更改当前conn事务为手动提交(谨慎使用)
   */
  public void setManCommit() {
    autoCommit = false;
  }

  /**
   * @title commit
   * @description 提交事务
   * @throws Exception
   */
  public void commit() {
    try {
      if (!isClosed()) {
        dbConnection.commit();
      }
    } catch (SQLException e) {
      logger.error("Database error···", e);
    }
  }

  /**
   * @title rollback
   * @description 回滚事务
   */
  public void rollback() {
    try {
      if (!isClosed()) {
        dbConnection.rollback();
      }
    } catch (SQLException e) {
      logger.error("Database error···", e);
    }
  }

  /**
   * @title clear
   * @description 释放资源
   */
  public void clear() {
    try {
      closeResultSet();
      closePreparedStatement();
      closeCallStatement();
    } catch (Exception e) {
      logger.error("Clear the conneticon is error···", e);
    }
  }

  public boolean execute(String sql, Object[] params) throws SQLException {
    showSql(sql, params);
    pstm = getConnection().prepareStatement(sql);
    setParams(pstm, params);
    return pstm.execute();
  }

  /**
   * @Title createPreparedStatement @Description 创建PreparedStatement对象
   *
   * @param sql
   * @param params
   * @return pstm
   * @throws SQLException
   */
  public int executeUpdate(String sql, Object[] params) throws SQLException {
    showSql(sql, params);
    pstm = getConnection().prepareStatement(sql);
    setParams(pstm, params);
    return pstm.executeUpdate();
  }

  /**
   * @Title getGeneratedKey @Description 插入一条数据到数据库并返回id
   *
   * @param sql
   * @param params
   * @return id
   * @throws SQLException
   */
  public int executeUpdateReturnKey(String sql, Object[] params) throws SQLException {
    showSql(sql, params);
    pstm = getConnection().prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
    setParams(pstm, params);
    pstm.executeUpdate();
    rs = pstm.getGeneratedKeys();
    int re = -1;
    if (rs.next()) {
      re = rs.getInt(1);
    }
    return re;
  }

  public int[] executeBatch(String sql, List<Object[]> list) throws SQLException {
    pstm = getConnection().prepareStatement(sql);
    for (int i = 0; i < list.size(); i++) {
      setParams(pstm, list.get(i));
      showSql(sql, list.get(i));
      pstm.addBatch();
    }
    return pstm.executeBatch();
  }

  public ResultSet executeBatchReturnKeys(String sql, List<Object[]> list) throws SQLException {
    pstm = getConnection().prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
    for (int i = 0; i < list.size(); i++) {
      setParams(pstm, list.get(i));
      showSql(sql, list.get(i));
      pstm.addBatch();
    }
    pstm.executeBatch();
    rs = pstm.getGeneratedKeys();
    return rs;
  }

  /**
   * @title getResultSet @Description 创建ResultSet对象
   * @param sql
   * @param params
   * @return ResultSet
   * @throws SQLException
   */
  public ResultSet executeQuery(String sql, Object[] params) throws SQLException {
    showSql(sql, params);
    pstm = getConnection().prepareStatement(sql);
    setParams(pstm, params);
    rs = pstm.executeQuery();
    return rs;
  }

  /**
   * @title createCallStam @Description 调用存储过程,创建CallableStatement对象
   * @param callSql
   * @param params
   * @return call
   * @throws SQLException
   */
  public CallableStatement createCallStam(String callSql, Object[] params) throws SQLException {
    showSql(callSql, params);
    call = getConnection().prepareCall(callSql);
    setParams(call, params);
    return call;
  }

  /**
   * @title prepareCall @Description 创建ResultSet对象
   * @param callSql
   * @param params
   * @return ResultSet
   * @throws SQLException
   */
  public ResultSet prepareCall(String callSql, Object[] params) throws SQLException {
    showSql(callSql, params);
    createCallStam(callSql, params);
    rs = call.executeQuery();
    return rs;
  }

  @Override
  public Map<String, Object> getMapFromResultSet() throws SQLException {
    if (rs == null) {
      return null;
    }
    Map<String, Object> tmpMap = new HashMap<String, Object>();
    ResultSetMetaData rsmd = rs.getMetaData();
    for (int i = 1; i <= rsmd.getColumnCount(); i++) {
      String columnName = rsmd.getColumnLabel(i);
      tmpMap.put(columnName, rs.getObject(columnName));
    }
    return tmpMap;
  }

  @Override
  public Object[] getArrayFromResultSet() throws SQLException {
    if (rs == null) {
      return null;
    }
    ResultSetMetaData rsmd = rs.getMetaData();
    Object[] values = new Object[rsmd.getColumnCount()];
    for (int i = 0; i < rsmd.getColumnCount(); i++) {
      values[i] = rs.getObject(i + 1);
    }
    return values;
  }

  private void setParams(PreparedStatement preparedStatement, Object[] params) throws SQLException {
    if (params != null && params.length > 0) {
      for (int i = 0; i < params.length; i++) {
        preparedStatement.setObject(i + 1, params[i]);
      }
    }
  }

  private void showSql(String sql, Object[] params) {
    if (logger.isDebugEnabled()) {
      String tmpSql = sql;
      try {
        if (params != null && params.length > 0) {
          for (int i = 0; i < params.length; i++) {
            tmpSql =
                tmpSql.replaceFirst(
                    "[?]", params[i] == null ? "null" : "'" + params[i].toString() + "'");
          }
        }
      } catch (Exception e) {
        e.printStackTrace();
      }
      logger.debug(tmpSql);
    }
  }
}
Ejemplo n.º 5
0
public class ControllerMapping {
  private static org.slf4j.Logger logger = LoggerFactory.getLogger(CentralController.class);
  private Class<?> classInfo;
  private Object object;
  private String path;
  private Method defaultMethod;
  private Map<String, Method> controllerMethods = new HashMap<>();
  private Map<Method, Class<?>[]> methodParameters = new HashMap<>();

  public ControllerMapping(Class<?> classInfo) {
    try {
      this.classInfo = classInfo;
      this.object = classInfo.newInstance();
      Method[] methods = classInfo.getDeclaredMethods();
      for (int i = 0; i < methods.length; i++) {
        Method tmp = methods[i];
        if (tmp.getName().equals("index")) {
          defaultMethod = tmp;
        }
        String methodPath = null;
        if (tmp.isAnnotationPresent(Path.class)) {
          methodPath = tmp.getAnnotation(Path.class).value();
        } else if (tmp.isAnnotationPresent(Code.class)) {
          methodPath = tmp.getAnnotation(Code.class).value();
        } else {
          methodPath = tmp.getName();
        }
        methodPath = methodPath.replaceAll("/", "");
        controllerMethods.put(methodPath.toLowerCase(), tmp);
        controllerMethods.put(methodPath.toUpperCase(), tmp);
        controllerMethods.put(methodPath, tmp);
        Class<?>[] classInfos = tmp.getParameterTypes();
        methodParameters.put(tmp, classInfos);
      }
    } catch (Exception e) {
      logger.error(e.getMessage(), e);
    }
  }

  public Class<?> getClassInfo() {
    return classInfo;
  }

  public void setClassInfo(Class<?> classInfo) {
    this.classInfo = classInfo;
  }

  public Object getObject() {
    return object;
  }

  public void setObject(Object object) {
    this.object = object;
  }

  public String getPath() {
    return path;
  }

  public void setPath(String path) {
    this.path = path;
  }

  public Method getDefaultMethod() {
    return defaultMethod;
  }

  public void setDefaultMethod(Method defaultMethod) {
    this.defaultMethod = defaultMethod;
  }

  public Method getControllerMethod(String path) {
    return controllerMethods.get(path);
  }

  public Class<?>[] getMethodParameters(Method method) {
    return methodParameters.get(method);
  }
}