FilenameUtils { public static String normalize(final String name) { if (name == null) { throw new IllegalArgumentException("name cannot be null"); } StringBuilder sb = new StringBuilder(); for (char c: name.toCharArray()) { if (RESERVED.contains(c)) { sb.append('%').append((c<16) ? "0" : "").append(Integer.toHexString(c).toUpperCase(Locale.ROOT)); } else { sb.append(c); } } return sb.toString(); }  static String normalize(final String name); static String getName(final String path); final static char[] RESERVED_FILENAME_CHARACTERS; }
@Test public void normalizeNothingTodo() throws Exception { final String TEST_NAME = "test.zip"; assertEquals(TEST_NAME, FilenameUtils.normalize(TEST_NAME)); }
@Test public void normalizeWithNull() throws Exception { try { FilenameUtils.normalize(null); fail("missing check for null parameters"); } catch (IllegalArgumentException x) { assertTrue(x.getMessage() != null && x.getMessage().contains("name")); assertTrue(x.getMessage() != null && x.getMessage().contains("not be null")); } }
@Test public void normalizeWithReservedChar() throws Exception { final String[] TEST_NAMES = { "test?.txt", "?test.txt", "test.txt?", "?test?txt?" }; final String[] EXPECTED_NAMES = { "test%3F.txt", "%3Ftest.txt", "test.txt%3F", "%3Ftest%3Ftxt%3F" }; for (int i=0; i<TEST_NAMES.length; ++i) { assertEquals(EXPECTED_NAMES[i], FilenameUtils.normalize(TEST_NAMES[i])); } }
@Test public void normalizeWithReservedChars() throws Exception { final String TEST_NAME = "?a/b\nc\td\re*f\\g:h<i>j.txt|"; final String EXPECTED_NAME = "%3Fa/b%0Ac%09d%0De%2Af\\g%3Ah%3Ci%3Ej.txt%7C"; assertEquals(EXPECTED_NAME, FilenameUtils.normalize(TEST_NAME)); }
@Test public void normalizeWithNotPrintableChars() throws Exception { final String TEST_NAME = new String( new char[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, '.', 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31 } ); final String EXPECTED_NAME = "%00%01%02%03%04%05%06%07%08%09%0A%0B%0C%0D%0E%0F" + "." + "%10%11%12%13%14%15%16%17%18%19%1A%1B%1C%1D%1E%1F"; assertEquals(EXPECTED_NAME, FilenameUtils.normalize(TEST_NAME)); }