/** 值分布日期格式 */
 private TimeBetween fillWithValueDistriTime(HttpServletRequest request, Model model)
     throws ParseException {
   final String valueDistriDateFormat = "yyyy-MM-dd";
   String valueDistriStartDateParam = request.getParameter("valueDistriStartDate");
   String valueDistriEndDateParam = request.getParameter("valueDistriEndDate");
   Date startDate;
   Date endDate;
   if (StringUtils.isBlank(valueDistriStartDateParam)
       || StringUtils.isBlank(valueDistriEndDateParam)) {
     // 如果为空默认取昨天和今天
     SimpleDateFormat sdf = new SimpleDateFormat(valueDistriDateFormat);
     startDate = sdf.parse(sdf.format(new Date()));
     endDate = DateUtils.addDays(startDate, 1);
     valueDistriStartDateParam = DateUtil.formatDate(startDate, valueDistriDateFormat);
     valueDistriEndDateParam = DateUtil.formatDate(endDate, valueDistriDateFormat);
   } else {
     endDate = DateUtil.parse(valueDistriEndDateParam, valueDistriDateFormat);
     startDate = DateUtil.parse(valueDistriStartDateParam, valueDistriDateFormat);
     // 限制不能超过1天
     if (endDate.getTime() - startDate.getTime() > TimeUnit.DAYS.toMillis(1)) {
       startDate = DateUtils.addDays(endDate, -1);
     }
   }
   // 前端需要
   model.addAttribute("valueDistriStartDate", valueDistriStartDateParam);
   model.addAttribute("valueDistriEndDate", valueDistriEndDateParam);
   // 查询后台需要
   long startTime = NumberUtils.toLong(DateUtil.formatDate(startDate, COLLECT_TIME_FORMAT));
   long endTime = NumberUtils.toLong(DateUtil.formatDate(endDate, COLLECT_TIME_FORMAT));
   return new TimeBetween(startTime, endTime, startDate, endDate);
 }
  @RequestMapping(value = "/order/search/integral")
  public void searchUserIntegralByOrder(String orderNoes, HttpServletResponse response)
      throws IOException {
    String[] orderNoArray = orderNoes.split("\\n");

    Map<Integer, UserIntegralAndCoupon> uicMap =
        new LinkedHashMap<Integer, UserIntegralAndCoupon>();
    StringBuilder sbd = new StringBuilder();
    for (String orderNo : orderNoArray) {
      if (StringUtils.isBlank(orderNo) || NumberUtils.toLong(orderNo) <= 0) continue;

      long no = NumberUtils.toLong(orderNo.trim());
      Order order = tradeCenterBossClient.queryOrderByOrderNo(no);
      if (order == null) continue;

      User user = userService.getUserById(order.getUserId());
      if (user == null || uicMap.get(user.getId()) != null) continue;

      UserIntegralAndCoupon uic = new UserIntegralAndCoupon();
      uic.setUserId(user.getId());
      uic.setUserName(user.getUserName());
      uic.setPhone(StringUtils.isNotBlank(user.getPhone()) ? user.getPhone() : "");
      uic.setEmail(StringUtils.isNotBlank(user.getEmail()) ? user.getEmail() : "");
      uic.setIntegral(user.getCurrency());

      List<Coupon> coupons = couponService.queryCouponByUserId(order.getUserId());
      sbd.delete(0, sbd.length());
      int i = 0;
      String str = "";
      for (Coupon coupon : coupons) {
        sbd.append(coupon.getCode());
        if (coupon.isUsed()) str = "已使用";
        else if (coupon.isExpire()) str = "已过期";
        if (StringUtils.isNotBlank(str)) sbd.append("(").append(str).append(")");

        if (i != coupons.size() - 1) sbd.append(", ");

        i++;
      }
      uic.setCoupon(sbd.toString());

      sbd.delete(0, sbd.length());
      // 从地址中去寻找
      List<Address> addresses = addressService.queryAllAddress(order.getUserId());
      i = 0;
      for (Address address : addresses) {
        sbd.append(address.getName()).append("/").append(address.getMobile()).append("/");
        sbd.append(address.getProvince()).append(address.getLocation());
        if (address.isDefaultAddress()) sbd.append("<span style='color:red;'>(默认地址)</span>");

        if (i != addresses.size() - 1) sbd.append("\n");
      }
      uic.setAddress(sbd.toString());

      uicMap.put(user.getId(), uic);
    }
    new JsonResult(true).addData("orderList", uicMap.values()).toJson(response);
  }
 /**
  * 应用客户端统计首页
  *
  * @param appId 应用id
  */
 @RequestMapping("/index")
 public ModelAndView doIndex(
     HttpServletRequest request, HttpServletResponse response, Model model) {
   Long appId = NumberUtils.toLong(request.getParameter("appId"));
   if (appId == null || appId <= 0) {
     return new ModelAndView("");
   }
   AppDesc appDesc = appService.getByAppId(appId);
   model.addAttribute("appId", appId);
   model.addAttribute("appDesc", appDesc);
   model.addAttribute("tabTag", request.getParameter("tabTag"));
   model.addAttribute("type", request.getParameter("type"));
   model.addAttribute("startDate", request.getParameter("startDate"));
   model.addAttribute("endDate", request.getParameter("endDate"));
   model.addAttribute("exceptionStartDate", request.getParameter("exceptionStartDate"));
   model.addAttribute("exceptionEndDate", request.getParameter("exceptionEndDate"));
   model.addAttribute("valueDistriStartDate", request.getParameter("valueDistriStartDate"));
   model.addAttribute("valueDistriEndDate", request.getParameter("valueDistriEndDate"));
   model.addAttribute("costDistriStartDate", request.getParameter("costDistriStartDate"));
   model.addAttribute("costDistriEndDate", request.getParameter("costDistriEndDate"));
   model.addAttribute("clientIp", request.getParameter("clientIp"));
   model.addAttribute("pageNo", request.getParameter("pageNo"));
   model.addAttribute("firstCommand", request.getParameter("firstCommand"));
   model.addAttribute("timeDimensionality", request.getParameter("timeDimensionality"));
   return new ModelAndView("client/appClientIndex");
 }
  /** 应用客户端值分布相关 */
  @RequestMapping("/valueDistribute")
  public ModelAndView doValueDistribute(
      HttpServletRequest request, HttpServletResponse response, Model model) throws ParseException {
    // 1.1 应用信息
    Long appId = NumberUtils.toLong(request.getParameter("appId"));
    if (appId <= 0) {
      return new ModelAndView("");
    }
    AppDesc appDesc = appService.getByAppId(appId);
    model.addAttribute("appDesc", appDesc);

    // 1.2 时间格式转换
    TimeBetween timeBetween = new TimeBetween();
    try {
      timeBetween = fillWithValueDistriTime(request, model);
    } catch (ParseException e) {
      logger.error(e.getMessage(), e);
    }
    long startTime = timeBetween.getStartTime();
    long endTime = timeBetween.getEndTime();

    // 值分布列表
    List<AppClientValueDistriSimple> appClientValueDistriSimpleList =
        clientReportValueDistriServiceV2.getAppValueDistriList(appId, startTime, endTime);
    model.addAttribute("appClientValueDistriSimpleList", appClientValueDistriSimpleList);

    // 值分布json
    model.addAttribute(
        "appClientValueDistriSimpleListJson",
        JSONObject.toJSONString(appClientValueDistriSimpleList));

    return new ModelAndView("client/clientValueDistribute");
  }
  /**
   * @param args
   * @throws java.io.IOException
   */
  public static void main(String[] args) throws IOException {
    String input = args[0];
    if (!new File(input).exists()) {
      return;
    }
    Map<String, Long> statusMap = getMap(input);
    if (statusMap == null) return;
    Report report = Report.newReport("闲置新发布商品来源跟踪");
    if (true) {
      Table table = report.newGroupTable("all", "商品发布来源分布", "来源", "数量");

      for (String key : SOURCE) {
        table.addCol(key, sum(statusMap, key));
      }
    }

    if (true) {
      for (String key : SOURCE) {
        Table table = report.newGroupTable("lite_" + key, key + "发布来源分布", "状态", "数量");
        for (String status : ItemUtils.allStatus) {
          Long _num = statusMap.get(key + "^" + status);
          if (_num == null) {
            _num = 0L;
          }
          table.addCol(status, ItemUtils.getItemStatusName(status), String.valueOf(_num));
        }
      }
    }

    if (true) {
      Map<String, List<String[]>> today = MapUtils.map(Utils.read(input, (String[]) null));
      if (true && today.containsKey("cat")) {
        Map<String, Long> _countMap = new HashMap<String, Long>();
        for (String[] array : today.get("cat")) {
          String catId = array[0];
          if (null != Category.getCategory(catId)) {
            catId = Category.getCategory(catId).getRootId();
          }
          long value = NumberUtils.toLong(array[1]);
          Long _v = _countMap.get(catId);
          if (_v == null) {
            _v = 0L;
          }
          _v = _v + value;
          _countMap.put(catId, _v);
        }
        Table table = report.newGroupTable("cat", "今天发布商品的各个类目分布");
        for (Map.Entry<String, Long> entry : _countMap.entrySet()) {
          table.addCol(
              entry.getKey(),
              Category.getCategoryName(entry.getKey()),
              String.valueOf(entry.getValue()));
        }
        table.sort(Table.SORT_VALUE);
      }
    }
    XmlReportFactory.dump(report, new FileOutputStream(args[0] + ".xml"));
  }
Exemple #6
0
 public static long toLong(final Object o) {
   if (o instanceof BigDecimal) {
     return NumberUtil.toLong((BigDecimal) o);
   } else if (o instanceof Number) {
     return new BigDecimal(String.valueOf(o)).longValue();
   } else {
     return NumberUtils.toLong(String.valueOf(o));
   }
 }
 static String sum(Map<String, Long> yesday, String key) {
   long sum = 0;
   for (String status : ItemUtils.allStatus) {
     String newKey = key + "^" + status;
     sum += NumberUtils.toLong(yesday.get(newKey) + "", 0);
   }
   if (sum <= 0) return "0";
   return String.valueOf(sum);
 }
 @RequestMapping(value = "/order/logistics/{orderId}")
 public void logisticsInfo(@PathVariable("orderId") String orderId, HttpServletResponse response)
     throws IOException {
   List<ProgressDetail> list =
       tradeCenterBossClient.getProgressDetail(NumberUtils.toLong(orderId));
   new JsonResult(true)
       .addData("totalCount", list.size())
       .addData("result", list)
       .toJson(response);
 }
 /** Inits the upload params. */
 private void initUploadParams() {
   this.uploadPath = getParameter(Constants.PARAM_UPLOAD_PATH);
   this.allowTypes = getParameter(Constants.PARAM_ALLOW_TYPES);
   this.maxSize = NumberUtils.toLong(getParameter(Constants.PARAM_MAX_SIZE), -1);
   if (uploadPath == null) {
     JOptionPane.showMessageDialog(this, getMessage(MessageCode.FTP_UPLOAD_PARAM_ERROR));
   }
   this.beforeUpload = getParameter(Constants.PARAM_BEFORE_UPLOAD);
   this.onUploadFinished = getParameter(Constants.PARAM_ON_UPLOAD_FINISHED);
 }
 public static long parseHumanDTToMills(String humanDateTime) {
   long datetime = 0;
   if (humanDateTime.indexOf("ms") != -1) {
     datetime =
         TimeValue.timeValueMillis(NumberUtils.toLong(humanDateTime.replaceAll("ms", "")))
             .getMillis();
   } else if (humanDateTime.indexOf("h") != -1) {
     datetime =
         TimeValue.timeValueHours(NumberUtils.toLong(humanDateTime.replaceAll("h", "")))
             .getMillis();
   } else if (humanDateTime.indexOf("m") != -1) {
     datetime =
         TimeValue.timeValueMinutes(NumberUtils.toLong(humanDateTime.replaceAll("m", "")))
             .getMillis();
   } else if (humanDateTime.indexOf("s") != -1) {
     datetime =
         TimeValue.timeValueSeconds(NumberUtils.toLong(humanDateTime.replaceAll("s", "")))
             .getMillis();
   }
   return datetime;
 }
  /**
   * 获取指定时间内某个命令某个客户端和实例的统计数据
   *
   * @param appId
   */
  @RequestMapping("/getAppClientInstanceCommandCost")
  public ModelAndView doGetAppClientInstanceCommandCost(
      HttpServletRequest request, HttpServletResponse response, Model model) throws ParseException {
    final String costDistriDateFormat = "yyyy-MM-dd";
    long appId = NumberUtils.toLong(request.getParameter("appId"));
    // 时间转换
    String costDistriStartDate = request.getParameter("costDistriStartDate");
    String costDistriEndDate = request.getParameter("costDistriEndDate");
    Date startDate = DateUtil.parse(costDistriStartDate, costDistriDateFormat);
    Date endDate = DateUtil.parse(costDistriEndDate, costDistriDateFormat);
    long startTime = NumberUtils.toLong(DateUtil.formatDate(startDate, COLLECT_TIME_FORMAT));
    long endTime = NumberUtils.toLong(DateUtil.formatDate(endDate, COLLECT_TIME_FORMAT));

    String firstCommand = request.getParameter("firstCommand");
    long instanceId = NumberUtils.toLong(request.getParameter("instanceId"));
    String clientIp = request.getParameter("clientIp");

    // 客户端和实例统计
    List<AppClientCostTimeStat> clientInstanceChartStatList =
        clientReportCostDistriService.getAppCommandClientToInstanceStat(
            appId, firstCommand, instanceId, clientIp, startTime, endTime);
    // 缩减字段
    List<Map<String, Object>> clientInstanceStat = new ArrayList<Map<String, Object>>();
    for (AppClientCostTimeStat appClientCostTimeStat : clientInstanceChartStatList) {
      Map<String, Object> map = new HashMap<String, Object>();
      map.put("timeStamp", appClientCostTimeStat.getTimeStamp());
      map.put("count", appClientCostTimeStat.getCount());
      map.put("mean", appClientCostTimeStat.getMean());
      map.put("median", appClientCostTimeStat.getMedian());
      map.put("max90", appClientCostTimeStat.getNinetyPercentMax());
      map.put("max99", appClientCostTimeStat.getNinetyNinePercentMax());
      map.put("max100", appClientCostTimeStat.getHundredMax());
      clientInstanceStat.add(map);
    }
    // 生成数据map json
    Map<String, Object> resultMap = new HashMap<String, Object>();
    resultMap.put("clientInstanceStat", clientInstanceStat);
    sendMessage(response, JSONObject.toJSONString(resultMap));
    return null;
  }
  @SuppressWarnings("unchecked")
  static Map<String, Long /* array[0]=count,array[1]=sum */> getMap(String date) {
    if (!new File(date).exists()) return null;
    try {

      Map<String, Long> statusMap = new HashMap<String, Long>();

      for (String line : (List<String>) FileUtils.readLines(new File(date), "GBK")) {
        String[] _array = StringUtils.split(line, "\t");
        String key = (_array[0] + "^" + _array[1]).toUpperCase();
        if (statusMap.containsKey(key)) {
          statusMap.put(key, statusMap.get(key) + NumberUtils.toLong(_array[2]));
        } else {
          statusMap.put(key, NumberUtils.toLong(_array[2]));
        }
      }
      return statusMap;
    } catch (Exception e) {
      e.printStackTrace();
    }
    return null;
  }
  public CrowdDirectoryConfiguration toCrowdConfiguration(Directory directory) {
    CrowdDirectoryConfiguration configuration = new CrowdDirectoryConfiguration();
    configuration.setCrowdPermissionOption(
        CrowdPermissionOption.fromAllowedOperations(directory.getAllowedOperations()));
    configuration.setDirectoryId(directory.getId() != null ? directory.getId() : 0);
    configuration.setActive(directory.isActive());
    configuration.setName(directory.getName());

    CrowdDirectoryAttributes attributes =
        CrowdDirectoryAttributes.fromAttributesMap(directory.getAttributes());
    BeanUtils.copyProperties(attributes, configuration);
    // Convert polling interval to minutes to display to user
    configuration.setCrowdServerSynchroniseIntervalInMin(
        NumberUtils.toLong(attributes.getCrowdServerSynchroniseIntervalInSeconds()) / 60);

    return configuration;
  }
  /** 客户端异常查询 */
  @RequestMapping("/exception")
  public ModelAndView doException(
      HttpServletRequest request, HttpServletResponse response, Model model) {
    // 1.1 应用信息
    Long appId = NumberUtils.toLong(request.getParameter("appId"));
    if (appId <= 0) {
      return new ModelAndView("");
    }
    AppDesc appDesc = appService.getByAppId(appId);
    model.addAttribute("appDesc", appDesc);

    // 1.2 异常类型
    int type = NumberUtil.toInt(request.getParameter("type"));
    model.addAttribute("type", type);

    // 1.3 客户端ip
    String clientIp = request.getParameter("clientIp");
    model.addAttribute("clientIp", clientIp);

    // 1.4 日期格式转换
    TimeBetween timeBetween = new TimeBetween();
    try {
      timeBetween = fillWithClientExceptionTime(request, model);
    } catch (ParseException e) {
      logger.error(e.getMessage(), e);
    }

    // 2. 分页查询异常
    int totalCount =
        clientReportExceptionService.getAppExceptionCount(
            appId, timeBetween.getStartTime(), timeBetween.getEndTime(), type, clientIp);
    int pageNo = NumberUtils.toInt(request.getParameter("pageNo"), 1);
    int pageSize = NumberUtils.toInt(request.getParameter("pageSize"), 10);
    Page page = new Page(pageNo, pageSize, totalCount);
    model.addAttribute("page", page);

    List<AppClientExceptionStat> appClientExceptionList =
        clientReportExceptionService.getAppExceptionList(
            appId, timeBetween.getStartTime(), timeBetween.getEndTime(), type, clientIp, page);
    model.addAttribute("appClientExceptionList", appClientExceptionList);

    return new ModelAndView("client/clientException");
  }
  /**
   * 获取某个命令时间分布图
   *
   * @param instanceId 实例id
   * @param commandName 命令名称
   * @throws java.text.ParseException
   */
  @RequestMapping("/getCommandStatsV2")
  public ModelAndView getCommandStatsV2(
      HttpServletRequest request,
      HttpServletResponse response,
      Model model,
      Long instanceId,
      String commandName)
      throws ParseException {
    String startDateParam = request.getParameter("startDate");
    String endDateParam = request.getParameter("endDate");

    if (StringUtils.isBlank(startDateParam) || StringUtils.isBlank(endDateParam)) {
      Date endDate = new Date();
      Date startDate = DateUtils.addDays(endDate, -1);
      startDateParam = DateUtil.formatDate(startDate, "yyyyMMdd");
      endDateParam = DateUtil.formatDate(endDate, "yyyyMMdd");
    }
    model.addAttribute("startDate", startDateParam);
    model.addAttribute("endDate", endDateParam);

    Date startDate = DateUtil.parseYYYYMMdd(startDateParam);
    Date endDate = DateUtil.parseYYYYMMdd(endDateParam);
    if (instanceId != null) {
      long firstDayBegin = NumberUtils.toLong(DateUtil.formatYYYYMMdd(startDate) + "0000");
      long firstDayEnd = NumberUtils.toLong(DateUtil.formatYYYYMMdd(startDate) + "2359");
      long secondDayBegin = NumberUtils.toLong(DateUtil.formatYYYYMMdd(endDate) + "0000");
      long secondDayEnd = NumberUtils.toLong(DateUtil.formatYYYYMMdd(endDate) + "2359");
      long bt = System.currentTimeMillis();
      List<InstanceCommandStats> instanceCommandStatsListFirst =
          instanceStatsCenter.getCommandStatsList(
              instanceId, firstDayBegin, firstDayEnd, commandName);
      List<InstanceCommandStats> instanceCommandStatsListSecond =
          instanceStatsCenter.getCommandStatsList(
              instanceId, secondDayBegin, secondDayEnd, commandName);
      long et = System.currentTimeMillis() - bt;
      Map<String, InstanceCommandStats> cmdStatsFirst = new HashMap<String, InstanceCommandStats>();
      Map<String, InstanceCommandStats> cmdStatsSecond =
          new HashMap<String, InstanceCommandStats>();

      for (InstanceCommandStats first : instanceCommandStatsListFirst) {
        cmdStatsFirst.put(first.getCollectTime() + "", first);
      }
      for (InstanceCommandStats second : instanceCommandStatsListSecond) {
        cmdStatsSecond.put(second.getCollectTime() + "", second);
      }

      SplineChartEntity splineChartEntity = new SplineChartEntity();
      String container = request.getParameter("container");
      if (container != null) {
        splineChartEntity.renderTo(container);
      }
      model.addAttribute("chart", splineChartEntity);
      splineChartEntity.putTitle(
          ChartKeysUtil.TitleKey.TEXT.getKey(),
          "命令:" + commandName + " 的比较曲线【" + startDateParam + "】-【" + endDateParam + "】");
      splineChartEntity.setYAxisTitle("y");
      List<Long> data1 = new ArrayList<Long>();
      List<Long> data2 = new ArrayList<Long>();
      Map<String, Object> marker = new HashMap<String, Object>();
      marker.put("radius", 1);
      Map<String, Object> serie1 = new HashMap<String, Object>();
      serie1.put("name", startDateParam);
      serie1.put("data", data1);
      serie1.put("marker", marker);
      Map<String, Object> serie2 = new HashMap<String, Object>();
      serie2.put("name", endDateParam);
      serie2.put("data", data2);
      serie2.put("marker", marker);
      splineChartEntity.putSeries(serie1);
      splineChartEntity.putSeries(serie2);
      List<Object> x = new LinkedList<Object>();
      for (int i = 0; i < 1440; i += 1) {
        Date date = DateUtils.addMinutes(startDate, i);
        String s = DateUtil.formatHHMM(date);
        if (cmdStatsFirst.containsKey(startDateParam + s)) {
          data1.add(cmdStatsFirst.get(startDateParam + s).getCommandCount());
        } else {
          data1.add(0l);
        }
        if (cmdStatsSecond.containsKey(endDateParam + s)) {
          data2.add(cmdStatsSecond.get(endDateParam + s).getCommandCount());
        } else {
          data2.add(0l);
        }

        x.add(s);
      }
      splineChartEntity.setXAxisCategories(x);
    }
    return new ModelAndView("");
  }
Exemple #16
0
  public SearchResult getResult() throws ForumException {

    if (null == result) {

      final PredicateGroup root = new PredicateGroup(PredicateGroup.TYPE);
      root.setAllRequired(true);

      String topicResourceType = null;
      String postResourceType = null;
      final Designer forumDesign = resolver.adaptTo(Designer.class);
      // -----------------< filter by paths >
      // -----------------------------------------------------------------
      final PredicateGroup pathFilter = new PredicateGroup("paths");
      pathFilter.setAllRequired(false);

      // -----------------< filter by resource type >
      // ----------------------------------------------------------
      final PredicateGroup resourceTypes = new PredicateGroup("resourceTypes");
      resourceTypes.setAllRequired(false);

      // no custom search paths specified, add default one
      if (pathFilter.size() == 0) {
        pathFilter.add(
            new Predicate("ugcRoot", PATH) {
              {
                set(PATH, PATH_UGC + "/content");
              }
            });
      }

      for (final String searchPath : searchPaths) {
        pathFilter.add(
            new Predicate(searchPath, PATH) {
              {
                set(PATH, PATH_UGC + searchPath);
              }
            });
        if (null != forumDesign) {
          final Resource forumResource = resolver.getResource(searchPath);
          final Style currentStyle = forumDesign.getStyle(forumResource);
          if (currentStyle != null) {
            topicResourceType = (String) currentStyle.get(PN_TOPIC_RESOURCETYPE);
            postResourceType = (String) currentStyle.get(PN_POST_RESOURCETYPE);
          }
        }
        if (topicResourceType != null) {
          final String _topicResourceType = topicResourceType;
          resourceTypes.add(
              new Predicate(topicResourceType, PROPERTY) {
                {
                  set(PROPERTY, SLING_RESOURCE_TYPE_PROPERTY);
                  set(VALUE, _topicResourceType);
                }
              });
        }
        if (postResourceType != null) {
          final String _postResourceType = postResourceType;
          resourceTypes.add(
              new Predicate(postResourceType, PROPERTY) {
                {
                  set(PROPERTY, SLING_RESOURCE_TYPE_PROPERTY);
                  set(VALUE, _postResourceType);
                }
              });
        }
      }

      resourceTypes.add(
          new Predicate(RESOURCE_TYPE_TOPIC, PROPERTY) {
            {
              set(PROPERTY, SLING_RESOURCE_TYPE_PROPERTY);
              set(VALUE, RESOURCE_TYPE_TOPIC);
            }
          });
      resourceTypes.add(
          new Predicate(RESOURCE_TYPE_POST, PROPERTY) {
            {
              set(PROPERTY, SLING_RESOURCE_TYPE_PROPERTY);
              set(VALUE, RESOURCE_TYPE_POST);
            }
          });

      // -----------------< filter by node type >
      // -------------------------------------------------------------
      final Predicate nodeTypeFilter =
          new Predicate(NODE_TYPE, TypePredicateEvaluator.TYPE) {
            {
              set(TypePredicateEvaluator.TYPE, NODE_TYPE);
            }
          };

      // -----------------< filter by query >
      // -------------------------------------------------------------
      final PredicateGroup fulltext = new PredicateGroup("fulltext");
      fulltext.setAllRequired(false);
      for (final String prop : getScopeProperties()) {
        fulltext.add(
            new Predicate(prop, FULLTEXT) {
              {
                set(FULLTEXT, getQuery());
                set(REL_PATH, "@" + prop);
              }
            });
      }

      // no custom properties to search, add default one
      if (fulltext.size() == 0) {
        fulltext.add(
            new Predicate(PN_SUBJECT, FULLTEXT) {
              {
                set(FULLTEXT, getQuery());
                set(REL_PATH, "@" + PN_SUBJECT);
              }
            });
      }

      // add predicates to root
      root.add(nodeTypeFilter);
      root.add(pathFilter);
      root.add(resourceTypes);
      root.add(fulltext);

      final QueryBuilder qb = resolver.adaptTo(QueryBuilder.class);
      final Query query = qb.createQuery(root, resolver.adaptTo(Session.class));
      query.setHitsPerPage(properties.get(PN_MAXPERPAGE, 10));
      query.setExcerpt(true);
      query.setStart(NumberUtils.toLong(request.getParameter(REQUEST_PARAM_START), 0));

      // add custom predicates
      for (final Predicate predicate : customPredicates) {
        query.getPredicates().add(predicate);
      }

      result = query.getResult();
    }

    return result;
  }
  /** 应用客户端耗时统计 */
  @RequestMapping("/costDistribute")
  public ModelAndView doCostDistribute(
      HttpServletRequest request, HttpServletResponse response, Model model) {
    // 1.应用信息
    Long appId = NumberUtils.toLong(request.getParameter("appId"));
    if (appId <= 0) {
      return new ModelAndView("");
    }
    AppDesc appDesc = appService.getByAppId(appId);
    model.addAttribute("appDesc", appDesc);
    model.addAttribute("appId", appId);

    // 2.获取时间区间
    TimeBetween timeBetween = new TimeBetween();
    try {
      timeBetween = fillWithCostDateFormat(request, model);
    } catch (ParseException e) {
      logger.error(e.getMessage(), e);
    }
    long startTime = timeBetween.getStartTime();
    long endTime = timeBetween.getEndTime();
    Date startDate = timeBetween.getStartDate();

    // 3.所有命令和第一个命令
    List<String> allCommands =
        clientReportCostDistriService.getAppDistinctCommand(appId, startTime, endTime);
    model.addAttribute("allCommands", allCommands);

    // 4.所有客户端和实例对应关系
    List<AppInstanceClientRelation> appInstanceClientRelationList =
        appInstanceClientRelationService.getAppInstanceClientRelationList(appId, startDate);
    model.addAttribute("appInstanceClientRelationList", appInstanceClientRelationList);

    String firstCommand = request.getParameter("firstCommand");
    if (StringUtils.isBlank(firstCommand) && CollectionUtils.isNotEmpty(allCommands)) {
      firstCommand = allCommands.get(0);
      model.addAttribute("firstCommand", firstCommand);
    } else {
      model.addAttribute("firstCommand", firstCommand);
    }

    // 5.1 应用下客户端和实例的全局耗时统计列表
    List<AppClientCostTimeTotalStat> appChartStatList =
        clientReportCostDistriService.getAppClientCommandTotalStat(
            appId, firstCommand, startTime, endTime);
    Map<String, Object> resultMap = new HashMap<String, Object>();

    // 5.2 简化字段
    List<Map<String, Object>> app = new ArrayList<Map<String, Object>>();
    for (AppClientCostTimeTotalStat appClientCostTimeTotalStat : appChartStatList) {
      Map<String, Object> map = new HashMap<String, Object>();
      map.put("timeStamp", appClientCostTimeTotalStat.getTimeStamp());
      map.put("count", appClientCostTimeTotalStat.getTotalCount());
      map.put("mean", appClientCostTimeTotalStat.getMean());
      map.put("median", appClientCostTimeTotalStat.getMedian());
      map.put("max90", appClientCostTimeTotalStat.getNinetyPercentMax());
      map.put("max99", appClientCostTimeTotalStat.getNinetyNinePercentMax());
      map.put("max100", appClientCostTimeTotalStat.getHundredMax());
      map.put(
          "maxInst",
          appClientCostTimeTotalStat.getMaxInstanceHost()
              + ":"
              + appClientCostTimeTotalStat.getMaxInstancePort());
      map.put("maxClient", appClientCostTimeTotalStat.getMaxClientIp());
      app.add(map);
    }

    resultMap.put("app", app);
    model.addAttribute("appChartStatListJson", JSONObject.toJSONString(resultMap));

    return new ModelAndView("client/clientCostDistribute");
  }