@Override @SuppressWarnings({"unchecked", "rawtypes"}) public void execute( Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException { Site site = FrontUtils.getSite(env); List<Content> list = getList(params, env); Map<String, TemplateModel> paramWrap = new HashMap<String, TemplateModel>(params); paramWrap.put(OUT_LIST, DEFAULT_WRAPPER.wrap(list)); Map<String, TemplateModel> origMap = DirectiveUtils.addParamsToVariable(env, paramWrap); InvokeType type = DirectiveUtils.getInvokeType(params); String listStyle = DirectiveUtils.getString(PARAM_STYLE_LIST, params); if (InvokeType.sysDefined == type) { if (StringUtils.isBlank(listStyle)) { throw new ParamsRequiredException(PARAM_STYLE_LIST); } env.include(TPL_STYLE_LIST + listStyle + TPL_SUFFIX, UTF8, true); } else if (InvokeType.userDefined == type) { if (StringUtils.isBlank(listStyle)) { throw new ParamsRequiredException(PARAM_STYLE_LIST); } FrontUtils.includeTpl(TPL_STYLE_LIST, site, env); } else if (InvokeType.custom == type) { FrontUtils.includeTpl(TPL_NAME, site, params, env); } else if (InvokeType.body == type) { body.render(env.getOut()); } else { throw new RuntimeException("invoke type not handled: " + type); } DirectiveUtils.removeParamsFromVariable(env, paramWrap, origMap); }
public void testIsBlank() { assertEquals(true, StringUtils.isBlank(null)); assertEquals(true, StringUtils.isBlank("")); assertEquals(true, StringUtils.isBlank(StringUtilsTest.WHITESPACE)); assertEquals(false, StringUtils.isBlank("foo")); assertEquals(false, StringUtils.isBlank(" foo ")); }
/** 保存添加和修改,对象的id不为空时,为修改,否则为添加 */ @PageType(EnumPageType.JSONPAGE) @RequestMapping(value = "/save/json", method = RequestMethod.POST) @ResponseBody public DwzJson settlementSave( UserAgent userAgent, @RequestParam(required = false) String dwzId, @ModelAttribute("settlement") Settlement settlement, @RequestParam(required = false) String dwzId, ModelMap model) { DwzJson dwzJson; if (settlement == null) { dwzJson = new DwzJson( "300", this.messageSource.getMessage("operation.failed", null, this.getThisLocale())); return dwzJson; } if (settlement.getId() != null && settlement.getId() >= 0) { // 保存修改 ServiceResult<Integer> result = settlementService.update(new ServiceRequest(settlement, userAgent)); if (result.getErrorNO() != null) { dwzJson = new DwzJson( "300", this.messageSource.getMessage( result.getErrorInfo(), result.getMsgArgs(), this.getThisLocale())); } else { dwzJson = new DwzJson( "200", this.messageSource.getMessage( "operation.success", result.getMsgArgs(), this.getThisLocale()), StringUtils.isBlank(dwzId) ? "dwz_tab_settlement" : dwzId, "closeCurrent"); } } else { // 保存新增 ServiceResult<Settlement> result = settlementService.save(new ServiceRequest(settlement, userAgent)); if (result.getErrorNO() != null) { dwzJson = new DwzJson( "300", this.messageSource.getMessage( result.getErrorInfo(), result.getMsgArgs(), this.getThisLocale())); } else { dwzJson = new DwzJson( "200", this.messageSource.getMessage( "operation.success", result.getMsgArgs(), this.getThisLocale()), StringUtils.isBlank(dwzId) ? "dwz_tab_settlement" : dwzId, "closeCurrent"); } } return dwzJson; }
/** * get file size * * <ul> * <li>if path is null or empty, return -1 * <li>if path exist and it is a file, return file size, else return -1 * <ul> * * @param path * @return 是否成功 */ public static long getFileSize(String path) { if (StringUtils.isBlank(path)) { return -1; } File file = new File(path); return (file.exists() && file.isFile() ? file.length() : -1); }
/** * 将一个字符串使用分隔符分割后转换为数组 * * @param str * @param splitChar * @return */ public static List<String> splitStringToList(String str, String splitChar) { if (StringUtils.isBlank(str)) { return null; } return arrayToList(str.split(splitChar)); }
/** * 检查是否是16进制数 * * @param str * @return */ public static boolean isValidHexString(String str) { if (StringUtils.isBlank(str)) { return false; } String pattern = "[0-9a-fA-F]+"; return str.matches(pattern); }
/** * 将逗号分隔的字符串转换为数组 * * @param str * @return */ public static String[] stringToArray(String str) { if (StringUtils.isBlank(str)) { return null; } String[] split = str.split(","); return split; }
public void testIsBlank() { String test = null; boolean result1 = StringUtils.isBlank(test); assertTrue(result1); test = ""; boolean result2 = StringUtils.isBlank(test); assertTrue(result2); test = " "; boolean result3 = StringUtils.isBlank(test); assertTrue(result3); test = " t "; boolean result4 = StringUtils.isBlank(test); assertFalse(result4); }
/** * 表明如果这个文件代表底层文件系统上的文件。 * * @param 文件路径 * @return */ public static boolean isFileExist(String filePath) { if (StringUtils.isBlank(filePath)) { return false; } File file = new File(filePath); return (file.exists() && file.isFile()); }
/** * 表明如果这个文件代表底层文件上的一个目录系统上的文件. * * @param 目录路径 * @return */ public static boolean isFolderExist(String directoryPath) { if (StringUtils.isBlank(directoryPath)) { return false; } File dire = new File(directoryPath); return (dire.exists() && dire.isDirectory()); }
public static <T extends CharSequence> T notBlank(final T argument, final String name) { if (argument == null) { throw new IllegalArgumentException(name + " may not be null"); } if (StringUtils.isBlank(argument)) { throw new IllegalArgumentException(name + " may not be blank"); } return argument; }
/** 进入添加页面 */ @PageType(EnumPageType.AJAXPAGE) @RequestMapping(value = "/addAjax") public String settlementAddAjax( UserAgent userAgent, @RequestParam(required = false) String dwzId, ModelMap model) { Settlement settlement = new Settlement(); model.put("settlement", settlement); model.put("operType", "add"); model.put("dwzId", StringUtils.isBlank(dwzId) ? "dwz_tab_settlement" : dwzId); return "settlement/objAjax"; }
/** * 后缀的文件路径 * * <pre> * getFileExtension(null) = "" * getFileExtension("") = "" * getFileExtension(" ") = " " * getFileExtension("a.mp3") = "mp3" * getFileExtension("a.b.rmvb") = "rmvb" * getFileExtension("abc") = "" * getFileExtension("c:\\") = "" * getFileExtension("c:\\a") = "" * getFileExtension("c:\\a.b") = "b" * getFileExtension("c:a.txt\\a") = "" * getFileExtension("/home/admin") = "" * getFileExtension("/home/admin/a.txt/b") = "" * getFileExtension("/home/admin/a.txt/b.mp3") = "mp3" * </pre> * * @param 文件路径 * @return */ public static String getFileExtension(String filePath) { if (StringUtils.isBlank(filePath)) { return filePath; } int extenPosi = filePath.lastIndexOf(FILE_EXTENSION_SEPARATOR); int filePosi = filePath.lastIndexOf(File.separator); if (extenPosi == -1) { return ""; } return (filePosi >= extenPosi) ? "" : filePath.substring(extenPosi + 1); }
/** 根据查询条件,批量删除 */ @PageType(EnumPageType.JSONPAGE) @RequestMapping(value = "/delJson", method = RequestMethod.POST) public @ResponseBody DwzJson settlementDelBatch( @ModelAttribute("query") SettlementQuery query, @RequestParam(required = false) String dwzId, UserAgent userAgent, ModelMap model) { DwzJson dwzJson; // 将query.ids的条件合并到query.id_in中 if (query != null && StringUtils.isNotBlank(query.getIds())) { List<Long> id_in = query.getIdsList(); if (query.getId_in() == null) { query.setId_in(id_in); } else { query.getId_in().addAll(id_in); } } // 如果没有条件,就拒绝删除操作,以免所有数据被删掉. if (query == null || (query.getId_in() == null || query.getId_in().size() <= 0)) { dwzJson = new DwzJson( "300", this.getMessageSource() .getMessage("delete.error.parameter.ids.null", null, this.getThisLocale())); return dwzJson; } ServiceResult<Integer> result = settlementService.remove(new ServiceRequest(query, userAgent)); if (result.getErrorNO() != null) { dwzJson = new DwzJson( "300", this.messageSource.getMessage( result.getErrorInfo(), result.getMsgArgs(), this.getThisLocale())); } else { if (result.getDataObj() > 0) { dwzJson = new DwzJson( "200", this.messageSource.getMessage( "operation.success", result.getMsgArgs(), this.getThisLocale()), StringUtils.isBlank(dwzId) ? "dwz_tab_settlement" : dwzId); } else { dwzJson = new DwzJson( "300", this.getMessageSource() .getMessage("delete.error", result.getMsgArgs(), this.getThisLocale())); } } return dwzJson; }
public JavaClassNameParser(String className) { if (StringUtils.isBlank(className)) { throw new InvalidParameterException("className is empty"); } if (!className.contains(".")) { className = className; return; } this.packageName = className.substring(0, className.lastIndexOf(".")); this.className = className.substring(className.lastIndexOf(".") + 1); }
/** * get Boolean from jsonObject * * @param jsonObject * @param key * @param defaultValue * @return * <ul> * <li>if jsonObject is null, return defaultValue * <li>if key is null or empty, return defaultValue * <li>return {@link JSONObject#getBoolean(String)} * </ul> */ public static boolean getBoolean(JSONObject jsonObject, String key, Boolean defaultValue) { if (jsonObject == null || StringUtils.isBlank(key)) { return defaultValue; } try { return jsonObject.getBoolean(key); } catch (JSONException e) { if (isPrintException) { e.printStackTrace(); } return defaultValue; } }
/** * get String from jsonData * * @param jsonData * @param defaultValue * @param keyArray * @return * <ul> * <li>if jsonData is null, return defaultValue * <li>if keyArray is null or empty, return defaultValue * <li>get {@link #getJSONObject(JSONObject, String, JSONObject)} by recursion, return it. * if anyone is null, return directly * </ul> */ public static String getStringCascade(String jsonData, String defaultValue, String... keyArray) { if (StringUtils.isBlank(jsonData)) { return defaultValue; } String data = jsonData; for (String key : keyArray) { data = getString(data, key, defaultValue); if (data == null) { return defaultValue; } } return data; }
public static Map<String, MessageAttributeValue> getValidNotificationAttributes( Map<String, MessageAttributeValue> notificationAttributes) { Map<String, MessageAttributeValue> validAttributes = new HashMap<String, MessageAttributeValue>(); if (notificationAttributes == null) return validAttributes; for (Map.Entry<String, MessageAttributeValue> entry : notificationAttributes.entrySet()) { if (!StringUtils.isBlank(entry.getValue().getStringValue())) { validAttributes.put(entry.getKey(), entry.getValue()); } } return validAttributes; }
/** * parse key-value pairs to map. ignore empty key, if getValue exception, put empty value * * @param source key-value pairs json * @return * <ul> * <li>if source is null or source's length is 0, return empty map * <li>if source {@link JSONObject#JSONObject(String)} exception, return null * <li>return {@link JSONUtils#parseKeyAndValueToMap(JSONObject)} * </ul> */ public static Map<String, String> parseKeyAndValueToMap(String source) { if (StringUtils.isBlank(source)) { return null; } try { JSONObject jsonObject = new JSONObject(source); return parseKeyAndValueToMap(jsonObject); } catch (JSONException e) { if (isPrintException) { e.printStackTrace(); } return null; } }
/** * get Long from jsonData * * @param jsonData * @param key * @param defaultValue * @return * <ul> * <li>if jsonObject is null, return defaultValue * <li>if jsonData {@link JSONObject#JSONObject(String)} exception, return defaultValue * <li>return {@link JSONUtils#getLong(JSONObject, String, JSONObject)} * </ul> */ public static Long getLong(String jsonData, String key, Long defaultValue) { if (StringUtils.isBlank(jsonData)) { return defaultValue; } try { JSONObject jsonObject = new JSONObject(jsonData); return getLong(jsonObject, key, defaultValue); } catch (JSONException e) { if (isPrintException) { e.printStackTrace(); } return defaultValue; } }
/** * get JSONObject from jsonData * * @param jsonData * @param defaultValue * @param keyArray * @return * <ul> * <li>if jsonData is null, return defaultValue * <li>if keyArray is null or empty, return defaultValue * <li>get {@link #getJSONObject(JSONObject, String, JSONObject)} by recursion, return it. * if anyone is null, return directly * </ul> */ public static JSONObject getJSONObjectCascade( String jsonData, JSONObject defaultValue, String... keyArray) { if (StringUtils.isBlank(jsonData)) { return defaultValue; } try { JSONObject jsonObject = new JSONObject(jsonData); return getJSONObjectCascade(jsonObject, defaultValue, keyArray); } catch (JSONException e) { if (isPrintException) { e.printStackTrace(); } return defaultValue; } }
/** * 获取字符串的MD5 * * @param string 字符串 * @return String MD5字符串 * @throws NoSuchAlgorithmException */ public static String getStringMD5(String string, String salt) throws NoSuchAlgorithmException { String target = null; if (StringUtils.isBlank(salt)) { target = string; } else { target = getStringMD5(salt + string + salt, null); } byte[] byteString = target.getBytes(Charset.forName("utf-8")); MessageDigest md = MessageDigest.getInstance("MD5"); byte[] array = md.digest(byteString); StringBuffer sb = new StringBuffer(); for (int i = 0; i < array.length; ++i) { sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).substring(1, 3)); } return sb.toString(); }
/** 删除一个数据 */ @PageType(EnumPageType.JSONPAGE) @RequestMapping(value = "/delJson/{id}") public @ResponseBody DwzJson settlementDel( @PathVariable("id") Long id, @RequestParam(required = false) String dwzId, UserAgent userAgent, ModelMap model) { DwzJson dwzJson; if (id == null || id < 0) { dwzJson = new DwzJson( "300", this.getMessageSource() .getMessage("delete.error.parameter.ids.null", null, this.getThisLocale())); return dwzJson; } SettlementQuery query = new SettlementQuery(); query.setId(id); ServiceResult<Integer> result = settlementService.remove(new ServiceRequest(query, userAgent)); if (result.getErrorNO() != null) { dwzJson = new DwzJson( "300", this.messageSource.getMessage( result.getErrorInfo(), result.getMsgArgs(), this.getThisLocale())); } else { if (result.getDataObj() > 0) { dwzJson = new DwzJson( "200", this.messageSource.getMessage( "operation.success", result.getMsgArgs(), this.getThisLocale()), StringUtils.isBlank(dwzId) ? "dwz_tab_settlement" : dwzId); } else { dwzJson = new DwzJson( "300", this.getMessageSource() .getMessage("delete.error", result.getMsgArgs(), this.getThisLocale())); } } return dwzJson; }
/** 查询 数据 */ @PageType(EnumPageType.AJAXPAGE) @RequestMapping(value = "/indexAjax") public String settlementIndexAjax( @ModelAttribute("query") SettlementQuery query, @RequestParam(required = false) String dwzId, UserAgent userAgent, ModelMap model) { ServiceResult<DwzPage<Settlement>> result = settlementService.pageQuery(new ServiceRequest(query, userAgent)); model.addAttribute("page", result.getDataObj()); model.addAttribute("srs", result); model.addAttribute("query", query); model.addAttribute("dwzId", StringUtils.isBlank(dwzId) ? "dwz_tab_settlement" : dwzId); if (query != null && "lookup".equals(query.getDwzId())) { return "settlement/lookupAjax"; } return "settlement/indexAjax"; }
/** 进入单条记录的修改页面 */ @PageType(EnumPageType.AJAXPAGE) @RequestMapping(value = "/editAjax/{id}") public String settlementEdit( @PathVariable("id") Long id, UserAgent userAgent, @RequestParam(required = false) String dwzId, ModelMap model) { Settlement settlement = settlementService.queryOne(new ServiceRequest(id, userAgent)).getDataObj(); if (settlement == null) { DwzJson dwzJson = new DwzJson(); dwzJson.setStatusCode("300"); dwzJson.setMessage("要修改的数据不存在."); model.put("msgJson", dwzJson); return "errorPage/msg" + EnumPageType.AJAXPAGE.getCode(); } model.put("settlement", settlement); model.put("operType", "edit"); model.put("dwzId", StringUtils.isBlank(dwzId) ? "dwz_tab_settlement" : dwzId); return "settlement/objAjax"; }
/** * get String array from jsonObject * * @param jsonObject * @param key * @param defaultValue * @return * <ul> * <li>if jsonObject is null, return defaultValue * <li>if key is null or empty, return defaultValue * <li>if {@link JSONObject#getJSONArray(String)} exception, return defaultValue * <li>if {@link JSONArray#getString(int)} exception, return defaultValue * <li>return string array * </ul> */ public static String[] getStringArray(JSONObject jsonObject, String key, String[] defaultValue) { if (jsonObject == null || StringUtils.isBlank(key)) { return defaultValue; } try { JSONArray statusArray = jsonObject.getJSONArray(key); if (statusArray != null) { String[] value = new String[statusArray.length()]; for (int i = 0; i < statusArray.length(); i++) { value[i] = statusArray.getString(i); } return value; } } catch (JSONException e) { if (isPrintException) { e.printStackTrace(); } return defaultValue; } return defaultValue; }
/** * delete file or directory * * <ul> * <li>if path is null or empty, return true * <li>if path not exist, return true * <li>if path exist, delete recursion. return true * <ul> * * @param path * @return 是否成功 */ public static boolean deleteFile(String path) { if (StringUtils.isBlank(path)) { return true; } File file = new File(path); if (file.exists()) { if (file.isFile()) { return file.delete(); } else if (file.isDirectory()) { for (File f : file.listFiles()) { if (f.isFile()) { f.delete(); } else if (f.isDirectory()) { deleteFile(f.getAbsolutePath()); } } return file.delete(); } return false; } return true; }
/** * get String list from jsonObject * * @param jsonObject * @param key * @param defaultValue * @return * <ul> * <li>if jsonObject is null, return defaultValue * <li>if key is null or empty, return defaultValue * <li>if {@link JSONObject#getJSONArray(String)} exception, return defaultValue * <li>if {@link JSONArray#getString(int)} exception, return defaultValue * <li>return string array * </ul> */ public static List<String> getStringList( JSONObject jsonObject, String key, List<String> defaultValue) { if (jsonObject == null || StringUtils.isBlank(key)) { return defaultValue; } try { JSONArray statusArray = jsonObject.getJSONArray(key); if (statusArray != null) { List<String> list = new ArrayList<String>(); for (int i = 0; i < statusArray.length(); i++) { list.add(statusArray.getString(i)); } return list; } } catch (JSONException e) { if (isPrintException) { e.printStackTrace(); } return defaultValue; } return defaultValue; }
/** * 获取当前html文本中所有可能存在图片的地址 * * @param html * @return */ public static List<String> getImagesOrLinks(String html) { Document doc = Jsoup.parse(html); Elements eles = doc.select("img,a"); List<String> result = new LinkedList<>(); for (Element element : eles) { boolean isa = "a".equals(element.nodeName()); String link = element.attr(isa ? "href" : "src"); if (StringUtils.isBlank(link)) continue; if (isa) { int question = link.indexOf("?"); if (question > 0) link = link.substring(0, question); int comma = link.lastIndexOf("."); String ext = link.substring(comma + 1).toLowerCase(); if (FileUtils.isImageExt(ext)) { result.add(link); } } else { result.add(link); } } return result; }
public void init() throws MQClientException { nameServer = PropertyFileUtil.get("rocketmq.namesrv.domain"); if (StringUtils.isBlank(nameServer)) { logger.warn("【MQ init】property rocketmq.namesrv.domain not found"); return; } if ("localTest".equals(nameServer)) { logger.warn("【MQ init】localTest"); return; } if (StringUtils.isBlank(System.getProperty("rocketmq.namesrv.domain"))) { System.setProperty("rocketmq.namesrv.domain", nameServer); } topicType = getTopic(); topic = RocketMqUtils.getTopic(topicType); if (StringUtils.isBlank(group)) { group = "S_" + topic.getTopic() + "_" + topic.getTags(); } consumer = new DefaultMQPushConsumer(group); consumer.setNamesrvAddr(nameServer); consumer.setMessageModel(getMessageModel()); consumer.setConsumeThreadMin(minConsumeThread); consumer.setConsumeThreadMax(maxConsumeThread); // 可以不设置 设置后可以起多个 消费端 try { consumer.setInstanceName("DEFAULT_CONSUMER-" + InetAddress.getLocalHost().getHostName()); } catch (UnknownHostException e) { logger.error("getHostName error", e); } // 设置订阅的topic 设置订阅过滤表达式 if (StringUtils.isBlank(subExpression)) { subExpression = topic.getTags(); consumer.subscribe(topic.getTopic(), subExpression); } else { consumer.subscribe(topic.getTopic(), subExpression); } try { consumer.registerMessageListener(this); consumer.start(); } catch (MQClientException e) { logger.error( "consumer start error!topic={},subExpression={},group={}", topic.getTopic(), subExpression, group, e); } logger.info( "consumer start! topic={},subExpression={},group={}", topic.getTopic(), subExpression, group); }