Exemple #1
0
 @Test
 public void testGetFollowerList() {
   log.info("====== UserAPI#getFollowerList ====== ");
   FollowList fl = ua.getFollowerList(null);
   assertNotNull(fl);
   log.info(fl);
 }
Exemple #2
0
 @Test
 public void testGetFollower() {
   log.info("====== UserAPI#getFollower ====== ");
   Follower f = ua.getFollower(openId, null);
   assertNotNull(f);
   log.info(f);
 }
Exemple #3
0
 @Test
 public void testUpdateRemark() {
   log.info("====== UserAPI#updateRemark ====== ");
   boolean flag = ua.updateRemark(openId, "Youself");
   assertTrue(flag);
   log.info(flag);
 }
Exemple #4
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);
    }
  }
Exemple #5
0
  @Override
  public View match(ActionContext actionContext) {

    if (!enable) {
      return null;
    }
    String sessionID = SessionUtil.getSessionId(actionContext.getRequest());
    String path = actionContext.getRequest().getServletPath();

    log.info("Auth for PATH:[" + path + "]");
    System.out.println("excludePaths:" + Json.toJson(excludePaths));
    if (excludePaths.contains(path)) {
      log.info("[pass] path:[" + path + "]");
      return null;
    }

    if (sessionID == null || sessionID.trim().equals("")) {
      handleResponse(actionContext.getRequest(), actionContext.getResponse());
      return new VoidView();
    }
    for (String url : patternMap.keySet()) {
      Matcher matcher = patternMap.get(url).matcher(path);
      if (matcher.find()) {
        int auth = authMap.get(url);
        log.debug("Path:{" + url + "] auth:[" + auth + ']');
        Integer sessionAuth =
            (Integer) SessionUtil.getFromSession("role", actionContext.getRequest());
        if (sessionAuth == null || sessionAuth > auth) {
          handleResponse(actionContext.getRequest(), actionContext.getResponse());
          return new VoidView();
        } else {
          log.info("[pass] path:[" + path + "]");
          return null;
        }
      }
    }

    // not find matcher

    int auth = PropertiesReader.getPropertiesInt("doe.defaultrole");
    Integer sessionAuth = (Integer) SessionUtil.getFromSession("role", actionContext.getRequest());
    log.info("sessionAuth: " + sessionAuth);
    if (sessionAuth == null || (sessionAuth >= auth && !path.equals("/"))) {
      handleResponse(actionContext.getRequest(), actionContext.getResponse());
      return new VoidView();
    } else if (sessionAuth == auth && path.equals("/")) {
      try {
        actionContext
            .getResponse()
            .sendRedirect(actionContext.getRequest().getContextPath() + studentligin);
      } catch (IOException e) {
        throw new RuntimeException(e);
      }
      return new VoidView();
    } else {
      log.info("[pass] path:[" + path + "]");
      return null;
    }
  }
Exemple #6
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);
  }
Exemple #7
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;
  }
Exemple #8
0
  @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));
  }
Exemple #9
0
 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);
     }
   }
 }
 @Override
 public void destroy(NutConfig config) {
   if (timer != null) {
     timer.cancel();
     timer = null;
     if (log.isInfoEnabled()) {
       log.info("schedule Runner 已关闭");
     }
   }
 }
Exemple #11
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!");
  }
Exemple #12
0
 public static String _3DES_encode(byte[] key, byte[] data) {
   SecretKey deskey = new SecretKeySpec(key, "DESede");
   IvParameterSpec iv = new IvParameterSpec(Iv.getBytes());
   try {
     Cipher c1 = Cipher.getInstance(Transformation);
     c1.init(Cipher.ENCRYPT_MODE, deskey, iv);
     byte[] re = c1.doFinal(data);
     return Lang.fixedHexString(re);
   } catch (Exception e) {
     log.info("3DES FAIL?", e);
     e.printStackTrace();
   }
   return null;
 }
Exemple #13
0
 public boolean send(String to, String subject, String html) {
   try {
     HtmlEmail email = ioc.get(HtmlEmail.class);
     email.setSubject(subject);
     email.setHtmlMsg(html);
     email.addTo(to);
     email.buildMimeMessage();
     email.sendMimeMessage();
     return true;
   } catch (Throwable e) {
     log.info("send email fail", e);
     return false;
   }
 }
Exemple #14
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());
   }
 }
Exemple #15
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;
 }
  @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("系统初始化完毕");
    }
  }
  private void addClass(Class<?> classZ) {
    if (classZ.isInterface()
        || classZ.isMemberClass()
        || classZ.isEnum()
        || classZ.isAnnotation()
        || classZ.isAnonymousClass()) return;
    int modify = classZ.getModifiers();
    if (Modifier.isAbstract(modify) || (!Modifier.isPublic(modify))) return;
    IocBean iocBean = classZ.getAnnotation(IocBean.class);
    if (iocBean != null) {
      if (log.isDebugEnabled()) log.debugf("Found a Class with Ioc-Annotation : %s", classZ);

      // 采用 @IocBean->name
      String beanName = iocBean.name();
      if (Strings.isBlank(beanName)) {
        // 否则采用 @InjectName
        InjectName innm = classZ.getAnnotation(InjectName.class);
        if (null != innm && !Strings.isBlank(innm.value())) {
          beanName = innm.value();
        }
        // 大哥(姐),您都不设啊!? 那就用 simpleName 吧
        else {
          beanName = Strings.lowerFirst(classZ.getSimpleName());
        }
      }

      if (map.containsKey(beanName))
        throw Lang.makeThrow(
            IocException.class,
            "Duplicate beanName=%s, by %s !!  Have been define by %s !!",
            beanName,
            classZ,
            map.get(beanName).getClass());

      IocObject iocObject = new IocObject();
      iocObject.setType(classZ);
      map.put(beanName, iocObject);

      iocObject.setSingleton(iocBean.singleton());
      if (!Strings.isBlank(iocBean.scope())) iocObject.setScope(iocBean.scope());

      // 看看构造函数都需要什么函数
      String[] args = iocBean.args();
      // if (null == args || args.length == 0)
      // args = iocBean.param();
      if (null != args && args.length > 0)
        for (String value : args) iocObject.addArg(convert(value));

      // 设置Events
      IocEventSet eventSet = new IocEventSet();
      iocObject.setEvents(eventSet);
      if (!Strings.isBlank(iocBean.create())) eventSet.setCreate(iocBean.create().trim().intern());
      if (!Strings.isBlank(iocBean.depose())) eventSet.setDepose(iocBean.depose().trim().intern());
      if (!Strings.isBlank(iocBean.fetch())) eventSet.setFetch(iocBean.fetch().trim().intern());

      // 处理字段(以@Inject方式,位于字段)
      List<String> fieldList = new ArrayList<String>();
      Mirror<?> mirror = Mirror.me(classZ);
      Field[] fields = mirror.getFields(Inject.class);
      for (Field field : fields) {
        Inject inject = field.getAnnotation(Inject.class);
        // 无需检查,因为字段名是唯一的
        // if(fieldList.contains(field.getName()))
        // throw duplicateField(classZ,field.getName());
        IocField iocField = new IocField();
        iocField.setName(field.getName());
        IocValue iocValue;
        if (Strings.isBlank(inject.value())) {
          iocValue = new IocValue();
          iocValue.setType(IocValue.TYPE_REFER);
          iocValue.setValue(field.getName());
        } else iocValue = convert(inject.value());
        iocField.setValue(iocValue);
        iocObject.addField(iocField);
        fieldList.add(iocField.getName());
      }
      // 处理字段(以@Inject方式,位于set方法)
      Method[] methods;
      try {
        methods = classZ.getMethods();
      } catch (Exception e) {
        // 如果获取失败,就忽略之
        log.info("Fail to call getMethods(), miss class or Security Limit, ignore it", e);
        methods = new Method[0];
      }
      for (Method method : methods) {
        Inject inject = method.getAnnotation(Inject.class);
        if (inject == null) continue;
        // 过滤特殊方法
        int m = method.getModifiers();
        if (Modifier.isAbstract(m) || (!Modifier.isPublic(m)) || Modifier.isStatic(m)) continue;
        String methodName = method.getName();
        if (methodName.startsWith("set")
            && methodName.length() > 3
            && method.getParameterTypes().length == 1) {
          IocField iocField = new IocField();
          iocField.setName(Strings.lowerFirst(methodName.substring(3)));
          if (fieldList.contains(iocField.getName()))
            throw duplicateField(classZ, iocField.getName());
          IocValue iocValue;
          if (Strings.isBlank(inject.value())) {
            iocValue = new IocValue();
            iocValue.setType(IocValue.TYPE_REFER);
            iocValue.setValue(Strings.lowerFirst(methodName.substring(3)));
          } else iocValue = convert(inject.value());
          iocField.setValue(iocValue);
          iocObject.addField(iocField);
          fieldList.add(iocField.getName());
        }
      }
      // 处理字段(以@IocBean.field方式)
      String[] flds = iocBean.fields();
      if (flds != null && flds.length > 0) {
        for (String fieldInfo : flds) {
          if (fieldList.contains(fieldInfo)) throw duplicateField(classZ, fieldInfo);
          IocField iocField = new IocField();
          if (fieldInfo.contains(":")) { // dao:jndi:dataSource/jdbc形式
            String[] datas = fieldInfo.split(":", 2);
            // 完整形式, 与@Inject完全一致了
            iocField.setName(datas[0]);
            iocField.setValue(convert(datas[1]));
            iocObject.addField(iocField);
          } else {
            // 基本形式, 引用与自身同名的bean
            iocField.setName(fieldInfo);
            IocValue iocValue = new IocValue();
            iocValue.setType(IocValue.TYPE_REFER);
            iocValue.setValue(fieldInfo);
            iocField.setValue(iocValue);
            iocObject.addField(iocField);
          }
          fieldList.add(iocField.getName());
        }
      }
    } else {
      if (log.isWarnEnabled()) {
        Field[] fields = classZ.getDeclaredFields();
        for (Field field : fields)
          if (field.getAnnotation(Inject.class) != null) {
            log.warnf(
                "class(%s) don't has @IocBean, but field(%s) has @Inject! Miss @IocBean ??",
                classZ.getName(), field.getName());
            break;
          }
      }
    }
  }
Exemple #18
0
  public void exec(Connection conn, DaoStatement st) {
    // 这个变量声明,后面两 case 要用到
    Object[][] paramMatrix;

    // 在这个块里执行语句
    try {
      /*
       * 语句执行前的预操作
       */
      st.onBefore(conn);
      /*
       * 开始执行语句
       */
      switch (st.getSqlType()) {
          // 查询
        case SELECT:
          _runSelect(conn, st);
          break;
          // 创建 & 删除 & 修改 & 清空
        case ALTER:
        case TRUNCATE:
        case CREATE:
        case DROP:
          _runStatement(conn, st);
          st.onAfter(conn, null);
          break;
          // 仅仅是运行回调
        case RUN:
          st.onAfter(conn, null);
          break;
          // 插入 & 删除 & 更新
          // case DELETE:
          // case UPDATE:
          // case INSERT:
          // 见鬼了,未知类型,也当作普通 SQL 运行吧,见 Issue#13
        default:
          if (st.getSqlType() == SqlType.OTHER && log.isInfoEnabled())
            log.info("Can't indentify SQL type :   " + st);
          paramMatrix = st.getParamMatrix();
          // 木有参数,直接运行
          if (null == paramMatrix || paramMatrix.length == 0) {
            _runStatement(conn, st);
          }
          // 有参数,用缓冲语句
          else {
            _runPreparedStatement(conn, st, paramMatrix);
          }
          // 运行回调
          st.onAfter(conn, null);
      }
    }
    // If any SQLException happend, throw out the SQL string
    catch (SQLException e) {
      if (log.isInfoEnabled()) log.debug("SQLException", e);
      throw new DaoException(
          format(
              "!Nutz SQL Error: '%s'\nPreparedStatement: \n'%s'",
              st.toString(), st.toPreparedStatement()),
          e);
    }
  }
Exemple #19
0
 @Before
 public void init() {
   log.info("====== UserAPITest ====== ");
   super.init();
   ua = WechatAPIImpl.create(mpAct);
 }
Exemple #20
0
  public Object[] adapt(
      ServletContext sc, HttpServletRequest req, HttpServletResponse resp, String[] pathArgs) {

    Object[] args = new Object[argTypes.length];

    if (args.length != injs.length)
      throw new IllegalArgumentException(
          "args.length != injs.length , You get a bug, pls report it!!");

    AdaptorErrorContext errCtx = null;
    // 也许用户有自己的AdaptorErrorContext实现哦
    if (argTypes.length > 0) {
      if (AdaptorErrorContext.class.isAssignableFrom(argTypes[argTypes.length - 1]))
        errCtx =
            (AdaptorErrorContext) Mirror.me(argTypes[argTypes.length - 1]).born(argTypes.length);
    }

    Object obj;
    try {
      obj = getReferObject(sc, req, resp, pathArgs);
    } catch (Throwable e) {
      if (errCtx != null) {
        if (log.isInfoEnabled())
          log.info(
              "Adapter Error catched , but I found AdaptorErrorContext param, so, set it to args, and continue",
              e);
        errCtx.setAdaptorError(e, this);
        args[args.length - 1] = errCtx;
        return args;
      }
      throw Lang.wrapThrow(e);
    }

    int len = Math.min(args.length, null == pathArgs ? 0 : pathArgs.length);
    for (int i = 0; i < args.length; i++) {
      Object value = null;
      if (i < len) { // 路径参数
        value = null == pathArgs ? null : pathArgs[i];
      } else { // 普通参数
        value = obj;
      }
      try {
        args[i] = injs[i].get(sc, req, resp, value);
      } catch (Throwable e) {
        if (errCtx != null) {
          log.infof("Adapter Param Error(%s) index=%d", method, i, e);
          errCtx.setError(i, e, method, value, injs[i]); // 先错误保存起来,全部转好了,再判断是否需要抛出
        } else throw Lang.wrapThrow(e);
      }
      if (args[i] == null && argTypes[i].isPrimitive()) {
        args[i] = Lang.getPrimitiveDefaultValue(argTypes[i]);
      }
    }

    // 看看是否有任何错误
    if (errCtx == null) return args;
    for (Throwable err : errCtx.getErrors()) {
      if (err == null) continue;
      int lastParam = argTypes.length - 1;
      if (AdaptorErrorContext.class.isAssignableFrom(argTypes[lastParam])) {
        if (log.isInfoEnabled())
          log.info(
              "Adapter Param Error catched , but I found AdaptorErrorContext param, so, set it to args, and continue");
        args[lastParam] = errCtx;
        return args;
      }
      // 没有AdaptorErrorContext参数? 那好吧,按之前的方式,抛出异常
      throw Lang.wrapThrow(err);
    }

    return args;
  }