1 package org.apache.archiva.common.utils;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 import org.apache.commons.lang.StringUtils;
23
24 import java.io.File;
25 import java.net.MalformedURLException;
26
27
28
29
30
31
32 public class PathUtil
33 {
34 public static String toUrl( String path )
35 {
36
37 if ( path.startsWith( "file:/" ) )
38 {
39 return path;
40 }
41
42 return toUrl( new File( path ) );
43 }
44
45 public static String toUrl( File file )
46 {
47 try
48 {
49 return file.toURI().toURL().toExternalForm();
50 }
51 catch ( MalformedURLException e )
52 {
53 String pathCorrected = StringUtils.replaceChars( file.getAbsolutePath(), '\\', '/' );
54 if ( pathCorrected.startsWith( "file:/" ) )
55 {
56 return pathCorrected;
57 }
58
59 return "file://" + pathCorrected;
60 }
61 }
62
63
64
65
66
67
68
69
70 public static String getRelative( String basedir, File file )
71 {
72 return getRelative( basedir, file.getAbsolutePath() );
73 }
74
75
76
77
78
79
80
81
82 public static String getRelative( String basedir, String child )
83 {
84 if ( basedir.endsWith( "/" ) || basedir.endsWith( "\\" ) )
85 {
86 basedir = basedir.substring( 0, basedir.length() - 1 );
87 }
88
89 if ( child.startsWith( basedir ) )
90 {
91
92 return child.substring( basedir.length() + 1 );
93 }
94
95 String absoluteBasedir = new File( basedir ).getAbsolutePath();
96 if ( child.startsWith( absoluteBasedir ) )
97 {
98
99 return child.substring( absoluteBasedir.length() + 1 );
100 }
101
102
103 throw new IllegalStateException(
104 "Unable to obtain relative path of file " + child + ", it is not within basedir " + basedir + "." );
105 }
106 }