Normalize a URI by removing any "./" segments, and "path/../" segments. @return a new URI instance with redundant segments removed. @see http://docs.oracle.com/javase/6/docs/api/java/net/URI.html#normalize%28%29</a
()
| 862 | * @see <a href="http://docs.oracle.com/javase/6/docs/api/java/net/URI.html#normalize%28%29">http://docs.oracle.com/javase/6/docs/api/java/net/URI.html#normalize%28%29</a> |
| 863 | */ |
| 864 | public URI normalize() { |
| 865 | String thisPath = getPath(); |
| 866 | StringTokenizer st = new StringTokenizer(thisPath, String.valueOf(PATH_SEPARATOR)); |
| 867 | List<String> segments = new ArrayList<String>(); |
| 868 | while (st.hasMoreTokens()) { |
| 869 | segments.add(st.nextToken()); |
| 870 | } |
| 871 | List<Integer> removals = new ArrayList<Integer>(); |
| 872 | for (int i = 0; i < segments.size(); i++) { |
| 873 | String segment = segments.get(i); |
| 874 | if (segment.equals(".")) { |
| 875 | removals.add(0, i); |
| 876 | continue; |
| 877 | } else if (i > 0 && segment.equals("..")) { |
| 878 | if (segments.get(i - 1).equals("..") == false) { |
| 879 | removals.add(0, i - 1); |
| 880 | removals.add(0, i); |
| 881 | continue; |
| 882 | } |
| 883 | } |
| 884 | } |
| 885 | Iterator<Integer> iter = removals.iterator(); |
| 886 | while (iter.hasNext()) { |
| 887 | segments.remove(iter.next().intValue()); |
| 888 | } |
| 889 | StringBuilder buffer = new StringBuilder(); |
| 890 | for (int i = 0; i < segments.size(); i++) { |
| 891 | String segment = segments.get(i); |
| 892 | if (i == 0) { |
| 893 | if (isAbsolute()) { |
| 894 | buffer.append(PATH_SEPARATOR); |
| 895 | } else if (segment.indexOf(SCHEME_SEPARATOR) != -1) { |
| 896 | buffer.append('.'); |
| 897 | buffer.append(PATH_SEPARATOR); |
| 898 | } |
| 899 | buffer.append(segment); |
| 900 | continue; |
| 901 | } |
| 902 | buffer.append(PATH_SEPARATOR); |
| 903 | buffer.append(segment); |
| 904 | } |
| 905 | try { |
| 906 | return new URI(getScheme(), getUserInfo(), getHost(), getPort(), buffer.toString(), getQuery(), |
| 907 | getFragment()); |
| 908 | } catch (URISyntaxException e) { |
| 909 | // since both URIs should already be valid, we should never get |
| 910 | // here. |
| 911 | throw new IllegalArgumentException(e.getMessage()); |
| 912 | } |
| 913 | } |
| 914 | |
| 915 | /* (non-Javadoc) |
| 916 | * @see java.lang.Object#hashCode() |