Java Code Examples for org.apache.commons.lang.StringUtils.trim()

The following are Jave code examples for showing how to use trim() of the org.apache.commons.lang.StringUtils class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: Hydrograph   File: JobLogger.java   View Source Code Vote up 6 votes
/**
 * 
 * log message
 * 
 * @param message
 */
public void logMessage(String message){
	for(AbstractJobLogger jobLogger: loggers){
		if(StringUtils.isNotBlank(message)){
			message = StringUtils.trim(message);
			jobLogger.log(message);
		}
		logger.debug("Logged message {} on {}", message, jobLogger.getClass().getName());
	}
}
 
Example 2
Project: Hydrograph   File: UiConverter.java   View Source Code Vote up 6 votes
/**
 * Generate basic properties that are common in all components.
 */
public void prepareUIXML() {
	componentId = StringUtils.trim(typeBaseComponent.getId());
	componentName=StringUtils.trim(typeBaseComponent.getName());
	if(StringUtils.isBlank(componentName)){
		componentName=componentId;
	}
	name_suffix = uiComponent.getComponentName() + "_";
	LOGGER.debug("Preparing basic properties for component Name:{} and Id{}", componentName,componentId);
	propertyMap.put(NAME, componentName);
	propertyMap.put(BATCH, typeBaseComponent.getBatch().toString());
	uiComponent.setComponentLabel(componentName);
	uiComponent.setParent(container);
	uiComponent.setComponentId(componentId);
	currentRepository.getComponentUiFactory().put(componentId, uiComponent);
}
 
Example 3
Project: Hydrograph   File: CategoriesDialogTargetComposite.java   View Source Code Vote up 6 votes
public void loadPackagesFromPropertyFileSettingFolder() {
	Properties properties = new Properties();
	IFolder folder = BuildExpressionEditorDataSturcture.INSTANCE.getCurrentProject().getFolder(
			PathConstant.PROJECT_RESOURCES_FOLDER);
	IFile file = folder.getFile(PathConstant.EXPRESSION_EDITOR_EXTERNAL_JARS_PROPERTIES_FILES);
	try {
		LOGGER.debug("Loading property file");
		targetList.removeAll();
		if (file.getLocation().toFile().exists()) {
			FileInputStream inStream = new FileInputStream(file.getLocation().toString());
			properties.load(inStream);
			for (Object key : properties.keySet()) {
				String jarFileName = StringUtils.trim(StringUtils.substringAfter((String) key, Constants.DASH));
				if (BuildExpressionEditorDataSturcture.INSTANCE.getIPackageFragment(jarFileName) != null) {
					targetList.add((String) key+SWT.SPACE+Constants.DASH+SWT.SPACE+properties.getProperty((String)key));
				}
			}
		}
	} catch (IOException | RuntimeException exception) {
		LOGGER.error("Exception occurred while loading jar files from projects setting folder", exception);
	}

}
 
Example 4
Project: Hydrograph   File: Container.java   View Source Code Vote up 6 votes
private boolean checkIfDuplicateComponentExists(String newNameORComponentId, Component currentComponent,
		boolean checkId) {
	newNameORComponentId=StringUtils.trim(newNameORComponentId);
	if (!getChildren().isEmpty()) {
		for (Object object : getChildren()) {
			if ( object instanceof Component && !object.equals(currentComponent)) {
				Component component = (Component) object;
				if (checkId && StringUtils.equalsIgnoreCase(StringUtils.trim(component.getComponentId()), newNameORComponentId)) {
					LoggerUtil.getLoger(this.getClass()).trace("Duplicate component exists.");
					return true;
				}else if(!checkId && StringUtils.equalsIgnoreCase(StringUtils.trim(component.getComponentLabel().getLabelContents()), newNameORComponentId)) {
					LoggerUtil.getLoger(this.getClass()).trace("Duplicate component exists.");
					return true;
				}
			}
		}
	}
	return false;
}
 
Example 5
Project: Hydrograph   File: TrackingDisplayUtils.java   View Source Code Vote up 6 votes
/**
 * This function will be return process ID which running on defined port.
 * 
 * @return the service port pid
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
public String getServicePortPID(Properties properties) throws IOException {
	int portNumber = Integer.parseInt(properties.getProperty(EXECUTION_TRACKING_PORT));
	if (OSValidator.isWindows()) {
		ProcessBuilder builder = new ProcessBuilder(new String[] { "cmd",
				"/c", "netstat -a -o -n |findstr :" + portNumber });
		Process process = builder.start();
		InputStream inputStream = process.getInputStream();
		BufferedReader bufferedReader = new BufferedReader(
				new InputStreamReader(inputStream));
		String str = bufferedReader.readLine();
		str = StringUtils.substringAfter(str, "LISTENING");
		str = StringUtils.trim(str);
		return str;
	}
	return "";
}
 
Example 6
Project: Hydrograph   File: ComponentPasteCommand.java   View Source Code Vote up 6 votes
private String getPrefix(Object node) {
	String currentName=((Component) node).getComponentLabel().getLabelContents();
	String prefix=currentName;
	StringBuffer buffer=new StringBuffer(currentName);
	try {
	if(buffer.lastIndexOf(UNDERSCORE)!=-1 && (buffer.lastIndexOf(UNDERSCORE)!=buffer.length())){
		String substring = StringUtils.trim(buffer.substring(buffer.lastIndexOf(UNDERSCORE)+1,buffer.length()));
		if(StringUtils.isNumeric(substring)){
			prefix=buffer.substring(0,buffer.lastIndexOf(UNDERSCORE)); 
		}
	}}
	catch (Exception exception) {
		LOGGER.warn("Cannot process component name for detecting prefix : ",exception.getMessage());
	}
	return prefix;
}
 
Example 7
Project: plpgsql-java-model   File: TemplaterEngine.java   View Source Code Vote up 5 votes
/**
     * Use file based template
     * @param fileName path to template in resources
     * @param data
     * @return
     */
    public String template(String fileName, Map<String, Object> data) {

        org.apache.velocity.Template t = ve.getTemplate(fileName);

        StringWriter writer = new StringWriter();
        VelocityContext vc = new VelocityContext(data);
//        vc.put("_nl", "\n");//иногда неоткуда взять перенос строки...
        t.merge(vc, writer);

        return StringUtils.trim(writer.toString());
    }
 
Example 8
Project: plpgsql-java-model   File: TemplaterEngine.java   View Source Code Vote up 5 votes
/**
 * Use string as a template
 * @param template string, contains template as is
 * @param data
 * @return
 */
public String evaluate(String template, Map<String, Object> data) {
    StringWriter writer = new StringWriter();
    VelocityContext vc = new VelocityContext(data);

    ve.evaluate(vc, writer, "stub template name", template);
    return StringUtils.trim(writer.toString());
}
 
Example 9
Project: airsonic   File: PodcastReceiverAdminController.java   View Source Code Vote up 5 votes
@RequestMapping(method = { RequestMethod.POST, RequestMethod.GET })
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {
    Integer channelId = ServletRequestUtils.getIntParameter(request, "channelId");

    if (request.getParameter("add") != null) {
        String url = StringUtils.trim(request.getParameter("add"));
        podcastService.createChannel(url);
        return new ModelAndView(new RedirectView("podcastChannels.view"));
    }
    if (request.getParameter("downloadEpisode") != null) {
        download(StringUtil.parseInts(request.getParameter("downloadEpisode")));
        return new ModelAndView(new RedirectView("podcastChannel.view?id=" + channelId));
    }
    if (request.getParameter("deleteChannel") != null) {
        podcastService.deleteChannel(channelId);
        return new ModelAndView(new RedirectView("podcastChannels.view"));
    }
    if (request.getParameter("deleteEpisode") != null) {
        for (int episodeId : StringUtil.parseInts(request.getParameter("deleteEpisode"))) {
            podcastService.deleteEpisode(episodeId, true);
        }
        return new ModelAndView(new RedirectView("podcastChannel.view?id=" + channelId));
    }
    if (request.getParameter("refresh") != null) {
        if (channelId != null) {
            podcastService.refreshChannel(channelId, true);
            return new ModelAndView(new RedirectView("podcastChannel.view?id=" + channelId));
        } else {
            podcastService.refreshAllChannels(true);
            return new ModelAndView(new RedirectView("podcastChannels.view"));
        }
    }

    return new ModelAndView(new RedirectView("podcastChannels.view"));
}
 
Example 10
Project: QLExpress   File: CustBean.java   View Source Code Vote up 5 votes
public static String firstToUpper(String value){
	if(StringUtils.isBlank(value))
		return "";
	value = StringUtils.trim(value);
	String f = StringUtils.substring(value,0,1);
	String s = "";
	if(value.length() > 1){
		s = StringUtils.substring(value,1);
	}
	return f.toUpperCase() + s;
}
 
Example 11
Project: otter-G   File: URLProtectedEditor.java   View Source Code Vote up 5 votes
/**
 * 把字符串文本转换成一堆Pattern,用于匹配URL
 */
private List<URLPatternHolder> convertTextToPatterns(String text) {
    List<URLPatternHolder> list = new ArrayList<URLPatternHolder>();
    if (StringUtils.isNotEmpty(text)) {
        BufferedReader br = new BufferedReader(new StringReader(text));
        int counter = 0;
        String line;
        while (true) {
            counter++;
            try {
                line = br.readLine();
            } catch (IOException ioe) {
                throw new IllegalArgumentException(ioe.getMessage());
            }
            if (line == null) {
                break;
            }
            line = StringUtils.trim(line);
            if (StringUtils.isBlank(line)) {
                continue;
            }
            if (logger.isDebugEnabled()) {
                logger.debug("Line " + counter + ": " + line);
            }
            list.add(convertStringToPattern(line));
        }
    }
    return list;
}
 
Example 12
Project: otter-G   File: ActionProtectedEditor.java   View Source Code Vote up 5 votes
/**
 * 把字符串文本转换成一堆Pattern,用于匹配URL
 */
private List<ActionPatternHolder> convertTextToPatterns(String text) {
    List<ActionPatternHolder> list = new ArrayList<ActionPatternHolder>();
    if (StringUtils.isNotEmpty(text)) {
        BufferedReader br = new BufferedReader(new StringReader(text));
        int counter = 0;
        String line;
        while (true) {
            counter++;
            try {
                line = br.readLine();
            } catch (IOException ioe) {
                throw new IllegalArgumentException(ioe.getMessage());
            }
            if (line == null) {
                break;
            }
            line = StringUtils.trim(line);
            if (StringUtils.isBlank(line)) {
                continue;
            }
            if (logger.isDebugEnabled()) {
                logger.debug("Line " + counter + ": " + line);
            }
            list.add(convertStringToPattern(line));
        }
    }
    return list;
}
 
Example 13
Project: otter-G   File: AbstractRuleMonitor.java   View Source Code Vote up 5 votes
protected boolean inPeriod(AlarmRule alarmRule) {
    String rule = alarmRule.getMatchValue();
    if (StringUtils.isEmpty(rule)) {
        log.info("rule is empty " + alarmRule);
        return false;
    }

    String periods = StringUtils.substringAfterLast(rule, "@");
    if (StringUtils.isEmpty(periods)) {
        // 没有时间要求,则任务在报警时间段内
        return isInPeriodWhenNoPeriod();
    }

    Calendar calendar = currentCalendar();
    periods = StringUtils.trim(periods);
    for (String period : StringUtils.split(periods, ",")) {
        String[] startAndEnd = StringUtils.split(period, "-");
        if (startAndEnd == null || startAndEnd.length != 2) {
            log.error("error period time format in rule : " + alarmRule);
            return isInPeriodWhenErrorFormat();
        }

        String start = startAndEnd[0];
        String end = startAndEnd[1];
        if (checkInPeriod(calendar, start, end)) {
            log.info("rule is in period : " + alarmRule);
            return true;
        }
    }

    log.info("rule is not in period : " + alarmRule);
    return false;
}
 
Example 14
Project: rent   File: UserController.java   View Source Code Vote up 5 votes
@ApiOperation("登录")
@PostMapping("/sessions")
public Result login(@RequestBody User user, HttpSession session) {
	//log记录信息
	logger.debug("method login get param:" + user);
	//通过session判断是否已登录
	if (TRUE.equals(session.getAttribute(IS_LOGIN))) {
		return new Result(false, "您已登录!");
	}
	//获取参数并trim必要的参数
	String username = StringUtils.trim(user.getUsername());
	String password = StringUtils.trim(user.getPassword());
	//认证并返回结果
	if(username == null || password == null) {
		return new Result(false, "密码和用户名不能为空");
	}
	UserExample userExample = new UserExample();
	userExample.createCriteria().andUsernameEqualTo(username);
	List<User> users = userService.selectByExample(userExample);
	User u = users.size() == 0 ? null : users.get(0);
	if (u == null) {
		return new Result(false, "用户名不存在");
	}
	if (!u.getPassword().equals(password)) {
		return new Result(false, "密码和用户名不匹配");
	}
	//session记录登录信息
	session.setAttribute(IS_LOGIN, TRUE);
	session.setAttribute(USER, u);
	return new Result(true, u);
}
 
Example 15
Project: rent   File: CategoryController.java   View Source Code Vote up 5 votes
@ApiOperation("添加类别")
@PostMapping("/categories")
public Result add(@RequestBody Category category) {
	//log记录信息
	logger.debug("method add get param:" + category);
	//判断空
	if(StringUtils.isBlank(category.getName())) {
		return new Result(false, "类别名称不能为空");
	}
	//trim参数
	String name = StringUtils.trim(category.getName());
	//判断已有
	CategoryExample categoryExample = new CategoryExample();
	categoryExample.createCriteria().andNameEqualTo(name);
	List<Category> categories = categoryService.selectByExample(categoryExample);
	if(!categories.isEmpty()) {
		return new Result(false, "该类别已存在");
	}
	//插入DB
	category.setName(name);
	categoryService.insert(category);
	//返回添加的对象
	CategoryExample categoryExample1 = new CategoryExample();
	categoryExample1.createCriteria().andNameEqualTo(name);
	Category c = categoryService.selectByExample(categoryExample1).get(0);
	return new Result(true, c);
}
 
Example 16
Project: Hydrograph   File: ExpressionEditorStyledText.java   View Source Code Vote up 5 votes
private String getExpressionText(String expressionText) {
	StringBuffer buffer=new StringBuffer(expressionText);
	int startIndex=buffer.indexOf(RETURN_STATEMENT);
	if(startIndex>-1){
		buffer.delete(0, startIndex);
		buffer.delete(0, buffer.indexOf("\n"));
	}
	return StringUtils.trim(buffer.toString());
}
 
Example 17
Project: Hydrograph   File: MethodDetails.java   View Source Code Vote up 5 votes
private void createPlaceHolderFromSource(IMethod iMethod, String className) throws JavaModelException {
	StringBuffer buffer = new StringBuffer(iMethod.getSource());
	int indexOfPlaceHolder = buffer.lastIndexOf("@see");
	if (indexOfPlaceHolder != -1 && iMethod.getParameterNames() != null && iMethod.getParameterNames().length > 0) {
		buffer = buffer.delete(0, indexOfPlaceHolder + 4);
		buffer = buffer.delete(buffer.indexOf("\n")+1, buffer.capacity());
		if(StringUtils.contains(buffer.toString(), className + Constants.DOT+iMethod.getElementName())){
			placeHolder = StringUtils.trim(buffer.toString());
		}
		else
			placeHolder = createDefaultPlaceHolder(iMethod, className);
	} else {
		placeHolder = createDefaultPlaceHolder(iMethod, className);
	}
}
 
Example 18
Project: Hydrograph   File: MethodDetails.java   View Source Code Vote up 5 votes
public String createDefaultPlaceHolder(IMethod iMethod, String className) throws JavaModelException {
	StringBuffer buffer = new StringBuffer();
	buffer.append(className + Constants.DOT);
	buffer.append(iMethod.getElementName()+ Constants.OPENING_BRACKET);
	if (iMethod.getParameterNames() != null && iMethod.getParameterNames() != null)
		for (int index = 0; index < iMethod.getParameterNames().length; index++) {
			buffer.append(iMethod.getParameterNames()[index]);
			if (index != iMethod.getParameterTypes().length - 1) {
				buffer.append(Constants.COMMA + SWT.SPACE);
			}
		}
	buffer.append(Constants.CLOSING_BRACKET);
	return StringUtils.trim(buffer.toString());
}
 
Example 19
Project: Hydrograph   File: ApplicationWorkbenchWindowAdvisor.java   View Source Code Vote up 5 votes
/**
 * This function will be return process ID which running on defined port
 *
 */
public String getServicePortPID(String portNumber) throws IOException{
	if(OSValidator.isWindows()){
		ProcessBuilder builder = new ProcessBuilder(new String[]{"cmd", "/c" ,"netstat -a -o -n |findstr :"+portNumber});
		Process process =builder.start();
		InputStream inputStream = process.getInputStream();
		BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
		String str = bufferedReader.readLine();
		str=StringUtils.substringAfter(str, "LISTENING");
		str=StringUtils.trim(str);
		return str;
	}
	return "";
}
 
Example 20
Project: airsonic   File: MetaDataParser.java   View Source Code Vote up 4 votes
/**
 * Guesses the title for the given file.
 */
public String guessTitle(File file) {
    return StringUtils.trim(FilenameUtils.getBaseName(file.getPath()));
}