1 /*
2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements. See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership. The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License. You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied. See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
19 package org.apache.myfaces.view.facelets.util;
20
21 /**
22 * @author Jacob Hookom
23 * @version $Id: Path.java 1188235 2011-10-24 17:09:33Z struberg $
24 */
25 public final class Path
26 {
27
28 public static final String normalize(String path)
29 {
30 if (path.length() == 0)
31 {
32 return path;
33 }
34 String n = path;
35 boolean abs = false;
36 while (n.indexOf('\\') >= 0)
37 {
38 n = n.replace('\\', '/');
39 }
40 if (n.charAt(0) != '/')
41 {
42 n = '/' + n;
43 abs = true;
44 }
45 int idx = 0;
46 while (true)
47 {
48 idx = n.indexOf("%20");
49 if (idx == -1)
50 {
51 break;
52 }
53 n = n.substring(0, idx) + " " + n.substring(idx + 3);
54 }
55 while (true)
56 {
57 idx = n.indexOf("/./");
58 if (idx == -1)
59 {
60 break;
61 }
62 n = n.substring(0, idx) + n.substring(idx + 2);
63 }
64 if (abs)
65 {
66 n = n.substring(1);
67 }
68 return n;
69 }
70
71 public static final String relative(String ctx, String path)
72 {
73 if (path.length() == 0)
74 {
75 return context(ctx);
76 }
77 String c = context(normalize(ctx));
78 String p = normalize(path);
79 p = c + p;
80
81 int idx = 0;
82 while (true)
83 {
84 idx = p.indexOf("/../");
85 if (idx == -1)
86 {
87 break;
88 }
89 int s = p.lastIndexOf('/', idx - 3);
90 if (s == -1)
91 {
92 break;
93 }
94 p = p.substring(0, s) + p.substring(idx + 3);
95 }
96 return p;
97 }
98
99 public static final String context(String path)
100 {
101 int idx = path.lastIndexOf('/');
102 if (idx == -1)
103 {
104 return "/";
105 }
106 return path.substring(0, idx + 1);
107 }
108
109 }