Пример #1
0
  public List<Topic> getRecentReplyTopics(int userId, Pager pager) {

    Map<Integer, UserProfile> authors = new HashMap<Integer, UserProfile>();
    Cnd cnd = Cnd.where("userId", "=", userId);
    cnd.desc("createTime");

    Sql sql =
        Sqls.queryString("select DISTINCT topicId from t_topic_reply $cnd")
            .setEntity(dao.getEntity(TopicReply.class))
            .setVar("cnd", cnd);
    pager.setRecordCount(
        dao.execute(
                Sqls.fetchInt("select count(DISTINCT topicId) from t_topic_reply $cnd")
                    .setEntity(dao.getEntity(TopicReply.class))
                    .setVar("cnd", cnd))
            .getInt());
    sql.setPager(pager);
    String[] replies_topic_ids = dao.execute(sql).getObject(String[].class);
    List<Topic> recent_replies = new ArrayList<Topic>();
    for (String topic_id : replies_topic_ids) {
      Topic _topic = dao.fetch(Topic.class, topic_id);
      if (_topic == null) continue;
      recent_replies.add(_topic);
    }
    if (!recent_replies.isEmpty()) {
      for (Topic topic : recent_replies) {
        fillTopic(topic, authors);
      }
    }
    return recent_replies;
  }
Пример #2
0
  public boolean createEntity(Dao dao, Entity<?> en) {
    StringBuilder sb = new StringBuilder("CREATE TABLE " + en.getTableName() + "(");
    // 创建字段
    for (MappingField mf : en.getMappingFields()) {
      if (mf.isReadonly()) continue;
      sb.append('\n').append(mf.getColumnName());
      // 自增主键特殊形式关键字
      if (mf.isId() && mf.isAutoIncreasement()) {
        sb.append(" SERIAL");
      } else {
        sb.append(' ').append(evalFieldType(mf));
        // 非主键的 @Name,应该加入唯一性约束
        if (mf.isName() && en.getPkType() != PkType.NAME) {
          sb.append(" UNIQUE NOT NULL");
        }
        // 普通字段
        else {
          if (mf.isUnsigned()) sb.append(" UNSIGNED");
          if (mf.isNotNull()) sb.append(" NOT NULL");
          if (mf.isAutoIncreasement()) throw Lang.noImplement();
          if (mf.hasDefaultValue())
            sb.append(" DEFAULT '").append(getDefaultValue(mf)).append('\'');
        }
      }
      sb.append(',');
    }
    // 创建主键
    List<MappingField> pks = en.getPks();
    if (!pks.isEmpty()) {
      sb.append('\n');
      sb.append(
          String.format(
              "CONSTRAINT %s_pkey PRIMARY KEY (",
              en.getTableName().replace('.', '_').replace('"', '_')));
      for (MappingField pk : pks) {
        sb.append(pk.getColumnName()).append(',');
      }
      sb.setCharAt(sb.length() - 1, ')');
      sb.append("\n ");
    }

    // 结束表字段设置
    sb.setCharAt(sb.length() - 1, ')');

    // 执行创建语句
    dao.execute(Sqls.create(sb.toString()));

    // 创建索引
    dao.execute(createIndexs(en).toArray(new Sql[0]));

    // 创建关联表
    createRelation(dao, en);

    // 添加注释(表注释与字段注释)
    addComment(dao, en);

    return true;
  }
Пример #3
0
  // TODO not tested!!
  public boolean createEntity(Dao dao, Entity<?> en) {
    StringBuilder sb = new StringBuilder("CREATE TABLE " + en.getTableName() + "(");
    // 创建字段
    for (MappingField mf : en.getMappingFields()) {
      sb.append('\n').append(mf.getColumnName());
      sb.append(' ').append(evalFieldType(mf));
      // 非主键的 @Name,应该加入唯一性约束
      if (mf.isName() && en.getPkType() != PkType.NAME) {
        sb.append(" UNIQUE NOT NULL");
      }
      // 普通字段
      else {
        if (mf.isNotNull() || mf.isPk()) sb.append(" NOT NULL");
        if (mf.hasDefaultValue()) sb.append(" DEFAULT '").append(getDefaultValue(mf)).append('\'');
        if (mf.isAutoIncreasement()) sb.append(" generated by default as identity ");
        if (mf.isPk() && en.getPks().size() == 1) {
          sb.append(" primary key ");
        }
      }
      sb.append(',');
    }
    // 结束表字段设置
    sb.setCharAt(sb.length() - 1, ')');

    // 执行创建语句
    dao.execute(Sqls.create(sb.toString()));

    // 创建联合主键
    if (en.getPks().size() > 1) {
      sb = new StringBuilder();
      sb.append("ALTER TABLE ").append(en.getTableName()).append(" ADD CONSTRAINT PK_");
      sb.append(makePksName(en));
      sb.append(" PRIMARY KEY (");
      for (MappingField mf : en.getPks()) {
        sb.append(mf.getColumnName()).append(",");
      }
      sb.setCharAt(sb.length() - 1, ')');
      dao.execute(Sqls.create(sb.toString()));
    }

    // 创建关联表
    createRelation(dao, en);
    // 创建索引
    dao.execute(createIndexs(en).toArray(new Sql[0]));
    // 添加注释(表注释与字段注释)
    addComment(dao, en);

    return true;
  }
Пример #4
0
  public boolean dropEntity(Dao dao, Entity<?> en) {
    String tableName = en.getTableName();
    String viewName = en.getViewName();

    try {
      dropRelation(dao, en);
      if (!tableName.equals(viewName) && dao.exists(viewName)) {
        dao.execute(Sqls.create("DROP VIEW " + viewName));
      }
      dao.execute(Sqls.create("DROP TABLE " + tableName));
    } catch (Exception e) {
      return false;
    }
    return true;
  }
Пример #5
0
 /** 查询某sql的结果条数 */
 public static long queryCount(Dao dao, String sql) {
   Sql sql2 =
       Sqls.fetchInt(
           "select count(1) from (" + sql + ") as _nutz_tmp_" + System.currentTimeMillis());
   dao.execute(sql2);
   return sql2.getInt();
 }
Пример #6
0
 public static Record getRecord(Dao dao, String sql) {
   Sql s = Sqls.create(sql);
   s.setCallback(Sqls.callback.entity());
   s.setEntity(dao.getEntity(Record.class));
   dao.execute(s);
   return (Record) s.getResult();
 }
Пример #7
0
  @Override
  public void init(NutConfig config) {
    Ioc ioc = config.getIoc();
    Dao dao = ioc.get(Dao.class);

    // 若必要的数据表不存在,则初始化数据库
    if (!dao.exists(User.class)) {
      dao.create(User.class, true);
      dao.create(Role.class, true);
      dao.create(Permission.class, true);
      FileSqlManager fm = new FileSqlManager("init_system_h2.sql");
      List<Sql> sqlList = fm.createCombo(fm.keys());
      dao.execute(sqlList.toArray(new Sql[sqlList.size()]));
      // 初始化用户密码(全部都是123)及salt
      List<User> userList = dao.query(User.class, null);
      for (User user : userList) {
        RandomNumberGenerator rng = new SecureRandomNumberGenerator();
        String salt = rng.nextBytes().toBase64();
        String hashedPasswordBase64 = new Sha256Hash("123", salt, 1024).toBase64();
        user.setSalt(salt);
        user.setPassword(hashedPasswordBase64);
        dao.update(user);
      }
    }

    // 设置 Shiro 的 securityManager
    SecurityManager securityManager = ioc.get(SecurityManager.class);
    SecurityUtils.setSecurityManager(securityManager);
  }
Пример #8
0
 public static List getRecords(Dao dao, String sql, Class t) {
   Sql s = Sqls.create(sql);
   s.setCallback(Sqls.callback.entities());
   s.setEntity(dao.getEntity(t));
   dao.execute(s);
   return s.getList(Record.class);
 }
Пример #9
0
  @Override
  public List<Item> listWithSkuByOrder(long orderId) {
    String exp =
        "select i.id as 'i.id', i.sku_id as 'i.sku_id', i.sku_more_id as 'i.sku_more_id'\n"
            + "     , i.dprice as 'i.dprice', i.dcount as 'i.dcount', i.payment as 'i.payment'\n"
            + "     , i.return_time as 'i.return_time', i.return_reason as 'i.return_reason'"
            + "     , i.return_desc as 'i.return_desc'\n"
            + "     , i.state as 'i.state', i.order_id as 'i.order_id'\n"
            + "     , g.cate_code as 's.cate_code', g.gname as 's.gname', sku.img as 's.img'\n"
            + "     , sku.model as 's.model', sku.sprice as 's.sprice', sm.size as 's.size'\n"
            + "from t_item i\n"
            + "inner join t_sku sku on sku.id = i.sku_id\n"
            + "inner join t_sku_more sm on sm.id = i.sku_more_id\n"
            + "inner join t_goods g on g.id = sku.goods_id\n"
            + "where i.order_id = @orderId";

    Sql sql = Sqls.queryRecord(exp);
    sql.params().set("orderId", orderId);

    dao.execute(sql);
    List<Record> list = sql.getList(Record.class);
    List<Item> itemList = new ArrayList<Item>();
    for (Record re : list) {
      Item item = re.toEntity(dao.getEntity(Item.class), "i.");
      Sku4Item skuInfo = re.toEntity(dao.getEntity(Sku4Item.class), "s.");
      item.setSku(skuInfo);
      itemList.add(item);
    }

    return itemList;
  }
Пример #10
0
 public static int getRecordSize(Dao dao, String s) {
   Sql _s = Sqls.create("select count(*) nums from ( " + s + " )");
   _s.setCallback(Sqls.callback.entity());
   _s.setEntity(dao.getEntity(Record.class));
   dao.execute(_s);
   return ((Record) _s.getResult()).getInt("nums");
 }
Пример #11
0
 public static Object getRecort(Dao dao, String sql, Class t) {
   Sql s = Sqls.create(sql);
   s.setCallback(Sqls.callback.entity());
   s.setEntity(dao.getEntity(t));
   dao.execute(s);
   return s.getResult();
 }
Пример #12
0
  /**
   * 无and关系的tag查询
   *
   * @param tagIds 标签ids
   * @param order
   * @param pager
   * @return
   */
  public List<Resource> resourceTagSearch(Integer tagId, String order, Pager pager) {

    List<Resource> query = null;

    if (tagId != null) {
      Sql sql_resource =
          Sqls.create(
              "select * from resource as r, resource_tag as rt where rt.resource_id = r.id and rt.tag_id = "
                  + tagId);
      sql_resource.setCallback(Sqls.callback.entities());
      sql_resource.setEntity(dao.getEntity(Resource.class));
      dao.execute(sql_resource);
      query = sql_resource.getList(Resource.class);
      if (pager != null) {
        pager.setRecordCount(query.size());
      }

    } else {
      System.out.print("resourceservice: tagid无效");
    }
    for (Resource resource : query) {
      resourceRelationFull(resource);
    }
    return query;
  }
Пример #13
0
 public void addComment(Dao dao, Entity<?> en, String commentTable, String commentColumn) {
   if (!en.hasTableComment() && !en.hasColumnComment()) {
     return;
   }
   List<Sql> sqls = new ArrayList<Sql>();
   // 表注释
   if (en.hasTableComment()) {
     Sql tableCommentSQL =
         Sqls.create(Strings.isBlank(commentTable) ? DEFAULT_COMMENT_TABLE : commentTable);
     tableCommentSQL
         .vars()
         .set("table", en.getTableName())
         .set("tableComment", en.getTableComment());
     sqls.add(tableCommentSQL);
   }
   // 字段注释
   if (en.hasColumnComment()) {
     for (MappingField mf : en.getMappingFields()) {
       if (mf.hasColumnComment()) {
         Sql columnCommentSQL =
             Sqls.create(Strings.isBlank(commentColumn) ? DEFAULT_COMMENT_COLUMN : commentColumn);
         columnCommentSQL
             .vars()
             .set("table", en.getTableName())
             .set("column", mf.getColumnName())
             .set("columnComment", mf.getColumnComment());
         sqls.add(columnCommentSQL);
       }
     }
   }
   // 执行创建语句
   dao.execute(sqls.toArray(new Sql[sqls.size()]));
 }
Пример #14
0
  private void resourceRelationFull(Resource resource) {
    List<Tag> tags;
    Sql sql_resource =
        Sqls.create(
            "select * from tag as t, resource_tag as rt where rt.resource_id = "
                + resource.getId()
                + " and rt.tag_id = t.id");
    sql_resource.setCallback(Sqls.callback.entities());
    sql_resource.setEntity(dao.getEntity(Tag.class));
    dao.execute(sql_resource);
    tags = sql_resource.getList(Tag.class);
    List<UserInfo> user = dao.query(UserInfo.class, Cnd.where("id", "=", resource.getAuthor()));
    if (user.size() > 0) {
      resource.setUserInfo(user.get(0));
    } else {
      System.out.print("resourceservice:用户id无效");
    }

    String tagString = ""; // 资源tag回填
    for (int i = 0; i < tags.size(); i++) {
      if (i < (tags.size() - 1)) {
        tagString = tagString + tags.get(i).getName() + ",";
      } else {
        tagString = tagString + tags.get(i).getName();
      }
    }

    resource.setTags(tagString);
    resource.setTagEntityList(tags);
  }
Пример #15
0
 public static List<Record> getRecords(Dao dao, String sql, int page, int size) {
   Sql s = Sqls.create(sql);
   s.setCallback(Sqls.callback.entities());
   s.setPager(dao.createPager(page, size));
   s.setEntity(dao.getEntity(Record.class));
   dao.execute(s);
   return (List<Record>) s.getList(Record.class);
 }
Пример #16
0
 /** 查询sql并把结果放入传入的class组成的List中 */
 public static <T> List<T> query(
     Dao dao, Class<T> classOfT, String sql, Condition cnd, Pager pager) {
   Sql sql2 = Sqls.queryEntity(sql);
   sql2.setEntity(dao.getEntity(classOfT));
   sql2.setCondition(cnd);
   sql2.setPager(pager);
   dao.execute(sql2);
   return sql2.getList(classOfT);
 }
Пример #17
0
 protected void dropRelation(Dao dao, Entity<?> en) {
   final List<Sql> sqls = new ArrayList<Sql>(5);
   for (LinkField lf : en.visitManyMany(null, null, null)) {
     ManyManyLinkField mm = (ManyManyLinkField) lf;
     if (!dao.exists(mm.getRelationName())) continue;
     sqls.add(Sqls.create("DROP TABLE " + mm.getRelationName()));
   }
   dao.execute(sqls.toArray(new Sql[sqls.size()]));
 }
Пример #18
0
 /**
  * 用没有处理过的Nutz.sql带分页
  *
  * @param dao
  * @param s
  * @param page
  * @param size
  * @return
  */
 public static Record getRecordsByNutSql(Dao dao, Sql s, int page, int size) {
   int total = getRecordSize(dao, s.toString());
   s.setCallback(Sqls.callback.entities());
   s.setPager(dao.createPager(page, size));
   s.setEntity(dao.getEntity(Record.class));
   dao.execute(s);
   Record rd = new Record();
   List<Record> records = s.getList(Record.class);
   rd.put("total", total);
   rd.put("rows", records);
   return rd;
 }
 // @RequiresPermissions("topic:index:rebuild")
 public void rebuild() throws IOException {
   Sql sql = Sqls.queryString("select id from t_topic where tp='ask'");
   dao.execute(sql);
   luceneIndex.writer.deleteAll();
   String[] topicIds = sql.getObject(String[].class);
   for (String topicId : topicIds) {
     Topic topic = dao.fetch(Topic.class, topicId);
     bigContentService.fill(topic);
     _add(topic);
   }
   luceneIndex.writer.commit();
 }
Пример #20
0
 public void createRelation(Dao dao, Entity<?> en) {
   final List<Sql> sqls = new ArrayList<Sql>(5);
   for (LinkField lf : en.visitManyMany(null, null, null)) {
     ManyManyLinkField mm = (ManyManyLinkField) lf;
     if (dao.exists(mm.getRelationName())) continue;
     String sql = "CREATE TABLE " + mm.getRelationName() + "(";
     sql += mm.getFromColumnName() + " " + evalFieldType(mm.getHostField()) + ",";
     sql += mm.getToColumnName() + " " + evalFieldType(mm.getLinkedField());
     sql += ")";
     sqls.add(Sqls.create(sql));
   }
   dao.execute(sqls.toArray(new Sql[sqls.size()]));
 }
Пример #21
0
  /**
   * 按照tag分页查找 resource
   *
   * @param tagId 标签id
   * @param order
   * @param pager
   * @return
   */
  public List<Resource> resourceTagSearchAnd(String tagIds, String order, Pager pager) {

    List<Resource> query = null;
    // 将tagids字符串拆分成id数组进行and查询
    String[] ids = tagIds.split(",");
    if (ids.length > 0) {
      String sqlTagsResource =
          "select * from resource as r, resource_tag as rt where (rt.resource_id = r.id and rt.tag_id = "
              + Integer.parseInt(ids[0])
              + ")";
      for (int j = 1; j < ids.length; j++) {
        sqlTagsResource =
            sqlTagsResource
                + " and (r.id in (select r"
                + j
                + ".id from resource as r"
                + j
                + ", resource_tag as rt"
                + j
                + " where (rt"
                + j
                + ".resource_id = r"
                + j
                + ".id and rt"
                + j
                + ".tag_id = "
                + Integer.parseInt(ids[j])
                + ")))";
      }
      Sql sql_resource = Sqls.create(sqlTagsResource);
      sql_resource.setCallback(Sqls.callback.entities());
      sql_resource.setEntity(dao.getEntity(Resource.class));
      dao.execute(sql_resource);
      query = sql_resource.getList(Resource.class);
      if (pager != null) {
        pager.setRecordCount(query.size());
      }
      for (Resource resource : query) {
        resourceRelationFull(resource);
      }
    } else {
      System.out.print("resourservice: tagids无效");
    }
    return query;
  }
Пример #22
0
  /**
   * 获取tagNames
   *
   * @param tagIds 标签ids
   * @return
   */
  public ArrayList<Tag> getTagNames(String tagIds) {
    ArrayList<Tag> tagNames = new ArrayList<Tag>();
    String[] ids = tagIds.split(",");
    for (String id : ids) {
      String sqlTags = "select * from tag as t where t.id=" + id;
      Sql sql_resource = Sqls.create(sqlTags);
      sql_resource.setCallback(Sqls.callback.entities());
      sql_resource.setEntity(dao.getEntity(Tag.class));
      dao.execute(sql_resource);
      List<Tag> tags = sql_resource.getList(Tag.class);
      if (tags.size() > 0) {
        tags.get(0).setQuery(tagIds);
        tagNames.add(tags.get(0));
      } else {
        System.out.print("resourceservice: tagid无效");
      }
    }

    return tagNames;
  }
Пример #23
0
  /**
   * 根据用户id资源查询
   *
   * @param userId 用户id
   * @param order
   * @param pager
   * @return
   */
  public List<Resource> userResourceSearch(Integer userId, String order, Pager pager) {

    List<Resource> query = null;

    if (userId != null) {
      Sql sql_resource = Sqls.create("select * from resource as r where r.author = " + userId);
      sql_resource.setCallback(Sqls.callback.entities());
      sql_resource.setEntity(dao.getEntity(Resource.class));
      dao.execute(sql_resource);
      query = sql_resource.getList(Resource.class);
      if (pager != null) {
        pager.setRecordCount(query.size());
      }

    } else {
      System.out.print("resourceservice: userid无效");
    }
    for (Resource resource : query) {
      resourceRelationFull(resource);
    }
    return query;
  }
Пример #24
0
 public static int excuteSql(Dao dao, String sql) {
   Sql s = Sqls.create(sql);
   dao.execute(s);
   return s.getUpdateCount();
 }
Пример #25
0
 /**
  * 根据sql查询特定的记录,并转化为指定的类对象
  *
  * @param dao Dao实例
  * @param klass Pojo类
  * @param sql_str sql语句
  * @return 查询结果
  */
 public static <T> List<T> queryList(Dao dao, Class<T> klass, String sql_str) {
   Sql sql =
       Sqls.create(sql_str).setCallback(Sqls.callback.entities()).setEntity(dao.getEntity(klass));
   dao.execute(sql);
   return sql.getList(klass);
 }
Пример #26
0
  /**
   * 为数据表自动增减字段
   *
   * @param dao Dao实例
   * @param klass 映射Pojo
   * @param add 是否允许添加
   * @param del 是否允许删除
   * @param tableName 动态表名上下文
   */
  public static void migration(
      Dao dao, final Class<?> klass, final boolean add, final boolean del, Object tableName) {
    final AbstractJdbcExpert expert = (AbstractJdbcExpert) ((NutDao) dao).getJdbcExpert();
    if (tableName != null && Strings.isNotBlank(tableName.toString())) {
      dao = ext(dao, tableName);
    }
    final Entity<?> en = dao.getEntity(klass);
    if (!dao.exists(klass)) return;
    final List<Sql> sqls = new ArrayList<Sql>();
    final Set<String> _indexs = new HashSet<String>();
    final boolean sqlAddNeedColumn = !dao.meta().isOracle();
    final boolean isCanComment = dao.meta().isMySql();
    dao.run(
        new ConnCallback() {
          public void invoke(Connection conn) throws Exception {
            expert.setupEntityField(conn, en);
            Statement stat = null;
            ResultSet rs = null;
            ResultSetMetaData meta = null;
            try {
              // 获取数据库元信息
              stat = conn.createStatement();
              rs = stat.executeQuery("select * from " + en.getTableName() + " where 1 != 1");
              meta = rs.getMetaData();

              Set<String> columnNames = new HashSet<String>();
              int columnCount = meta.getColumnCount();
              for (int i = 1; i <= columnCount; i++) {
                columnNames.add(meta.getColumnName(i).toLowerCase());
              }
              for (MappingField mf : en.getMappingFields()) {
                if (mf.isReadonly()) continue;
                String colName = mf.getColumnName();
                if (columnNames.contains(colName.toLowerCase())) {
                  columnNames.remove(colName.toLowerCase());
                  continue;
                }
                if (add) {
                  log.infof("add column[%s] to table[%s]", mf.getColumnName(), en.getTableName());
                  StringBuilder sb = new StringBuilder("ALTER TABLE ");
                  sb.append(meta.getTableName(1)).append(" ADD ");
                  if (sqlAddNeedColumn) sb.append("COLUMN ");
                  sb.append(colName).append(" ").append(expert.evalFieldType(mf));
                  if (mf.isUnsigned()) {
                    sb.append(" UNSIGNED");
                  }
                  if (mf.isNotNull()) {
                    sb.append(" NOT NULL");
                  }
                  if (mf.getColumnType() == ColType.TIMESTAMP) {
                    if (mf.hasDefaultValue()) {
                      sb.append(" ").append(mf.getDefaultValue(null).replaceAll("@", "@@"));
                    } else {
                      if (mf.isNotNull()) {
                        sb.append(" DEFAULT 0");
                      } else {
                        sb.append(" NULL DEFAULT NULL");
                      }
                    }
                  } else {
                    if (mf.hasDefaultValue()) expert.addDefaultValue(sb, mf);
                  }
                  if (mf.hasColumnComment() && isCanComment) {
                    sb.append(" COMMENT '").append(mf.getColumnComment()).append("'");
                  }
                  sb.append(';');
                  Sql sql = Sqls.create(sb.toString());
                  sqls.add(sql);
                }
              }
              if (del) {
                for (String colName : columnNames) {
                  log.infof("del column[%s] from table[%s]", colName, en.getTableName());
                  Sql sql = Sqls.create("ALTER table $table DROP column $name");
                  sql.vars().set("table", en.getTableName());
                  sql.vars().set("name", colName);
                  sqls.add(sql);
                }
              }
              // show index from mytable;
              String showIndexs = "show index from " + en.getTableName();
              PreparedStatement ppstat = conn.prepareStatement(showIndexs);
              ResultSet rest = ppstat.executeQuery();
              while (rest.next()) {
                String index = rest.getString(3);
                _indexs.add(index);
              }
            } catch (SQLException e) {
              if (log.isDebugEnabled())
                log.debugf("migration Table '%s' fail!", en.getTableName(), e);
            }
            // Close ResultSet and Statement
            finally {
              Daos.safeClose(stat, rs);
            }
          }
        });
    for (Sql sql : sqls) {
      dao.execute(sql);
    }
    // 创建索引
    List<Sql> indexsSql = createIndexs(dao, en, _indexs, tableName);
    if (!Lang.isEmpty(indexsSql)) {
      dao.execute(indexsSql.toArray(new Sql[0]));
    }
    // 创建关联表
    expert.createRelation(dao, en);
  }
Пример #27
0
  @At("/wechat/gaoseng")
  @POST
  @Ok("raw")
  public void responseMsg() throws IOException, DocumentException {

    SAXReader reader = new SAXReader();
    InputStream in = Mvcs.getReq().getInputStream();
    Document doc = reader.read(in);
    Element root = doc.getRootElement();

    String toUserName = root.elementText("ToUserName"); // 开发者微信号
    String fromUserName = root.elementText("FromUserName"); // 发送方帐号(一个OpenID)
    String createTime = root.elementText("CreateTime"); // 消息创建时间 (整型)
    String msgType = root.elementText("MsgType"); // 消息类型
    String content = root.elementText("Content"); // 文本消息内容
    String msgId = root.elementText("MsgId"); // 消息id,64位整型

    //		System.out.println("fromUserName: "******"toUserName: "******"qq") || content.equals("求签")) {

      Date date = new Date();
      DateFormat format = new SimpleDateFormat("yyyy-MM-dd");

      Sql sql1 =
          Sqls.create(
              "SELECT t.* FROM gs_qiuqian_result t WHERE t.OPENID = @OPENID AND t.CREATETIME = @CREATETIME");
      sql1.params().set("CREATETIME", format.format(date).substring(0, 10));
      sql1.params().set("OPENID", fromUserName);
      sql1.setCallback(
          new SqlCallback() {
            public Object invoke(Connection conn, ResultSet rs, Sql sql1) throws SQLException {
              Map<String, String> map = new HashMap<String, String>();
              while (rs.next()) map.put("qwid", rs.getString("qwid"));
              return map;
            }
          });
      dao.execute(sql1);
      Map<String, String> map = sql1.getObject(HashMap.class);
      if (map.size() == 0) {
        String qwId = cn.gaoseng.tool.Lottery.getLottery("1");
        Sql sql2 = Sqls.create("SELECT t.* FROM gs_qiuqian_qianwen t WHERE t.ID=@ID");
        sql2.params().set("ID", qwId);

        Sql sql3 =
            Sqls.create(
                "INSERT INTO gs_qiuqian_result(OPENID,CREATETIME,QWID) VALUES(@OPENID,@CREATETIME,@QWID)");
        sql3.params().set("QWID", qwId);
        sql3.params().set("OPENID", fromUserName);
        sql3.params().set("CREATETIME", format.format(date).substring(0, 10));
        sql2.setCallback(
            new SqlCallback() {
              public Object invoke(Connection conn, ResultSet rs, Sql sql2) throws SQLException {
                Map<String, String> map1 = new HashMap<String, String>();
                while (rs.next()) {
                  map1.put("id", rs.getString("id"));
                  map1.put("title", rs.getString("title"));
                  map1.put("url", rs.getString("url"));
                  map1.put("jieqian", rs.getString("jieqian"));
                  map1.put("picurl", rs.getString("picurl"));
                  map1.put("typeid", rs.getString("typeid"));
                }
                return map1;
              }
            });
        dao.execute(sql2, sql3);
        Map<String, String> map1 = sql2.getObject(HashMap.class);
        if (map1.size() == 0) {
          out.printf(
              RESPONSE_TXT,
              fromUserName,
              toUserName,
              System.currentTimeMillis(),
              "text",
              "欢迎您访问高僧网[呲牙]   在线求签 请输入 qq或者求签");
        } else {

          out.printf(
              RESPONSE_IMAGE_TXT,
              fromUserName,
              toUserName,
              System.currentTimeMillis(),
              map1.get("title"),
              map1.get("jieqian"),
              map1.get("picurl"),
              map1.get("url"));
        }
      } else {
        Sql sql4 = Sqls.create("SELECT t.* FROM gs_qiuqian_qianwen t WHERE t.ID=@ID");
        sql4.params().set("ID", map.get("qwid"));
        sql4.setCallback(
            new SqlCallback() {
              public Object invoke(Connection conn, ResultSet rs, Sql sql4) throws SQLException {
                Map<String, String> map2 = new HashMap<String, String>();
                while (rs.next()) {
                  map2.put("id", rs.getString("id"));
                  map2.put("title", rs.getString("title"));
                  map2.put("url", rs.getString("url"));
                  map2.put("jieqian", rs.getString("jieqian"));
                  map2.put("picurl", rs.getString("picurl"));
                  map2.put("typeid", rs.getString("typeid"));
                }
                return map2;
              }
            });
        dao.execute(sql4);
        Map<String, String> map2 = sql4.getObject(HashMap.class);
        if (map2.size() == 0) {
          out.printf(
              RESPONSE_TXT,
              fromUserName,
              toUserName,
              System.currentTimeMillis(),
              "text",
              "欢迎您访问高僧网[呲牙]   在线求签 请输入 qq或者求签");
        } else {

          out.printf(
              RESPONSE_IMAGE_TXT,
              fromUserName,
              toUserName,
              System.currentTimeMillis(),
              map2.get("title"),
              map2.get("jieqian"),
              map2.get("picurl"),
              map2.get("url"));
        }
      }

    } else {

      out.printf(
          RESPONSE_TXT,
          fromUserName,
          toUserName,
          System.currentTimeMillis(),
          "text",
          "欢迎您访问高僧网[呲牙]   在线求签 请输入 qq或者求签");
    }
    /** The Dead Code end */
    in.close();
    in = null;
    out.close();
    out = null;
  }
Пример #28
0
 /**
  * 执行sql和callback
  *
  * @param dao Dao实例
  * @param sql_str sql语句
  * @param callback sql回调
  * @return 回调的返回值
  */
 public static Object query(Dao dao, String sql_str, SqlCallback callback) {
   Sql sql = Sqls.create(sql_str).setCallback(callback);
   dao.execute(sql);
   return sql.getResult();
 }