Skip to content
Snippets Groups Projects
Commit 77978dfd authored by srosse's avatar srosse
Browse files

OO-1038: better check of long without exception, try and catch in...

OO-1038: better check of long without exception, try and catch in PersistingCourseGroupManager, unit tests
parent d8ab2978
No related branches found
No related tags found
No related merge requests found
......@@ -68,6 +68,8 @@ public class StringHelper {
private static final String WHITESPACE_REGEXP = "^\\s*$";
private static final Pattern WHITESPACE_PATTERN = Pattern.compile(WHITESPACE_REGEXP);
private static final int LONG_MAX_LENGTH = Long.toString(Long.MAX_VALUE).length();
/**
* regex for not allowing
* <code>;,:</code> <code>ALL_WITHOUT_COMMA_2POINT_STRPNT</code>
......@@ -384,11 +386,21 @@ public class StringHelper {
return FileUtils.normalizeFilename(s);
}
/**
* The method do only a precheck if the string can be a number. It's goal
* is to prevent to generate hunderds of exceptions in a loop by using
* the Long.parseLong() method (exceptions is time and CPU intensive).
*
* return True if the string can be a digit (there is not boundaries check)
*/
public static boolean isLong(String string) {
if(string == null || string.length() == 0) {
return false;
}
int stop = string.startsWith("-") ? 1 : 0;
if(string.length() > LONG_MAX_LENGTH + stop) {
return false;
}
char[] charArr = string.toCharArray();
for(int i=charArr.length; i-->stop; ) {
char ch = charArr[i];
......
......@@ -172,8 +172,12 @@ public class PersistingCourseGroupManager extends BasicManager implements Course
public boolean existGroup(String nameOrKey) {
SearchBusinessGroupParams params = new SearchBusinessGroupParams();
if(StringHelper.isLong(nameOrKey)) {
params.setGroupKeys(Collections.singletonList(new Long(nameOrKey)));
}else {
try {
params.setGroupKeys(Collections.singletonList(new Long(nameOrKey)));
} catch (NumberFormatException e) {
params.setExactName(nameOrKey);
}
} else {
params.setExactName(nameOrKey);
}
return businessGroupService.countBusinessGroups(params, courseResource) > 0;
......
......@@ -108,4 +108,16 @@ public class StringHelperTest {
String value12 = StringHelper.cleanUTF8ForXml("Hello\u10B7x pahlavi");
Assert.assertEquals("Pahlavi test", "Hello\u10B7x pahlavi", value12);
}
@Test
public void isLong() {
Assert.assertTrue(StringHelper.isLong("234"));
Assert.assertTrue(StringHelper.isLong("9223372036854775807"));
Assert.assertTrue(StringHelper.isLong("-9223372036854775807"));
Assert.assertFalse(StringHelper.isLong("10223372036854775807"));
Assert.assertFalse(StringHelper.isLong("-dru"));
Assert.assertFalse(StringHelper.isLong("OpenOLAT"));
Assert.assertFalse(StringHelper.isLong("A very long number with a lot of characters"));
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment