예제 #1
0
 @Test
 public void testGetFollowerList() {
   log.info("====== UserAPI#getFollowerList ====== ");
   FollowList fl = ua.getFollowerList(null);
   assertNotNull(fl);
   log.info(fl);
 }
예제 #2
0
 @Test
 public void testGetFollower() {
   log.info("====== UserAPI#getFollower ====== ");
   Follower f = ua.getFollower(openId, null);
   assertNotNull(f);
   log.info(f);
 }
예제 #3
0
 @Test
 public void testUpdateRemark() {
   log.info("====== UserAPI#updateRemark ====== ");
   boolean flag = ua.updateRemark(openId, "Youself");
   assertTrue(flag);
   log.info(flag);
 }
예제 #4
0
  // @RequestMapping(value = "queryAllRoleList", method = { RequestMethod.POST })
  public String queryAllRoleList(HttpServletRequest request, HttpServletResponse response) {
    int page = Integer.parseInt(request.getParameter("page")); // 当前页数
    int rows = Integer.parseInt(request.getParameter("rows")); // 每页多少行
    int startNum = page * rows - rows; // 分页查询开始位置
    String roleJsonStr = "";
    Datagrid datagrid = new Datagrid();
    int roleTotalCount = roleService.queryRoleTotalCount(); // 统计角色数量
    List<Role> roleList = roleService.quryAllRoleList(startNum, rows); // 查询角色列表
    datagrid.setRows(roleList);
    datagrid.setTotal(roleTotalCount);
    try {
      // 将查询的角色集合list转换成json格式字符串
      roleJsonStr = Json.toJson(datagrid); // JsonUtils.objectToJackson(datagrid, Datagrid.class);
      PrintWriter out = response.getWriter();
      out.print(roleJsonStr);
      out.flush();
      out.close();
      request.setAttribute("roleJsonStr", roleJsonStr);
    } catch (Exception e) {
      log.error("处理json数据报错:" + e.getStackTrace());
    }
    log.info(roleJsonStr);

    return null;
  }
예제 #5
0
  @SuppressWarnings("unchecked")
  public void add(Class<?> klass, Scheduled scheduled) throws SchedulerException {
    String name = klass.getName();
    if (!Strings.isBlank(scheduled.cron())) {
      try {
        log.debugf("job define name=%s cron=%s", name, scheduled.cron());
        cron(scheduled.cron(), klass);
        return;
      } catch (SchedulerException e) {
        throw new RuntimeException(e);
      }
    }
    if (scheduled.fixedRate() > 0) {
      log.debugf(
          "job define name=%s fixedRate=%s count=%s initialDelay=%s",
          name, scheduled.fixedRate(), scheduled.count(), scheduled.initialDelay());
      SimpleScheduleBuilder schedule = SimpleScheduleBuilder.simpleSchedule();
      if (scheduled.fixedRate() > 0) schedule.withIntervalInSeconds(scheduled.fixedRate());
      if (scheduled.count() > 0) {
        schedule.withRepeatCount(scheduled.count());
      } else {
        schedule.repeatForever();
      }
      TriggerBuilder<SimpleTrigger> trigger =
          TriggerBuilder.newTrigger().withIdentity(name).withSchedule(schedule);
      if (scheduled.initialDelay() > 0)
        trigger.startAt(new Date(System.currentTimeMillis() + scheduled.initialDelay() * 1000));

      JobDetail job = JobBuilder.newJob((Class<? extends Job>) klass).withIdentity(name).build();
      scheduler.scheduleJob(job, trigger.build());
    }
  }
예제 #6
0
  protected ParamInjector evalInjectorBy(Type type, Param param) {
    // TODO 这里的实现感觉很丑, 感觉可以直接用type进行验证与传递
    // TODO 这里将Type的影响局限在了 github issue #30 中提到的局部范围
    Class<?> clazz = Lang.getTypeClass(type);
    if (clazz == null) {
      if (log.isWarnEnabled())
        log.warnf("!!Fail to get Type Class : type=%s , param=%s", type, param);
      return null;
    }

    // Map
    if (Map.class.isAssignableFrom(clazz)) return new MapSelfInjector();

    if (null == param) return super.evalInjectorBy(type, null);

    String paramName = param.value();

    // File
    if (File.class.isAssignableFrom(clazz)) return new FileInjector(paramName);
    // FileMeta
    if (FieldMeta.class.isAssignableFrom(clazz)) return new FileMetaInjector(paramName);
    // TempFile
    if (TempFile.class.isAssignableFrom(clazz)) return new TempFileInjector(paramName);
    // InputStream
    if (InputStream.class.isAssignableFrom(clazz)) return new InputStreamInjector(paramName);
    // Reader
    if (Reader.class.isAssignableFrom(clazz)) return new ReaderInjector(paramName);
    // List
    if (List.class.isAssignableFrom(clazz)) return new MapListInjector(paramName);
    if (TempFile[].class.isAssignableFrom(clazz)) {
      return new TempFileArrayInjector(paramName);
    }
    // Other
    return super.evalInjectorBy(type, param);
  }
예제 #7
0
파일: AuthFilter.java 프로젝트: kanghai/DOE
  @SuppressWarnings({"unchecked"})
  public void init() throws FileNotFoundException {

    File config = Files.findFile("auth.json");
    if (null == config) {
      log.error("Can not find path:[classpath:auth.json]");
      throw new FileNotFoundException("[classpath:auth.json]");
    }

    FileReader reader = new FileReader(config);
    authMap = new LinkedHashMap<String, Integer>();
    authMap = Json.fromJson(authMap.getClass(), reader);
    log.info("Get url mapping:[" + authMap + "]");
    patternMap = new LinkedHashMap<String, Pattern>();
    if (!authMap.isEmpty()) {
      for (String url : authMap.keySet()) {
        patternMap.put(url, Pattern.compile(url));
      }
    }

    excludePaths = new HashSet<String>();
    Collections.addAll(
        excludePaths, PropertiesReader.getProperties("doe.url.pass").trim().split(","));
    //          System.out.println(Json.toJson(excludePaths));
  }
예제 #8
0
 public UploadingContext setBufferSize(int bufferSize) {
   this.bufferSize = bufferSize;
   if (bufferSize < 128 && log.isWarnEnabled()) {
     log.warn("Uploading buffer is less than 128!! Auto-fix to 128!! 8192 will be much better!!");
     this.bufferSize = 128;
   }
   return this;
 }
예제 #9
0
 @Override
 public Item insert(Item i) {
   if (!ItemDaoValidator.save(i)) {
     log.error("insert item failed:");
     log.error(i);
     throw new IllegalParameterException();
   }
   return dao.insert(i);
 }
예제 #10
0
 @Override
 public void destroy(NutConfig config) {
   if (timer != null) {
     timer.cancel();
     timer = null;
     if (log.isInfoEnabled()) {
       log.info("schedule Runner 已关闭");
     }
   }
 }
예제 #11
0
 @At
 public boolean update(@Param("..") Tmp1 obj) {
   try {
     dao().update(obj);
     return true;
   } catch (Throwable e) {
     if (log.isDebugEnabled()) log.debug("E!!", e);
     return false;
   }
 }
예제 #12
0
  private void _runPreparedStatement(Connection conn, DaoStatement st, Object[][] paramMatrix)
      throws SQLException {
    ValueAdaptor[] adaptors = st.getAdaptors();
    if (adaptors.length != paramMatrix[0].length)
      throw Lang.makeThrow("DaoStatement adaptor MUST same width with param matrix.");

    boolean statIsClosed = false;
    String sql = st.toPreparedStatement();
    PreparedStatement pstat = null;

    // 打印调试信息
    if (log.isDebugEnabled()) log.debug(st);

    try {
      // 创建 SQL 语句
      pstat = conn.prepareStatement(sql);

      // 就一条记录,不要批了吧
      if (paramMatrix.length == 1) {
        for (int i = 0; i < paramMatrix[0].length; i++) {
          adaptors[i].set(pstat, paramMatrix[0][i], i + 1);
        }
        pstat.execute();
        st.getContext().setUpdateCount(pstat.getUpdateCount());
        pstat.close();
        statIsClosed = true;
      }
      // 恩,批
      else {
        for (Object[] params : paramMatrix) {
          for (int i = 0; i < params.length; i++) {
            adaptors[i].set(pstat, params[i], i + 1);
          }
          pstat.addBatch(); // 需要配置一下batchSize,嘻嘻,不然分分钟爆内存!!
        }
        int[] counts = pstat.executeBatch();

        // 计算总共影响的行数
        int sum = 0;
        for (int i : counts) if (i > 0) sum += i;

        if (sum == 0) sum = pstat.getUpdateCount();

        pstat.close();
        statIsClosed = true;

        st.getContext().setUpdateCount(sum);
      }
    } finally {
      if (!statIsClosed) Daos.safeClose(pstat);
    }

    // 打印更详细的调试信息
    if (log.isTraceEnabled()) log.trace("...DONE");
  }
예제 #13
0
  /**
   * 启动的主函数,接受一个参数,为 web 服务器的配置文件路径。如果没有这个参数,默认在 classpath 下寻找 "web.properties" 文件。
   *
   * <p>这个文件遵循 Nutz 多行属性文件规范,同时必须具备如下的键:
   *
   * <ul>
   *   <li>"app-root" - 应用的根路径,比如 "~/workspace/git/danoo/strato/domain/ROOT"
   *   <li>"app-port" - 应用监听的端口,比如 8080
   *   <li>"app-rs" - 应用静态资源的地址前缀,比如 "http://localhost/strato",或者 "/rs" 等
   *   <li>"app-classpath" - 应用的类路径,可多行
   *   <li>"admin-port" - 应用的管理端口,比如 8081
   * </ul>
   *
   * 这个文件的例子,请参看源码 conf 目录下的 web.properties
   *
   * @param args 接受一个参数作为 web 服务器的配置文件路径
   */
  public static void main(String[] args) {
    String path = Strings.sBlank(Lang.first(args), Webs.CONF_PATH);

    log.infof("launch by '%s'", path);

    final WebServer server = new WebServer(new WebConfig(path));

    server.run();

    log.info("Server is down!");
  }
예제 #14
0
파일: DaoUp.java 프로젝트: xing-kenny/nutz
 /**
  * 构建DataSource,子类可覆盖. 如果存在Druid,则使用之,否则使用内置的SimpleDataSource
  *
  * @param props 配置信息
  * @return 目标DataSource
  */
 protected DataSource buildDataSource(Properties props) {
   if (druidFactoryClass != null) {
     log.debug("build DruidDataSource by props");
     Mirror<?> mirror = Mirror.me(druidFactoryClass);
     DataSource ds = (DataSource) mirror.invoke(null, "createDataSource", props);
     if (!props.containsKey("maxWait")) Mirror.me(ds).setValue(ds, "maxWait", 15 * 1000);
     return ds;
   }
   log.debug("build SimpleteDataSource by props");
   return SimpleDataSource.createDataSource(props);
 }
예제 #15
0
  @Test
  public void testGetFollowers() {
    log.info("====== UserAPI#getFollowers ====== ");
    List<Follower2> getfs = new ArrayList<Follower2>();
    getfs.add(new Follower2(openId));
    getfs.add(new Follower2(_cr.get("openId2")));

    List<Follower> fs = ua.getFollowers(getfs);
    assertNotNull(fs);
    assertEquals(2, fs.size());
    log.info(fs);
  }
예제 #16
0
파일: Daos.java 프로젝트: GaoHuijian/nutz
  /**
   * 执行一个特殊的Chain(事实上普通Chain也能执行,但不建议使用)
   *
   * @see org.nutz.dao.Chain#addSpecial(String, Object)
   */
  @SuppressWarnings({"rawtypes"})
  public static void insertBySpecialChain(Dao dao, Entity en, String tableName, Chain chain) {
    if (en != null) tableName = en.getTableName();
    if (tableName == null) throw Lang.makeThrow(DaoException.class, "tableName and en is NULL !!");
    final StringBuilder sql = new StringBuilder("INSERT INTO ").append(tableName).append(" (");
    StringBuilder _value_places = new StringBuilder(" VALUES(");
    final List<Object> values = new ArrayList<Object>();
    final List<ValueAdaptor> adaptors = new ArrayList<ValueAdaptor>();
    Chain head = chain.head();
    while (head != null) {
      String colName = head.name();
      MappingField mf = null;
      if (en != null) {
        mf = en.getField(colName);
        if (mf != null) colName = mf.getColumnName();
      }
      sql.append(colName);

      if (head.special()) {
        _value_places.append(head.value());
      } else {
        if (en != null) mf = en.getField(head.name());
        _value_places.append("?");
        values.add(head.value());
        ValueAdaptor adaptor = Jdbcs.getAdaptorBy(head.value());
        if (mf != null && mf.getAdaptor() != null) adaptor = mf.getAdaptor();
        adaptors.add(adaptor);
      }

      head = head.next();
      if (head != null) {
        sql.append(", ");
        _value_places.append(", ");
      }
    }
    sql.append(")");
    _value_places.append(")");
    sql.append(_value_places);
    if (log.isDebugEnabled()) log.debug(sql);
    dao.run(
        new ConnCallback() {
          public void invoke(Connection conn) throws Exception {
            PreparedStatement ps = conn.prepareStatement(sql.toString());
            try {
              for (int i = 0; i < values.size(); i++) adaptors.get(i).set(ps, values.get(i), i + 1);
              ps.execute();
            } finally {
              Daos.safeClose(ps);
            }
          }
        });
  }
예제 #17
0
  /** 这是最后的大招了,查一下形参的名字,作为@Param("形参名")进行处理 */
  protected ParamInjector paramNameInject(Method method, int index) {
    if (!Lang.isAndroid) {
      List<String> names = MethodParamNamesScaner.getParamNames(method);
      if (names != null)
        return new NameInjector(names.get(index), null, method.getParameterTypes()[index], null);
      else if (log.isInfoEnabled())
        log.infof(
            "Complie without debug info? can't deduce param name. fail back to PathArgInjector!! index=%d > %s",
            index, method);
    }

    return new PathArgInjector(method.getParameterTypes()[index]);
  }
예제 #18
0
 public AnnotationIocLoader(String... packages) {
   for (String packageZ : packages)
     for (Class<?> classZ : Scans.me().scanPackage(packageZ)) addClass(classZ);
   if (map.size() > 0) {
     if (log.isInfoEnabled())
       log.infof(
           "Scan complete ! Found %s classes in %s base-packages!\nbeans = %s",
           map.size(), packages.length, Castors.me().castToString(map.keySet()));
   } else {
     log.warn(
         "NONE Annotation-Class found!! Check your configure or report a bug!! packages="
             + Arrays.toString(packages));
   }
 }
예제 #19
0
 public Object eject(Object obj) {
   try {
     return null == obj ? null : getter.invoke(obj);
   } catch (InvocationTargetException e) {
     throw new FailToGetValueException("getter=" + getter, e);
   } catch (Exception e) {
     if (log.isInfoEnabled()) log.info("Fail to value by getter", e);
     throw Lang.makeThrow(
         "Fail to invoke getter %s.'%s()' because [%s]: %s",
         getter.getDeclaringClass().getName(),
         getter.getName(),
         Lang.unwrapThrow(e),
         Lang.unwrapThrow(e).getMessage());
   }
 }
예제 #20
0
파일: NutDao.java 프로젝트: JRed1989/nutz
 // ==========================================================
 // 下面是 3 个构造函数
 public NutDao() {
   super();
   _selfId = atomLong.getAndIncrement();
   // 设置默认的回调
   _pojo_queryEntity = new PojoQueryEntityCallback();
   _pojo_fetchEntity = new PojoFetchEntityCallback();
   _pojo_eachEntity = new PojoEachEntityCallback();
   _pojo_fetchInt = new PojoFetchIntCallback();
   _pojo_fetchObject = new PojoFetchObjectCallback();
   _pojo_queryRecord = new PojoQueryRecordCallback();
   _pojo_fetchRecord = new PojoFetchRecordCallback();
   _pojo_eachRecord = new PojoEachRecordCallback();
   if (log.isDebugEnabled())
     log.debugf("%s[_selfId=%d] init ...", getClass().getSimpleName(), _selfId);
 }
예제 #21
0
 @Aop("redis")
 public boolean updateTags(String topicId, @Param("tags") Set<String> tags) {
   if (Strings.isBlank(topicId) || tags == null) {
     return false;
   }
   Topic topic = dao.fetch(Topic.class, topicId);
   if (topic == null) return false;
   Set<String> oldTags = topic.getTags();
   if (oldTags == null) oldTags = new HashSet<>();
   log.debugf("update from '%s' to '%s'", oldTags, tags);
   topic.setTags(tags);
   dao.update(topic, "tags");
   Set<String> newTags = new HashSet<>(tags);
   newTags.removeAll(oldTags);
   Set<String> removeTags = new HashSet<>(oldTags);
   ;
   removeTags.remove(tags);
   fillTopic(topic, null);
   Date lastReplyTime = topic.getCreateTime();
   if (topic.getLastComment() != null) lastReplyTime = topic.getLastComment().getCreateTime();
   Pipeline pipe = jedis().pipelined();
   for (String tag : removeTags) {
     pipe.zrem(RKEY_TOPIC_TAG + tag.toLowerCase().trim(), topic.getId());
     pipe.zincrby(RKEY_TOPIC_TAG_COUNT, -1, tag.toLowerCase().trim());
   }
   for (String tag : newTags) {
     pipe.zadd(RKEY_TOPIC_TAG + tag.toLowerCase().trim(), lastReplyTime.getTime(), topic.getId());
     pipe.zincrby(RKEY_TOPIC_TAG_COUNT, 1, tag.toLowerCase().trim());
   }
   pipe.sync();
   return true;
 }
예제 #22
0
  @At("/?/json")
  @Ok("raw")
  public ObjectNode getEditorJson(String modelId) {
    ObjectNode modelNode = null;

    Model model = repositoryService.getModel(modelId);

    if (model != null) {
      try {
        ObjectMapper objectMapper = new ObjectMapper();
        if (StringUtils.isNotEmpty(model.getMetaInfo())) {
          modelNode = (ObjectNode) objectMapper.readTree(model.getMetaInfo());
        } else {
          modelNode = objectMapper.createObjectNode();
          modelNode.put(ModelDataJsonConstants.MODEL_NAME, model.getName());
        }
        modelNode.put(ModelDataJsonConstants.MODEL_ID, model.getId());
        ObjectNode editorJsonNode =
            (ObjectNode)
                objectMapper.readTree(
                    new String(repositoryService.getModelEditorSource(model.getId()), "utf-8"));
        modelNode.put("model", editorJsonNode);

      } catch (Exception e) {
        log.error("Error creating model JSON", e);
        throw new ActivitiException("Error creating model JSON", e);
      }
    }
    return modelNode;
  }
예제 #23
0
  // @RequestMapping(value="getRoleByRoleName",method={RequestMethod.POST})
  public String getRoleByRoleName(
      HttpServletRequest request, HttpServletResponse response, String roleName) {
    int page = Integer.parseInt(request.getParameter("page")); // 当前页数
    int rows = Integer.parseInt(request.getParameter("rows")); // 每页多少行
    int startNum = page * rows - rows; // 分页查询开始位置

    List<Role> roles = roleService.getRoleByRoleName(roleName, startNum, rows);
    int rolesTotalCountByRoleName = roleService.getRolesTotalCountByRoleName(roleName);
    Datagrid datagrid = new Datagrid();
    datagrid.setRows(roles);
    datagrid.setTotal(rolesTotalCountByRoleName);
    String rolesJsonStr = "";
    try {
      rolesJsonStr =
          Json.toJson(
              datagrid); // JsonUtils.objectToJackson(datagrid, Datagrid.class);// 将对象转换成json字符串
      PrintWriter out = response.getWriter();
      out.print(rolesJsonStr);
      out.flush();
      out.close();
    } catch (Exception e) {
      log.error("处理json数据报错:" + e.getStackTrace());
    }
    return null;
  }
예제 #24
0
 // @RequestMapping(value = "loadAllAuthTree", method = { RequestMethod.POST })
 public String loadAllAuthTree(HttpServletRequest request, HttpServletResponse response) {
   String id = request.getParameter("id");
   List<Authority> checkedAuthList = roleService.getCheckedAuthIds(id);
   String authTreeJson = menusService.createAuthTree(checkedAuthList);
   log.info(authTreeJson);
   PrintWriter out;
   try {
     out = response.getWriter();
     out.print(authTreeJson);
     out.flush();
     out.close();
   } catch (IOException e) {
     log.error("处理json数据报错:" + e.getStackTrace());
   }
   return null;
 }
예제 #25
0
  @Override
  public void init(NutConfig config) {
    Ioc ioc = config.getIoc();

    final Dao dao = ioc.get(null, "dao");

    timer.schedule(
        new TimerTask() {
          @Override
          public void run() {}
        },
        1000,
        INTERVAL);
    if (log.isInfoEnabled()) {
      log.info("系统初始化完毕");
    }
  }
예제 #26
0
  public void run() {
    // ----------------------------------------- 建立
    log.infof("start TcpServer [%s] @ %d", Thread.currentThread().getName(), port);
    try {
      listener = new ServerSocket(port);
    } catch (IOException e1) {
      throw Lang.wrapThrow(e1);
    }
    // ----------------------------------------- 循环
    log.infof("TcpServer listen @ %d", port);
    while (!stop) {
      log.info("before accept ...");
      Socket socket = null;
      try {
        socket = listener.accept();
      } catch (IOException e) {
        log.fatalf("Fail to accept %s @ %d , System.exit!", Thread.currentThread().getName(), port);
        System.exit(0);
      }

      log.info("do listen ...");
      listen(socket);
      log.infof(
          "done for listen [%s:%d], stop=%b",
          socket.getInetAddress().getHostName(), socket.getPort(), stop);
    }
    // ----------------------------------------- 关闭
    try {
      listener.close();
      log.infof("TcpServer shutdown @ %d", port);
    } catch (IOException e) {
      throw Lang.wrapThrow(e);
    }
  }
예제 #27
0
  @Override
  protected long exec() {
    // 首先以间隔 1000 ms 的时间,自旋等待 schedule 的准备完成
    while (!factory.schedule().isReady() && !factory.schedule().isStop()) {

      if (log.isDebugEnabled()) log.debug("check schedule ...");

      synchronized (factory.schedule()) {
        try {
          factory.schedule().wait(1000);
        } catch (InterruptedException e) {
          throw Lang.wrapThrow(e);
        }
      }
    }

    return factory.schedule().runSlot(Calendar.getInstance(), log);
  }
예제 #28
0
파일: Daos.java 프로젝트: GaoHuijian/nutz
 /**
  * 获取colName所在的行数
  *
  * @param meta 从连接中取出的ResultSetMetaData
  * @param colName 字段名
  * @return 所在的索引,如果不存在就抛出异常
  * @throws SQLException 指定的colName找不到
  */
 public static int getColumnIndex(ResultSetMetaData meta, String colName) throws SQLException {
   if (meta == null) return 0;
   int columnCount = meta.getColumnCount();
   for (int i = 1; i <= columnCount; i++)
     if (meta.getColumnName(i).equalsIgnoreCase(colName)) return i;
   // TODO 尝试一下meta.getColumnLabel?
   log.infof("Can not find @Column(%s) in table/view (%s)", colName, meta.getTableName(1));
   throw Lang.makeThrow(SQLException.class, "Can not find @Column(%s)", colName);
 }
예제 #29
0
파일: AuthFilter.java 프로젝트: kanghai/DOE
 private void handleResponse(HttpServletRequest req, HttpServletResponse resp) {
   String path = req.getServletPath();
   if (path.endsWith(".do")) {
     try {
       log.info("[rejected] send error message path[" + path + "]");
       resp.getWriter().append("{\"success\":false,\"message\":\"亲爱的用户,您无权执行此操作\"}");
     } catch (IOException e) {
       throw new RuntimeException(e);
     }
   } else {
     try {
       log.info("[rejected] send redirect path:[" + path + "]");
       resp.sendRedirect(req.getContextPath() + redirectPage);
     } catch (IOException e) {
       throw new RuntimeException(e);
     }
   }
 }
예제 #30
0
 @Override
 public void init(NutConfig config, ActionInfo ai) throws Throwable {
   // 需要特别提醒一下使用jsonView,但方法的返回值是String的!!
   if ("json".equals(ai.getOkView()) && String.class.equals(ai.getMethod().getReturnType())) {
     log.warn(
         "Not a good idea : Return String ,and using JsonView!! (Using @Ok(\"raw\") or return map/list/pojo)--> "
             + Lang.simpleMetodDesc(ai.getMethod()));
   }
   view = evalView(config, ai, ai.getOkView());
 }