@RequestMapping(params = "method=upload", method = RequestMethod.POST) public String upload( HttpServletRequest request, HttpServletResponse response, @RequestParam("dataId") String dataId, @RequestParam("group") String group, @RequestParam("contentFile") MultipartFile contentFile, ModelMap modelMap) { response.setCharacterEncoding(Constants.ENCODE); boolean checkSuccess = true; String errorMessage = "参数错误"; if (StringUtils.isBlank(dataId) || DiamondUtils.hasInvalidChar(dataId.trim())) { checkSuccess = false; errorMessage = "无效的DataId"; } if (StringUtils.isBlank(group) || DiamondUtils.hasInvalidChar(group.trim())) { checkSuccess = false; errorMessage = "无效的分组"; } String content = getContentFromFile(contentFile); if (StringUtils.isBlank(content)) { checkSuccess = false; errorMessage = "无效的内容"; } if (!checkSuccess) { modelMap.addAttribute("message", errorMessage); return "/admin/config/upload"; } this.configService.addConfigInfo(dataId, group, content); modelMap.addAttribute("message", "提交成功!"); return listConfig(request, response, dataId, group, 1, 20, modelMap); }
/** * 查询区域树节点 * * @param regionId 区域ID * @return */ @RequestMapping(value = "/findRegionTreeNode") @ResponseBody public List<TRegion> findRegionTreeNode(String regionId, HttpSession session) { List<TRegion> data = new ArrayList<TRegion>(); User user = (User) session.getAttribute(UserService.USER_CODE); if (user == null) { return data; } if (user.isSuperAdmin()) { // 超级管理员,可查看所有正常状态的区域信息 if (StringUtils.isBlank(regionId)) { // 第一次加载 data.addAll(regionService.findAllTopInNormal()); } else { data.addAll(regionService.findChildrenByRegionIdInNormal(NumberUtils.toInt(regionId))); } } else { if (StringUtils.isBlank(regionId)) { // 第一次加载,获取当前登录用户归属公司的所在区域 data.addAll(regionService.findByCompanyIdForTree(user.getCompanyId())); } else { data.addAll(regionService.findChildrenByRegionIdForTree(NumberUtils.toInt(regionId))); } } return data; }
public static Map<String, String> readFile2Map(String path, String regular) throws IOException { if (StringUtils.isBlank(regular)) { return null; } if (StringUtils.isBlank(path)) { return null; } Map<String, String> map = new HashMap<String, String>(); File file = new File(path); FileReader fReader = new FileReader(file); BufferedReader bReader = new BufferedReader(fReader); String temp = null; String[] tempArr = (String[]) null; while ((temp = bReader.readLine()) != null) { if (StringUtils.isNotBlank(temp)) { tempArr = temp.split(regular); if (tempArr.length > 1) { String username = tempArr[0]; String password = tempArr[1]; if ((StringUtils.isNotBlank(username)) && (StringUtils.isNotBlank(password))) { map.put(username.trim(), password.trim()); } } } temp = null; tempArr = (String[]) null; } bReader.close(); fReader.close(); file = null; return map; }
@Override public Page<Map<String, Object>> searchPageMap( String sql, List<Object> params, Page<Map<String, Object>> page) throws Exception { if (StringUtils.isBlank(sql)) { List<Map<String, Object>> list = new ArrayList<>(); page.setTotalCount(0); page.setResult(list); return page; } if (params == null) { params = new ArrayList<>(); } StringBuilder sb = new StringBuilder(sql); int count = getCount(sb.toString(), params); page.setTotalCount(count); if (!StringUtils.isBlank(page.getOrder())) { sb.append(" ORDER BY ").append(page.getOrder()); if (!StringUtils.isBlank(page.getSort())) { sb.append(" ").append(page.getSort()); } } sb.append(" LIMIT "); sb.append(String.valueOf(page.getFirstResult())); sb.append(","); sb.append(String.valueOf(page.getPageSize())); List<Map<String, Object>> list = searchForListMap(sql, params); page.setResult(list); return page; }
/** * 添加一个定时任务 * * @param jobName 任务名 * @param jobGroupName 任务组名 * @param triggerName 触发器名 * @param triggerGroupName 触发器组名 * @param job 任务 * @param cronExpression 时间设置,参考quartz说明文档 */ public static void addJob( String jobName, String jobGroupName, String triggerName, String triggerGroupName, Job job, String cronExpression) throws SchedulerException, ParseException { if (StringUtils.isBlank(jobGroupName)) { jobGroupName = JOB_GROUP_NAME; } if (StringUtils.isBlank(triggerGroupName)) { triggerGroupName = TRIGGER_GROUP_NAME; } Scheduler sched = sf.getScheduler(); // JobDetail jobDetail = new JobDetail(jobName, jobGroupName, // job.getClass());//任务名,任务组,任务执行类 // CronTrigger trigger = new // CronTrigger(jobName,triggerGroupName,cronExpression);//触发器名,触发器组,cron表达式 // sched.scheduleJob(jobDetail,trigger); // 启动 if (!sched.isShutdown()) { sched.start(); } }
/** * 解析token数据 * * @param data * @return */ private boolean parseData(String data) { JSONObject jsonObject = JSONObject.parseObject(data); String tokenName = tokenName(); String expiresInName = expiresInName(); try { String token = jsonObject.get(tokenName).toString(); if (StringUtils.isBlank(token)) { logger.error("token获取失败,获取结果" + data); return false; } this.token = token; this.tokenTime = (new Date()).getTime(); String expiresIn = jsonObject.get(expiresInName).toString(); if (StringUtils.isBlank(expiresIn)) { logger.error("token获取失败,获取结果" + expiresIn); return false; } else { this.expires = Long.valueOf(expiresIn); } } catch (Exception e) { logger.error( "token 结果解析失败,token参数名称: " + tokenName + "有效期参数名称:" + expiresInName + "token请求结果:" + data); e.printStackTrace(); return false; } return true; }
private void checkForm(PartnerActivityProductAudit form, String domain) { if (StringUtils.isBlank(form.getActId())) { throw new BizException(GlobalErrorCode.UNKNOWN, "活动Id不存在"); } if (StringUtils.isBlank(form.getProductId())) { throw new BizException(GlobalErrorCode.UNKNOWN, "商品Id不存在"); } if (form.getAuditState() == null) { throw new BizException(GlobalErrorCode.UNKNOWN, "审核状态不存在"); } if (form.getAuditor() == null) { throw new BizException(GlobalErrorCode.UNKNOWN, "审核人不存在"); } if (ActivityTicketAuditStatus.APPROVED.equals(form.getAuditState())) { if (form.getStartTime() == null || form.getEndTime() == null) throw new BizException(GlobalErrorCode.UNKNOWN, "审核通过必须分配活动开始结束时间"); if (form.getProductId() == null) throw new BizException(GlobalErrorCode.UNKNOWN, "审核信息不完整"); } User user = userService.loadExtUser(StringUtils.defaultString(domain, "xiangqu"), form.getAuditor()); if (user == null) { throw new BizException(GlobalErrorCode.UNAUTHORIZED, "您没有权限审核该活动"); } }
protected void validateRequiredSystemProperties() { String jndiPropertiesDir = System.getProperty(CartridgeAgentConstants.JNDI_PROPERTIES_DIR); if (StringUtils.isBlank(jndiPropertiesDir)) { if (log.isErrorEnabled()) { log.error( String.format( "System property not found: %s", CartridgeAgentConstants.JNDI_PROPERTIES_DIR)); } return; } String payloadPath = System.getProperty(CartridgeAgentConstants.PARAM_FILE_PATH); if (StringUtils.isBlank(payloadPath)) { if (log.isErrorEnabled()) { log.error( String.format( "System property not found: %s", CartridgeAgentConstants.PARAM_FILE_PATH)); } return; } String extensionsDir = System.getProperty(CartridgeAgentConstants.EXTENSIONS_DIR); if (StringUtils.isBlank(extensionsDir)) { if (log.isWarnEnabled()) { log.warn( String.format("System property not found: %s", CartridgeAgentConstants.EXTENSIONS_DIR)); } } }
private Map<AccessLevel, List<DocumentReference>> getCollaborators(XWikiDocument doc) { Map<AccessLevel, List<DocumentReference>> collaborators = new LinkedHashMap<AccessLevel, List<DocumentReference>>(); List<BaseObject> collaboratorObjects = doc.getXObjects(Collaborator.CLASS_REFERENCE); if (collaboratorObjects == null || collaboratorObjects.isEmpty()) { return Collections.emptyMap(); } for (BaseObject collaborator : collaboratorObjects) { if (collaborator == null) { continue; } String collaboratorName = collaborator.getStringValue("collaborator"); String accessName = collaborator.getStringValue("access"); if (StringUtils.isBlank(collaboratorName) || StringUtils.isBlank(accessName)) { continue; } DocumentReference userOrGroup = this.stringEntityResolver.resolve(collaboratorName, doc.getDocumentReference()); AccessLevel access = this.manager.resolveAccessLevel(accessName); List<DocumentReference> list = collaborators.get(access); if (list == null) { list = new LinkedList<DocumentReference>(); collaborators.put(access, list); } list.add(userOrGroup); } return collaborators; }
@Override public void remove(String appid, String id) { if (!StringUtils.isBlank(id) && !StringUtils.isBlank(appid)) { logger.debug("Cache.remove() {} {}", appid, id); client().getMap(appid).delete(id); } }
@Override public boolean contains(String appid, String id) { if (StringUtils.isBlank(id) || StringUtils.isBlank(appid)) { return false; } return client().getMap(appid).containsKey(id); }
/** * * * <ul> * <li><b>IsEmpty/IsBlank</b> - checks if a String contains text * <li><b>Equals</b> - compares two strings null-safe * <li><b>startsWith</b> - check if a String starts with a prefix null-safe * <li><b>endsWith</b> - check if a String ends with a suffix null-safe * <li><b>IndexOf/LastIndexOf/Contains</b> - null-safe index-of checks * <li><b>IndexOfAny/LastIndexOfAny/IndexOfAnyBut/LastIndexOfAnyBut</b> - index-of any of a set * of Strings * <li><b>ContainsOnly/ContainsNone/ContainsAny</b> - does String contains only/none/any of * these characters * <li><b>Chomp/Chop</b> - removes the last part of a String * <li><b>UpperCase/LowerCase/SwapCase/Capitalize/Uncapitalize</b> - changes the case of a * String * <li><b>CountMatches</b> - counts the number of occurrences of one String in another * <li><b>DefaultString</b> - protects against a null input String * <li><b>Reverse/ReverseDelimited</b> - reverses a String * <li><b>Abbreviate</b> - abbreviates a string using ellipsis * <li><b>Difference</b> - compares Strings and reports on their differences * <li><b>LevenshteinDistance</b> - the number of changes needed to change one String into * another * </ul> */ @Test public void testEmptyBlankStringUtils() { String[] array = new String[2]; array[0] = StringUtils.repeat('*', 10) + strOne + StringUtils.repeat('*', 10); array[1] = StringUtils.repeat('~', 10) + strTwo + StringUtils.repeat('~', 10); System.out.println(StringUtils.join(array, ",")); System.out.println("判断是否为空或者空格"); System.out.println( "empty:" + StringUtils.isEmpty(strOne) + "\t" + StringUtils.isEmpty(null) + "\t" + StringUtils.isEmpty("") + "\t" + StringUtils.isEmpty(" ")); System.out.println( "whitespace:" + StringUtils.isBlank(strOne) + "\t" + StringUtils.isBlank(null) + "\t" + StringUtils.isBlank("") + "\t" + StringUtils.isBlank(" ")); }
@RequestMapping(params = "method=changePassword", method = RequestMethod.GET) public String changePassword( HttpServletRequest request, HttpServletResponse response, @RequestParam("userName") String userName, @RequestParam("password") String password, ModelMap modelMap) { userName = userName.trim(); password = password.trim(); if (StringUtils.isBlank(userName) || DiamondUtils.hasInvalidChar(userName.trim())) { modelMap.addAttribute("message", "无效的用户名"); return listUser(request, response, modelMap); } if (StringUtils.isBlank(password) || DiamondUtils.hasInvalidChar(password.trim())) { modelMap.addAttribute("message", "无效的新密码"); return listUser(request, response, modelMap); } if (this.adminService.updatePassword(userName, password)) { modelMap.addAttribute("message", "更改成功,下次登录请用新密码!"); } else { modelMap.addAttribute("message", "更改失败!"); } return listUser(request, response, modelMap); }
@RequestMapping(params = "method=listConfigLike", method = RequestMethod.GET) public String listConfigLike( HttpServletRequest request, HttpServletResponse response, @RequestParam("dataId") String dataId, @RequestParam("group") String group, @RequestParam("pageNo") int pageNo, @RequestParam("pageSize") int pageSize, ModelMap modelMap) { if (StringUtils.isBlank(dataId) && StringUtils.isBlank(group)) { modelMap.addAttribute("message", "模糊查询请至少设置一个查询参数"); return "/admin/config/list"; } Page<ConfigInfo> page = this.configService.findConfigInfoLike(pageNo, pageSize, group, dataId); String accept = request.getHeader("Accept"); if (accept != null && accept.indexOf("application/json") >= 0) { try { String json = JSONUtils.serializeObject(page); modelMap.addAttribute("pageJson", json); } catch (Exception e) { log.error("序列化page对象出错", e); } return "/admin/config/list_json"; } else { modelMap.addAttribute("page", page); modelMap.addAttribute("dataId", dataId); modelMap.addAttribute("group", group); modelMap.addAttribute("method", "listConfigLike"); return "/admin/config/list"; } }
/** @see com.lowagie.tools.AbstractTool#execute() */ public static void execute(String srcvalue, String destvalue, String rotvalue) { try { if (StringUtils.isBlank(srcvalue)) { throw new InstantiationException("You need to choose a sourcefile"); } File src = new File(srcvalue); if (StringUtils.isBlank(destvalue)) { throw new InstantiationException("You need to choose a destination file"); } File dest = new File(destvalue); if (StringUtils.isBlank(rotvalue)) { throw new InstantiationException("You need to choose a rotation"); } int rotation = Integer.parseInt(rotvalue); // we create a reader for a certain document PdfReader reader = new PdfReader(src.getAbsolutePath()); // we retrieve the total number of pages and the page size int total = reader.getNumberOfPages(); System.out.println("There are " + total + " pages in the original file."); PdfDictionary pageDict; int currentRotation; for (int p = 1; p <= total; p++) { currentRotation = reader.getPageRotation(p); pageDict = reader.getPageN(p); pageDict.put(PdfName.ROTATE, new PdfNumber(currentRotation + rotation)); } PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest)); stamper.close(); } catch (Exception e) { e.printStackTrace(); } }
public static <T extends Comparable<T>> Range<T> parse(String value, Function<String, T> parser) { Validate.notNull(parser, "Parser is required"); if (StringUtils.isBlank(value) || StringUtils.equals(SEPARATOR, value)) { return Ranges.all(); } else if (!StringUtils.contains(value, SEPARATOR)) { T element = parser.apply(value); return Ranges.atMost(element); } else { String lower = StringUtils.substringBefore(value, SEPARATOR); String upper = StringUtils.substringAfter(value, SEPARATOR); if (StringUtils.isBlank(lower)) { // ..n Pair<T, BoundType> boundary = parseUpperBoundary(upper, parser); return Ranges.upTo(boundary.getLeft(), boundary.getRight()); } else if (StringUtils.isBlank(upper)) { // n.. Pair<T, BoundType> boundary = parseLowerBoundary(lower, parser); return Ranges.downTo(boundary.getLeft(), boundary.getRight()); } else { // n..m Pair<T, BoundType> down = parseLowerBoundary(lower, parser); Pair<T, BoundType> up = parseUpperBoundary(upper, parser); return Ranges.range(down.getLeft(), down.getRight(), up.getLeft(), up.getRight()); } } }
public void validate(UserRegModel target) { String login = target.getLogin(); String email = target.getEmail(); String lastName = target.getLastName(); String firstName = target.getFirstName(); if (StringUtils.isBlank(login) || login.length() < 2 || login.length() > 30) { target.setLoginWarn("Must be in range [3-30]"); } else if (!userService.isLoginFree(login)) { target.setLoginWarn("Login busy"); } if (StringUtils.isBlank(email) || !EMAIL_PATTERN.matcher(email).matches()) { target.setEmailWarn("Invalid email format"); } if (StringUtils.isBlank(lastName) || lastName.length() < 2 || lastName.length() > 20) { target.setLastNameWarn("Must be in range [2-20]"); } else if (lastName.matches(NUMBER_REGEX)) { target.setLastNameWarn("May contains only letters"); } if (StringUtils.isBlank(firstName) || firstName.length() < 2 || firstName.length() > 20) { target.setFirstNameWarn("Must be in range [2-20]"); } else if (firstName.matches(NUMBER_REGEX)) { target.setFirstNameWarn("May contains only letters"); } }
@Override public Object exec(List arguments) throws TemplateModelException { if (null == arguments || arguments.size() == 0) { return ""; } // 获取资源文件名 String url = (String) arguments.get(0); int imgNumber = FIVE; if (!StringUtils.isBlank(imgHostNumber)) { imgNumber = Integer.valueOf(imgHostNumber); } if (StringUtils.isBlank(url)) { return ""; } // 获取新域名编号 int suffix = Math.abs(stringToInt(url) % imgNumber) + imgUrlStarNum; // 替换编号所在位置的占位符 String hostName = host.replace(imgHostTag, String.valueOf(suffix)); if (!hostName.endsWith("/")) { hostName = hostName + "/"; } if (url.startsWith("/")) { url = url.substring(1); } // 组装形成新域名 String result = hostName + url; return result; }
public MailConfiguration(XWiki xwiki) { this(); String smtpServer = this.mailSenderConfiguration.getHost(); if (!StringUtils.isBlank(smtpServer)) { setHost(smtpServer); } int port = this.mailSenderConfiguration.getPort(); setPort(port); String from = this.mailSenderConfiguration.getFromAddress(); if (!StringUtils.isBlank(from)) { setFrom(from); } String smtpServerUsername = this.mailSenderConfiguration.getUsername(); String smtpServerPassword = this.mailSenderConfiguration.getPassword(); if (!StringUtils.isEmpty(smtpServerUsername) && !StringUtils.isEmpty(smtpServerPassword)) { setSmtpUsername(smtpServerUsername); setSmtpPassword(smtpServerPassword); } Properties javaMailExtraProps = this.mailSenderConfiguration.getAdditionalProperties(); if (!javaMailExtraProps.isEmpty()) { setExtraProperties(javaMailExtraProps); } }
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(true); String currentclassuuid = StringUtils.trimToEmpty(request.getParameter("currentclassroomuuid")); String currentclssteacher = StringUtils.trimToEmpty(request.getParameter("teacheruuid")); if (StringUtils.isBlank(currentclassuuid)) { session.setAttribute(SessionConstants.PROMOTE_CALSS_ERROR, CLASS_DELETE_ERROR); } else if (StringUtils.isBlank(currentclssteacher)) { session.setAttribute(SessionConstants.PROMOTE_CALSS_ERROR, CLASS_DELETE_ERROR); } else { ClassTeacher classTeacher = new ClassTeacher(); classTeacher.setClassRoomUuid(currentclassuuid); classTeacher.setTeacherUuid(currentclssteacher); if (classTeacherDAO.deleteClassTeacher(classTeacher)) { session.setAttribute(SessionConstants.PROMOTE_CALSS_SUCCESS, CLASS_DELETED_SUCCESS); } else { session.setAttribute(SessionConstants.PROMOTE_CALSS_ERROR, CLASS_DELETE_ERROR); } } response.sendRedirect("classTeachers.jsp"); return; }
/* * detect which mediafiles has to be parsed and start a thread to do that */ private void gatherMediaInformationForUngatheredMediaFiles(TvShow tvShow) { // get mediainfo for tv show (fanart/poster..) ArrayList<MediaFile> ungatheredMediaFiles = new ArrayList<MediaFile>(); for (MediaFile mf : tvShow.getMediaFiles()) { if (StringUtils.isBlank(mf.getContainerFormat())) { ungatheredMediaFiles.add(mf); } } if (ungatheredMediaFiles.size() > 0) { submitTask(new MediaFileInformationFetcherTask(ungatheredMediaFiles, tvShow, false)); } // get mediainfo for all episodes within this tv show for (TvShowEpisode episode : new ArrayList<TvShowEpisode>(tvShow.getEpisodes())) { ungatheredMediaFiles = new ArrayList<MediaFile>(); for (MediaFile mf : episode.getMediaFiles()) { if (StringUtils.isBlank(mf.getContainerFormat())) { ungatheredMediaFiles.add(mf); } } if (ungatheredMediaFiles.size() > 0) { submitTask(new MediaFileInformationFetcherTask(ungatheredMediaFiles, episode, false)); } } }
public static ZKPool getZkPool(String zkAddr) throws PlatformException { if (pools.get(zkAddr) == null) { synchronized (LOCK) { if (pools.get(zkAddr) == null) { GenericObjectPoolConfig config = new GenericObjectPoolConfig(); config.setMaxTotal(total); config.setTestOnBorrow(false); config.setMinIdle(10); int timeOut = 2000; if (StringUtils.isBlank(zkAddr)) { throw new PlatformException( ZkErrorCodeConstants.NO_PARSE_ZK_INFO, "zkAddr can not be null,and its format is ip:port"); } if (!StringUtils.isBlank(zkTimeout)) { timeOut = Integer.parseInt(zkTimeout); } ZKPool zkPool = new ZKPool(config, zkAddr, timeOut); pools.put(zkAddr, zkPool); } } } return pools.get(zkAddr); }
/** * Checks if a subject is allowed to call method X on resource Y. * * @param subjectid subject id * @param resourceName resource name (type) * @param httpMethod HTTP method name * @return true if allowed */ public boolean isAllowedTo(String subjectid, String resourceName, String httpMethod) { boolean allow = false; if (subjectid != null && !StringUtils.isBlank(resourceName) && !StringUtils.isBlank(httpMethod)) { if (getResourcePermissions().isEmpty()) { // Default policy is "deny all". Returning true here would make it "allow all". return false; } if (getResourcePermissions().containsKey(subjectid) && getResourcePermissions().get(subjectid).containsKey(resourceName)) { // subject-specific permissions have precedence over wildcard permissions // i.e. only the permissions for that subjectid are checked, other permissions are ignored allow = isAllowed(subjectid, resourceName, httpMethod); } else { allow = isAllowed(subjectid, resourceName, httpMethod) || isAllowed(subjectid, ALLOW_ALL, httpMethod) || isAllowed(ALLOW_ALL, resourceName, httpMethod) || isAllowed(ALLOW_ALL, ALLOW_ALL, httpMethod); } } boolean isRootApp = StringUtils.equals(App.id(Config.APP_NAME_NS), getId()); boolean isRootAppAccessAllowed = Config.getConfigBoolean("clients_can_access_root_app", !Config.IN_PRODUCTION); return isRootApp ? (isRootAppAccessAllowed && allow) : allow; }
public static ZKPool getZkPool(String zkAddr, Properties poolConfig) throws PlatformException { synchronized (LOCK) { if (pools.get(zkAddr) == null) { GenericObjectPoolConfig config = new GenericObjectPoolConfig(); try { // ConfigUtil.propertiesToProperty(poolConfig, config); } catch (Exception e) { throw new PlatformException(ZkErrorCodeConstants.CONFIG_ZK_ERROR, "传入的配置错误", e); } int timeOut = 2000; if (StringUtils.isBlank(zkAddr)) { throw new PlatformException( ZkErrorCodeConstants.NO_PARSE_ZK_INFO, "zkAddr can not be null,and its format is ip:port"); } if (!StringUtils.isBlank(zkTimeout)) { timeOut = Integer.parseInt(zkTimeout); } ZKPool zkPool = new ZKPool(config, zkAddr, timeOut); pools.put(zkAddr, zkPool); } } return pools.get(zkAddr); }
public static String signUp( String userName, String firstName, String lastName, String email, String password) { String message = "Sign up failed. Please try again."; if (StringUtils.isBlank(userName)) { return "User name is required."; } if (StringUtils.isBlank(firstName)) { return "First name is required."; } if (StringUtils.isBlank(lastName)) { return "Last name is required."; } if (StringUtils.isBlank(password)) { return "Password is required and must be at least 6 characters."; } if (userExist(userName)) { message = "The username you input has been used. Please choose another."; } else { int row = getJdbcTemplate() .update(CREATE_USER, firstName + " " + lastName, userName, password, email); if (row > 0) { message = ""; } } return message; }
@GET @Path("logout") @Consumes(MediaType.TEXT_PLAIN) @Override public Response logout( @QueryParam("serviceKey") String serviceKey, @QueryParam("email") String email, @QueryParam("sessionKey") String sessionKey) { RegisteredServiceRequest request = new RegisteredServiceRequest() {}; request.setServiceKey(serviceKey); try { securityChecker.checkService(request); } catch (ServiceNotAllowedException e) { return Response.status(405).build(); } if (StringUtils.isBlank(email) || StringUtils.isBlank(sessionKey)) { return Response.status(400).build(); } userService.logout(email, sessionKey); return Response.status(200).build(); }
public static boolean writeString2File(String content, String path) throws Exception { if (StringUtils.isBlank(content)) { return false; } if (StringUtils.isBlank(path)) { return false; } File file = new File(path); FileWriter fileWriter = null; try { fileWriter = new FileWriter(file); fileWriter.write(content); return true; } catch (IOException e) { e.printStackTrace(); } finally { if (fileWriter != null) { try { fileWriter.close(); } catch (IOException e) { e.printStackTrace(); } fileWriter = null; } if (file != null) { file = null; } } return false; }
@POST @Path("register") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Override public AuthenticationResponse register(UserRegistrationRequest request) { AuthenticationResponse response = new AuthenticationResponse(); try { securityChecker.checkService(request); } catch (ServiceNotAllowedException ee) { ServiceNotAllowedJSONException exception = new ServiceNotAllowedJSONException("user/register", request.getServiceKey()); response.setServiceNotAllowedException(exception); return response; } if (StringUtils.isBlank(request.getEmail())) { response.setFieldRequiredJSONException( new FieldRequiredJSONException("user/register", request, "email")); return response; } else if (StringUtils.isBlank(request.getPassword())) { response.setFieldRequiredJSONException( new FieldRequiredJSONException("user/register", request, "password")); return response; } else if (StringUtils.isBlank(request.getFirstName())) { response.setFieldRequiredJSONException( new FieldRequiredJSONException("user/register", request, "firstName")); return response; } else if (StringUtils.isBlank(request.getLastName())) { response.setFieldRequiredJSONException( new FieldRequiredJSONException("user/register", request, "lastName")); return response; } if (!EmailValidator.getInstance().isValid(request.getEmail())) { response.setInvalidEmailJSONException( new InvalidEmailJSONException("user/register", request.getEmail())); return response; } User user = new User(); user.setEmail(request.getEmail().toLowerCase()); user.setFirstName(request.getFirstName()); user.setLastName(request.getLastName()); try { String sessionKey = userService.register(user, request.getPassword(), Platform.OTHER); response.setSessionKey(sessionKey); return response; } catch (EmailAlreadyInUseException e) { response.setRegisterEmailAlreadyInUseJSONException( new RegisterEmailAlreadyInUseJSONException("user/register", request.getEmail())); return response; } catch (PasswordLenghtInvalidException e) { response.setPasswordLengthInvalidJSONException( new PasswordLengthInvalidJSONException("user/register")); return response; } }
private boolean isValidPort(String text) { if (StringUtils.isBlank(text)) return false; String[] ports = text.trim().split(","); boolean ok = false; // linux (and OSX?) if (SystemUtils.IS_OS_LINUX || SystemUtils.IS_OS_MAC_OSX) { // each will be /dev/tty* or /dev/cu* for (String port : ports) { if (StringUtils.isBlank(port)) continue; if (portNamesRegexLinux.matcher(port.trim()).matches()) { // must be at least one good ok = true; } else { // doesnt match, its bad so outa here. return false; } } } // windows if (SystemUtils.IS_OS_WINDOWS) { // each will be COM* for (String port : ports) { if (StringUtils.isBlank(port)) continue; if (portNamesRegexWindows.matcher(port.trim()).matches()) { // must be at least one good ok = true; } else { // doesnt match, its bad so outa here. return false; } } } return ok; }
@Override public Double convertCurrency(Number amount, String from, String to) { if (amount == null || StringUtils.isBlank(from) || StringUtils.isBlank(to)) { return 0.0; } Sysprop s = dao.read(FXRATES_KEY); if (s == null) { s = fetchFxRatesJSON(); } else if ((Utils.timestamp() - s.getTimestamp()) > REFRESH_AFTER) { // lazy refresh fx rates Para.asyncExecute( new Runnable() { public void run() { fetchFxRatesJSON(); } }); } double ratio = 1.0; if (s.hasProperty(from) && s.hasProperty(to)) { Double f = NumberUtils.toDouble(s.getProperty(from).toString(), 1.0); Double t = NumberUtils.toDouble(s.getProperty(to).toString(), 1.0); ratio = t / f; } return amount.doubleValue() * ratio; }