/** 值分布日期格式 */ 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); }
public void createImage(HttpServletRequest request, HttpServletResponse response) throws IOException { response.setHeader("Pragma", "no-cache"); response.setHeader("Cache-Control", "no-cache"); response.setDateHeader("Expires", 0); response.setContentType("image/jpg"); /** 取得高度和宽度 */ String width = request.getParameter("width"); String height = request.getParameter("height"); if (StringUtils.isNumeric(width) && StringUtils.isNumeric(height)) { w = NumberUtils.toInt(width); h = NumberUtils.toInt(height); } /** */ BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB); Graphics g = image.getGraphics(); createBackground(g); /** */ String s = createCharacter(g); request.getSession().setAttribute(VALIDATE_CODE, s); g.dispose(); OutputStream out = response.getOutputStream(); ImageIO.write(image, "JPEG", out); out.close(); }
private void updateTotalVA() { tv.setText( "" + (NumberUtils.toInt(batteryVoltage.getText().toString()) * NumberUtils.toInt(batteryAmpHour.getText().toString()) * NumberUtils.toInt(batteryCount.getText().toString()))); }
@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); }
/** {@inheritDoc} */ public String doExport(final String descriptorGroup, final String fileName, final boolean async) { final AsyncContext ctx = getAsyncContext(); final String imgVault = systemService.getImageRepositoryDirectory(); // Max char of report to UI since it will get huge and simply will crash the UI, not to mention // traffic cost. final int logSize = NumberUtils.toInt( nodeService.getConfiguration().get(AttributeNamesKeys.System.IMPORT_JOB_LOG_SIZE), 100); // Timeout - just in case runnable crashes and we need to unlock through timeout. final int timeout = NumberUtils.toInt( nodeService.getConfiguration().get(AttributeNamesKeys.System.IMPORT_JOB_TIMEOUT_MS), 100); final String rootPath = resolveExportDirectory(); final String absFile = resolveExportFile(fileName); return doJob( new JobContextImpl( async, new JobStatusListenerImpl(logSize, timeout), new HashMap<String, Object>() { { put(JobContextKeys.EXPORT_DESCRIPTOR_GROUP, descriptorGroup); put(JobContextKeys.EXPORT_FILE, absFile); put(JobContextKeys.IMAGE_VAULT_PATH, imgVault); put(JobContextKeys.EXPORT_DIRECTORY_ROOT, rootPath); putAll(ctx.getAttributes()); } })); }
/** * Returns the value as a {@link Double} value. The returned value will be <code>0</code> or * <code>1</code> if the {@link #value} is a boolean value. If {@link #value} can not be converted * into a number, a {@link NumberFormatException} is thrown. * * @return {@link #value} as {@link Double} */ public double getValueAsDouble() { if (NumberUtils.isNumber(value)) { return NumberUtils.createDouble(value); } if (isBooleanValue(value)) { return BooleanUtils.toBoolean(value) ? 1 : 0; } throw new NumberFormatException(); }
// For example, here is a line from the 5kb chr1 MAPQGE30 raw observed contact matrix // (GM12878_combined/5kb_resolution_intrachromosomal/chr1/MAPQGE30/chr1_5kb.RAWobserved): // 40000000 40100000 59.0 private static void processRawContactInformation( String fileToRead, double minValue, ArrayList<DesiredChrContact> contactsToCheck, boolean intra) throws IOException { // Check if sorted version is available // If not make sorted available. if (!Gpio.exists(fileToRead + ".sorted")) { if (intra) { umcg.genetica.io.chrContacts.SortIntraChrContacts.readNonSortedWriteSorted( fileToRead, fileToRead + ".sorted"); } else { umcg.genetica.io.chrContacts.SortInterChrContacts.readNonSortedWriteSorted( fileToRead, fileToRead + ".sorted"); } } int numberToBeMatched = 0; LineIterator it = FileUtils.lineIterator(new File(fileToRead + ".sorted"), "UTF-8"); try { while (it.hasNext()) { String[] parts = StringUtils.split(it.nextLine(), '\t'); int posChr1 = org.apache.commons.lang.math.NumberUtils.createInteger(parts[0]); int posChr2 = org.apache.commons.lang.math.NumberUtils.createInteger(parts[1]); while (numberToBeMatched < contactsToCheck.size()) { if (posChr1 < contactsToCheck.get(numberToBeMatched).getChrLocationSmaller()) { break; } else if (posChr1 == contactsToCheck.get(numberToBeMatched).getChrLocationSmaller()) { if (posChr2 < contactsToCheck.get(numberToBeMatched).getChrLocationLarger()) { break; } if (posChr2 == contactsToCheck.get(numberToBeMatched).getChrLocationLarger()) { double contact = org.apache.commons.lang.math.NumberUtils.createDouble(parts[2]); if (contact >= minValue) { contactsToCheck.get(numberToBeMatched).setContact(); numberToBeMatched++; } else { numberToBeMatched++; } } else if (posChr2 > contactsToCheck.get(numberToBeMatched).getChrLocationLarger()) { numberToBeMatched++; } } else if (posChr1 > contactsToCheck.get(numberToBeMatched).getChrLocationSmaller()) { numberToBeMatched++; } } } } finally { LineIterator.closeQuietly(it); } }
/** Faz as validações solicitadas no manual de integração */ public String isValid() { if (getTpAmb() == null || getTpAmb().length() != 1) { return "Tipo de Ambiente inválido"; } if (getcUF() == null || getcUF().length() != 2) { return "Código da UF inválido"; } if (getAno() == null || getAno().length() != 2) { return "O Ano de inutilização é inválido"; } if (getCNPJ() == null || getCNPJ().length() != 14) { return "CNPJ inválido"; } if (getMod() == null || getMod().length() != 2 || !TextUtil.isNumber(getMod())) { return "Modelo da NF inválido"; } if (getSerie() == null || getSerie().length() < 1 || getSerie().length() > 3 || !TextUtil.isNumber(getSerie())) { return "Série da NF inválida"; } if (getnNFIni() == null || getnNFIni().length() < 1 || getnNFIni().length() > 9 || !NumberUtils.isNumber(getnNFIni())) { return "Número Inicial da NF para inutilização é inválido"; } if (getnNFFin() == null || getnNFFin().length() < 1 || getnNFFin().length() > 9 || !NumberUtils.isNumber(getnNFFin())) { return "Número Final da NF para inutilização é inválido"; } if (getxJust() == null || getxJust().length() < 15) { return "Justificativa deve ser maior que 15 caracteres"; } if (Integer.parseInt(getnNFIni()) > Integer.parseInt(getnNFFin())) { return "Número Final da NF não pode ser menor que Número Inicial da NF"; } setID(); return null; } // isValid
private static boolean hasOnlyZeroVariations(MeasureVariations variations) { return (!variations.hasVariation1() || NumberUtils.compare(variations.getVariation1(), 0.0) == 0) && (!variations.hasVariation2() || NumberUtils.compare(variations.getVariation2(), 0.0) == 0) && (!variations.hasVariation3() || NumberUtils.compare(variations.getVariation3(), 0.0) == 0) && (!variations.hasVariation4() || NumberUtils.compare(variations.getVariation4(), 0.0) == 0) && (!variations.hasVariation5() || NumberUtils.compare(variations.getVariation5(), 0.0) == 0); }
/** * 应用客户端统计首页 * * @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"); }
/** * Aggregate all income receipt for given period The result format is: * Map<accountId,'accountName|amount'> * * @param from * @param to * @return */ public Map<Integer, Object[]> aggregateIncomeReceiptItem(Date from, Date to) { String squery = "select ir.account.id, ir.account.name, sum(ir.amount) from IncomeReceiptItem as ir " + " left join ir.receipt as r " + "where r.receiptDate >= :from and r.receiptDate <= :to " + " group by ir.account.name"; Query query = sessionFactory.getCurrentSession().createQuery(squery); query.setParameter("from", from); query.setParameter("to", to); List result = query.list(); Map<Integer, Object[]> mapResult = new HashMap<Integer, Object[]>(); String accountName; BigDecimal amount; Integer accountId; String tmp; if (result != null && result.size() > 0) { for (Object o : result) { Object[] obj = (Object[]) o; accountId = NumberUtils.toInt(obj[0].toString()); mapResult.put(accountId, obj); } } return mapResult; }
@Override @Nonnull public HstQueryBuilder sizeParam(final String parameterName) { String value = SiteUtils.getAnyParameter(parameterName, request, component); size = NumberUtils.toInt(value, SiteUtils.DEFAULT_PAGE_SIZE); return this; }
protected MemcachedImpl(boolean isTTStore) throws Exception { Properties configuration = new Properties(); configuration.load(MemcachedImpl.class.getResourceAsStream("/config.properties")); List<InetSocketAddress> addrList = new ArrayList<InetSocketAddress>(); int nb = 1; String prefix = isTTStore ? "ttcached." : "memcached."; while (configuration.containsKey(prefix + nb + ".host")) { String hostandport = configuration.getProperty(prefix + nb + ".host"); String host = StringUtils.substringBefore(hostandport, ":"); String portStr = StringUtils.substringAfter(hostandport, ":"); int port = NumberUtils.toInt(portStr, 11211); System.out.println( "memcached init [host:" + host + ",port:" + port + ",portStr:" + portStr + "]"); addrList.add(new InetSocketAddress(host, port)); nb++; } if (addrList.size() == 0) { throw new Exception("Bad configuration for memcached or tt store"); } MemcachedClientBuilder builder = new XMemcachedClientBuilder(addrList); try { builder.setConnectionPoolSize(5); this.client = builder.build(); } catch (IOException e) { e.printStackTrace(); } }
@Override public void updateUsername(String externalId, String username) { InternalAuthDAO internalAuthDAO = DAOFactory.getInstance().getInternalAuthDAO(); InternalAuth internalAuth = internalAuthDAO.findById(NumberUtils.createLong(externalId)); internalAuthDAO.updateUsername(internalAuth, username); }
private HkPaymentResponse createPayment( String gatewayOrderId, String gatewayReferenceId, String rrn, String respMsg, String txnType, String amount, String authIdCode) { HkPaymentResponse hkPaymentResponse = new HkPaymentResponse( gatewayOrderId, gatewayReferenceId, respMsg, EnumGateway.EBS.asGateway(), null, null, rrn, authIdCode, NumberUtils.toDouble(amount)); if (txnType.equalsIgnoreCase(EnumPaymentTransactionType.SALE.getName())) { hkPaymentResponse.setGatewayOrderId(gatewayOrderId); hkPaymentResponse.setTransactionType(EnumPaymentTransactionType.SALE.getName()); } else if (txnType.equalsIgnoreCase(EnumPaymentTransactionType.REFUND.getName())) { hkPaymentResponse.setTransactionType(EnumPaymentTransactionType.REFUND.getName()); } return hkPaymentResponse; }
public void decreaseIndent() { if (currentEditor.getValue().getMediaType().equals(MediaType.XHTML)) { XHTMLCodeEditor xhtmlCodeEditor = (XHTMLCodeEditor) currentEditor.getValue(); XMLTagPair pair = xhtmlCodeEditor.findSurroundingTags(new XHTMLCodeEditor.BlockTagInspector()); if (pair != null) { logger.info("found xml block tag " + pair.getTagName()); String tagAtttributes = xhtmlCodeEditor.getRange(pair.getOpenTagEnd(), pair.getTagAttributesEnd()); Matcher regexMatcher = indentRegex.matcher(tagAtttributes); if (regexMatcher.find()) { String currentIndentStr = regexMatcher.group(2); int currentIndent = NumberUtils.toInt(currentIndentStr, 0); String currentUnit = regexMatcher.group(3); switch (currentUnit) { case "%": case "rem": case "em": currentIndent--; break; case "px": currentIndent = currentIndent - 10; break; } insertStyle("text-indent", currentIndent + currentUnit); } else { insertStyle("text-indent", "-1em"); } } } }
@RequestMapping(value = "/find.html") public ModelAndView find(@RequestParam(value = "q", required = false) String q) { ModelAndView mav = new ModelAndView(); mav.addObject("operation", "find"); if (StringUtils.isEmpty(q)) { mav.setViewName("find"); return mav; } try { if (NumberUtils.isNumber(q) && StringUtils.length(q) == 7) { return show(Integer.valueOf(q)); } else { long startTs = System.currentTimeMillis(); List<TConcept> concepts = nodeService.findConcepts(q); mav.addObject("concepts", concepts); long endTs = System.currentTimeMillis(); mav.addObject("q", q); mav.addObject("elapsed", new Long(endTs - startTs)); } } catch (Exception e) { mav.addObject("error", e.getMessage()); } mav.setViewName("find"); return mav; }
@RequestMapping("/apply") public String getApplyBrandsByPage(HttpServletRequest request) { // 处理分页信息 PageInfo pageInfo = null; if (request.getParameter("query") != null) { // 查询 pageInfo = PageUtils.registerPageInfo(request); } else if (request.getParameter("pageNo") != null) { // 分页 int pageNo = NumberUtils.toInt(request.getParameter("pageNo"), 1); pageInfo = PageUtils.getPageInfo(request); pageInfo.setPageNo(pageNo); } else { pageInfo = PageUtils.getPageInfo(request); if (pageInfo == null) { pageInfo = PageUtils.registerPageInfo(request); pageInfo.getConditions().put("status", SystemConstants.DB_STATUS_VALID); // 默认有效 pageInfo.getConditions().put("createDate", "DESC"); // 默认降序 } } request.setAttribute("pageInfo", pageInfo); // 查询 Map<String, Object> map = Maps.newHashMap(); if (StringUtils.isNotBlank(pageInfo.getConditions().get("brandName"))) { map.put("brandName", pageInfo.getConditions().get("brandName")); } if (StringUtils.isNotBlank(pageInfo.getConditions().get("coName"))) { map.put("coName", pageInfo.getConditions().get("coName").toLowerCase()); } if (StringUtils.isNotBlank(pageInfo.getConditions().get("startDt"))) { map.put( "startDt", DateUtils.parseDate(pageInfo.getConditions().get("startDt"), "yyyy-MM-dd")); } if (StringUtils.isNotBlank(pageInfo.getConditions().get("endDt"))) { Date endDt = DateUtils.parseDate(pageInfo.getConditions().get("endDt"), "yyyy-MM-dd"); endDt = DateUtils.addDay(endDt, 1); map.put("endDt", endDt); } if (StringUtils.isNotBlank(pageInfo.getConditions().get("status"))) { map.put("status", pageInfo.getConditions().get("status")); } if (StringUtils.isNotBlank(pageInfo.getConditions().get("loginName"))) { map.put("loginName", pageInfo.getConditions().get("loginName")); } Page<SellerBrand> sellerBrands = this.sellerBrandService.queryWaitAuditApplyByPage(map, pageInfo.getPageNo()); request.setAttribute("sellerBrands", sellerBrands); return "brand/applyList"; }
/** * 对字符串进行混淆,字符串必须是有效整数数字 * * @param id * @return */ public static String chaos(String id) { if (StringUtils.isEmpty(id)) { return StringUtils.EMPTY; } else if (!NumberUtils.isNumber(id)) { return StringUtils.EMPTY; } return chaos(Long.valueOf(id)); }
public void process(JSONRequestContext jsonRequestContext) { ResourceDAO resourceDAO = DAOFactory.getInstance().getResourceDAO(); ResourceCategoryDAO resourceCategoryDAO = DAOFactory.getInstance().getResourceCategoryDAO(); WorkResourceDAO workResourceDAO = DAOFactory.getInstance().getWorkResourceDAO(); TagDAO tagDAO = DAOFactory.getInstance().getTagDAO(); String name = jsonRequestContext.getRequest().getParameter("name"); Long resourceId = NumberUtils.createLong(jsonRequestContext.getRequest().getParameter("resource")); Double hourlyCost = NumberUtils.createDouble(jsonRequestContext.getRequest().getParameter("hourlyCost")); Double costPerUse = NumberUtils.createDouble(jsonRequestContext.getRequest().getParameter("costPerUse")); Long version = NumberUtils.createLong(jsonRequestContext.getRequest().getParameter("version")); String tagsText = jsonRequestContext.getString("tags"); Set<Tag> tagEntities = new HashSet<Tag>(); if (!StringUtils.isBlank(tagsText)) { List<String> tags = Arrays.asList(tagsText.split("[\\ ,]")); for (String tag : tags) { if (!StringUtils.isBlank(tag)) { Tag tagEntity = tagDAO.findByText(tag.trim()); if (tagEntity == null) tagEntity = tagDAO.create(tag); tagEntities.add(tagEntity); } } } WorkResource workResource = workResourceDAO.findById(resourceId); if (!version.equals(workResource.getVersion())) throw new SmvcRuntimeException( PyramusStatusCode.CONCURRENT_MODIFICATION, Messages.getInstance() .getText( jsonRequestContext.getRequest().getLocale(), "generic.errors.concurrentModification")); ResourceCategory resourceCategory = resourceCategoryDAO.findById( NumberUtils.createLong(jsonRequestContext.getRequest().getParameter("category"))); workResourceDAO.update(workResource, name, resourceCategory, costPerUse, hourlyCost); resourceDAO.setResourceTags(workResource, tagEntities); jsonRequestContext.setRedirectURL(jsonRequestContext.getReferer(true)); }
@Override public boolean validate() { if (NumberUtils.isNumber(_textf.getText())) { return true; } return false; }
private static int getInt(Element element, String name) { if (element == null) { return -1; } else { String text = element.getChildTextTrim(name); return NumberUtils.stringToInt(text, -1); } }
public static void main(String[] args) { String hostandport = "192.168.10.11:11218"; String host = StringUtils.substringBefore(hostandport, ":"); Integer port = NumberUtils.toInt(StringUtils.substringAfter(hostandport, ":"), 11211); System.out.println(host); System.out.println(port); }
/** * @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")); }
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); }
public static double toDouble(final Object o, final int casas) { if (o == null) { return 0d; } else if (o instanceof BigDecimal) { return ((BigDecimal) o).setScale(casas, RoundingMode.HALF_UP).doubleValue(); } else { return NumberUtils.toDouble(String.valueOf(o), casas); } }
public static double toDouble(final Object o) { if (o == null) { return 0d; } else if (o instanceof BigDecimal) { return ((BigDecimal) o).doubleValue(); } else { return NumberUtils.toDouble(String.valueOf(o)); } }
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)); } }
public static int toInt(final Object o) { if (o instanceof BigDecimal) { return NumberUtil.toInt((BigDecimal) o); } else if (o instanceof Number) { return new BigDecimal(String.valueOf(o)).intValue(); } else { return NumberUtils.toInt(String.valueOf(o)); } }