1 /**
2 * Copyright 2011 meltmedia
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16 package org.xchain.framework.scanner;
17
18 import java.net.URL;
19
20 /**
21 * @author Christian Trimble
22 * @author Josh Kennedy
23 * @author Devon Tackett
24 * @author John Trimble
25 */
26 public class ScanUtil
27 {
28 /**
29 * <p>Removes the resource name from the resource url to compute the url of the root resource.</p>
30 *
31 * @param resourceUrl a resource url obtained from ClassLoader.getResource(String) or ClassLoader.getResources(String)
32 * @param resourceName the resource name that was used to obtain the resourceUrl.
33 * @return the root url for the artifact that contains the resource.
34 */
35 public static URL computeResourceRoot( URL resourceUrl, String resourceName )
36 throws Exception
37 {
38 String resourceString = resourceUrl.toString();
39
40 // correct the root relative path if it ends in a different "/" character than the resource string.
41 if( resourceString.endsWith("/") && !resourceName.endsWith("/") ) {
42 resourceName = resourceName + "/";
43 }
44 else if( !resourceString.endsWith("/") && resourceName.endsWith("/") ) {
45 resourceName = resourceName.substring(0, resourceName.length() - 1);
46 }
47
48 // ASSERT: the ends in the same "/" character as the resource string.
49
50 // replaces the path with the correct number of ".." characters to make a relative path that points at the root.
51 String relativePath = "./" + resourceName.replaceAll("\\A(?:(.+)/[^/]*|([^/]*))\\Z", "$1").replaceAll("[^/]+", "..");
52
53 return new URL(resourceUrl, relativePath);
54 }
55
56 }